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 a4fa14482ad..1f46fb47d27 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 @@ -44,7 +44,7 @@ public class ComponentConstants { public static final QName UI_FOCUS_TAB_POLICY_RULES = new QName(NS_COMPONENTS_PREFIX, "focusTabPolicyRules"); public static final String UI_FOCUS_TAB_POLICY_RULES_URL = QNameUtil.qNameToUri(UI_FOCUS_TAB_POLICY_RULES); - + public static final QName UI_FOCUS_TAB_CONSENTS = new QName(NS_COMPONENTS_PREFIX, "focusTabConsents"); public static final String UI_FOCUS_TAB_CONSENTS_URL = QNameUtil.qNameToUri(UI_FOCUS_TAB_CONSENTS); @@ -70,6 +70,6 @@ public class ComponentConstants { public static final String UI_FOCUS_TAB_POLICY_CONSTRAINTS_URL = QNameUtil.qNameToUri(UI_FOCUS_TAB_POLICY_CONSTRAINTS); public static final QName UI_FOCUS_TAB_MEMBERS = new QName(NS_COMPONENTS_PREFIX, "focusTabMembers"); - public static final String UI_FOCUS_TAB_MEMBERS_URL = QNameUtil.qNameToUri(UI_FOCUS_TAB_MEMBERS); + public static final String UI_FOCUS_TAB_MEMBERS_URL = QNameUtil.qNameToUri(UI_FOCUS_TAB_MEMBERS); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/GuiConstants.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/GuiConstants.java index 002f9076ee9..654d4743232 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/GuiConstants.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/GuiConstants.java @@ -21,5 +21,5 @@ public class GuiConstants { public static final String NS_UI_PREFIX = SchemaConstants.NS_MIDPOINT_PUBLIC_PREFIX + "ui/"; public static final String NS_UI_FEATURE = NS_UI_PREFIX + "feature"; - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/GuiFeature.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/GuiFeature.java index dd5278976d3..d65829c3cf6 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/GuiFeature.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/GuiFeature.java @@ -27,7 +27,7 @@ public enum GuiFeature { ORGTREE_EXPAND_ALL("orgTreeExpandAll"), ORGTREE_COLLAPSE_ALL("orgTreeCollapseAll"); - + private String uri; private GuiFeature(String suffix) { @@ -37,5 +37,5 @@ private GuiFeature(String suffix) { public String getUri() { return uri; } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/GuiStyleConstants.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/GuiStyleConstants.java index 597da4ea166..066d8f70c19 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/GuiStyleConstants.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/GuiStyleConstants.java @@ -20,44 +20,44 @@ * */ public class GuiStyleConstants { - + public static final String CLASS_BOX = "box"; public static final String CLASS_BOX_DEFAULT = "box-default"; - + public static final String CLASS_OBJECT_USER_ICON = "fa fa-user"; public static final String CLASS_OBJECT_USER_ICON_COLORED = CLASS_OBJECT_USER_ICON + " object-user-color"; public static final String CLASS_OBJECT_USER_BOX_CSS_CLASSES = "object-user-box"; public static final String CLASS_OBJECT_USER_BOX_THIN_CSS_CLASSES = "object-user-box-thin"; - + public static final String CLASS_OBJECT_ROLE_ICON = "fa fa-street-view"; public static final String CLASS_OBJECT_ROLE_BG = "object-role-bg"; public static final String CLASS_DISABLED_OBJECT_ROLE_BG = "object-disabled-bg"; public static final String CLASS_OBJECT_ROLE_ICON_COLORED = CLASS_OBJECT_ROLE_ICON + " object-role-color"; public static final String CLASS_OBJECT_ROLE_BOX_CSS_CLASSES = "object-role-box"; public static final String CLASS_OBJECT_ROLE_BOX_THIN_CSS_CLASSES = "object-role-box-thin"; - + public static final String CLASS_OBJECT_ORG_ICON = "fa fa-building"; public static final String CLASS_OBJECT_ORG_BG = "object-org-bg"; public static final String CLASS_OBJECT_ORG_ICON_COLORED = CLASS_OBJECT_ORG_ICON + " object-org-color"; public static final String CLASS_OBJECT_ORG_BOX_CSS_CLASSES = "object-org-box"; public static final String CLASS_OBJECT_ORG_BOX_THIN_CSS_CLASSES = "object-org-box-thin"; - + public static final String CLASS_OBJECT_SERVICE_ICON = "fa fa-cloud"; public static final String CLASS_OBJECT_SERVICE_BG = "object-service-bg"; public static final String CLASS_OBJECT_SERVICE_ICON_COLORED = CLASS_OBJECT_SERVICE_ICON + " object-service-color"; public static final String CLASS_OBJECT_SERVICE_BOX_CSS_CLASSES = "object-service-box"; public static final String CLASS_OBJECT_SERVICE_BOX_THIN_CSS_CLASSES = "object-service-box-thin"; - + public static final String CLASS_OBJECT_RESOURCE_ICON = "fa fa-database"; public static final String CLASS_OBJECT_RESOURCE_ICON_COLORED = CLASS_OBJECT_RESOURCE_ICON + " object-resource-color"; public static final String CLASS_OBJECT_RESOURCE_BOX_CSS_CLASSES = "object-resource-box"; public static final String CLASS_OBJECT_RESOURCE_BOX_THIN_CSS_CLASSES = "object-resource-box-thin"; - + public static final String CLASS_OBJECT_SHADOW_ICON = "fa fa-eye"; public static final String CLASS_OBJECT_SHADOW_ICON_COLORED = CLASS_OBJECT_RESOURCE_ICON + " object-shadow-color"; public static final String CLASS_OBJECT_SHADOW_BOX_CSS_CLASSES = "object-shadow-box"; public static final String CLASS_OBJECT_SHADOW_BOX_THIN_CSS_CLASSES = "object-shadow-box-thin"; - + public static final String CLASS_OBJECT_TASK_ICON = "fa fa-tasks"; public static final String CLASS_OBJECT_TASK_ICON_COLORED = CLASS_OBJECT_TASK_ICON + " object-task-color"; public static final String CLASS_OBJECT_TASK_BOX_CSS_CLASSES = "object-task-box"; @@ -85,7 +85,7 @@ public class GuiStyleConstants { public static final String CLASS_ICON_STYLE_UP = "icon-style-up"; public static final String CLASS_ICON_STYLE_DOWN = "icon-style-down"; public static final String CLASS_ICON_STYLE_BROKEN = "icon-style-broken"; - + public static final String CLASS_SHADOW_ICON_ACCOUNT = "fa fa-male"; public static final String CLASS_SHADOW_ICON_ENTITLEMENT = "fa fa-group"; public static final String CLASS_SHADOW_ICON_GENERIC = "fa fa-circle-o"; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/PredefinedDashboardWidgetId.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/PredefinedDashboardWidgetId.java index 05d0a27a383..9d3ef5ba999 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/PredefinedDashboardWidgetId.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/PredefinedDashboardWidgetId.java @@ -31,10 +31,10 @@ public enum PredefinedDashboardWidgetId { MY_REQUESTS("myRequests"), MY_ASSIGNMENTS("myAssignments"), MY_ACCOUNTS("myAccounts"); - + private final QName qname; private final String uri; - + private PredefinedDashboardWidgetId(String localPart) { this.qname = new QName(ComponentConstants.NS_DASHBOARD_WIDGET, localPart); this.uri = QNameUtil.qNameToUri(qname); @@ -47,5 +47,5 @@ public QName getQname() { public String getUri() { return uri; } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/BasePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/BasePanel.java index 44f26a47de4..b14a739f618 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/BasePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/BasePanel.java @@ -31,9 +31,9 @@ * Base class for most midPoint GUI panels. It has a constructor and * utility methods for convenient handling of the model. It also has * other utility methods often used in reusable components. - * + * * Almost all reusable components should extend this class. - * + * * @author lazyman * @author semancik */ @@ -101,7 +101,7 @@ public StringResourceModel createStringResource(Enum e, String prefix, String nu return createStringResource(sb.toString()); } - + public PageBase getPageBase() { return WebComponentUtil.getPageBase(this); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/DisplayNamePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/DisplayNamePanel.java index 78f8435dc30..2173ce84645 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/DisplayNamePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/DisplayNamePanel.java @@ -14,19 +14,19 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; public class DisplayNamePanel extends BasePanel{ - + private static final long serialVersionUID = 1L; - + private final static String ID_DESCRIPTION = "description"; private final static String ID_TYPE_IMAGE = "typeImage"; private final static String ID_ASSIGNMENT_NAME = "assignmentName"; public DisplayNamePanel(String id, IModel model) { super(id, model); - + initLayout(); } - + private void initLayout() { WebMarkupContainer typeImage = new WebMarkupContainer(ID_TYPE_IMAGE); typeImage.setOutputMarkupId(true); @@ -40,35 +40,35 @@ private void initLayout() { add(name); add(new Label(ID_DESCRIPTION, new PropertyModel(getModel(), ObjectType.F_DESCRIPTION.getLocalPart()))); - + } - + private String createImageModel() { if (ObjectType.class.isAssignableFrom(getModelObject().getClass())) { return WebComponentUtil.createDefaultIcon((ObjectType) getModelObject()); - } - + } + return WebComponentUtil.createDefaultColoredIcon(getModelObject().asPrismContainerValue().getComplexTypeDefinition().getTypeName()); - + } - + private IModel getAdditionalNameLabelStyleClass() { return Model.of("text-bold"); } - + private IModel createHeaderModel() { if (ObjectType.class.isAssignableFrom(getModelObject().getClass())) { return Model.of(WebComponentUtil.getEffectiveName((ObjectType) getModelObject(), AbstractRoleType.F_DISPLAY_NAME)); - } + } PrismProperty name = getModelObject().asPrismContainerValue().findProperty(ObjectType.F_NAME); if (name == null || name.isEmpty()) { return Model.of(""); } return Model.of(name.getRealValue()); } - - - - + + + + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/MainObjectListPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/MainObjectListPanel.java index aba7f4ce833..b6aae3d8db4 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/MainObjectListPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/MainObjectListPanel.java @@ -218,22 +218,22 @@ public boolean isVisible(){ } }); add(importObject); - + CsvDownloadButtonPanel exportDataLink = new CsvDownloadButtonPanel(ID_EXPORT_DATA) { - + private static final long serialVersionUID = 1L; @Override protected DataTable getDataTable() { return mainObjectListPanel.getTable().getDataTable(); } - + @Override protected String getFilename() { return mainObjectListPanel.getType().getSimpleName() + "_" + mainObjectListPanel.createStringResource("MainObjectListPanel.exportFileName").getString(); } - + }; exportDataLink.add(new VisibleEnableBehaviour(){ private static final long serialVersionUID = 1L; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/ObjectListPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/ObjectListPanel.java index 415330dc66d..0a3f06ad00f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/ObjectListPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/ObjectListPanel.java @@ -75,7 +75,7 @@ public abstract class ObjectListPanel extends BasePanel private Collection> options; private boolean multiselect; - + private TableId tableId; protected List selectedObjects = null; @@ -151,7 +151,7 @@ private void initLayout() { mainForm.add(table); } - + private LoadableModel initSearchModel(){ return new LoadableModel(false) { @@ -174,11 +174,11 @@ public Search load() { } }; } - + protected Search createSearch() { return SearchFactory.createSearch(type, parentPage); } - + private BoxedTablePanel> createTable() { List, String>> columns; @@ -189,8 +189,8 @@ private BoxedTablePanel> createTable() { } BaseSortableDataProvider> provider = initProvider(); - - + + BoxedTablePanel> table = new BoxedTablePanel>(ID_TABLE, provider, columns, tableId, tableId == null ? 10 : parentPage.getSessionStorage().getUserProfile().getPagingSize(tableId)) { private static final long serialVersionUID = 1L; @@ -216,7 +216,7 @@ protected WebMarkupContainer createButtonToolbar(String id) { table.setOutputMarkupId(true); String storageKey = getStorageKey(); if (StringUtils.isNotEmpty(storageKey)) { - PageStorage storage = getPageStorage(storageKey); + PageStorage storage = getPageStorage(storageKey); if (storage != null) { table.setCurrentPage(storage.getPaging()); } @@ -224,7 +224,7 @@ protected WebMarkupContainer createButtonToolbar(String id) { return table; } - + protected List, String>> initCustomColumns() { LOGGER.trace("Start to init custom columns for table of type {}", type); List, String>> columns = new ArrayList, String>>(); @@ -324,10 +324,10 @@ public SelectableBean createDataObjectWrapper(O obj) { } return bean; } - + @Override protected List createObjectOrderings(SortParam sortParam) { - List customOrdering = createCustomOrdering(sortParam); + List customOrdering = createCustomOrdering(sortParam); if (customOrdering != null) { return customOrdering; } @@ -346,14 +346,14 @@ protected List createObjectOrderings(SortParam sortParam provider.setOptions(options); } provider.setQuery(getQuery()); - + return provider; } - + protected List createCustomOrdering(SortParam sortParam) { return null; } - + private SearchFormPanel initSearch(String headerId) { SearchFormPanel searchPanel = new SearchFormPanel(headerId, searchModel) { @@ -384,15 +384,15 @@ public void setAdditionalBoxCssClasses(String boxCssClasses) { protected WebMarkupContainer createTableButtonToolbar(String id) { return null; } - + private String getStorageKey() { String storageKey = WebComponentUtil.getStorageKeyForPage(parentPage.getClass()); if (storageKey == null) { storageKey = WebComponentUtil.getStorageKeyForTableId(tableId); } - + return storageKey; - + } private PageStorage getPageStorage(String storageKey){ @@ -416,8 +416,8 @@ protected BaseSortableDataProvider> getDataProvider() { protected BoxedTablePanel> getTable() { return (BoxedTablePanel>) get(createComponentPath(ID_MAIN_FORM, ID_TABLE)); } - - + + @SuppressWarnings("deprecation") private void searchPerformed(ObjectQuery query, AjaxRequestTarget target) { 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 e8d2ef6b752..6dafb8edf17 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 @@ -43,7 +43,7 @@ public abstract class PopupObjectListPanel extends ObjectL */ public PopupObjectListPanel(String id, Class defaultType, boolean multiselect, PageBase parentPage) { super(id, defaultType, multiselect, parentPage); - + } public PopupObjectListPanel(String id, Class defaultType, Collection> options, @@ -57,13 +57,13 @@ protected IColumn, String> createCheckboxColumn() { if (isMultiselect()) { return new CheckBoxHeaderColumn>() { private static final long serialVersionUID = 1L; - + @Override protected void onUpdateRow(AjaxRequestTarget target, DataTable table, IModel> rowModel) { super.onUpdateRow(target, table, rowModel); onUpdateCheckbox(target); }; - + @Override protected void onUpdateHeader(AjaxRequestTarget target, boolean selected, DataTable table) { super.onUpdateHeader(target, selected, table); @@ -122,18 +122,18 @@ public void onClick(AjaxRequestTarget target, IModel> rowModel protected List, String>> createColumns() { return ColumnUtils.getDefaultColumns(getType()); } - + protected void onSelectPerformed(AjaxRequestTarget target, O object){ - + } - + @Override protected List createInlineMenu() { return null; } - + protected void onUpdateCheckbox(AjaxRequestTarget target){ - + } } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/TypedAssignablePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/TypedAssignablePanel.java index 43bc39526c2..bc1758a5402 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/TypedAssignablePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/TypedAssignablePanel.java @@ -62,13 +62,13 @@ public class TypedAssignablePanel extends BasePanel implements Popupable{ private static final long serialVersionUID = 1L; - + private static final String ID_TYPE = "type"; private static final String ID_RELATION = "relation"; private static final String ID_ROLE_TABLE = "roleTable"; private static final String ID_RESOURCE_TABLE = "resourceTable"; private static final String ID_ORG_TABLE = "orgTable"; - + private static final String ID_SELECTED_ROLES = "rolesSelected"; private static final String ID_SELECTED_RESOURCES = "resourcesSelected"; private static final String ID_SELECTED_ORGS = "orgSelected"; @@ -77,7 +77,7 @@ public class TypedAssignablePanel extends BasePanel imp private static final String ID_COUNT_CONTAINER = "countContainer"; private static final String ID_SERVICE_TABLE = "serviceTable"; private static final String ID_SELECTED_SERVICES = "servicesSelected"; - + private static final String ID_BUTTON_ASSIGN = "assignButton"; private static final String DOT_CLASS = TypedAssignablePanel.class.getName(); @@ -103,7 +103,7 @@ protected QName load() { initLayout(type, multiselect); } - + private void initLayout(Class type, final boolean multiselect) { initAssignmentParametersPanel(); @@ -119,13 +119,13 @@ private void initLayout(Class type, final boolean multiselect) { tablesContainer.add(listOrgPanel); PopupObjectListPanel listServicePanel = createObjectListPanel(ID_SERVICE_TABLE, ID_SELECTED_SERVICES, ServiceType.COMPLEX_TYPE); tablesContainer.add(listServicePanel); - - - + + + WebMarkupContainer countContainer = createCountContainer(); add(countContainer); - - + + AjaxButton addButton = new AjaxButton(ID_BUTTON_ASSIGN, createStringResource("userBrowserDialog.button.addButton")) { @@ -140,9 +140,9 @@ public void onClick(AjaxRequestTarget target) { TypedAssignablePanel.this.addPerformed(target, selected, getSelectedRelation()); } }; - + addButton.add(new VisibleEnableBehaviour() { - + private static final long serialVersionUID = 1L; @Override @@ -153,7 +153,7 @@ public boolean isVisible() { add(addButton); } - + protected void initAssignmentParametersPanel(){ DropDownChoicePanel typeSelect = new DropDownChoicePanel<>(ID_TYPE, typeModel, Model.ofList(WebComponentUtil.createAssignableTypesList()), new QNameChoiceRenderer()); typeSelect.getBaseFormComponent().add(new OnChangeAjaxBehavior() { @@ -169,10 +169,10 @@ protected void onUpdate(AjaxRequestTarget target) { typeSelect.setOutputMarkupId(true); add(typeSelect); - + DropDownChoicePanel relationSelector = WebComponentUtil.createEnumPanel(RelationTypes.class, ID_RELATION, WebComponentUtil.createReadonlyModelFromEnum(RelationTypes.class), Model.of(RelationTypes.MEMBER), TypedAssignablePanel.this, false); - relationSelector.getBaseFormComponent().add(new EmptyOnChangeAjaxFormUpdatingBehavior()); + relationSelector.getBaseFormComponent().add(new EmptyOnChangeAjaxFormUpdatingBehavior()); relationSelector.add(new VisibleEnableBehaviour(){ private static final long serialVersionUID = 1L; @@ -180,32 +180,32 @@ protected void onUpdate(AjaxRequestTarget target) { public boolean isEnabled(){ return !ResourceType.COMPLEX_TYPE.equals(typeModel.getObject()); } - + @Override public boolean isVisible() { return TypedAssignablePanel.this.isRelationPanelVisible(); } - + }); relationSelector.setOutputMarkupId(true); relationSelector.setOutputMarkupPlaceholderTag(true); add(relationSelector); - + } private List getSelectedData(String id){ return ((ObjectListPanel) get(createComponentPath(ID_TABLES_CONTAINER, id))).getSelectedObjects(); } - + private QName getSelectedRelation(){ DropDownChoicePanel relationPanel = (DropDownChoicePanel) get(ID_RELATION); RelationTypes relation = relationPanel.getModel().getObject(); if (relation == null) { - return SchemaConstants.ORG_DEFAULT; + return SchemaConstants.ORG_DEFAULT; } return relation.getRelation(); } - + private WebMarkupContainer createCountContainer(){ WebMarkupContainer countContainer = new WebMarkupContainer(ID_COUNT_CONTAINER); countContainer.setOutputMarkupId(true); @@ -215,17 +215,17 @@ private WebMarkupContainer createCountContainer(){ countContainer.add(createCountLabel(ID_SELECTED_SERVICES, (PopupObjectListPanel)get(createComponentPath(ID_TABLES_CONTAINER, ID_SERVICE_TABLE)))); return countContainer; } - + private Label createCountLabel(String id, ObjectListPanel panel){ Label label = new Label(id, panel.getSelectedObjects().size()); label.setOutputMarkupId(true); return label; } - + protected void onClick(AjaxRequestTarget target, T focus) { getPageBase().hideMainPopup(target); } - + private void refreshCounts(AjaxRequestTarget target) { addOrReplace(createCountContainer()); target.add(get(ID_COUNT_CONTAINER)); @@ -233,7 +233,7 @@ private void refreshCounts(AjaxRequestTarget target) { private PopupObjectListPanel createObjectListPanel(String id, final String countId, final QName type) { PopupObjectListPanel listPanel = new PopupObjectListPanel(id, qnameToCompileTimeClass(type), true, getPageBase()) { - + private static final long serialVersionUID = 1L; @@ -270,7 +270,7 @@ protected ObjectQuery addFilterToContentQuery(ObjectQuery query) { } return query; } - + }; listPanel.setOutputMarkupId(true); @@ -284,7 +284,7 @@ public boolean isVisible() { }); return listPanel; } - + protected boolean isRelationPanelVisible() { return true; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/autocomplete/AutoCompleteItemDefinitionPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/autocomplete/AutoCompleteItemDefinitionPanel.java index 8f0fc9b2337..75dc48442e0 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/autocomplete/AutoCompleteItemDefinitionPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/autocomplete/AutoCompleteItemDefinitionPanel.java @@ -23,15 +23,15 @@ public class AutoCompleteItemDefinitionPanel extends AbstractAutoCompletePanel { - + private static final long serialVersionUID = 1L; private static final String ID_INPUT = "input"; - + public AutoCompleteItemDefinitionPanel(String id, final IModel> model) { super(id); initLayout(model); } - + private void initLayout(final IModel> model) { final Model itemDefinitionAsStringModel = new Model(null); AutoCompleteTextField input = new AutoCompleteTextField( @@ -46,17 +46,17 @@ protected Iterator getChoices(String input) { defsAsString.add(def.getName().getLocalPart()); } return defsAsString.iterator(); - + } - + @Override protected void onConfigure() { itemDefinitionAsStringModel.setObject(null); } - - + + }; - + input.add(new OnChangeAjaxBehavior() { private static final long serialVersionUID = 1L; @@ -71,14 +71,14 @@ protected void onUpdate(AjaxRequestTarget target) { } } }); - + add(input); } - + protected Map> listChoices(String input){ return new HashMap>(); } - + @Override public FormComponent getBaseFormComponent() { return (FormComponent) get(ID_INPUT); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/autocomplete/AutoCompleteItemDefinitionRenderer.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/autocomplete/AutoCompleteItemDefinitionRenderer.java index 4c82d6f677e..1c43194231b 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/autocomplete/AutoCompleteItemDefinitionRenderer.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/autocomplete/AutoCompleteItemDefinitionRenderer.java @@ -7,21 +7,21 @@ import com.evolveum.midpoint.prism.ItemDefinition; public class AutoCompleteItemDefinitionRenderer extends AbstractAutoCompleteRenderer>{ - + private static final long serialVersionUID = 1L; @Override protected String getTextValue(ItemDefinition object) { return object.getName().getLocalPart(); } - + @Override protected void renderChoice(ItemDefinition object, Response response, String criteria) { String textValue = getTextValue(object); textValue = Strings.escapeMarkup(textValue).toString(); response.write(textValue); - + } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/autocomplete/AutoCompleteQNamePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/autocomplete/AutoCompleteQNamePanel.java index 1f0480dceb8..d9624dc8369 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/autocomplete/AutoCompleteQNamePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/autocomplete/AutoCompleteQNamePanel.java @@ -37,16 +37,16 @@ /** * Autocomplete field for QNames. - * + * * For now it assumes that local part of the QNames will be unique (e.g. for object classes) - * + * * TODO: prefixes, URL formatting, etc. - * + * * @author semancik * */ public abstract class AutoCompleteQNamePanel extends AbstractAutoCompletePanel { private static final long serialVersionUID = 1L; - + private static final String ID_INPUT = "input"; private Map choiceMap = null; @@ -57,7 +57,7 @@ public AutoCompleteQNamePanel(String id, final IModel model) { private void initLayout(final IModel model) { setOutputMarkupId(true); - + AutoCompleteSettings autoCompleteSettings = createAutoCompleteSettings(); final IModel stringModel = new Model() { @@ -66,9 +66,9 @@ public void setObject(String object) { super.setObject(object); model.setObject(convertToQname(object)); } - + }; - + // The inner autocomplete field is always String. Non-string auto-complete fields are problematic final AutoCompleteTextField input = new AutoCompleteTextField(ID_INPUT, stringModel, String.class, autoCompleteSettings) { private static final long serialVersionUID = 1L; @@ -77,8 +77,8 @@ public void setObject(String object) { protected Iterator getChoices(String input) { return getIterator(input); } - - + + }; input.add(new OnChangeAjaxBehavior() { private static final long serialVersionUID = 1L; @@ -108,8 +108,8 @@ protected void onUpdate(AjaxRequestTarget target) { }); add(input); } - - + + private Iterator getIterator(String input) { Map choiceMap = getChoiceMap(); @@ -122,7 +122,7 @@ private Iterator getIterator(String input) { } return selected.iterator(); } - + private Map getChoiceMap() { if (choiceMap == null) { Collection choices = loadChoices(); @@ -134,15 +134,15 @@ private Map getChoiceMap() { } return choiceMap; } - + private QName convertToQname(String input) { Map choiceMap = getChoiceMap(); return choiceMap.get(input); } - + public abstract Collection loadChoices(); - + protected void onChange(AjaxRequestTarget target) { // Nothing to do by default. For use in subclasses } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/autocomplete/AutoCompleteTextPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/autocomplete/AutoCompleteTextPanel.java index dcc843d2e4e..a1983316936 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/autocomplete/AutoCompleteTextPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/autocomplete/AutoCompleteTextPanel.java @@ -33,22 +33,22 @@ /** * Autocomplete field for Strings. - * + * * TODO: may need some work to properly support non-string values. - * + * * @author shood * @author semancik * */ public abstract class AutoCompleteTextPanel extends AbstractAutoCompletePanel { private static final long serialVersionUID = 1L; - + private static final String ID_INPUT = "input"; public AutoCompleteTextPanel(String id, final IModel model, Class type) { super(id); AutoCompleteSettings autoCompleteSettings = createAutoCompleteSettings(); - + // this has to be copied because the AutoCompleteTextField dies if renderer=null final AutoCompleteTextField input = new AutoCompleteTextField(ID_INPUT, model, type, autoCompleteSettings) { private static final long serialVersionUID = 1L; @@ -64,12 +64,12 @@ protected void updateAjaxAttributes(AjaxRequestAttributes attributes){ attributes.setThrottlingSettings(new ThrottlingSettings(Duration.ONE_SECOND, true)); } }; - + input.setType(type); if (model instanceof LookupPropertyModel) { input.add(new OnChangeAjaxBehavior() { private static final long serialVersionUID = 1L; - + @Override protected void onUpdate(AjaxRequestTarget target) { checkInputValue(input, target, (LookupPropertyModel)model); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/button/CsvDownloadButtonPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/button/CsvDownloadButtonPanel.java index 4f2ccd6f8e7..a70291e3fad 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/button/CsvDownloadButtonPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/button/CsvDownloadButtonPanel.java @@ -32,7 +32,7 @@ public abstract class CsvDownloadButtonPanel extends BasePanel { private static final String OPERATION_GET_EXPORT_SIZE_LIMIT = DOT_CLASS + "getDefaultExportSizeLimit"; private static final String ID_EXPORT_DATA = "exportData"; - + public CsvDownloadButtonPanel(String id) { super(id); initLayout(); @@ -43,7 +43,7 @@ public CsvDownloadButtonPanel(String id) { private void initLayout() { CSVDataExporter csvDataExporter = new CSVDataExporter() { private static final long serialVersionUID = 1L; - + @Override public void exportData(IDataProvider dataProvider, List> columns, OutputStream outputStream) throws IOException { @@ -63,19 +63,19 @@ public void exportData(IDataProvider dataProvider, List("fa fa-download"), createStringResource("CsvDownloadButtonPanel.export")) { @@ -113,9 +113,9 @@ public void yesPerformed(AjaxRequestTarget target) { }; add(exportDataLink); } - + protected abstract DataTable getDataTable(); - + protected abstract String getFilename(); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/button/DropdownButtonDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/button/DropdownButtonDto.java index ef638b05378..3e9970f9fb5 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/button/DropdownButtonDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/button/DropdownButtonDto.java @@ -24,13 +24,13 @@ public class DropdownButtonDto implements Serializable, InlineMenuable{ /** - * + * */ private static final long serialVersionUID = 1L; private String info; private String icon; private String label; - + private List items; public DropdownButtonDto(String info, String icon, String label, List items) { @@ -63,7 +63,7 @@ public String getLabel() { public void setLabel(String label) { this.label = label; } - + @Override public List getMenuItems() { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/button/DropdownButtonPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/button/DropdownButtonPanel.java index 843320b5079..e3bb7390f22 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/button/DropdownButtonPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/button/DropdownButtonPanel.java @@ -34,30 +34,30 @@ public class DropdownButtonPanel extends BasePanel{ private static final String ID_INFO = "info"; private static final String ID_ICON = "icon"; private static final String ID_LABEL = "label"; - + private static String ID_MENU_ITEM = "menuItem"; private static String ID_MENU_ITEM_BODY = "menuItemBody"; - + public DropdownButtonPanel(String id, DropdownButtonDto model) { super(id); initLayout(model); } - + private void initLayout(DropdownButtonDto model){ - - + + Label info = new Label(ID_INFO, model.getInfo()); add(info); - + Label label = new Label(ID_LABEL, model.getLabel()); add(label); - + WebMarkupContainer icon = new WebMarkupContainer(ID_ICON); icon.add(AttributeModifier.append("class", model.getIcon())); add(icon); - - + + ListView li = new ListView(ID_MENU_ITEM, new Model((Serializable) model.getMenuItems())) { @Override @@ -65,11 +65,11 @@ protected void populateItem(ListItem item) { initMenuItem(item); } }; - + add(li); - + } - + private void initMenuItem(ListItem menuItem) { final InlineMenuItem item = menuItem.getModelObject(); @@ -77,6 +77,6 @@ private void initMenuItem(ListItem menuItem) { menuItemBody.setRenderBodyOnly(true); menuItem.add(menuItemBody); } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/captcha/CaptchaPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/captcha/CaptchaPanel.java index 293a36a1a38..5f0b96a7e77 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/captcha/CaptchaPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/captcha/CaptchaPanel.java @@ -77,14 +77,14 @@ protected byte[] render() { getChallengeIdModel().setObject(randomText); return super.render(); } - + }; } - + public void invalidateCaptcha() { captchaImageResource.invalidate(); } - + static int randomInt(int min, int max) { return (int)(Math.random() * (max - min) + min); @@ -92,24 +92,24 @@ static int randomInt(int min, int max) static String randomString() { - return new Integer(randomInt(1000, 9999)).toString(); + return new Integer(randomInt(1000, 9999)).toString(); // for (int i = 0; i< length; i++){ -// +// // } -// +// // int num = randomInt(min, max); // byte b[] = new byte[num]; // for (int i = 0; i < num; i++) // b[i] = (byte)randomInt('a', 'z'); // return new String(b); } - + public String getCaptchaText() { return captchaText; } - + public String getRandomText() { return captchaImageResource.getChallengeId(); } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/delta/ObjectDeltaOperationPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/delta/ObjectDeltaOperationPanel.java index d81ddf2f637..7072ae2698d 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/delta/ObjectDeltaOperationPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/delta/ObjectDeltaOperationPanel.java @@ -67,14 +67,14 @@ private void initLayout() { // ObjectDeltaType od = getModel().getObjectDelta(); WebMarkupContainer objectDeltaOperationMarkup = new WebMarkupContainer(ID_OBJECT_DELTA_OPERATION_MARKUP); objectDeltaOperationMarkup.setOutputMarkupId(true); - + objectDeltaOperationMarkup.add(AttributeModifier.append("class", new AbstractReadOnlyModel() { - + @Override public String getObject() { return getBoxCssClass(); } - + })); add(objectDeltaOperationMarkup); @@ -121,20 +121,20 @@ public void headerOnClickPerformed(AjaxRequestTarget target, IModel mo objectDeltaOperationMarkup.add(deltaPanel); } - + private String getBoxCssClass() { if (getModel().getObject() == null) { return " box-primary"; } - + if (getModel().getObject().getExecutionResult() == null) { return " box-primary"; } - + if (getModel().getObject().getExecutionResult().getStatus() == null) { return " box-primary"; } - + OperationResultStatusType status = getModel().getObject().getExecutionResult().getStatus(); switch (status) { case PARTIAL_ERROR : @@ -145,10 +145,10 @@ private String getBoxCssClass() { case IN_PROGRESS : return " box-primary"; case NOT_APPLICABLE : return " box-primary"; case SUCCESS : return " box-success"; - + } return " box-primary"; - + } private SceneDto loadSceneForDelta() throws SchemaException, ExpressionEvaluationException { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/objecttypeselect/ObjectTypeSelectPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/objecttypeselect/ObjectTypeSelectPanel.java index cdfc9645949..f871d462343 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/objecttypeselect/ObjectTypeSelectPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/objecttypeselect/ObjectTypeSelectPanel.java @@ -37,11 +37,11 @@ */ public class ObjectTypeSelectPanel extends BasePanel { private static final long serialVersionUID = 1L; - + private static final String ID_SELECT = "select"; - + private DropDownChoice select; - + public ObjectTypeSelectPanel(String id, IModel model, Class superclass) { super(id, model); initLayout(model, superclass); @@ -67,10 +67,10 @@ public List getObject() { } }, new QNameChoiceRenderer()); select.setNullValid(true); - + add(select); } - + public void addInput(Behavior behavior) { select.add(behavior); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/package-info.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/package-info.java index d7e01c49cbd..b911820937f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/package-info.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/package-info.java @@ -15,9 +15,9 @@ */ /** * Package for reusable and stable GUI Wicket Components. - * + * * It is expected that each component will be placed in its own sub-package. - * + * * @author Radovan Semancik */ package com.evolveum.midpoint.gui.api.component; \ No newline at end of file diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/password/PasswordPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/password/PasswordPanel.java index 43cd9d185ac..a865404eaf5 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/password/PasswordPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/password/PasswordPanel.java @@ -64,9 +64,9 @@ public class PasswordPanel extends InputPanel { private static final String ID_INPUT_CONTAINER = "inputContainer"; private static final String ID_PASSWORD_ONE = "password1"; private static final String ID_PASSWORD_TWO = "password2"; - + private static final Trace LOGGER = TraceManager.getTrace(PasswordPanel.class); - + private boolean passwordInputVisble; public PasswordPanel(String id, IModel model) { @@ -78,7 +78,7 @@ public PasswordPanel(String id, IModel model, boolean isRea this.passwordInputVisble = model.getObject() == null; initLayout(model, isReadOnly); } - + public PasswordPanel(String id, IModel model, boolean isReadOnly, boolean isInputVisible) { super(id); this.passwordInputVisble = isInputVisible; @@ -95,7 +95,7 @@ public boolean isVisible() { }; inputContainer.setOutputMarkupId(true); add(inputContainer); - + final PasswordTextField password1 = new PasswordTextField(ID_PASSWORD_ONE, new PasswordModel(model)); password1.setRequired(false); password1.setResetPassword(false); @@ -109,7 +109,7 @@ public boolean isVisible() { password2.setOutputMarkupId(true); password2.add(new EmptyOnBlurAjaxFormUpdatingBehaviour()); inputContainer.add(password2); - + password1.add(new AjaxFormComponentUpdatingBehavior("change") { @Override protected void onUpdate(AjaxRequestTarget target) { @@ -121,7 +121,7 @@ protected void onUpdate(AjaxRequestTarget target) { } }); password2.add(new PasswordValidator(password1, password2)); - + final WebMarkupContainer linkContainer = new WebMarkupContainer(ID_LINK_CONTAINER) { @Override public boolean isVisible() { @@ -131,10 +131,10 @@ public boolean isVisible() { inputContainer.setOutputMarkupId(true); linkContainer.setOutputMarkupId(true); add(linkContainer); - + final Label passwordSetLabel = new Label(ID_PASSWORD_SET, new ResourceModel("passwordPanel.passwordSet")); linkContainer.add(passwordSetLabel); - + final Label passwordRemoveLabel = new Label(ID_PASSWORD_REMOVE, new ResourceModel("passwordPanel.passwordRemoveLabel")); passwordRemoveLabel.setVisible(false); linkContainer.add(passwordRemoveLabel); @@ -170,7 +170,7 @@ public void onClick(AjaxRequestTarget target) { }; removePassword.add(new VisibleEnableBehaviour() { - + @Override public boolean isVisible() { PageBase pageBase = (PageBase)getPage(); @@ -192,7 +192,7 @@ public boolean isVisible() { removeButtonContainer.add(removePassword); add(removeButtonContainer); } - + private void onLinkClick(AjaxRequestTarget target) { passwordInputVisble = true; target.add(this); @@ -239,7 +239,7 @@ public void validate(IValidatable validatable) { if (StringUtils.isEmpty(s1) && StringUtils.isEmpty(s2)) { return; } - + boolean equal = s1 != null ? s1.equals(s2) : s2 == null; if (!equal) { validatable = p1.newValidatable(); @@ -249,7 +249,7 @@ public void validate(IValidatable validatable) { } } } - + private static class EmptyOnBlurAjaxFormUpdatingBehaviour extends AjaxFormComponentUpdatingBehavior { public EmptyOnBlurAjaxFormUpdatingBehaviour() { @@ -260,15 +260,15 @@ public EmptyOnBlurAjaxFormUpdatingBehaviour() { protected void onUpdate(AjaxRequestTarget target) { } } - + private class PasswordModel implements IModel { IModel psModel; - + PasswordModel(IModel psModel) { this.psModel = psModel; } - + @Override public void detach() { // Nothing to do @@ -294,6 +294,6 @@ public void setObject(String object) { psModel.getObject().setClearValue(object); } } - + } } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/path/ItemPathDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/path/ItemPathDto.java index 0890343f740..da485479712 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/path/ItemPathDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/path/ItemPathDto.java @@ -11,36 +11,36 @@ public class ItemPathDto implements Serializable{ private static final long serialVersionUID = 1L; private QName objectType; - + private ItemPathDto parentPath; - + private ItemDefinition itemDef; - + private ItemPath path; - + public ItemPathDto() { // TODO Auto-generated constructor stub } - + public ItemPathDto(ItemPathDto parentPath) { this.parentPath = parentPath; this.path = parentPath.toItemPath(); // this.parent = parentPath.toItemPath(); } - - + + public QName getObjectType() { return objectType; } - + public void setObjectType(QName objectType) { this.objectType = objectType; } - + public ItemDefinition getItemDef() { return itemDef; } - + public void setItemDef(ItemDefinition itemDef) { if (parentPath == null) { this.path = new ItemPath(itemDef.getName()); @@ -49,15 +49,15 @@ public void setItemDef(ItemDefinition itemDef) { } this.itemDef = itemDef; } - + public ItemPathDto getParentPath() { return parentPath; } - + public void setParentPath(ItemPathDto parentPath) { this.parentPath = parentPath; } - + public ItemPath toItemPath() { if (parentPath == null) { if (itemDef == null) { @@ -71,9 +71,9 @@ public ItemPath toItemPath() { this.path = parentPath.toItemPath().append(itemDef.getName()); } return path; - + } - - - + + + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/path/ItemPathPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/path/ItemPathPanel.java index 2e723759093..98d40bf396f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/path/ItemPathPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/path/ItemPathPanel.java @@ -42,7 +42,7 @@ public ItemPathPanel(String id, IModel model, PageBase parent) { super(id, model); setParent(parent); - + initLayout(); @@ -56,7 +56,7 @@ public ItemPathPanel(String id, ItemPathDto model, PageBase parent) { private void initLayout() { ItemPathSegmentPanel itemDefPanel = new ItemPathSegmentPanel(ID_DEFINITION, new AbstractReadOnlyModel() { - + private static final long serialVersionUID = 1L; public ItemPathDto getObject() { return ItemPathPanel.this.getModelObject(); @@ -156,7 +156,7 @@ private void refreshItemPathPanel(ItemPathDto itemPathDto, boolean isAdd, AjaxRe if (isAdd && !pathSegmentPanel.validate()) { return; } - + if (!isAdd) { ItemPathDto newItem = itemPathDto; ItemPathDto currentItem = itemPathDto.getParentPath(); @@ -179,9 +179,9 @@ private void refreshItemPathPanel(ItemPathDto itemPathDto, boolean isAdd, AjaxRe // target.add(pathSegmentPanel); } - + private void refreshItemPath(ItemPathDto itemPathDto, AjaxRequestTarget target) { - + this.getModel().setObject(itemPathDto); target.add(this); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/path/ItemPathSegmentPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/path/ItemPathSegmentPanel.java index 8df293e26ae..b831e9e5700 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/path/ItemPathSegmentPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/path/ItemPathSegmentPanel.java @@ -33,7 +33,7 @@ public class ItemPathSegmentPanel extends BasePanel { public ItemPathSegmentPanel(String id, ItemPathDto model) { this(id, Model.of(model)); } - + public ItemPathSegmentPanel(String id, IModel model) { super(id, model); @@ -47,15 +47,15 @@ private void initLayout() { private static final long serialVersionUID = 1L; @Override public String getObject() { - + if (getModelObject().getParentPath() == null) { return null; } - + if (getModelObject().getParentPath().toItemPath() == null) { return null; } - + return getString("ItemPathSegmentPanel.itemToSearch", getModelObject().getParentPath().toItemPath().toString()); } }); @@ -122,7 +122,7 @@ public void refreshModel(ItemPathDto newModel) { protected Map>> getSchemaDefinitionMap() { return new HashMap<>(); } - + public boolean validate() { // AutoCompleteItemDefinitionPanel autocompletePanel = (AutoCompleteItemDefinitionPanel) get(ID_DEFINITION); // String current = (String) autocompletePanel.getBaseFormComponent().getModelObject(); @@ -132,7 +132,7 @@ public boolean validate() { // ( != // } return getModelObject().getItemDef() != null; - + // return autocompletePanel.getBaseFormComponent().getModelObject() != null; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/progressbar/ProgressbarPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/progressbar/ProgressbarPanel.java index 72dd4f89c24..ce1b52167c8 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/progressbar/ProgressbarPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/progressbar/ProgressbarPanel.java @@ -26,16 +26,16 @@ */ public class ProgressbarPanel extends Panel{ private static final long serialVersionUID = 1L; - + private static final String ID_PROGRESS_BAR = "progressBar"; public ProgressbarPanel(String id, IModel model) { super(id, model); initLayout(model); } - + private void initLayout(final IModel model){ - + WebMarkupContainer progressBar = new WebMarkupContainer(ID_PROGRESS_BAR); IModel styleAttributeModel = new Model(){ private static final long serialVersionUID = 1L; @@ -48,6 +48,6 @@ public String getObject() { progressBar.add(new AttributeModifier("style", styleAttributeModel)); add(progressBar); } - - + + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/result/OpResult.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/result/OpResult.java index 12d3ed38425..e6718097cda 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/result/OpResult.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/result/OpResult.java @@ -70,20 +70,20 @@ public class OpResult implements Serializable, Visitable { // we assume there is at most one background task created (TODO revisit this assumption) private String backgroundTaskOid; private Boolean backgroundTaskVisible; // available on root opResult only - + private boolean showMore; private boolean showError; - + private boolean alreadyShown; - + public boolean isAlreadyShown() { return alreadyShown; } - + public void setAlreadyShown(boolean alreadyShown) { this.alreadyShown = alreadyShown; } - + public static OpResult getOpResult(PageBase page, OperationResult result){ OpResult opResult = new OpResult(); Validate.notNull(result, "Operation result must not be null."); @@ -97,8 +97,8 @@ public static OpResult getOpResult(PageBase page, OperationResult result){ .setParameters(localizableMessage.getArgs()); opResult.message = stringResourceModel.getString(); } - } - + } + if (opResult.message == null) { opResult.message = result.getMessage(); } @@ -126,7 +126,7 @@ public static OpResult getOpResult(PageBase page, OperationResult result){ opResult.getParams().add(new Param(entry.getKey(), paramValue)); } } - + if(result.getContext() != null){ for (Map.Entry> entry : result.getContext().entrySet()) { String contextValue = null; @@ -197,19 +197,19 @@ public void determineBackgroundTaskVisibility(PageBase pageBase) { public boolean isShowMore() { return showMore; } - + public void setShowMore(boolean showMore) { this.showMore = showMore; } - + public boolean isShowError() { return showError; } - + public void setShowError(boolean showError) { this.showError = showError; } - + public List getSubresults() { if (subresults == null) { subresults = new ArrayList(); @@ -239,7 +239,7 @@ public List getParams() { } return params; } - + public List getContexts() { if (contexts == null) { contexts = new ArrayList(); @@ -254,7 +254,7 @@ public OperationResultStatus getStatus() { public int getCount() { return count; } - + public String getXml() { return xml; } @@ -275,15 +275,15 @@ public boolean isBackgroundTaskVisible() { @Override public void accept(Visitor visitor) { - + visitor.visit(this); - + for (OpResult result : this.getSubresults()){ result.accept(visitor); } - + } - + public void setShowMoreAll(final boolean show) { Visitor visitor = new Visitor() { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/result/OperationResultPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/result/OperationResultPanel.java index c00a3cf5c45..2e2e22b9010 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/result/OperationResultPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/result/OperationResultPanel.java @@ -98,7 +98,7 @@ private void initHeader(WebMarkupContainer box) { iconType.setOutputMarkupId(true); iconType.add(new AttributeAppender("class", new AbstractReadOnlyModel() { private static final long serialVersionUID = 1L; - + @Override public String getObject() { StringBuilder sb = new StringBuilder(); @@ -163,7 +163,7 @@ public void onClick(AjaxRequestTarget target) { }; backgroundTask.add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; - + @Override public boolean isVisible() { return getModelObject().getBackgroundTaskOid() != null @@ -182,7 +182,7 @@ public void onClick(AjaxRequestTarget target) { }; showAll.add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; - + @Override public boolean isVisible() { return !OperationResultPanel.this.getModelObject().isShowMore(); @@ -201,7 +201,7 @@ public void onClick(AjaxRequestTarget target) { }; hideAll.add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; - + @Override public boolean isVisible() { return OperationResultPanel.this.getModelObject().isShowMore(); @@ -295,7 +295,7 @@ public boolean isVisible() { operationPanel.setOutputMarkupId(true); operationPanel.add(new AttributeAppender("class", new LoadableModel() { private static final long serialVersionUID = 1L; - + @Override protected String load() { return getLabelCss(getModel()); @@ -448,7 +448,7 @@ public boolean isVisible() { ListView contexts = new ListView("contexts", createContextsModel(model)) { private static final long serialVersionUID = 1L; - + @Override protected void populateItem(ListItem item) { item.add(new Label("contextName", new PropertyModel(item.getModel(), "name"))); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/result/ValidationErrorPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/result/ValidationErrorPanel.java index 721004bbbbc..e7c6d353cc4 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/result/ValidationErrorPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/result/ValidationErrorPanel.java @@ -79,13 +79,13 @@ private void initHeader(WebMarkupContainer box) { iconType.add(new AttributeAppender("class", new AbstractReadOnlyModel() { @Override public Object getObject() { - + FeedbackMessage result = getModelObject(); if (result == null) { return " fa-info"; } - + switch (result.getLevel()) { case FeedbackMessage.INFO: case FeedbackMessage.DEBUG: @@ -122,9 +122,9 @@ public void onClick(AjaxRequestTarget target) { box.add(close); - + } - + public void close(AjaxRequestTarget target){ this.setVisible(false); target.add(this); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/togglebutton/ToggleBackgroundButton.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/togglebutton/ToggleBackgroundButton.java index c37cc47589f..58d341c16ba 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/togglebutton/ToggleBackgroundButton.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/togglebutton/ToggleBackgroundButton.java @@ -25,7 +25,7 @@ /** * Simple button that toggles two states (on-off). * The button changes the background when pressed. - * + * * @author semancik */ public abstract class ToggleBackgroundButton extends AjaxLink { @@ -33,12 +33,12 @@ public abstract class ToggleBackgroundButton extends AjaxLink { private String cssClassOff = GuiStyleConstants.CLASS_BUTTON_TOGGLE_OFF; private String cssClassOn = GuiStyleConstants.CLASS_BUTTON_TOGGLE_ON; - + public ToggleBackgroundButton(String id) { super(id); initLayout(); } - + public ToggleBackgroundButton(String id, String cssClassOff, String cssClassOn) { super(id); this.cssClassOff = cssClassOff; @@ -74,5 +74,5 @@ public String getObject() { } public abstract boolean isOn(); - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/togglebutton/ToggleIconButton.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/togglebutton/ToggleIconButton.java index b70d95450b7..881dc7515ce 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/togglebutton/ToggleIconButton.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/togglebutton/ToggleIconButton.java @@ -22,7 +22,7 @@ /** * Simple button that toggles two states (on-off, alphasort-numericsort, etc). * The button changes the icon when pressed. - * + * * @author semancik */ public abstract class ToggleIconButton extends AjaxLink { @@ -30,12 +30,12 @@ public abstract class ToggleIconButton extends AjaxLink { private String cssClassOff; private String cssClassOn; - + public ToggleIconButton(String id) { super(id); initLayout(); } - + public ToggleIconButton(String id, String cssClassOff, String cssClassOn) { super(id); this.cssClassOff = cssClassOff; @@ -72,5 +72,5 @@ public String getObject() { } public abstract boolean isOn(); - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/model/CountModelProvider.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/model/CountModelProvider.java index 4f05a4c469f..057bd0b1daa 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/model/CountModelProvider.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/model/CountModelProvider.java @@ -21,12 +21,12 @@ * Interface for objects that provide Wicket model which represents * object count or similar tag. The count in usually displayed as a * small "bubble" in the tab, next to the menu item, etc. - * + * * @author semancik */ @FunctionalInterface public interface CountModelProvider { - + /** * Return count model. May return null. If null is * returned then no count should be displayed. diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/model/LoadableModel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/model/LoadableModel.java index c3d130cdf1d..ea26d70499c 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/model/LoadableModel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/model/LoadableModel.java @@ -28,7 +28,7 @@ * that loads the model content only when needed. This is supposed * to be used for objects that are expensive to load. So we can avoid * loading the at all when a component that uses them is not visible. - * + * * @author lazyman */ public abstract class LoadableModel implements IModel { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/model/package-info.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/model/package-info.java index e323d3ae26c..dfbb5b2d867 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/model/package-info.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/model/package-info.java @@ -15,9 +15,9 @@ */ /** - * The package that contains Wicket models (implementations of IModel + * The package that contains Wicket models (implementations of IModel * interface) and other model-related utilities. - * + * * @author Radovan Semancik */ package com.evolveum.midpoint.gui.api.model; \ No newline at end of file diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/package-info.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/package-info.java index 3f3942a3264..3d4961f861c 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/package-info.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/package-info.java @@ -17,7 +17,7 @@ /** * GUI API package contains classes that are stable and intended for * public (third-party) usage. - * + * * @author Radovan Semancik */ package com.evolveum.midpoint.gui.api; \ No newline at end of file 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 1c928a75b60..300351bda11 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 @@ -207,13 +207,13 @@ public abstract class PageBase extends WebPage implements ModelServiceLocator { // Strictly speaking following fields should be transient. // But making them transient is causing problems on some - // JVM version or tomcat configurations (MID-3357). + // JVM version or tomcat configurations (MID-3357). // It seems to be somehow related to session persistence. // But honestly I have no idea about the real cause. // Anyway, setting these fields to non-transient seems to // fix it. And surprisingly it does not affect the session // size. - + @SpringBean(name = "modelController") private ScriptingService scriptingService; @@ -258,7 +258,7 @@ public abstract class PageBase extends WebPage implements ModelServiceLocator { @SpringBean(name = "accessDecisionManager") private SecurityEnforcer securityEnforcer; - + @SpringBean private MidpointFormValidatorRegistry formValidatorRegistry; @@ -275,7 +275,7 @@ public abstract class PageBase extends WebPage implements ModelServiceLocator { // No need to store this in the session. Retrieval is cheap. private transient AdminGuiConfigurationType adminGuiConfiguration; - + // No need for this to store in session. It is used only during single init and render. private transient Task pageTask; @@ -283,7 +283,7 @@ public PageBase(PageParameters parameters) { super(parameters); LOGGER.debug("Initializing page {}", this.getClass()); - + Injector.get().inject(this); Validate.notNull(modelService, "Model service was not injected."); Validate.notNull(taskManager, "Task manager was not injected."); @@ -294,8 +294,8 @@ public PageBase(PageParameters parameters) { add(new NewWindowNotifyingBehavior()); initializeModel(); - - initLayout(); + + initLayout(); } @Override @@ -309,11 +309,11 @@ protected void onConfigure() { createBreadcrumb(); } - + private void initializeModel() { workItemCountModel = new LoadableModel() { private static final long serialVersionUID = 1L; - + @Override protected Integer load() { try { @@ -523,7 +523,7 @@ public Task getPageTask() { public MidpointFormValidatorRegistry getFormValidatorRegistry() { return formValidatorRegistry; } - + public MidPointPrincipal getPrincipal() { return SecurityUtils.getPrincipalUser(); } @@ -540,7 +540,7 @@ public static String createEnumResourceKey(Enum e) { public Task createAnonymousTask(String operation) { TaskManager manager = getTaskManager(); Task task = manager.createTaskInstance(operation); - + task.setChannel(SchemaConstants.CHANNEL_GUI_USER_URI); return task; @@ -774,7 +774,7 @@ public boolean isVisible(){ WebMarkupContainer version = new WebMarkupContainer(ID_VERSION) { private static final long serialVersionUID = 1L; - + @Deprecated public String getDescribe() { return PageBase.this.getDescribe(); @@ -782,7 +782,7 @@ public String getDescribe() { }; version.add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; - + @Override public boolean isVisible() { return RuntimeConfigurationType.DEVELOPMENT.equals(getApplication().getConfigurationType()); @@ -858,7 +858,7 @@ public boolean isVisible() { } }; } - + protected boolean isSideMenuVisible(boolean visibleIfLoggedIn) { return SecurityUtils.getPrincipalUser() != null ? visibleIfLoggedIn : !visibleIfLoggedIn; } @@ -941,7 +941,7 @@ public StringResourceModel createStringResource(String resourceKey, Object... ob return new StringResourceModel(resourceKey, this).setModel(new Model()).setDefaultValue(resourceKey) .setParameters(objects); } - + public StringResourceModel createStringResource(Enum e) { String resourceKey = e.getDeclaringClass().getSimpleName() + "." + e.name(); return createStringResource(resourceKey); @@ -969,7 +969,7 @@ public OpResult showResult(OperationResult result) { public OpResult showResult(OperationResult result, String errorMessageKey, boolean showSuccess) { Validate.notNull(result, "Operation result must not be null."); Validate.notNull(result.getStatus(), "Operation result status must not be null."); - + OpResult opResult = OpResult.getOpResult((PageBase) getPage(), result); opResult.determineBackgroundTaskVisibility(this); switch (opResult.getStatus()) { @@ -1195,7 +1195,7 @@ protected List createMenuItems() { AuthorizationConstants.AUTZ_GUI_ALL_DEPRECATED_URL)) { items.add(createRolesItems()); } - + if (WebComponentUtil.isAuthorized(AuthorizationConstants.AUTZ_UI_SERVICES_URL, AuthorizationConstants.AUTZ_UI_SERVICES_ALL_URL, AuthorizationConstants.AUTZ_GUI_ALL_URL, AuthorizationConstants.AUTZ_GUI_ALL_DEPRECATED_URL)) { @@ -1267,7 +1267,7 @@ public String getBubbleLabel() { return workItemCount.toString(); } } - + }; List submenu = item.getItems(); @@ -1749,7 +1749,7 @@ private MainMenuItem createRolesItems() { return item; } - + private MainMenuItem createServicesItems() { MainMenuItem item = new MainMenuItem(GuiStyleConstants.CLASS_OBJECT_SERVICE_ICON_COLORED, createStringResource("PageAdmin.menu.top.services"), null); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/page/package-info.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/page/package-info.java index 43e4391b90a..02f6fe36ad8 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/page/package-info.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/page/package-info.java @@ -18,7 +18,7 @@ * Package that contains base page classes. These classes are used as * (abstract) superclasses for midPoint GUI pages. They contain the basic * components that any fully-interoperable midPoint GUI page must have. - * + * * @author Radovan Semancik */ package com.evolveum.midpoint.gui.api.page; \ No newline at end of file diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/FeatureVisibleEnableBehaviour.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/FeatureVisibleEnableBehaviour.java index 3cfc270785f..197621b2309 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/FeatureVisibleEnableBehaviour.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/FeatureVisibleEnableBehaviour.java @@ -23,7 +23,7 @@ /** * Behaviour class that determines visibility of (configurable) UI feature. - * + * * @author semancik */ public class FeatureVisibleEnableBehaviour extends VisibleEnableBehaviour { @@ -35,7 +35,7 @@ public FeatureVisibleEnableBehaviour(GuiFeature feature, AdminGuiConfigurationTy super(); visibility = AdminGuiConfigTypeUtil.getFeatureVisibility(adminGuiConfig, feature.getUri()); } - + @Override public boolean isVisible() { return AdminGuiConfigTypeUtil.isVisible(visibility, this::isVisibleAutomatic); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/ModelServiceLocator.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/ModelServiceLocator.java index 7ea77c18db6..74517b2082d 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/ModelServiceLocator.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/ModelServiceLocator.java @@ -25,35 +25,35 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.AdminGuiConfigurationType; /** - * Interface that allows location of model and model-like services, + * Interface that allows location of model and model-like services, * such as ModelService and ModelInteractionService. * Used by GUI components that need to interact with the midPoint IDM model, * especially for loading data. * Usually implemented by PageBase and similar "central" GUI classes. - * + * * @author Radovan Semancik */ public interface ModelServiceLocator { - + ModelService getModelService(); - + ModelInteractionService getModelInteractionService(); - + Task createSimpleTask(String operationName); - + /** * Returns a task, that is used to retrieve and render the entire content * of the page. A single task is created to render the whole page, so * the summary result can be collected in the task result. */ Task getPageTask(); - + PrismContext getPrismContext(); - + SecurityEnforcer getSecurityEnforcer(); - + ExpressionFactory getExpressionFactory(); - + /** * Returns adminGuiConfiguraiton applicable to currently logged-in user. * Strictly speaking, this can be retrieved from modelInteractionService. 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 d7ba0ff7421..38ab6974401 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 @@ -172,7 +172,7 @@ /** * Utility class containing miscellaneous methods used mostly in Wicket * components. - * + * * @author lazyman */ public final class WebComponentUtil { @@ -214,7 +214,7 @@ public final class WebComponentUtil { storageKeyMap.put(PageRoles.class, SessionStorage.KEY_ROLES); storageKeyMap.put(PageServices.class, SessionStorage.KEY_SERVICES); } - + private static Map storageTableIdMap; static { @@ -226,7 +226,7 @@ public final class WebComponentUtil { storageTableIdMap.put(TableId.PAGE_RESOURCE_GENERIC_PANEL_REPOSITORY_MODE, SessionStorage.KEY_RESOURCE_GENERIC_CONTENT + SessionStorage.KEY_RESOURCE_PAGE_REPOSITORY_CONTENT); storageTableIdMap.put(TableId.PAGE_RESOURCE_GENERIC_PANEL_RESOURCE_MODE, SessionStorage.KEY_RESOURCE_GENERIC_CONTENT + SessionStorage.KEY_RESOURCE_PAGE_RESOURCE_CONTENT); storageTableIdMap.put(TableId.PAGE_RESOURCE_OBJECT_CLASS_PANEL, SessionStorage.KEY_RESOURCE_OBJECT_CLASS_CONTENT); - + } public static String nl2br(String text) { @@ -296,7 +296,7 @@ public enum Channel { USER(SchemaConstants.CHANNEL_GUI_USER_URI), SELF_REGISTRATION(SchemaConstants.CHANNEL_GUI_SELF_REGISTRATION_URI), RESET_PASSWORD(SchemaConstants.CHANNEL_GUI_RESET_PASSWORD_URI); - + private String channel; Channel(String channel) { @@ -315,7 +315,7 @@ public String getChannel() { throw new IllegalStateException("Exception while obtaining Datatype Factory instance", dce); } } - + public static DateValidator getRangeValidator(Form form, ItemPath path) { DateValidator validator = null; List validators = form.getBehaviors(DateValidator.class); @@ -340,15 +340,15 @@ public static DateValidator getRangeValidator(Form form, ItemPath path) { public static Class qnameToClass(PrismContext prismContext, QName type) { return prismContext.getSchemaRegistry().determineCompileTimeClass(type); } - + public static Class qnameToClass(PrismContext prismContext, QName type, Class returnType) { return returnType = prismContext.getSchemaRegistry().determineCompileTimeClass(type); } - + public static QName classToQName(PrismContext prismContext, Class clazz) { return prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(clazz).getTypeName(); } - + public static TaskType createSingleRecurrenceTask(String taskName, QName applicableType, ObjectQuery query, ObjectDelta delta, ModelExecuteOptions options, String category, PageBase pageBase) throws SchemaException { @@ -433,24 +433,24 @@ public static Integer safeLongToInteger(Long l) { return (int) l.longValue(); } - + // TODO: move to schema component public static List createObjectTypeList() { - + List types = new ArrayList<>(ObjectTypes.values().length); for (ObjectTypes t : ObjectTypes.values()) { types.add(t.getTypeQName()); } - + return types.stream().sorted((type1, type2) -> { Validate.notNull(type1); Validate.notNull(type2); return String.CASE_INSENSITIVE_ORDER.compare(QNameUtil.qNameToUri(type1), QNameUtil.qNameToUri(type2)); - + }).collect(Collectors.toList()); - + } // TODO: move to schema component @@ -464,7 +464,7 @@ public static List createFocusTypeList() { return focusTypeList; } - + // TODO: move to schema component public static List createAbstractRoleTypeList() { List focusTypeList = new ArrayList<>(); @@ -488,12 +488,12 @@ public static List createAssignableTypesList() { return focusTypeList; } - + /** * Takes a collection of object types (classes) that may contain abstract types. Returns a collection * that only contain concrete types. * @param common supertype for all the types in the collections - * + * * TODO: move to schema component */ public static List resolveObjectTypesToQNames(Collection> types, PrismContext prismContext) { @@ -615,7 +615,7 @@ public static DropDownChoicePanel createEnumPanel(Class clazz, public static DropDownChoicePanel createEnumPanel(Class clazz, String id, IModel> choicesList, final IModel model, final Component component, boolean allowNull) { - return new DropDownChoicePanel(id, model, choicesList, + return new DropDownChoicePanel(id, model, choicesList, new IChoiceRenderer() { private static final long serialVersionUID = 1L; @@ -646,7 +646,7 @@ public static DropDownChoicePanel createEnumPanel(final PrismPropertyDefinition final Object o = model.getObject(); final IModel> enumModelValues = new AbstractReadOnlyModel>() { - + private static final long serialVersionUID = 1L; @Override @@ -657,8 +657,8 @@ public List getObject() { }; return new DropDownChoicePanel(id, model, enumModelValues, new DisplayableValueChoiceRenderer(getDisplayableValues(def)), true); - - + + // @Override // public Object getObject(String id, IModel choices) { // if (StringUtils.isBlank(id)) { @@ -695,7 +695,7 @@ public List getObject() { // } } - + private static List getDisplayableValues(PrismPropertyDefinition def) { List values = null; @@ -774,17 +774,17 @@ public static String getName(ObjectReferenceType ref, Pag } return name; } - + public static String getEffectiveName(ObjectReferenceType ref, QName propertyName, PageBase pageBase, String operation) { PrismObject object = WebModelServiceUtils.loadObject(ref, pageBase, pageBase.createSimpleTask(operation), new OperationResult(operation)); - + if (object == null) { return "Not Found"; } - + return getEffectiveName(object, propertyName); - + } public static String getName(ObjectReferenceType ref) { @@ -1120,7 +1120,7 @@ public static boolean isSuccessOrHandledError(OperationResult result) { return result.isSuccess() || result.isHandledError(); } - + public static boolean isSuccessOrHandledError(OperationResultType resultType) { if (resultType == null) { return false; @@ -1147,7 +1147,7 @@ public static boolean isSuccessOrHandledErrorOrInProgress(OperationResult result public static String createDefaultIcon(T object) { return createDefaultIcon(object.asPrismObject()); } - + public static String createDefaultIcon(PrismObject object) { Class type = object.getCompileTimeClass(); if (type.equals(UserType.class)) { @@ -1361,7 +1361,7 @@ public static String createResourceIcon(PrismObject object) { return GuiStyleConstants.CLASS_OBJECT_RESOURCE_ICON + " " + GuiStyleConstants.CLASS_ICON_STYLE_DOWN; } - + if (lastAvailabilityStatus == AvailabilityStatusType.BROKEN) { return GuiStyleConstants.CLASS_OBJECT_RESOURCE_ICON + " " + GuiStyleConstants.CLASS_ICON_STYLE_BROKEN; @@ -1778,7 +1778,7 @@ public static boolean hasDetailsPage(ObjectReferenceType ref) { public static String getStorageKeyForPage(Class pageClass) { return storageKeyMap.get(pageClass); } - + public static String getStorageKeyForTableId(TableId tableId) { return storageTableIdMap.get(tableId); } @@ -1896,7 +1896,7 @@ public boolean isVisible() { public static Behavior enabledIfFalse(final NonEmptyModel model) { return new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; - + @Override public boolean isEnabled() { return !model.getObject(); @@ -2000,7 +2000,7 @@ public static boolean getElementVisibility(UserInterfaceElementVisibilityType vi } return true; } - + public static IModel createAbstractRoleConfirmationMessage(String actionName, ColumnMenuAction action, MainObjectListPanel abstractRoleTable, PageBase pageBase) { List selectedRoles = new ArrayList<>(); if (action.getRowModel() == null) { 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 4900c7eb17e..715ff89c946 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 @@ -67,7 +67,7 @@ /** * Utility class that contains methods that interact with ModelService and other * midPoint components. - * + * * @author lazyman */ public class WebModelServiceUtils { @@ -123,23 +123,23 @@ public static PrismObject resolveReferenceRaw(ObjectRe return loadObject(definition.getCompileTimeClass(), reference.getOid(), SelectorOptions.createCollection(GetOperationOptions.createRaw()), 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(); if(objects != null){ List references = new ArrayList<>(); - + for(PrismObject object: objects){ referenceMap.put(object.getOid(), WebComponentUtil.getName(object)); references.add(ObjectTypeUtil.createObjectRef(object)); - + } return references; } @@ -176,16 +176,16 @@ public static String runTask(TaskType taskToRun, Task operationalTask, Operation 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); @@ -204,7 +204,7 @@ public static void runTask(Collection tasksToRun, Task operationalTask // LoggingUtils.logUnexpectedException(LOGGER, "Couldn't run task " + e.getMessage(), e); // return null; // } - + } @Nullable @@ -213,7 +213,7 @@ public static PrismObject loadObject(ObjectReferenceTy 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) { @@ -301,7 +301,7 @@ public static List> searchObjects(Class OperationResult result, PageBase page) { return searchObjects(type, query, null, result, page, null); } - + public static List> searchObjects(Class type, ObjectQuery query, Collection> options, OperationResult result, PageBase page) { @@ -342,7 +342,7 @@ public static List> searchObjects(Class 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); @@ -419,16 +419,16 @@ public static Collection> createMinimalOpti 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 {}", new Object[]{deltas, options}); @@ -441,10 +441,10 @@ public static void save(Collection> deltas, Mo } try { - if (task == null) { + if (task == null) { task = page.createSimpleTask(result.getOperation()); } - + page.getModelService().executeChanges(deltas, options, task, result); } catch (Exception ex) { subResult.recordFatalError(ex.getMessage()); @@ -469,7 +469,7 @@ public static ObjectDelta createActivationAdminStatusD return objectDelta; } - + public static String getLoggedInUserOid() { MidPointPrincipal principal = SecurityUtils.getPrincipalUser(); Validate.notNull(principal, "No principal"); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/package-info.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/package-info.java index 6698da7931b..9b30b0b1b4f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/package-info.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/package-info.java @@ -15,8 +15,8 @@ */ /** - * GUI API package for various utility classes and interfaces. - * + * GUI API package for various utility classes and interfaces. + * * @author Radovan Semancik */ package com.evolveum.midpoint.gui.api.util; \ No newline at end of file diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/model/FlexibleLabelModel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/model/FlexibleLabelModel.java index 6651b448beb..a7cf00c6a1b 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/model/FlexibleLabelModel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/model/FlexibleLabelModel.java @@ -53,7 +53,7 @@ /** * Model that returns string value for a flexible label. The label value defaults to * the value of a fixed property. But if an expression is specified then the value - * is determined by the expression. + * is determined by the expression. * This implementation works on containerable models (not wrappers). * * @author semancik @@ -83,7 +83,7 @@ public FlexibleLabelModel(IModel model, ItemPath path, ModelServiceLocator se } @Override - public String getObject() { + public String getObject() { if (configuration == null) { return getDefaultValue(); } else { @@ -102,7 +102,7 @@ public String getObject() { if (InternalsConfig.nonCriticalExceptionsAreFatal()) { throw new SystemException(e.getMessage(), e); } else { - return "[Expression error]"; + return "[Expression error]"; } } } @@ -121,13 +121,13 @@ private String getDefaultValue() { } return getStringRealValue(property != null ? property.getRealValue() : null); - } - + } + private String getExpressionValue(ExpressionType expressionType, String contextDesc, Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException { - + C object = model.getObject(); ExpressionFactory expressionFactory = serviceLocator.getExpressionFactory(); - PrismPropertyDefinition outputDefinition = new PrismPropertyDefinitionImpl<>(ExpressionConstants.OUTPUT_ELEMENT_NAME, + PrismPropertyDefinition outputDefinition = new PrismPropertyDefinitionImpl<>(ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_STRING, object.asPrismContainerValue().getPrismContext()); Expression,PrismPropertyDefinition> expression = expressionFactory.makeExpression(expressionType, outputDefinition, contextDesc, task, result); ExpressionVariables variables = new ExpressionVariables(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/package-info.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/package-info.java index 5685968a248..464b24051e7 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/package-info.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/package-info.java @@ -21,11 +21,11 @@ * do it at your own risk. It is likely that midPoint upgrades will fail * in a spectacular way and your customizations will not survive. * You have been warned. - * + * * If there is any class or interface in this package that you think * may be useful as reusable component please contact the midPoint team. * We will consider moving it to the API. - * + * * @author Radovan Semancik */ package com.evolveum.midpoint.gui.impl; \ No newline at end of file diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/util/GuiImplUtil.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/util/GuiImplUtil.java index 2c6393b28a3..9874f466778 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/util/GuiImplUtil.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/util/GuiImplUtil.java @@ -21,12 +21,12 @@ /** * Class for misc GUI util methods (impl). - * + * * @author semancik * */ public class GuiImplUtil { - + public static ItemPathType getPathType(AbstractFormItemType aItem) { if (aItem == null) { return null; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/init/InitialDataImport.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/init/InitialDataImport.java index 69d286d4115..9acf7ee6b9d 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/init/InitialDataImport.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/init/InitialDataImport.java @@ -80,7 +80,7 @@ public class InitialDataImport { private TaskManager taskManager; @Autowired private MidpointConfiguration configuration; - + public void setModel(ModelService model) { Validate.notNull(model, "Model service must not be null."); this.model = model; @@ -103,7 +103,7 @@ public void init() throws SchemaException { File[] files = getInitialImportObjects(); LOGGER.debug("Files to be imported: {}.", Arrays.toString(files)); - + // We need to provide a fake Spring security context here. // We have to fake it because we do not have anything in the repository yet. And to get // something to the repository we need a context. Chicken and egg. So we fake the egg. @@ -145,7 +145,7 @@ public void init() throws SchemaException { } securityContext.setAuthentication(null); - + mainResult.recomputeStatus("Couldn't import objects."); LOGGER.info("Initial object import finished ({} objects imported, {} errors)", count, errors); @@ -221,7 +221,7 @@ private File[] getInitialImportObjects() { File[] files = null; File folder = null; - + if ("zip".equals(resourceType) || "jar".equals(resourceType)) { try { File tmpDir = new File(configuration.getMidpointHome()+"/tmp"); @@ -233,11 +233,11 @@ private File[] getInitialImportObjects() { if (!tmpDir.mkdir()) { LOGGER.warn("Failed to create temporary directory for initial objects {}. Maybe it already exists", configuration.getMidpointHome()+"/tmp/initial-objects"); } - + //prerequisite: we are expecting that the files are store in the same archive as the source code that is loading it URI src = InitialDataImport.class.getProtectionDomain().getCodeSource().getLocation().toURI(); LOGGER.trace("InitialDataImport code location: {}", src); - Map env = new HashMap<>(); + Map env = new HashMap<>(); env.put("create", "false"); URI normalizedSrc = new URI(src.toString().replaceFirst("file:", "jar:file:")); LOGGER.trace("InitialDataImport normalized code location: {}", normalizedSrc); @@ -255,7 +255,7 @@ public FileVisitResult visitFile(Path file, Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING); return FileVisitResult.CONTINUE; } - + @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { @@ -269,20 +269,20 @@ public FileVisitResult preVisitDirectory(Path dir, } }); - + } folder = new File(configuration.getMidpointHome()+"/tmp/initial-objects"); } catch (IOException ex) { throw new RuntimeException("Failed to copy initial objects file out of the archive to the temporary directory", ex); } catch (URISyntaxException ex) { throw new RuntimeException("Failed get URI for the source code bundled with initial objects", ex); - } + } } - + if ("file".equals(resourceType)) { folder = getResource("initial-objects"); } - + files = folder.listFiles(new FileFilter() { @Override @@ -304,7 +304,7 @@ public int compare(File o1, File o2) { return n1 - n2; } }); - + return files; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/application/AuthorizationActionValue.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/application/AuthorizationActionValue.java index fd139d0994f..c678bd265d6 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/application/AuthorizationActionValue.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/application/AuthorizationActionValue.java @@ -59,5 +59,5 @@ public String toString() { return "AuthorizationActionValue(value=" + value + ", label=" + label + ", description=" + description + ")"; } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/application/DescriptorLoader.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/application/DescriptorLoader.java index 6245a3b0376..33f2b119a32 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/application/DescriptorLoader.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/application/DescriptorLoader.java @@ -48,7 +48,7 @@ public final class DescriptorLoader implements DebugDumpable { private static Map[]> actions = new HashMap<>(); private static Map urlClassMap = new HashMap<>(); - + private String baseFileName = "/WEB-INF/descriptor.xml"; private String customFileName = "/WEB-INF/classes/descriptor.xml"; @@ -101,11 +101,11 @@ public void loadData(MidPointApplication application) { if (customDescriptor != null) { scanPackagesForPages(customDescriptor.getPackagesToScan(), application); } - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("loaded:\n{}", debugDump(1)); } - + } catch (Exception ex) { LoggingUtils.logUnexpectedException(LOGGER, "Couldn't process application descriptor", ex); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/AbstractAjaxDownloadBehavior.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/AbstractAjaxDownloadBehavior.java index 6cc0c69ed66..0f43dfc92c2 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/AbstractAjaxDownloadBehavior.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/AbstractAjaxDownloadBehavior.java @@ -62,7 +62,7 @@ public void initiate(AjaxRequestTarget target) { } public void onRequest() { - + IResourceStream resourceStream = getResourceStream(); if (resourceStream == null) { return; // We hope the error was already processed and will be shown. @@ -80,7 +80,7 @@ public void respond(IRequestCycle requestCycle) { } getComponent().getRequestCycle().scheduleRequestHandlerAfterCurrent(reqHandler); } - + public void setContentType(String contentType) { this.contentType = contentType; } @@ -92,6 +92,6 @@ public String getFileName() { public void setFileName(String fileName) { this.fileName = fileName; } - + public abstract IResourceStream getResourceStream(); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/AbstractSummaryPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/AbstractSummaryPanel.java index 5315e9894e2..34e003567eb 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/AbstractSummaryPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/AbstractSummaryPanel.java @@ -65,7 +65,7 @@ public abstract class AbstractSummaryPanel extends Base protected static final String ICON_BOX_CSS_CLASS = "info-box-icon"; protected SummaryPanelSpecificationType configuration; - + protected WebMarkupContainer box; protected WebMarkupContainer tagBox; protected WebMarkupContainer iconBox; @@ -82,7 +82,7 @@ protected void initLayoutCommon(ModelServiceLocator serviceLocator) { add(box); box.add(new AttributeModifier("class", BOX_CSS_CLASS + " " + getBoxAdditionalCssClass())); - + box.add(new Label(ID_DISPLAY_NAME, createLabelModel(getDisplayNamePropertyName(), SummaryPanelSpecificationType.F_DISPLAY_NAME, serviceLocator))); WebMarkupContainer identifierPanel = new WebMarkupContainer(ID_IDENTIFIER_PANEL); @@ -172,7 +172,7 @@ public boolean isVisible() { private FlexibleLabelModel createLabelModel(QName modelPropertyName, QName configurationPropertyName, ModelServiceLocator serviceLocator) { return createFlexibleLabelModel(modelPropertyName, serviceLocator, getLabelConfiguration(configurationPropertyName)); } - + private FlexibleLabelModel createFlexibleLabelModel(QName modelPropertyName, ModelServiceLocator serviceLocator, GuiFlexibleLabelType configuration) { return new FlexibleLabelModel(getModel(), modelPropertyName, serviceLocator, configuration) { private static final long serialVersionUID = 1L; @@ -183,9 +183,9 @@ protected void addAdditionalExpressionVariables(ExpressionVariables variables) { } }; } - + protected void addAdditionalExpressionVariables(ExpressionVariables variables) { - + } private GuiFlexibleLabelType getLabelConfiguration(QName configurationPropertyName) { @@ -262,7 +262,7 @@ protected IModel getParentOrgModel(ModelServiceLocator serviceLocator) { return getDefaltParentOrgModel(); } } - + protected IModel getDefaltParentOrgModel() { return new Model<>(null); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/AjaxDownloadBehaviorFromFile.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/AjaxDownloadBehaviorFromFile.java index dcc852536e5..74adb4abcf0 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/AjaxDownloadBehaviorFromFile.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/AjaxDownloadBehaviorFromFile.java @@ -62,7 +62,7 @@ public void initiate(AjaxRequestTarget target) { } public void onRequest() { - final File file = initFile(); + final File file = initFile(); IResourceStream resourceStream = new FileResourceStream(new File(file)); getComponent().getRequestCycle().scheduleRequestHandlerAfterCurrent( new ResourceStreamRequestHandler(resourceStream) { @@ -81,7 +81,7 @@ public void respond(IRequestCycle requestCycle) { }.setFileName(file.getName()).setContentDisposition(ContentDisposition.ATTACHMENT) .setCacheDuration(Duration.ONE_SECOND)); } - + public void setContentType(String contentType) { this.contentType = contentType; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/AjaxDownloadBehaviorFromStream.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/AjaxDownloadBehaviorFromStream.java index 51085cb4ce5..0321436006d 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/AjaxDownloadBehaviorFromStream.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/AjaxDownloadBehaviorFromStream.java @@ -37,14 +37,14 @@ public abstract class AjaxDownloadBehaviorFromStream extends AbstractAjaxDownloa private String contentType = "text"; private String fileName = null; - + public AjaxDownloadBehaviorFromStream() { super(); } - + public AjaxDownloadBehaviorFromStream(boolean addAntiCache) { super(addAntiCache); - + } @@ -55,7 +55,7 @@ public IResourceStream getResourceStream() { if (byteStream == null) { return null; } - + IResourceStream resourceStream = new AbstractResourceStream(){ private static final long serialVersionUID = 1L; @@ -73,11 +73,11 @@ public InputStream getInputStream() throws ResourceStreamNotFoundException { public void close() throws IOException { byteStream.close(); } - + }; return resourceStream; } - + protected abstract InputStream initStream(); public String getFileName() { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/FocusSummaryPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/FocusSummaryPanel.java index 033d8136934..fb5650ee21f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/FocusSummaryPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/FocusSummaryPanel.java @@ -53,7 +53,7 @@ public abstract class FocusSummaryPanel extends ObjectSumm private static final String ID_ACTIVATION_TAG = "activationTag"; private IModel> wrapperModel; - + public FocusSummaryPanel(String id, Class type, final IModel> model, ModelServiceLocator serviceLocator) { super(id, type, new ReadOnlyPrismObjectFromObjectWrapperModel(model), serviceLocator); @@ -73,17 +73,17 @@ protected void initialize(ObjectWrapper wrapper) { if (activation == null) { setIconCssClass(GuiStyleConstants.CLASS_ICON_ACTIVATION_ACTIVE); setLabel(getString("ActivationStatusType.ENABLED")); - + } else if (activation.getEffectiveStatus() == ActivationStatusType.DISABLED) { setIconCssClass(GuiStyleConstants.CLASS_ICON_ACTIVATION_INACTIVE); setLabel(getString("ActivationStatusType.DISABLED")); setCssClass(GuiStyleConstants.CLASS_ICON_STYLE_DISABLED); - + } else if (activation.getEffectiveStatus() == ActivationStatusType.ARCHIVED) { setIconCssClass(GuiStyleConstants.CLASS_ICON_ACTIVATION_INACTIVE); setLabel(getString("ActivationStatusType.ARCHIVED")); setCssClass(GuiStyleConstants.CLASS_ICON_STYLE_ARCHIVED); - + } else { setIconCssClass(GuiStyleConstants.CLASS_ICON_ACTIVATION_ACTIVE); setLabel(getString("ActivationStatusType.ENABLED")); @@ -125,7 +125,7 @@ public String getObject() { } }; } - + @Override protected void addAdditionalExpressionVariables(ExpressionVariables variables) { Collection> parentOrgs = wrapperModel.getObject().getParentOrgs(); @@ -137,7 +137,7 @@ protected void addAdditionalExpressionVariables(ExpressionVariables variables) { protected IModel getPhotoModel() { return new AbstractReadOnlyModel() { private static final long serialVersionUID = 1L; - + @Override public AbstractResource getObject() { byte[] jpegPhoto = null; @@ -157,7 +157,7 @@ public AbstractResource getObject() { protected boolean isActivationVisible() { return true; } - + public static void addSummaryPanel(MarkupContainer parentComponent, PrismObject focus, ObjectWrapper focusWrapper, String id, ModelServiceLocator serviceLocator) { if (focus.getCompileTimeClass().equals(UserType.class)) { parentComponent.add(new UserSummaryPanel(id, diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/GuiComponents.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/GuiComponents.java index 4a0844e83a7..f548604ca6e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/GuiComponents.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/GuiComponents.java @@ -59,8 +59,8 @@ public static Future submitCallable(Callable callable) { public static DropDownChoice createTriStateCombo(String id, IModel model) { final IChoiceRenderer renderer = new IChoiceRenderer() { - - + + @Override public T getObject(String id, IModel> choices) { return id != null ? choices.getObject().get(Integer.parseInt(id)) : null; @@ -77,7 +77,7 @@ public String getDisplayValue(T object) { } StringResourceModel model = PageBase.createStringResourceStatic(null, key); -// +// return model.getString(); } @@ -87,7 +87,7 @@ public String getIdValue(T object, int index) { } - + }; DropDownChoice dropDown = new DropDownChoice(id, model, createChoices(), renderer) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/ObjectPolicyConfigurationEditor.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/ObjectPolicyConfigurationEditor.java index 43d4f5998e2..fbb0ee76ab3 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/ObjectPolicyConfigurationEditor.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/ObjectPolicyConfigurationEditor.java @@ -72,7 +72,7 @@ public ObjectPolicyConfigurationEditor(String id, IModel extends AbstractSummaryPanel { private static final long serialVersionUID = -3755521482914447912L; - + public ObjectSummaryPanel(String id, Class type, final IModel> model, ModelServiceLocator serviceLocator) { super(id, new ContainerableFromPrismObjectModel(model), serviceLocator, determineConfig(type, serviceLocator.getAdminGuiConfiguration())); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/TabbedPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/TabbedPanel.java index 6db1fc5ad02..d030233f823 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/TabbedPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/TabbedPanel.java @@ -51,7 +51,7 @@ public class TabbedPanel extends Panel { public static final String TAB_PANEL_ID = "panel"; public static final String RIGHT_SIDE_TAB_ITEM_ID = "rightSideTabItem"; public static final String RIGHT_SIDE_TAB_ID = "rightSideTab"; - + protected static final String ID_TITLE = "title"; protected static final String ID_COUNT = "count"; protected static final String ID_LINK = "link"; @@ -122,7 +122,7 @@ protected void populateItem(final LoopItem item) { titleLink.add(newTitle(ID_TITLE, tab.getTitle(), index)); item.add(titleLink); - + final IModel countModel; if (tab instanceof CountModelProvider) { countModel = ((CountModelProvider)tab).getCountModel(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AbstractAssignmentDetailsPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AbstractAssignmentDetailsPanel.java index 5281b0a7718..ae2ddc21410 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AbstractAssignmentDetailsPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AbstractAssignmentDetailsPanel.java @@ -43,17 +43,17 @@ public abstract class AbstractAssignmentDetailsPanel extends BasePanel form, IModel void initLayout(Form form){ - + DisplayNamePanel displayNamePanel = new DisplayNamePanel(ID_DISPLAY_NAME, new AbstractReadOnlyModel() { - + private static final long serialVersionUID = 1L; @Override @@ -77,7 +77,7 @@ public C getObject() { Task task = AbstractAssignmentDetailsPanel.this.pageBase.createSimpleTask("Load target"); com.evolveum.midpoint.schema.result.OperationResult result = task.getResult(); return (C) WebModelServiceUtils.loadObject(getModelObject().getAssignment().getTargetRef(), AbstractAssignmentDetailsPanel.this.pageBase, task, result).asObjectable(); - } + } AssignmentType assignmentType = assignemtn.getAssignment(); if (assignmentType.getConstruction() != null) { return (C) assignmentType.getConstruction(); @@ -86,24 +86,24 @@ public C getObject() { } else if (assignmentType.getPolicyRule() !=null) { return (C) assignmentType.getPolicyRule(); } - + return null; - - + + } - + }); - + displayNamePanel.setOutputMarkupId(true); add(displayNamePanel); - - + + WebMarkupContainer properties = new WebMarkupContainer(ID_PROPERTIES_PANEL); add(properties); properties.setOutputMarkupId(true); - + initPropertiesPanel(properties); - + AssignmentActivationPopupablePanel activationPanel = new AssignmentActivationPopupablePanel(ID_ACTIVATION_PANEL, new PropertyModel(getModel(), AssignmentDto.F_VALUE + "." + AssignmentType.F_ACTIVATION.getLocalPart())){ private static final long serialVersionUID = 1L; @@ -118,19 +118,19 @@ protected boolean getButtonsPanelVisibility() { } - - - + + + protected IModel getAdditionalNameLabelStyleClass(){ return Model.of(""); } - + protected boolean isVisible(Object path) { return !getHiddenItems().contains(path); } protected abstract List getHiddenItems(); - + protected abstract void initPropertiesPanel(WebMarkupContainer propertiesPanel); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AbstractAssignmentListPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AbstractAssignmentListPanel.java index b2fd21fb9eb..54e7b4b53f6 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AbstractAssignmentListPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AbstractAssignmentListPanel.java @@ -62,7 +62,7 @@ protected void deleteAssignmentPerformed(AjaxRequestTarget target, AssignmentEdi target.add(getPageBase().getFeedbackPanel()); return; } - + getPageBase().showMainPopup(getDeleteAssignmentPopupContent(dto), target); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AbstractRoleAssignmentDetailsPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AbstractRoleAssignmentDetailsPanel.java index 1a2eb2fbf05..3a868ed1c0f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AbstractRoleAssignmentDetailsPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AbstractRoleAssignmentDetailsPanel.java @@ -32,25 +32,25 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; public class AbstractRoleAssignmentDetailsPanel extends AbstractAssignmentDetailsPanel { - + private static final long serialVersionUID = 1L; - + private static final String ID_RELATION_CONTAINER = "relationContainer"; private static final String ID_RELATION = "relation"; - + private static final String ID_TENANT_CONTAINER = "tenantContainer"; private static final String ID_TENANT = "tenant"; private static final String ID_PROJECT_CONTAINER = "projectContainer"; private static final String ID_PROJECT = "project"; private static final String ID_POLICY_SITUATIONS = "policySituations"; private static final String ID_POLICY_SITUATION = "policySituation"; - + private static List hiddenItems = new ArrayList<>(); - + static { hiddenItems.add(AssignmentType.F_POLICY_RULE); }; - + public AbstractRoleAssignmentDetailsPanel(String id, Form form, IModel assignmentModel, PageBase pageBase) { super(id, form, assignmentModel, pageBase); } @@ -59,7 +59,7 @@ public AbstractRoleAssignmentDetailsPanel(String id, Form form, IModel tenantChooser = createParameterChooserPanel(ID_TENANT, assignmentType.getTenantRef(), true); tenantContainer.add(tenantChooser); propertiesPanel.add(tenantContainer); tenantContainer.setOutputMarkupId(true); tenantContainer.add(new VisibleEnableBehaviour() { - + private static final long serialVersionUID = 1L; @Override @@ -93,24 +93,24 @@ public boolean isVisible() { return AbstractRoleAssignmentDetailsPanel.this.isVisible(AssignmentType.F_TENANT_REF); } }); - + WebMarkupContainer projectContainer = new WebMarkupContainer(ID_PROJECT_CONTAINER); ChooseTypePanel projectChooser = createParameterChooserPanel(ID_PROJECT, assignmentType.getOrgRef(), false); projectContainer.add(projectChooser); propertiesPanel.add(projectContainer); projectContainer.setOutputMarkupId(true); projectContainer.add(new VisibleEnableBehaviour() { - + private static final long serialVersionUID = 1L; - + @Override public boolean isVisible() { return AbstractRoleAssignmentDetailsPanel.this.isVisible(AssignmentType.F_ORG_REF); } }); - + ListView policySituations = new ListView(ID_POLICY_SITUATIONS, new PropertyModel>(getModel(), AssignmentDto.F_VALUE + "." + AssignmentType.F_POLICY_SITUATION.getLocalPart())) { - + private static final long serialVersionUID = 1L; @Override @@ -118,7 +118,7 @@ protected void populateItem(ListItem item) { TextPanel textPanel = new TextPanel(ID_POLICY_SITUATION, item.getModel()); textPanel.setOutputMarkupId(true); item.add(textPanel); - + } }; policySituations.setOutputMarkupId(true); @@ -127,7 +127,7 @@ protected void populateItem(ListItem item) { private ChooseTypePanel createParameterChooserPanel(String id, ObjectReferenceType ref, boolean isTenant){ ChooseTypePanel orgSelector = new ChooseTypePanel(id, ref) { - + private static final long serialVersionUID = 1L; @Override @@ -139,7 +139,7 @@ protected void executeCustomAction(AjaxRequestTarget target, OrgType object) { } target.add(AbstractRoleAssignmentDetailsPanel.this); } - + @Override protected void executeCustomRemoveAction(AjaxRequestTarget target) { if (isTenant) { @@ -149,33 +149,33 @@ protected void executeCustomRemoveAction(AjaxRequestTarget target) { } target.add(AbstractRoleAssignmentDetailsPanel.this); } - + @Override protected ObjectQuery getChooseQuery() { ObjectFilter tenantFilter = QueryBuilder.queryFor(OrgType.class, getPageBase().getPrismContext()).item(OrgType.F_TENANT).eq(true).buildFilter(); - + if (isTenant) { return ObjectQuery.createObjectQuery(tenantFilter); - } + } return ObjectQuery.createObjectQuery(NotFilter.createNot(tenantFilter)); - + } - + @Override protected boolean isSearchEnabled() { return true; } - + @Override public Class getObjectTypeClass() { return OrgType.class; } - + }; orgSelector.setOutputMarkupId(true); return orgSelector; - + } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AbstractRoleAssignmentPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AbstractRoleAssignmentPanel.java index 134bc15b99c..b152d8ca90e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AbstractRoleAssignmentPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AbstractRoleAssignmentPanel.java @@ -64,17 +64,17 @@ * Created by honchar. */ public class AbstractRoleAssignmentPanel extends AssignmentPanel { - + private static final long serialVersionUID = 1L; - + private static final String ID_RELATION = "relation"; private static final String ID_SHOW_ALL_ASSIGNMENTS_BUTTON = "showAllAssignmentsButton"; - + public AbstractRoleAssignmentPanel(String id, IModel> assignmentsModel, PageBase pageBase){ super(id, assignmentsModel, pageBase); } - + protected void initCustomLayout(WebMarkupContainer assignmentsContainer){ DropDownChoicePanel relation = WebComponentUtil.createEnumPanel(RelationTypes.class, ID_RELATION, @@ -90,20 +90,20 @@ protected void onUpdate(AjaxRequestTarget target) { relation.setOutputMarkupId(true); relation.setOutputMarkupPlaceholderTag(true); relation.add(new VisibleEnableBehaviour() { - + private static final long serialVersionUID = 1L; @Override public boolean isVisible() { return AbstractRoleAssignmentPanel.this.isRelationVisible(); } - + }); assignmentsContainer.addOrReplace(relation); AjaxButton showAllAssignmentsButton = new AjaxButton(ID_SHOW_ALL_ASSIGNMENTS_BUTTON, createStringResource("AssignmentTablePanel.menu.showAllAssignments")) { - + private static final long serialVersionUID = 1L; @Override @@ -115,12 +115,12 @@ public void onClick(AjaxRequestTarget ajaxRequestTarget) { showAllAssignmentsButton.setOutputMarkupId(true); } - + private DropDownChoicePanel getRelationPanel() { return (DropDownChoicePanel) getAssignmentContainer().get(ID_RELATION); } - - + + protected void showAllAssignments(AjaxRequestTarget target) { } @@ -128,7 +128,7 @@ protected void showAllAssignments(AjaxRequestTarget target) { protected void newAssignmentClickPerformed(AjaxRequestTarget target) { TypedAssignablePanel panel = new TypedAssignablePanel( getPageBase().getMainPopupBodyId(), RoleType.class, true, getPageBase()) { - + private static final long serialVersionUID = 1L; @Override @@ -152,7 +152,7 @@ protected void addSelectedAssignmentsPerformed(AjaxReques AssignmentDto dto = new AssignmentDto(assignment, UserDtoStatus.ADD); getModelObject().add(0, dto); } - + refreshTable(target); } @@ -161,7 +161,7 @@ protected List> initColumns() { List> columns = new ArrayList<>(); columns.add(new PropertyColumn(createStringResource("ObjectReferenceType.relation"), AssignmentDto.F_RELATION_TYPE)); - + //commented since these columns are not used // columns.add(new DirectlyEditablePropertyColumn(createStringResource("AssignmentDataTablePanel.descriptionColumnName"), AssignmentEditorDto.F_DESCRIPTION){ // private static final long serialVersionUID = 1L; @@ -236,7 +236,7 @@ protected List> initColumns() { // } // }); // columns.add(new AbstractColumn(createStringResource("AssignmentDataTablePanel.activationColumnName")) { -// +// // private static final long serialVersionUID = 1L; // // @Override @@ -248,7 +248,7 @@ protected List> initColumns() { // } // }); - + return columns; } @@ -262,7 +262,7 @@ public boolean isVisible(){ } }; } - + protected void initPaging(){ getAssignmentsStorage().setPaging(ObjectPaging.createPaging(0, (int) getParentPage().getItemsPerPage(UserProfileStorage.TableId.ASSIGNMENTS_TAB_TABLE))); } @@ -276,28 +276,28 @@ protected TableId getTableId() { protected int getItemsPerPage() { return (int) getParentPage().getItemsPerPage(UserProfileStorage.TableId.ASSIGNMENTS_TAB_TABLE); } - + protected ObjectQuery createObjectQuery() { return QueryBuilder.queryFor(AssignmentType.class, getParentPage().getPrismContext()).item(new ItemPath(AssignmentType.F_TARGET_REF)) .ref(getRelation()) .build(); }; - + private QName getRelation() { DropDownChoicePanel relationPanel = getRelationPanel(); if (relationPanel == null) { return PrismConstants.Q_ANY; } - + if (relationPanel.getModel() == null) { - return PrismConstants.Q_ANY; + return PrismConstants.Q_ANY; } - + if (relationPanel.getModel().getObject() == null) { return PrismConstants.Q_ANY; } - - return relationPanel.getModel().getObject().getRelation(); + + return relationPanel.getModel().getObject().getRelation(); } @Override @@ -305,9 +305,9 @@ protected AbstractAssignmentDetailsPanel createDetailsPanel(String idAssignmentD PageBase parentPage) { return new AbstractRoleAssignmentDetailsPanel(ID_ASSIGNMENT_DETAILS, form, model, getParentPage()); } - + protected boolean isRelationVisible() { return true; } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentCatalogPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentCatalogPanel.java index ea1601ad88f..a167e74c572 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentCatalogPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentCatalogPanel.java @@ -169,7 +169,7 @@ private void initHeaderPanel(){ initCartButton(headerPanel); addOrReplaceSearchPanel(headerPanel); } - + public void addOrReplaceLayout(AjaxRequestTarget target, WebMarkupContainer panelContainer, ModelServiceLocator serviceLocator) { WebMarkupContainer treePanelContainer = new WebMarkupContainer(ID_TREE_PANEL_CONTAINER); treePanelContainer.setOutputMarkupId(true); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentDto.java index f6f0ae515de..1a9853c2361 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentDto.java @@ -34,23 +34,23 @@ public class AssignmentDto extends Selectable implements Comparable, Serializable{ private static final long serialVersionUID = 1L; - + private AssignmentType assignment; private UserDtoStatus status; private AssignmentType oldAssignment; // private RelationTypes relationType; - + public static final String F_VALUE = "assignment"; public static final String F_RELATION_TYPE = "relationType"; - + public AssignmentDto(AssignmentType assignment, UserDtoStatus status) { this.assignment = assignment; this.oldAssignment = assignment.clone(); this.status = status; } - + /** - * + * * @return true if this is an assignment of a RoleType, OrgType, ServiceType or Resource * @return false if this is an assignment of a User(delegation, deputy) or PolicyRules */ @@ -58,44 +58,44 @@ public boolean isAssignableObject(){ if (assignment.getPersonaConstruction() != null) { return false; } - + if (assignment.getPolicyRule() != null) { return false; } - + //TODO: uncomment when GDPR is in // if (assignment.getTargetRef() != null && assignment.getTargetRef().getRelation().equals(SchemaConstants.ORG_CONSENT)) { // return false; // } - + return true; } - + public Collection computeAssignmentDelta() { Collection deltas = oldAssignment.asPrismContainerValue().diff(assignment.asPrismContainerValue()); return deltas; } - + public void revertChanges() { assignment = oldAssignment.clone(); } - + public QName getRelation() { - + //TODO: what kind of rlation should be returned for the PERSONA CONSTRUCTION? - + if (assignment.getConstruction() != null) { return SchemaConstants.ORG_DEFAULT; } - + if (assignment.getTargetRef() == null) { return null; } - + return assignment.getTargetRef().getRelation(); - + } - + public QName getTargetType() { if (assignment.getTarget() != null) { // object assignment @@ -106,7 +106,7 @@ public QName getTargetType() { if (assignment.getPolicyRule() != null){ return PolicyRuleType.COMPLEX_TYPE; } - + if (assignment.getPersonaConstruction() != null) { return PersonaConstructionType.COMPLEX_TYPE; } @@ -114,20 +114,20 @@ public QName getTargetType() { return ConstructionType.COMPLEX_TYPE; } - + public RelationTypes getRelationType() { return RelationTypes.getRelationType(getRelation()); } - + public void setRelationType(RelationTypes relationType){ if (assignment.getTargetRef() == null) { return; } - + assignment.getTargetRef().setRelation(relationType.getRelation()); } - - + + public AssignmentType getAssignment() { return assignment; } @@ -141,13 +141,13 @@ public int compareTo(AssignmentDto other) { return String.CASE_INSENSITIVE_ORDER.compare(name1, name2); } - + public UserDtoStatus getStatus() { return status; } - + public void setStatus(UserDtoStatus status) { this.status = status; } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentEditorDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentEditorDto.java index 1d0c4c5f9a6..a1fcfb54f76 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentEditorDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentEditorDto.java @@ -55,7 +55,7 @@ /** * TODO: unify with AssignmentItemDto - * + * * @author lazyman */ public class AssignmentEditorDto extends SelectableBean implements Comparable, Serializable { @@ -385,7 +385,7 @@ private ObjectViewDto loadTenantOrgReference(AssignmentType assignment, ObjectRe dto = new ObjectViewDto(ObjectViewDto.BAD_OID); dto.setType(OrgType.class); } - + return dto; } } @@ -629,7 +629,7 @@ public void setDescription(String description) { public void setFocusType(QName focusType) { newAssignment.setFocusType(focusType); } - + public Boolean isOrgUnitManager() { return isOrgUnitManager; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentEditorDtoType.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentEditorDtoType.java index 0f0b54afaeb..c742fee4de7 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentEditorDtoType.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentEditorDtoType.java @@ -29,7 +29,7 @@ public enum AssignmentEditorDtoType { ORG_UNIT(OrgType.class, OrgType.COMPLEX_TYPE, GuiStyleConstants.CLASS_OBJECT_ORG_ICON), ROLE(RoleType.class, RoleType.COMPLEX_TYPE, GuiStyleConstants.CLASS_OBJECT_ROLE_ICON), - + SERVICE(ServiceType.class, ServiceType.COMPLEX_TYPE, GuiStyleConstants.CLASS_OBJECT_SERVICE_ICON), USER(UserType.class, UserType.COMPLEX_TYPE, GuiStyleConstants.CLASS_OBJECT_USER_ICON), @@ -37,7 +37,7 @@ public enum AssignmentEditorDtoType { CONSTRUCTION(null, ConstructionType.COMPLEX_TYPE, GuiStyleConstants.CLASS_OBJECT_RESOURCE_ICON), POLICY_RULE(null, PolicyRuleType.COMPLEX_TYPE, GuiStyleConstants.CLASS_FILE_TEXT), - + PERSONA_CONSTRUCTION(null, PersonaConstructionType.COMPLEX_TYPE, GuiStyleConstants.CLASS_OBJECT_USER_ICON); private Class type; @@ -71,7 +71,7 @@ public static AssignmentEditorDtoType getType(Class type) throw new IllegalArgumentException("Unknown assignment type '" + type.getName() + "'."); } - + public static AssignmentEditorDtoType getType(QName type) { if (type == null) { return CONSTRUCTION; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentEditorPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentEditorPanel.java index 9f2d6decaa8..da9d7305b7f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentEditorPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentEditorPanel.java @@ -629,9 +629,9 @@ public boolean isVisible(){ WebComponentUtil.addAjaxOnUpdateBehavior(body); } - + private void updateAssignmentName(AjaxRequestTarget target, Boolean isManager){ - + Label nameLabel = new Label(ID_NAME_LABEL, createAssignmentNameLabelModel(isManager)); nameLabel.setOutputMarkupId(true); AjaxLink name = (AjaxLink) get(createComponentPath(ID_HEADER_ROW, ID_NAME)); 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 36b5acf9de3..a5d402d1b61 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 @@ -184,17 +184,17 @@ protected AssignmentsTabStorage getAssignmentsStorage() { protected List> initBasicColumns() { List> columns = new ArrayList<>(); - + columns.add(new CheckBoxHeaderColumn()); columns.add(new IconColumn(Model.of("")) { - + private static final long serialVersionUID = 1L; @Override protected IModel createIconModel(IModel rowModel) { return new AbstractReadOnlyModel() { - + private static final long serialVersionUID = 1L; @Override @@ -203,9 +203,9 @@ public String getObject() { } }; } - - }); - + + }); + columns.add(new LinkColumn(createStringResource("PolicyRulesPanel.nameColumn")){ private static final long serialVersionUID = 1L; @@ -216,7 +216,7 @@ protected IModel createLinkModel(IModel rowModel) { return createStringResource("AssignmentPanel.noName"); } return Model.of(name); - + } @Override @@ -224,14 +224,14 @@ public void onClick(AjaxRequestTarget target, IModel rowModel) { assignmentDetailsPerformed(target, rowModel); } }); - + columns.add(new LinkColumn(createStringResource("AssignmentType.activation")){ private static final long serialVersionUID = 1L; @Override protected IModel createLinkModel(IModel rowModel) { return AssignmentsUtil.createActivationTitleModelExperimental(rowModel, AssignmentPanel.this); - + } @Override @@ -239,7 +239,7 @@ public void onClick(AjaxRequestTarget target, IModel rowModel) { updateAssignmnetActivation(target, rowModel); } }); - + // columns.add(new IconColumn(Model.of("")){ // private static final long serialVersionUID = 1L; // @@ -272,17 +272,17 @@ public void onClick(AjaxRequestTarget target, IModel rowModel) { // } // // }); - - - + + + columns.addAll(initColumns()); return columns; } - + protected abstract List> initColumns(); protected abstract void newAssignmentClickPerformed(AjaxRequestTarget target); - + protected void initCustomLayout(WebMarkupContainer assignmentsContainer) { } @@ -344,7 +344,7 @@ public void onClick(AjaxRequestTarget ajaxRequestTarget) { } }; details.add(doneButton); - + AjaxButton cancelButton = new AjaxButton(ID_CANCEL_BUTTON, createStringResource("AssignmentPanel.cancelButton")) { private static final long serialVersionUID = 1L; @@ -439,10 +439,10 @@ protected void updateAssignmnetActivation(AjaxRequestTarget target, IModel(rowModel, AssignmentDto.F_VALUE + "." + AssignmentType.F_ACTIVATION.getLocalPart())); activationPanel.setOutputMarkupId(true); - + getParentPage().showMainPopup(activationPanel, target); } - + protected abstract TableId getTableId(); protected abstract int getItemsPerPage(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentTablePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentTablePanel.java index e9099b46769..8b6df434396 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentTablePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentTablePanel.java @@ -218,7 +218,7 @@ public void onClick(AjaxRequestTarget target) { @Override protected void addPerformed(AjaxRequestTarget target, List selected, QName relation) { super.addPerformed(target, selected, relation); - addSelectedAssignablePerformed(target, selected, relation, + addSelectedAssignablePerformed(target, selected, relation, getPageBase().getMainPopup().getId()); reloadMainFormButtons(target); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentsUtil.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentsUtil.java index c3131783574..f9bf642b75a 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentsUtil.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentsUtil.java @@ -73,24 +73,24 @@ public String getObject() { } }; } - + public static IModel createActivationTitleModelExperimental(IModel model, BasePanel basePanel) { return createActivationTitleModelExperimental(model.getObject(), basePanel); } - + public static IModel createActivationTitleModelExperimental(AssignmentDto model, BasePanel basePanel) { - + // AssignmentDto assignmentDto = model.getObject(); ActivationType activation = model.getAssignment().getActivation(); if (activation == null) { return basePanel.createStringResource("lower.ActivationStatusType.null"); } - + TimeIntervalStatusType timeIntervalStatus = activation.getValidityStatus(); if (timeIntervalStatus != null) { return createTimeIntervalStatusMessage(timeIntervalStatus, activation, basePanel); } - + ActivationStatusType status = activation.getEffectiveStatus(); if (activation.getValidFrom() != null && activation.getValidTo() != null) { @@ -105,9 +105,9 @@ public static IModel createActivationTitleModelExperimental(AssignmentDt } return basePanel.createStringResource(status); - + } - + private static IModel createTimeIntervalStatusMessage(TimeIntervalStatusType timeIntervalStatus, ActivationType activation, BasePanel basePanel) { switch (timeIntervalStatus) { case AFTER: @@ -156,7 +156,7 @@ public void setObject(Date object) { // } // }; // } - + public static IModel createAssignmentStatusClassModel(final IModel model) { return new AbstractReadOnlyModel() { private static final long serialVersionUID = 1L; @@ -168,7 +168,7 @@ public String getObject() { } }; } - + public static IModel createAssignmentStatusClassModel(final UserDtoStatus model) { return new AbstractReadOnlyModel() { private static final long serialVersionUID = 1L; @@ -220,7 +220,7 @@ public String getObject() { } }; } - + public static String getName(AssignmentType assignment, PageBase pageBase) { if (assignment == null) { return null; @@ -248,27 +248,27 @@ public static String getName(AssignmentType assignment, PageBase pageBase) { sb.append(WebComponentUtil.getEffectiveName(assignment.getTarget(), OrgType.F_DISPLAY_NAME)); } else if (assignment.getTargetRef() != null) { sb.append(WebComponentUtil.getEffectiveName(assignment.getTargetRef(), OrgType.F_DISPLAY_NAME, pageBase, "loadTargetName")); - } + } appendTenantAndOrgName(assignment, sb, pageBase); appendRelation(assignment, sb); return sb.toString(); } - + private static void appendTenantAndOrgName(AssignmentType assignmentType, StringBuilder sb, PageBase pageBase) { ObjectReferenceType tenantRef = assignmentType.getTenantRef(); if (tenantRef != null) { WebComponentUtil.getEffectiveName(tenantRef, OrgType.F_DISPLAY_NAME, pageBase, "loadTargetName"); } - + ObjectReferenceType orgRef = assignmentType.getOrgRef(); if (orgRef != null) { WebComponentUtil.getEffectiveName(orgRef, OrgType.F_DISPLAY_NAME, pageBase, "loadTargetName"); } } - + private static void appendRelation(AssignmentType assignment, StringBuilder sb) { if (assignment.getTargetRef() == null) { return; @@ -276,7 +276,7 @@ private static void appendRelation(AssignmentType assignment, StringBuilder sb) sb.append(" - " + RelationTypes.getRelationType(assignment.getTargetRef().getRelation()).getHeaderLabel()); } - + public static AssignmentEditorDtoType getType(AssignmentType assignment) { if (assignment.getTarget() != null) { // object assignment @@ -287,7 +287,7 @@ public static AssignmentEditorDtoType getType(AssignmentType assignment) { if (assignment.getPolicyRule() != null){ return AssignmentEditorDtoType.POLICY_RULE; } - + if (assignment.getPersonaConstruction() != null) { return AssignmentEditorDtoType.PERSONA_CONSTRUCTION; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/GdprAssignmentPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/GdprAssignmentPanel.java index 641f182a30e..9f2be0f4c82 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/GdprAssignmentPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/GdprAssignmentPanel.java @@ -25,29 +25,29 @@ public class GdprAssignmentPanel extends AbstractRoleAssignmentPanel{ private static final long serialVersionUID = 1L; - + public GdprAssignmentPanel(String id, IModel> assignmentsModel, PageBase pageBase) { super(id, assignmentsModel, pageBase); } - + @Override protected List> initColumns() { List> columns = new ArrayList<>(); columns.add(new PropertyColumn<>(createStringResource("AssignmentType.lifecycle"), AssignmentDto.F_VALUE + "." + AssignmentType.F_LIFECYCLE_STATE.getLocalPart())); - + columns.add(new CheckBoxColumn(createStringResource("AssignmnetType.accepted")) { - + private static final long serialVersionUID = 1L; @Override protected IModel getEnabled() { return Model.of(Boolean.FALSE); } - + @Override protected IModel getCheckBoxValueModel(IModel rowModel) { return new AbstractReadOnlyModel() { - + private static final long serialVersionUID = 1L; @Override @@ -57,18 +57,18 @@ public Boolean getObject() { if (assignmentType.getLifecycleState() == null) { return Boolean.FALSE; } - + if (assignmentType.getLifecycleState().equals(SchemaConstants.LIFECYCLE_ACTIVE)) { return Boolean.TRUE; } - + return Boolean.FALSE; } }; } - + }); - + return columns; } @@ -76,13 +76,13 @@ public Boolean getObject() { protected boolean isRelationVisible() { return false; } - + @Override protected void addSelectedAssignmentsPerformed(AjaxRequestTarget target, List assignmentsList, QName relation) { super.addSelectedAssignmentsPerformed(target, assignmentsList, SchemaConstants.ORG_CONSENT); } - - - + + + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/PolicyRuleDetailsPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/PolicyRuleDetailsPanel.java index 5708ac996f5..728738b12ea 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/PolicyRuleDetailsPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/PolicyRuleDetailsPanel.java @@ -33,18 +33,18 @@ */ public class PolicyRuleDetailsPanel extends AbstractAssignmentDetailsPanel { private static final long serialVersionUID = 1L; - + private static final String ID_POLICY_RULE = "policyRule"; private static List hiddenItems = new ArrayList<>(); - + static { hiddenItems.add(AssignmentType.F_TENANT_REF); hiddenItems.add(AssignmentType.F_ORG_REF); hiddenItems.add(AssignmentType.F_FOCUS_TYPE); hiddenItems.add(ID_PROPERTIES_PANEL); }; - + public PolicyRuleDetailsPanel(String id, Form form, IModel model, PageBase pageBase){ super(id, form, model, pageBase); } @@ -53,13 +53,13 @@ public PolicyRuleDetailsPanel(String id, Form form, IModel mod protected List getHiddenItems() { return hiddenItems; } - + @Override protected void initPropertiesPanel(WebMarkupContainer propertiesPanel) { PolicyRulePropertiesPanel policyDetails = new PolicyRulePropertiesPanel(ID_POLICY_RULE, getModel(), pageBase); policyDetails.setOutputMarkupId(true); policyDetails.add(new VisibleEnableBehaviour() { - + private static final long serialVersionUID = 1L; @Override @@ -69,5 +69,5 @@ public boolean isVisible() { }); propertiesPanel.add(policyDetails); } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/PolicyRulePropertiesPanel.html b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/PolicyRulePropertiesPanel.html index 77cbcbe7a2d..b6195f843d1 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/PolicyRulePropertiesPanel.html +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/PolicyRulePropertiesPanel.html @@ -20,7 +20,31 @@
-
+
+
+
+
+
+
+
+
+
+
+ + + +
+
+
diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/PolicyRulePropertiesPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/PolicyRulePropertiesPanel.java index 5ed774c68a0..098e0807eb4 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/PolicyRulePropertiesPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/PolicyRulePropertiesPanel.java @@ -17,18 +17,16 @@ import com.evolveum.midpoint.gui.api.component.BasePanel; import com.evolveum.midpoint.gui.api.page.PageBase; -import com.evolveum.midpoint.prism.PrismContainer; +import com.evolveum.midpoint.web.component.AjaxButton; import com.evolveum.midpoint.web.component.form.multivalue.MultiValueExpandablePanel; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AbstractPolicyConstraintType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ExclusionPolicyConstraintType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.PolicyConstraintsType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.PolicyRuleType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import java.util.ArrayList; -import java.util.List; /** * Created by honchar @@ -37,9 +35,23 @@ * */ public class PolicyRulePropertiesPanel extends BasePanel{ - private static final String ID_CONSTRAINTS_VALUE = "constraintsValue"; + private static final String ID_CONSTRAINTS_CONTAINER = "constraintsContainer"; + private static final String ID_EXCLUSION_CONSTRAINTS = "exclusionConstraints"; + private static final String ID_MIN_ASSIGNEES_CONSTRAINTS = "minAssigneesConstraints"; + private static final String ID_MAX_ASSIGNEES_CONSTRAINTS = "maxAssigneesConstraints"; + private static final String ID_MODIFICATION_CONSTRAINTS = "modificationConstraints"; + private static final String ID_ASSIGNMENT_CONSTRAINTS = "assignmentConstraints"; + private static final String ID_TIME_VALIDITY_CONSTRAINTS = "timeValidityConstraints"; + private static final String ID_SITUATION_CONSTRAINTS = "situationConstraints"; private static final String ID_SITUATION_VALUE = "situationValue"; private static final String ID_ACTION_VALUE = "actionValue"; + private static final String ID_ADD_EXCLUSION = "addExclusionConstraints"; + private static final String ID_ADD_MIN_ASSIGNEES = "addMinAssigneesConstraints"; + private static final String ID_ADD_MAX_ASSIGNEES = "addMaxAssigneesConstraints"; + private static final String ID_ADD_MODIFICATION = "addModificationConstraints"; + private static final String ID_ADD_ASSIGNMENT = "addAssignmentConstraints"; + private static final String ID_ADD_TIME_VALIDITY = "addTimeValidityConstraints"; + private static final String ID_ADD_SITUATION = "addSituationConstraints"; private PageBase pageBase; @@ -52,42 +64,163 @@ public PolicyRulePropertiesPanel(String id, IModel policyRuleMode private void initLayout(){ AssignmentDto policyRuleDto = getModelObject(); - PolicyRuleType policyRuleContainer = policyRuleDto.getAssignment().getPolicyRule(); - add(new MultiValueExpandablePanel(ID_CONSTRAINTS_VALUE, - Model.ofList(getAllPolicyConstraintsList(policyRuleContainer.getPolicyConstraints())))); + WebMarkupContainer constraintsContainer = new WebMarkupContainer(ID_CONSTRAINTS_CONTAINER); + constraintsContainer.setOutputMarkupId(true); + add(constraintsContainer); - add(new Label(ID_SITUATION_VALUE, Model.of(policyRuleContainer == null ? "" : policyRuleContainer.getPolicySituation()))); + initConstraintsContainer(constraintsContainer); - add(new Label(ID_ACTION_VALUE, Model.of(PolicyRuleUtil.convertPolicyActionsContainerToString(policyRuleContainer)))); + PolicyRuleType policyRule = getPolicyRuleTypeObject(); + add(new Label(ID_SITUATION_VALUE, Model.of(policyRule == null ? "" : policyRule.getPolicySituation()))); + + add(new Label(ID_ACTION_VALUE, Model.of(PolicyRuleUtil.convertPolicyActionsContainerToString(policyRule)))); + + constraintsContainer.add(new AjaxButton(ID_ADD_EXCLUSION) { + @Override + public void onClick(AjaxRequestTarget ajaxRequestTarget) { + addNewExclusionPerformed(ajaxRequestTarget); + } + }); + constraintsContainer.add(new AjaxButton(ID_ADD_MIN_ASSIGNEES) { + @Override + public void onClick(AjaxRequestTarget ajaxRequestTarget) { + addNewMinAssigneesPerformed(ajaxRequestTarget); + } + }); + constraintsContainer.add(new AjaxButton(ID_ADD_MAX_ASSIGNEES) { + @Override + public void onClick(AjaxRequestTarget ajaxRequestTarget) { + addNewMaxAssigneesPerformed(ajaxRequestTarget); + } + }); + constraintsContainer.add(new AjaxButton(ID_ADD_MODIFICATION) { + @Override + public void onClick(AjaxRequestTarget ajaxRequestTarget) { + addNewModificationPerformed(ajaxRequestTarget); + } + }); + constraintsContainer.add(new AjaxButton(ID_ADD_ASSIGNMENT) { + @Override + public void onClick(AjaxRequestTarget ajaxRequestTarget) { + addNewAssignmentPerformed(ajaxRequestTarget); + } + }); + constraintsContainer.add(new AjaxButton(ID_ADD_TIME_VALIDITY) { + @Override + public void onClick(AjaxRequestTarget ajaxRequestTarget) { + addNewTimeValidityPerformed(ajaxRequestTarget); + } + }); + constraintsContainer.add(new AjaxButton(ID_ADD_SITUATION) { + @Override + public void onClick(AjaxRequestTarget ajaxRequestTarget) { + addNewSituationPerformed(ajaxRequestTarget); + } + }); } - private List getAllPolicyConstraintsList(PolicyConstraintsType constraintsType){ - List constraintsList = new ArrayList<>(); - if (constraintsType == null){ - return constraintsList; + private void initConstraintsContainer(WebMarkupContainer constraintsContainer){ + PolicyConstraintsType policyConstraints = getPolicyConstraints(); + constraintsContainer.addOrReplace(new MultiValueExpandablePanel(ID_EXCLUSION_CONSTRAINTS, + Model.ofList(policyConstraints == null || policyConstraints.getExclusion() == null ? new ArrayList<>() : policyConstraints.getExclusion()), pageBase)); + constraintsContainer.addOrReplace(new MultiValueExpandablePanel(ID_MIN_ASSIGNEES_CONSTRAINTS, + Model.ofList(policyConstraints == null || policyConstraints.getMinAssignees() == null ? new ArrayList<>() : policyConstraints.getMinAssignees()), pageBase)); + constraintsContainer.addOrReplace(new MultiValueExpandablePanel(ID_MAX_ASSIGNEES_CONSTRAINTS, + Model.ofList(policyConstraints == null || policyConstraints.getMaxAssignees() == null ? new ArrayList<>() : policyConstraints.getMaxAssignees()), pageBase)); + constraintsContainer.addOrReplace(new MultiValueExpandablePanel(ID_MODIFICATION_CONSTRAINTS, + Model.ofList(policyConstraints == null || policyConstraints.getModification() == null ? new ArrayList<>() : policyConstraints.getModification()), pageBase)); + constraintsContainer.addOrReplace(new MultiValueExpandablePanel(ID_ASSIGNMENT_CONSTRAINTS, + Model.ofList(policyConstraints == null || policyConstraints.getAssignment() == null ? new ArrayList<>() : policyConstraints.getAssignment()), pageBase)); + constraintsContainer.addOrReplace(new MultiValueExpandablePanel(ID_TIME_VALIDITY_CONSTRAINTS, + Model.ofList(policyConstraints == null || policyConstraints.getTimeValidity() == null ? new ArrayList<>() : policyConstraints.getTimeValidity()), pageBase)); + constraintsContainer.addOrReplace(new MultiValueExpandablePanel(ID_SITUATION_CONSTRAINTS, + Model.ofList(policyConstraints == null || policyConstraints.getSituation() == null ? new ArrayList<>() : policyConstraints.getSituation()), pageBase)); + + } + + private void addNewExclusionPerformed(AjaxRequestTarget target){ + if (getPolicyConstraints().getExclusion() == null){ + getPolicyConstraints().createExclusionList(); } - if (constraintsType.getExclusion() != null){ - constraintsList.addAll(constraintsType.getExclusion()); + getPolicyConstraints().getExclusion().add(new ExclusionPolicyConstraintType()); + initConstraintsContainer(getConstraintsContainer()); + target.add(getConstraintsContainer()); + } + + private void addNewMinAssigneesPerformed(AjaxRequestTarget target){ + if (getPolicyConstraints().getMinAssignees() == null){ + getPolicyConstraints().createMinAssigneesList(); } - if (constraintsType.getMinAssignees() != null){ - constraintsList.addAll(constraintsType.getMinAssignees()); + getPolicyConstraints().getMinAssignees().add(new MultiplicityPolicyConstraintType()); + initConstraintsContainer(getConstraintsContainer()); + target.add(getConstraintsContainer()); + } + + private void addNewMaxAssigneesPerformed(AjaxRequestTarget target){ + if (getPolicyConstraints().getMaxAssignees() == null){ + getPolicyConstraints().createMaxAssigneesList(); } - if (constraintsType.getMaxAssignees() != null){ - constraintsList.addAll(constraintsType.getMaxAssignees()); + getPolicyConstraints().getMaxAssignees().add(new MultiplicityPolicyConstraintType()); + initConstraintsContainer(getConstraintsContainer()); + target.add(getConstraintsContainer()); + } + + private void addNewModificationPerformed(AjaxRequestTarget target){ + if (getPolicyConstraints().getModification() == null){ + getPolicyConstraints().createModificationList(); } - if (constraintsType.getModification() != null){ - constraintsList.addAll(constraintsType.getModification()); + getPolicyConstraints().getModification().add(new ModificationPolicyConstraintType()); + initConstraintsContainer(getConstraintsContainer()); + target.add(getConstraintsContainer()); + } + + private void addNewTimeValidityPerformed(AjaxRequestTarget target){ + if (getPolicyConstraints().getTimeValidity() == null){ + getPolicyConstraints().createTimeValidityList(); } - if (constraintsType.getAssignment() != null){ - constraintsList.addAll(constraintsType.getAssignment()); + getPolicyConstraints().getTimeValidity().add(new TimeValidityPolicyConstraintType()); + initConstraintsContainer(getConstraintsContainer()); + target.add(getConstraintsContainer()); + } + + private void addNewAssignmentPerformed(AjaxRequestTarget target){ + if (getPolicyConstraints().getAssignment() == null){ + getPolicyConstraints().createAssignmentList(); + } + getPolicyConstraints().getAssignment().add(new AssignmentPolicyConstraintType()); + initConstraintsContainer(getConstraintsContainer()); + target.add(getConstraintsContainer()); + } + + private void addNewSituationPerformed(AjaxRequestTarget target){ + if (getPolicyConstraints().getSituation() == null){ + getPolicyConstraints().createSituationList(); } - if (constraintsType.getTimeValidity() != null){ - constraintsList.addAll(constraintsType.getTimeValidity()); + getPolicyConstraints().getSituation().add(new PolicySituationPolicyConstraintType()); + initConstraintsContainer(getConstraintsContainer()); + target.add(getConstraintsContainer()); + } + + private PolicyConstraintsType getPolicyConstraints(){ + PolicyRuleType policyRule = getPolicyRuleTypeObject(); + PolicyConstraintsType constraints = policyRule.getPolicyConstraints(); + if (constraints == null){ + policyRule.setPolicyConstraints(new PolicyConstraintsType()); } - if (constraintsType.getSituation() != null){ - constraintsList.addAll(constraintsType.getSituation()); + return policyRule.getPolicyConstraints(); + } + + private PolicyRuleType getPolicyRuleTypeObject(){ + PolicyRuleType policyRule = getModelObject().getAssignment().getPolicyRule(); + if (policyRule == null){ + getModelObject().getAssignment().setPolicyRule(new PolicyRuleType()); } - return constraintsList; + return getModelObject().getAssignment().getPolicyRule(); } + + private WebMarkupContainer getConstraintsContainer(){ + return (WebMarkupContainer) get(ID_CONSTRAINTS_CONTAINER); + } + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/PolicyRuleUtil.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/PolicyRuleUtil.java index a7726de9d23..522190837ee 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/PolicyRuleUtil.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/PolicyRuleUtil.java @@ -69,6 +69,7 @@ public static String getPolicyConstraintsAsString(PolicyConstraintsType policyCo } } if (policyConstraints.getMinAssignees() != null){ + addNewLineIfNotEmpty(policyConstraintsString); for (MultiplicityPolicyConstraintType multiplicity : policyConstraints.getMinAssignees()){ policyConstraintsString.append(getMultiplicityPolicyConstraintTypeAsString(multiplicity, PolicyConstraintsType.F_MIN_ASSIGNEES.getLocalPart())); if (policyConstraints.getMinAssignees().indexOf(multiplicity) < policyConstraints.getMinAssignees().size() - 1){ @@ -77,6 +78,7 @@ public static String getPolicyConstraintsAsString(PolicyConstraintsType policyCo } } if (policyConstraints.getMaxAssignees() != null){ + addNewLineIfNotEmpty(policyConstraintsString); for (MultiplicityPolicyConstraintType multiplicity : policyConstraints.getMaxAssignees()){ policyConstraintsString.append(getMultiplicityPolicyConstraintTypeAsString(multiplicity, PolicyConstraintsType.F_MAX_ASSIGNEES.getLocalPart())); if (policyConstraints.getMinAssignees().indexOf(multiplicity) < policyConstraints.getMinAssignees().size() - 1){ @@ -85,6 +87,7 @@ public static String getPolicyConstraintsAsString(PolicyConstraintsType policyCo } } if (policyConstraints.getModification() != null){ + addNewLineIfNotEmpty(policyConstraintsString); for (ModificationPolicyConstraintType modification : policyConstraints.getModification()){ policyConstraintsString.append(getModificationAsString(modification)); if (policyConstraints.getModification().indexOf(modification) < policyConstraints.getModification().size() - 1){ @@ -93,6 +96,7 @@ public static String getPolicyConstraintsAsString(PolicyConstraintsType policyCo } } if (policyConstraints.getAssignment() != null){ + addNewLineIfNotEmpty(policyConstraintsString); for (AssignmentPolicyConstraintType assignment : policyConstraints.getAssignment()){ policyConstraintsString.append(getAssignmentAsString(assignment)); if (policyConstraints.getAssignment().indexOf(assignment) < policyConstraints.getAssignment().size() - 1){ @@ -101,6 +105,7 @@ public static String getPolicyConstraintsAsString(PolicyConstraintsType policyCo } } if (policyConstraints.getTimeValidity() != null){ + addNewLineIfNotEmpty(policyConstraintsString); for (TimeValidityPolicyConstraintType timeValidity : policyConstraints.getTimeValidity()){ policyConstraintsString.append(getTimeValidityAsString(timeValidity)); if (policyConstraints.getTimeValidity().indexOf(timeValidity) < policyConstraints.getTimeValidity().size() - 1){ @@ -109,6 +114,7 @@ public static String getPolicyConstraintsAsString(PolicyConstraintsType policyCo } } if (policyConstraints.getSituation() != null){ + addNewLineIfNotEmpty(policyConstraintsString); for (PolicySituationPolicyConstraintType situation : policyConstraints.getSituation()){ policyConstraintsString.append(getSituationAsString(situation)); if (policyConstraints.getSituation().indexOf(situation) < policyConstraints.getSituation().size() - 1){ @@ -217,12 +223,14 @@ public static String getExclusionAsString(ExclusionPolicyConstraintType exclusio if (exclusion == null){ return ""; } - StringBuilder sb = new StringBuilder(PolicyConstraintsType.F_EXCLUSION.getLocalPart()); + StringBuilder sb = new StringBuilder(PolicyConstraintsType.F_EXCLUSION.getLocalPart() + ":"); if (exclusion.getTargetRef() != null){ - sb.append(" ").append(WebModelServiceUtils.resolveReferenceName(exclusion.getTargetRef(), pageBase)); + sb.append(" ").append(ExclusionPolicyConstraintType.F_TARGET_REF.getLocalPart() + " " + + WebModelServiceUtils.resolveReferenceName(exclusion.getTargetRef(), pageBase) + ";"); } if (exclusion.getPolicy() != null){ - sb.append(" ").append(exclusion.getPolicy().value()); + sb.append(" ").append(ExclusionPolicyConstraintType.F_POLICY.getLocalPart() + " " + + exclusion.getPolicy().value() + ";"); } return sb.toString(); } @@ -263,4 +271,10 @@ public static String getPolicyActionsAsString(PolicyActionsType policyActions){ } return sb.toString(); } + + private static void addNewLineIfNotEmpty(StringBuilder sb){ + if (sb.length() > 0){ + sb.append("\n"); + } + } } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/PolicyRulesPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/PolicyRulesPanel.java index 89443799cc7..0b71b604314 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/PolicyRulesPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/PolicyRulesPanel.java @@ -24,6 +24,7 @@ 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.markup.html.basic.Label; +import org.apache.wicket.markup.html.basic.MultiLineLabel; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; @@ -51,15 +52,15 @@ * @author katkav */ public class PolicyRulesPanel extends AssignmentPanel { - + private static final long serialVersionUID = 1L; - - + + public PolicyRulesPanel(String id, IModel> policyRulesModel, PageBase pageBase){ super(id, policyRulesModel, pageBase); - + } - + protected List> initColumns() { List> columns = new ArrayList<>(); columns.add(new AbstractColumn(createStringResource("PolicyRulesPanel.constraintsColumn")){ @@ -69,7 +70,7 @@ protected List> initColumns() { public void populateItem(Item> cellItem, String componentId, final IModel rowModel) { PolicyRuleType policyRuleType = rowModel.getObject().getAssignment().getPolicyRule(); - cellItem.add(new Label(componentId, Model.of(PolicyRuleUtil.convertPolicyConstraintsContainerToString(policyRuleType, getParentPage())))); + cellItem.add(new MultiLineLabel(componentId, Model.of(PolicyRuleUtil.convertPolicyConstraintsContainerToString(policyRuleType, getParentPage())))); } }); @@ -92,7 +93,7 @@ public void populateItem(Item> cellItem, String co public void populateItem(Item> cellItem, String componentId, final IModel rowModel) { PolicyRuleType policyRuleType = rowModel.getObject().getAssignment().getPolicyRule(); - cellItem.add(new Label(componentId, Model.of(PolicyRuleUtil.convertPolicyActionsContainerToString(policyRuleType)))); + cellItem.add(new MultiLineLabel(componentId, Model.of(PolicyRuleUtil.convertPolicyActionsContainerToString(policyRuleType)))); } }); @@ -116,11 +117,11 @@ public void populateItem(Item> cellItem, String co }); return columns; } - + @Override protected void initPaging() { getPolicyRulesTabStorage().setPaging(ObjectPaging.createPaging(0, getItemsPerPage())); - + } @Override @@ -140,7 +141,7 @@ private AssignmentsTabStorage getPolicyRulesTabStorage(){ @Override protected void newAssignmentClickPerformed(AjaxRequestTarget target) { // TODO Auto-generated method stub - + } @Override diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/SelfConsentPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/SelfConsentPanel.java index a4fdc7bb8d6..b72455b99e0 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/SelfConsentPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/SelfConsentPanel.java @@ -29,51 +29,51 @@ public class SelfConsentPanel extends BasePanel{ private static final long serialVersionUID = 1L; - + private static final String ID_DISPLAY_NAME = "displayName"; private static final String ID_CONSENT_ICON = "consentIcon"; private static final String ID_VALIDITY = "validity"; - + private static final String ID_REVOKE = "revoke"; private static final String ID_AGREE = "agree"; - + private static final String DOT_CLASS = SelfConsentPanel.class.getSimpleName() + "."; private static final String OPERATION_LOAD_TARGET = DOT_CLASS + "loadTargetRef"; // private PageBase parentPage; public SelfConsentPanel(String id, IModel model, PageBase parentPage) { super(id, model); - + Task task = parentPage.createSimpleTask(OPERATION_LOAD_TARGET); OperationResult result = task.getResult(); PrismObject abstractRole = WebModelServiceUtils .loadObject(getModelObject().getAssignment().getTargetRef(), parentPage, task, result); - + if (abstractRole == null) { getSession().error("Failed to load target ref"); throw new RestartResponseException(PageSelfDashboard.class); } - + initLayout(abstractRole.asObjectable()); } - + private void initLayout(final AbstractRoleType abstractRole) { - + DisplayNamePanel displayName = new DisplayNamePanel<>(ID_DISPLAY_NAME, Model.of(abstractRole)); displayName.setOutputMarkupId(true); add(displayName); - + WebMarkupContainer iconCssClass = new WebMarkupContainer(ID_CONSENT_ICON); iconCssClass.add(AttributeAppender.append("class", getIconCssClass(getModelObject()))); iconCssClass.setOutputMarkupId(true); add(iconCssClass); - + Label validityLabel = new Label(ID_VALIDITY, AssignmentsUtil.createActivationTitleModelExperimental(getModel(), displayName)); validityLabel.setOutputMarkupId(true); add(validityLabel); - + AjaxButton revoke = new AjaxButton(ID_REVOKE, createStringResource("SelfConsentPanel.button.revoke")) { - + private static final long serialVersionUID = 1L; @Override @@ -84,7 +84,7 @@ public void onClick(AjaxRequestTarget target) { }; add(revoke); revoke.add(new VisibleEnableBehaviour() { - + private static final long serialVersionUID = 1L; @Override @@ -92,9 +92,9 @@ public boolean isVisible() { return isActiveConsent(); } }); - + AjaxButton activate = new AjaxButton(ID_AGREE, createStringResource("SelfConsentPanel.button.agree")) { - + private static final long serialVersionUID = 1L; @Override @@ -105,7 +105,7 @@ public void onClick(AjaxRequestTarget target) { }; add(activate); activate.add(new VisibleEnableBehaviour() { - + private static final long serialVersionUID = 1L; @Override @@ -114,37 +114,37 @@ public boolean isVisible() { } }); } - - //TODO move to the WebComponentUtil ??? + + //TODO move to the WebComponentUtil ??? private String getIconCssClass(AssignmentDto assignment) { AssignmentType assignmentType = assignment.getAssignment(); String currentLifecycle = assignmentType.getLifecycleState(); if (StringUtils.isBlank(currentLifecycle)) { return GuiStyleConstants.CLASS_APPROVAL_OUTCOME_ICON_FUTURE_COLORED; } - + if (SchemaConstants.LIFECYCLE_DRAFT.equals(currentLifecycle) || SchemaConstants.LIFECYCLE_PROPOSED.equals(currentLifecycle)) { return GuiStyleConstants.CLASS_APPROVAL_OUTCOME_ICON_IN_PROGRESS_COLORED; } - + if (SchemaConstants.LIFECYCLE_ACTIVE.equals(currentLifecycle)) { return GuiStyleConstants.CLASS_APPROVAL_OUTCOME_ICON_APPROVED_COLORED; } - + if (SchemaConstants.LIFECYCLE_FAILED.equals(currentLifecycle)) { return GuiStyleConstants.CLASS_APPROVAL_OUTCOME_ICON_REJECTED_COLORED; } - + return GuiStyleConstants.CLASS_APPROVAL_OUTCOME_ICON_FUTURE_COLORED; } - + private boolean isActiveConsent(){ String lifecycle = SelfConsentPanel.this.getModelObject().getAssignment().getLifecycleState(); if (StringUtils.isBlank(lifecycle)) { return false; } - + return lifecycle.equals(SchemaConstants.LIFECYCLE_ACTIVE); } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/SimpleParametricRoleSelector.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/SimpleParametricRoleSelector.java index 3ac14fc8d11..8deacc0cc75 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/SimpleParametricRoleSelector.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/SimpleParametricRoleSelector.java @@ -133,7 +133,7 @@ private List initParamList(List assignmentDtos) { private String getParamValue(AssignmentDto assignmentDto) { PrismContainerValue newValue = assignmentDto.getAssignment().asPrismContainerValue(); - + if (newValue != null) { PrismProperty paramProp = newValue.findProperty(parameterPath); if (paramProp != null) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/box/InfoBoxPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/box/InfoBoxPanel.java index d80561f67f5..599dceb081e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/box/InfoBoxPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/box/InfoBoxPanel.java @@ -34,7 +34,7 @@ */ public class InfoBoxPanel extends Panel{ private static final long serialVersionUID = 1L; - + private static final String ID_INFO_BOX = "infoBox"; private static final String ID_INFO_BOX_ICON = "infoBoxIcon"; private static final String ID_IMAGE_ID = "imageId"; @@ -51,34 +51,34 @@ public InfoBoxPanel(String id, IModel model) { initLayout(model, null); } - + public InfoBoxPanel(String id, IModel model, Class linkPage) { super(id, model); add(AttributeModifier.append("class", "dashboard-info-box")); initLayout(model, linkPage); } - + private void initLayout(final IModel model, final Class linkPage) { - + WebMarkupContainer infoBox = new WebMarkupContainer(ID_INFO_BOX); add(infoBox); infoBox.add(AttributeModifier.append("class", new PropertyModel(model, InfoBoxType.BOX_BACKGROUND_COLOR))); - + WebMarkupContainer infoBoxIcon = new WebMarkupContainer(ID_INFO_BOX_ICON); infoBox.add(infoBoxIcon); infoBoxIcon.add(AttributeModifier.append("class", new PropertyModel(model, InfoBoxType.ICON_BACKGROUND_COLOR))); - - + + WebMarkupContainer image = new WebMarkupContainer(ID_IMAGE_ID); image.add(AttributeModifier.append("class", new PropertyModel(model, InfoBoxType.IMAGE_ID))); infoBoxIcon.add(image); - + Label message = new Label(ID_MESSAGE, new PropertyModel(model, InfoBoxType.MESSAGE)); infoBox.add(message); - + Label number = new Label(ID_NUMBER, new PropertyModel(model, InfoBoxType.NUMBER)); infoBox.add(number); - + WebMarkupContainer progress = new WebMarkupContainer(ID_PROGRESS); infoBox.add(progress); progress.add(new VisibleEnableBehaviour() { @@ -98,7 +98,7 @@ public boolean isVisible() { if (linkPage != null) { add(new AjaxEventBehavior("click") { private static final long serialVersionUID = 1L; - + @Override protected void onEvent(AjaxRequestTarget target) { setResponsePage(linkPage); @@ -106,6 +106,6 @@ protected void onEvent(AjaxRequestTarget target) { }); } } - - + + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/box/InfoBoxType.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/box/InfoBoxType.java index 0601d965eca..313869925bc 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/box/InfoBoxType.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/box/InfoBoxType.java @@ -31,7 +31,7 @@ public class InfoBoxType implements Serializable{ public static final String NUMBER = "number"; public static final String PROGRESS = "progress"; public static final String DESCRIPTION = "description"; - + private String iconBackgroundColor; private String boxBackgroundColor; private String imageId; @@ -39,21 +39,21 @@ public class InfoBoxType implements Serializable{ private String number; private Integer progress; private String description; - + public InfoBoxType(String boxBackgroundColor, String imageId, String message) { this.boxBackgroundColor = boxBackgroundColor; this.imageId = imageId; this.message = message; } - + public String getIconBackgroundColor() { return iconBackgroundColor; } - + public void setIconBackgroundColor(String iconBackgroundColor) { this.iconBackgroundColor = iconBackgroundColor; } - + public String getBoxBackgroundColor() { return boxBackgroundColor; } @@ -65,7 +65,7 @@ public void setBoxBackgroundColor(String boxBackgroundColor) { public String getImageId() { return imageId; } - + public void setImageId(String imageId) { this.imageId = imageId; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/breadcrumbs/Breadcrumb.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/breadcrumbs/Breadcrumb.java index 1efa60d28f0..3286edb65ea 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/breadcrumbs/Breadcrumb.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/breadcrumbs/Breadcrumb.java @@ -32,13 +32,13 @@ /** * Breadcrumb object that is stored in the session. It represents the way "back" to the main menu. - * + * * We need to be extra careful about the memory references here. This object goes in the session. * Therefore we cannot allow models to be stored in the session. The models may have references * to (possibly big) pages and other rich objects. The references are there mostly to load the * models. But we do not want that. We want to store only the values. Therefore the model values * are copied to simple strings on model detach(). - * + * * @author Viliam Repan (lazyman) * @author semancik */ @@ -108,7 +108,7 @@ public void detach() { Breadcrumb.this.label = label.getObject(); Breadcrumb.this.labelModel = null; } - + }; } @@ -150,7 +150,7 @@ public void detach() { Breadcrumb.this.icon = icon.getObject(); Breadcrumb.this.iconModel = null; } - + }; } @@ -200,7 +200,7 @@ public void detach() { super.detach(); model.getObject(); } - + }; } @@ -240,6 +240,6 @@ public String debugDump(int indent) { } protected void extendsDebugDump(StringBuilder sb, int indent) { - + } } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/breadcrumbs/BreadcrumbPageClass.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/breadcrumbs/BreadcrumbPageClass.java index 9a0d625ae8e..953c19a868f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/breadcrumbs/BreadcrumbPageClass.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/breadcrumbs/BreadcrumbPageClass.java @@ -113,7 +113,7 @@ protected void extendsDebugDump(StringBuilder sb, int indent) { DebugUtil.debugDumpWithLabel(sb, "parameters", parameters==null?null:parameters.toString(), indent+1); } - - - + + + } 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 8c01c08ada1..5732b3e55cd 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 @@ -257,11 +257,11 @@ protected void onPageChanged(AjaxRequestTarget target, long page) { protected void pageSizeChanged(AjaxRequestTarget target) { Table table = findParent(Table.class); UserProfileStorage.TableId tableId = table.getTableId(); - + if (tableId != null) { PageBase page = (PageBase) getPage(); Integer pageSize = page.getSessionStorage().getUserProfile().getPagingSize(tableId); - + table.setItemsPerPage(pageSize); } target.add(findParent(PagingFooter.class)); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/MultiButtonPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/MultiButtonPanel.java index b6804951cc8..197d9b5093c 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/MultiButtonPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/MultiButtonPanel.java @@ -62,7 +62,7 @@ protected void initLayout() { for (int id = 0; id < numberOfButtons; id++) { final int finalId = getButtonId(id); AjaxButton button = new AjaxButton(String.valueOf(finalId), createStringResource(getCaption(finalId))) { - + private static final long serialVersionUID = 1L; @Override public void onClick(AjaxRequestTarget target) { @@ -73,11 +73,11 @@ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { super.updateAjaxAttributes(attributes); attributes.setEventPropagation(AjaxRequestAttributes.EventPropagation.BUBBLE); } - + }; - + button.add(new VisibleEnableBehaviour() { - + private static final long serialVersionUID = 1L; @Override public boolean isEnabled(){ diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/MultiButtonTable.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/MultiButtonTable.java index 5c692512b7f..32928478a35 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/MultiButtonTable.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/MultiButtonTable.java @@ -145,7 +145,7 @@ public boolean isEnabled(){ }); inner.add(new AttributeAppender("title", assignment.getName())); cellContainer.add(inner); - + Label nameLabel = new Label(ID_INNER_LABEL, assignment.getName()); inner.add(nameLabel); @@ -270,7 +270,7 @@ protected String load() { private boolean canAssign(final AssignmentEditorDto assignment) { return assignment.isAssignable(); } - + private void assignmentDetailsPerformed(final AssignmentEditorDto assignment, AjaxRequestTarget target){ if (!plusIconClicked) { assignment.setMinimized(false); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/ObjectDataProvider.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/ObjectDataProvider.java index daa2772abf0..966ac2f06df 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/ObjectDataProvider.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/ObjectDataProvider.java @@ -53,7 +53,7 @@ public class ObjectDataProvider private static final String OPERATION_COUNT_OBJECTS = DOT_CLASS + "countObjects"; private Set selected = new HashSet<>(); - + private Class type; private Collection> options; @@ -63,7 +63,7 @@ public ObjectDataProvider(Component component, Class type) { Validate.notNull(type); this.type = type; } - + public List getSelectedData() { for (Serializable s : super.getAvailableData()){ if (s instanceof SelectableBean) { @@ -77,12 +77,12 @@ public List getSelectedData() { allSelected.addAll(selected); return allSelected; } - - + + @Override public Iterator internalIterator(long first, long count) { LOGGER.trace("begin::iterator() from {} count {}.", new Object[]{first, count}); - + for (W available : getAvailableData()){ if (available instanceof SelectableBean){ SelectableBean selectableBean = (SelectableBean) available; @@ -91,7 +91,7 @@ public Iterator internalIterator(long first, long count) { } } } - + for (W available : getAvailableData()) { if (available instanceof SelectableBean) { SelectableBean selectableBean = (SelectableBean) available; @@ -102,14 +102,14 @@ public Iterator internalIterator(long first, long count) { } } } - + getAvailableData().clear(); OperationResult result = new OperationResult(OPERATION_SEARCH_OBJECTS); try { ObjectPaging paging = createPaging(first, count); Task task = getPage().createSimpleTask(OPERATION_SEARCH_OBJECTS); - + ObjectQuery query = getQuery(); if (query == null){ query = new ObjectQuery(); @@ -121,11 +121,11 @@ public Iterator internalIterator(long first, long count) { } List> list = getModel().searchObjects(type, query, options, task, result); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Query {} resulted in {} objects", type.getSimpleName(), list.size()); } - + for (PrismObject object : list) { getAvailableData().add(createDataObjectWrapper(object)); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/RepositoryObjectDataProvider.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/RepositoryObjectDataProvider.java index bcc97317bc6..08953c30034 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/RepositoryObjectDataProvider.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/RepositoryObjectDataProvider.java @@ -96,7 +96,7 @@ public Iterator internalIterator(long first, long count) { } getPage().showResult(result, false); - + LOGGER.trace("end::iterator()"); return getAvailableData().iterator(); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/SelectableBeanObjectDataProvider.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/SelectableBeanObjectDataProvider.java index db3f1dcef11..cd53c6d036c 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/SelectableBeanObjectDataProvider.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/SelectableBeanObjectDataProvider.java @@ -58,27 +58,27 @@ */ public class SelectableBeanObjectDataProvider extends BaseSortableDataProvider> { private static final long serialVersionUID = 1L; - + private static final Trace LOGGER = TraceManager.getTrace(SelectableBeanObjectDataProvider.class); private static final String DOT_CLASS = SelectableBeanObjectDataProvider.class.getName() + "."; private static final String OPERATION_SEARCH_OBJECTS = DOT_CLASS + "searchObjects"; private static final String OPERATION_COUNT_OBJECTS = DOT_CLASS + "countObjects"; private Set selected = new HashSet<>(); - + private boolean emptyListOnNullQuery = false; private boolean useObjectCounting = true; // we use special options when exporting to CSV (due to bulk nature of the operation) private boolean export; - + /** * The number of all objects that the query can return. Defaults to a really big number * if we cannot count the number of objects. * TODO: make this default more reasonable. -1 or something like that (MID-3339) */ // private int size = Integer.MAX_VALUE; - + private Class type; private Collection> options; @@ -95,7 +95,7 @@ public SelectableBeanObjectDataProvider(Component component, Class public void clearSelectedObjects(){ selected.clear(); } - + public List getSelectedData() { preprocessSelectedDataInternal(); for (SelectableBean selectable : super.getAvailableData()) { @@ -107,19 +107,19 @@ public List getSelectedData() { allSelected.addAll(selected); return allSelected; } - + private void preprocessSelectedData() { preprocessSelectedDataInternal(); getAvailableData().clear(); } - + private void preprocessSelectedDataInternal() { for (SelectableBean available : getAvailableData()) { if (available.isSelected() && available.getValue() != null) { ((Set)selected).add(available.getValue()); } } - + for (SelectableBean available : getAvailableData()) { if (!available.isSelected()) { if (selected.contains(available.getValue())) { @@ -128,8 +128,8 @@ private void preprocessSelectedDataInternal() { } } } - - + + @Override public Iterator> internalIterator(long offset, long pageSize) { LOGGER.trace("begin::iterator() offset {} pageSize {}.", new Object[]{offset, pageSize}); @@ -137,14 +137,14 @@ public Iterator> internalIterator(long offset, long pageSize) // // Failsafe. Do not even try this. This can have huge impact on the resource. (MID-3336) // throw new IllegalArgumentException("Requested huge page size: "+pageSize); // } - + preprocessSelectedData(); - + OperationResult result = new OperationResult(OPERATION_SEARCH_OBJECTS); try { ObjectPaging paging = createPaging(offset, pageSize); Task task = getPage().createSimpleTask(OPERATION_SEARCH_OBJECTS); - + ObjectQuery query = getQuery(); if (query == null){ if (emptyListOnNullQuery) { @@ -176,11 +176,11 @@ public Iterator> internalIterator(long offset, long pageSize) } } List> list = (List)getModel().searchObjects(type, query, currentOptions, task, result); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Query {} resulted in {} objects", type.getSimpleName(), list.size()); } - + for (PrismObject object : list) { getAvailableData().add(createDataObjectWrapper(object.asObjectable())); } @@ -271,11 +271,11 @@ public void setType(Class type) { clearCache(); } - + public boolean isUseObjectCounting(){ return useObjectCounting; } - + public void setUseObjectCounting(boolean useCounting) { this.useObjectCounting = useCounting; } @@ -287,11 +287,11 @@ public Collection> getOptions() { public void setOptions(Collection> options) { this.options = options; } - + public boolean isEmptyListOnNullQuery() { return emptyListOnNullQuery; } - + public void setEmptyListOnNullQuery(boolean emptyListOnNullQuery) { this.emptyListOnNullQuery = emptyListOnNullQuery; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/TableConfigurationPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/TableConfigurationPanel.java index 497181548d3..b241d07b339 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/TableConfigurationPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/TableConfigurationPanel.java @@ -44,7 +44,7 @@ public class TableConfigurationPanel extends BasePanel { private static final String ID_FORM = "form"; private static final String ID_INPUT = "input"; private static final String ID_BUTTON = "button"; - + // private static final String ID_FEEDBACK = "feedback"; public TableConfigurationPanel(String id) { @@ -118,7 +118,7 @@ protected void onSubmit(AjaxRequestTarget target, Form form) { input.add(new SearchFormEnterBehavior(button)); input.setType(Integer.class); input.setOutputMarkupId(true); - + FeedbackPanel feedback = new FeedbackPanel("inputFeedback", new ComponentFeedbackMessageFilter(input)); feedback.setOutputMarkupId(true); form.add(feedback); @@ -163,8 +163,8 @@ public void detach() { protected void pageSizeChanged(AjaxRequestTarget target) { } - + protected void onPageSizeChangedError(AjaxRequestTarget target) { - + } } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/TableHeadersToolbar.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/TableHeadersToolbar.java index eb236316881..eccfaa20276 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/TableHeadersToolbar.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/TableHeadersToolbar.java @@ -44,7 +44,7 @@ protected WebMarkupContainer newSortableHeader(String headerId, final String pro protected void onSortChanged() { getTable().setCurrentPage(0); } - + @Override protected void onAjaxClick(AjaxRequestTarget target) { target.add(getTable()); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/CheckBoxHeaderColumn.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/CheckBoxHeaderColumn.java index 54589026bbf..631e6bd947e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/CheckBoxHeaderColumn.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/CheckBoxHeaderColumn.java @@ -46,7 +46,7 @@ public class CheckBoxHeaderColumn extends CheckBoxColumn public CheckBoxHeaderColumn() { super(null); } - + private boolean visible = true; @Override @@ -64,27 +64,27 @@ public void onUpdate(AjaxRequestTarget target) { }; panel.setOutputMarkupId(true); panel.add(new VisibleEnableBehaviour() { - + @Override public boolean isVisible() { return CheckBoxHeaderColumn.this.isCheckboxVisible(); } - + }); return panel; } - + @Override public String getCssClass() { return "icon"; } - + protected boolean isCheckboxVisible(){ return visible; } - + public void setCheckboxVisible(boolean visible){ this.visible = visible; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/CheckBoxPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/CheckBoxPanel.java index 2f11871b6c5..cc83f4c45d4 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/CheckBoxPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/CheckBoxPanel.java @@ -71,13 +71,13 @@ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { public void onUpdate(AjaxRequestTarget target) { } - + public boolean getValue() { Boolean val = getPanelComponent().getModelObject(); if (val == null) { return false; } - + return val.booleanValue(); } } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/ColumnTypeDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/ColumnTypeDto.java index bf51f9ee8c7..3f25c053172 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/ColumnTypeDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/ColumnTypeDto.java @@ -3,22 +3,22 @@ import java.io.Serializable; public class ColumnTypeDto implements Serializable{ - + private static final long serialVersionUID = 1L; - + private String columnName; private String columnValue; private String sortableColumn; private boolean sortable = false; private boolean multivalue = false; - + public ColumnTypeDto(String columnName, String columnValue, String sortableColumn) { super(); this.columnName = columnName; this.columnValue = columnValue; // this.sortableColumn = sortableColumn; } - + public ColumnTypeDto(String columnName, String sortableColumn, String columnValue, boolean multivalue) { super(); this.columnName = columnName; @@ -26,7 +26,7 @@ public ColumnTypeDto(String columnName, String sortableColumn, String columnValu this.sortableColumn = sortableColumn; this.multivalue = multivalue; } - + public String getColumnName() { return columnName; } @@ -39,23 +39,23 @@ public String getColumnValue() { public void setColumnValue(String columnValue) { this.columnValue = columnValue; } - + public String getSortableColumn() { return sortableColumn; } - - + + public boolean isMultivalue() { return multivalue; } - + public void setMultivalue(boolean multivalue) { this.multivalue = multivalue; } - + public boolean isSortable() { return sortableColumn != null; } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/ColumnUtils.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/ColumnUtils.java index 84c71998d47..4f82121daaf 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/ColumnUtils.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/ColumnUtils.java @@ -111,13 +111,13 @@ public static List, String>> ge // throw new UnsupportedOperationException("Will be implemented eventually"); } } - + public static IColumn, String> createIconColumn(Class type){ - + if (type.equals(ObjectType.class)){ return getDefaultIcons(); } - + if (type.equals(UserType.class)) { return getUserIconColumn(); } else if (RoleType.class.equals(type)) { @@ -139,7 +139,7 @@ public static IColumn, String> createIc // throw new UnsupportedOperationException("Will be implemented eventually"); } } - + private static IColumn, String> getEmptyIconColumn(){ return new IconColumn>(createIconColumnHeaderModel()) { private static final long serialVersionUID = 1L; @@ -157,7 +157,7 @@ public String getObject() { } }; } - + private static IColumn, String> getDefaultIcons(){ return new IconColumn>(createStringResource("userBrowserDialog.type")) { @@ -176,7 +176,7 @@ public String getObject() { } }; } - + private static IModel createIconColumnHeaderModel() { return new Model() { @Override @@ -185,7 +185,7 @@ public String getObject() { } }; } - + private static IColumn, String> getUserIconColumn(){ return new IconColumn>(createIconColumnHeaderModel()) { private static final long serialVersionUID = 1L; @@ -227,7 +227,7 @@ public String getObject() { }; } - + public static IColumn, String> getShadowIconColumn(){ return new IconColumn>(createIconColumnHeaderModel()) { private static final long serialVersionUID = 1L; @@ -271,7 +271,7 @@ public IModel getDisplayModel(){ } }; } - + private static IColumn, String> getRoleIconColumn(){ return new IconColumn>(createIconColumnHeaderModel()) { private static final long serialVersionUID = 1L; @@ -502,16 +502,16 @@ public void populateItem(Item>> cellItem, public static List, String>> getDefaultRoleColumns() { List, String>> columns = new ArrayList, String>>(); - + columns.addAll((Collection)getDefaultAbstractRoleColumns(RoleType.COMPLEX_TYPE)); return columns; } - + public static List, String>> getDefaultServiceColumns() { List, String>> columns = new ArrayList, String>>(); - + columns.addAll((Collection)getDefaultAbstractRoleColumns(ServiceType.COMPLEX_TYPE)); return columns; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/LinkColumn.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/LinkColumn.java index 4f2c9ff90be..09dbfb79f65 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/LinkColumn.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/LinkColumn.java @@ -34,7 +34,7 @@ public class LinkColumn extends AbstractColumn implements IExporta private static final long serialVersionUID = 1L; private String propertyExpression; - + public LinkColumn(IModel displayModel) { super(displayModel); } @@ -55,11 +55,11 @@ protected String getPropertyExpression() { protected IModel createLinkModel(IModel rowModel) { return new PropertyModel(rowModel, propertyExpression); } - + @Override public void populateItem(Item> cellItem, String componentId, final IModel rowModel) { - + IModel model = createLinkModel(rowModel); cellItem.add(new LinkPanel(componentId, model) { private static final long serialVersionUID = 1L; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/ObjectLinkColumn.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/ObjectLinkColumn.java index b3b835c7fc9..970d5d08069 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/ObjectLinkColumn.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/ObjectLinkColumn.java @@ -45,11 +45,11 @@ public ObjectLinkColumn(IModel displayModel, String propertyExpression) public ObjectLinkColumn(IModel displayModel, String sortProperty, String propertyExpression) { super(displayModel, sortProperty); } - + @Override public void populateItem(Item> cellItem, String componentId, final IModel rowModel) { - + IModel superModel = createLinkModel(rowModel); final ObjectType targetObjectType = superModel.getObject(); IModel nameModel = new PropertyModel(superModel, FocusType.F_NAME.getLocalPart() + ".orig"); @@ -67,8 +67,8 @@ public boolean isEnabled() { } }); } - - + + public boolean isEnabled(IModel rowModel) { return true; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/ObjectNameColumn.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/ObjectNameColumn.java index 792ea5a05b6..6a212ab29a0 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/ObjectNameColumn.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/ObjectNameColumn.java @@ -45,7 +45,7 @@ public class ObjectNameColumn extends AbstractColumn displayModel) { super(displayModel, ObjectType.F_NAME.getLocalPart()); } @@ -60,7 +60,7 @@ public void populateItem(final Item>> cellItem, IModel labelModel = new AbstractReadOnlyModel() { private static final long serialVersionUID = 1L; - + @Override public String getObject() { SelectableBean selectableBean = rowModel.getObject(); @@ -80,8 +80,8 @@ public String getObject() { return complexName.toString(); } return name; - - + + } } }; @@ -110,7 +110,7 @@ public void onClick(AjaxRequestTarget target) { cellItem.add(new Label(componentId, labelModel)); } } - + public boolean isClickable(IModel> rowModel) { return true; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/dialog/ChooseFocusTypeDialogPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/dialog/ChooseFocusTypeDialogPanel.java index 531f221a368..f8587f79e03 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/dialog/ChooseFocusTypeDialogPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/dialog/ChooseFocusTypeDialogPanel.java @@ -19,37 +19,37 @@ public class ChooseFocusTypeDialogPanel extends BasePanel implements Popupable{ private static final String ID_OBJECT_TYPE = "type"; private static final String ID_BUTTON_OK = "ok"; - + public ChooseFocusTypeDialogPanel(String id) { super(id); initLayout(); } - + private void initLayout(){ DropDownChoice type = new DropDownChoice(ID_OBJECT_TYPE, Model.of(UserType.COMPLEX_TYPE), WebComponentUtil.createFocusTypeList(), new QNameChoiceRenderer()); type.add(new EmptyOnChangeAjaxFormUpdatingBehavior()); type.setOutputMarkupId(true); add(type); - + AjaxButton confirmButton = new AjaxButton(ID_BUTTON_OK, createStringResource("Button.ok")) { - - + + @Override public void onClick(AjaxRequestTarget target) { DropDownChoice type = (DropDownChoice) getParent().get(ID_OBJECT_TYPE); QName typeChosen = type.getModelObject(); ChooseFocusTypeDialogPanel.this.okPerformed(typeChosen, target); - + } }; - + add(confirmButton); } protected void okPerformed(QName type, AjaxRequestTarget target) { // TODO Auto-generated method stub - + } @Override @@ -72,5 +72,5 @@ public Component getComponent() { return this; } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/dialog/MainPopupDialog.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/dialog/MainPopupDialog.java index 59efc4d944d..ee1086534b8 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/dialog/MainPopupDialog.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/dialog/MainPopupDialog.java @@ -31,7 +31,7 @@ public class MainPopupDialog extends ModalWindow { private static final long serialVersionUID = 1L; private static final String ID_MAIN_POPUP_BODY = "popupBody"; - + private boolean initialized; public MainPopupDialog(String id) { @@ -61,15 +61,15 @@ public void onClose(AjaxRequestTarget target) { MainPopupDialog.this.close(target); } }); - + WebMarkupContainer content = new WebMarkupContainer(getContentId()); setContent(content); } - + @Override protected void onBeforeRender(){ super.onBeforeRender(); - + if(initialized){ return; } @@ -77,12 +77,12 @@ protected void onBeforeRender(){ setBody(new Label(ID_MAIN_POPUP_BODY, new Model("Not initialized"))); initialized = true; } - + private void setBody(Component component){ WebMarkupContainer content = (WebMarkupContainer) get(getContentId()); content.addOrReplace(component); } - + public void setBody(Popupable popupable){ setTitle(popupable.getTitle()); setInitialHeight(popupable.getHeight()); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/dialog/Popupable.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/dialog/Popupable.java index 7b89ab2b6d9..49521be809c 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/dialog/Popupable.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/dialog/Popupable.java @@ -4,11 +4,11 @@ import org.apache.wicket.model.StringResourceModel; public interface Popupable { - + public int getWidth(); public int getHeight(); public StringResourceModel getTitle(); public Component getComponent(); - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/AceEditorFormGroup.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/AceEditorFormGroup.java index 6cb1946069f..89ebe76de04 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/AceEditorFormGroup.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/AceEditorFormGroup.java @@ -93,7 +93,7 @@ public boolean isVisible() { }); tooltipLabel.setOutputMarkupId(true); tooltipLabel.setOutputMarkupPlaceholderTag(true); - labelContainer.add(tooltipLabel); + labelContainer.add(tooltipLabel); WebMarkupContainer textWrapper = new WebMarkupContainer(ID_TEXT_WRAPPER); if (StringUtils.isNotEmpty(textSize)) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/Form.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/Form.java index 27693566512..28984dcf2e5 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/Form.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/Form.java @@ -33,7 +33,7 @@ public class Form extends org.apache.wicket.markup.html.form.Form { public Form(String id) { super(id); } - + public Form(String id, final IModel model) { super(id); } @@ -68,5 +68,5 @@ public void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) ""); } } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/TextAreaFormGroup.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/TextAreaFormGroup.java index 6d87569dc03..689f55a679c 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/TextAreaFormGroup.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/TextAreaFormGroup.java @@ -93,7 +93,7 @@ public boolean isVisible() { }); tooltipLabel.setOutputMarkupId(true); tooltipLabel.setOutputMarkupPlaceholderTag(true); - labelContainer.add(tooltipLabel); + labelContainer.add(tooltipLabel); WebMarkupContainer textWrapper = new WebMarkupContainer(ID_TEXT_WRAPPER); if (StringUtils.isNotEmpty(textSize)) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/multivalue/MultiValueChoosePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/multivalue/MultiValueChoosePanel.java index 5ffa829fb9b..20a4d5c93cb 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/multivalue/MultiValueChoosePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/multivalue/MultiValueChoosePanel.java @@ -54,7 +54,7 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; /** - * + * * @param model/chosen object types */ public class MultiValueChoosePanel extends BasePanel> { @@ -71,7 +71,7 @@ public class MultiValueChoosePanel extends BasePanel extends BasePanel defaultType; private Collection> types; - + public MultiValueChoosePanel(String id, IModel> value, Collection> types) { this(id, value, null, false, types); } - + public MultiValueChoosePanel(String id, IModel> value, Collection> types, boolean multiselect) { this(id, value, null, false, types, multiselect); } @@ -103,11 +103,11 @@ public MultiValueChoosePanel(String id, IModel> chosenValues, List t1.getLocalPart().compareTo(t2.getLocalPart())); } - + private void initLayout(final IModel> chosenValues, final List filterValues, final boolean required, final boolean multiselect) { @@ -137,13 +137,13 @@ public void onClick(AjaxRequestTarget target) { @Override protected void populateItem(ListItem item) { WebMarkupContainer textWrapper = new WebMarkupContainer(ID_TEXT_WRAPPER); - + textWrapper.setOutputMarkupPlaceholderTag(true); - + TextField text = new TextField(ID_TEXT, createTextModel(item.getModel())); //was value text.add(new AjaxFormComponentUpdatingBehavior("blur") { private static final long serialVersionUID = 1L; - + @Override protected void onUpdate(AjaxRequestTarget ajaxRequestTarget) { } @@ -152,13 +152,13 @@ protected void onUpdate(AjaxRequestTarget ajaxRequestTarget) { text.setEnabled(false); text.setOutputMarkupPlaceholderTag(true); textWrapper.add(text); - + FeedbackPanel feedback = new FeedbackPanel(ID_FEEDBACK, new ComponentFeedbackMessageFilter(text)); feedback.setOutputMarkupPlaceholderTag(true); textWrapper.add(feedback); - + initButtons(item, item); - + item.add(textWrapper); } }; @@ -210,7 +210,7 @@ protected void editValuePerformed(List chosenValues, List selected) { getPageBase().hideMainPopup(target); @@ -260,17 +260,17 @@ public WebMarkupContainer getTextWrapperComponent(){ protected void initButtons(ListItem item, WebMarkupContainer parent) { WebMarkupContainer buttonGroup = new WebMarkupContainer(ID_BUTTON_GROUP); { buttonGroup.setOutputMarkupId(true); - + AjaxLink remove = new AjaxLink(ID_REMOVE) { - + @Override public void onClick(AjaxRequestTarget target) { removeValuePerformed(target, item.getModelObject()); } }; - + remove.add(new VisibleEnableBehaviour() { - + @Override public boolean isVisible() { return isRemoveButtonVisible(); @@ -287,16 +287,16 @@ private boolean isRemoveButtonVisible() { } private void removeValuePerformed(AjaxRequestTarget target, T value) { - + LOGGER.debug("Removing value {} from selected list", value); - + getModelObject().remove(value); removePerformedHook(target, value); target.add(this); } protected void removePerformedHook(AjaxRequestTarget target, T value) { - + } /** diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/multivalue/MultiValueDropDownPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/multivalue/MultiValueDropDownPanel.java index 299b6c804a1..e46b443fd6c 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/multivalue/MultiValueDropDownPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/multivalue/MultiValueDropDownPanel.java @@ -239,7 +239,7 @@ public List getObject() { * */ protected IChoiceRenderer createRenderer(){ return new IChoiceRenderer() { - + @Override public T getObject(String id, IModel> choices) { return StringUtils.isNotBlank(id) ? choices.getObject().get(Integer.parseInt(id)) : null; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/multivalue/MultiValueExpandablePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/multivalue/MultiValueExpandablePanel.java index 0f8b5ee028f..fefd220884f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/multivalue/MultiValueExpandablePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/form/multivalue/MultiValueExpandablePanel.java @@ -16,11 +16,14 @@ package com.evolveum.midpoint.web.component.form.multivalue; import com.evolveum.midpoint.gui.api.component.BasePanel; +import com.evolveum.midpoint.gui.api.page.PageBase; import com.evolveum.midpoint.gui.api.util.WebComponentUtil; import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.web.component.AjaxButton; +import com.evolveum.midpoint.web.component.dialog.ConfirmationPanel; import com.evolveum.midpoint.web.component.input.TextPanel; +import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItem; import com.evolveum.midpoint.web.page.admin.configuration.component.ChooseTypePanel; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.apache.wicket.Component; @@ -34,6 +37,7 @@ import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.model.StringResourceModel; import java.util.HashMap; import java.util.List; @@ -51,12 +55,17 @@ public class MultiValueExpandablePanel extends BasePan private static final String ID_ATTRIBUTE_LABEL = "attributeLabel"; private static final String ID_ATTRIBUTE_VALUE = "attributeValue"; - public MultiValueExpandablePanel(String id, IModel> model){ + PageBase pageBase; + + public MultiValueExpandablePanel(String id, IModel> model, PageBase pageBase){ super(id, model); + this.pageBase = pageBase; initLayout(); } private void initLayout(){ + setOutputMarkupId(true); + ListView repeater = new ListView(ID_REPEATER, getModel()) { @Override @@ -67,6 +76,7 @@ protected void populateItem(final ListItem listItem) { AjaxButton removeRowButton = new AjaxButton(ID_REMOVE_BUTTON) { @Override public void onClick(AjaxRequestTarget ajaxRequestTarget) { + removeItemPerformed(listItem.getModelObject(), ajaxRequestTarget); } }; listItem.add(removeRowButton); @@ -96,7 +106,7 @@ public void onClick(AjaxRequestTarget ajaxRequestTarget) { listItem.add(attributesPanel); } }; - + repeater.setOutputMarkupId(true); add(repeater); } @@ -121,7 +131,7 @@ private Component createTypedAttributePanel(String componentId, Class type, IMod panel = WebComponentUtil.createEnumPanel(type, componentId, model != null ? new PropertyModel<>(model, expression) : new Model(), this); } else if (ObjectReferenceType.class.isAssignableFrom(type)) { ObjectReferenceType ort = new ObjectReferenceType(); - ort.setupReferenceValue((PrismReferenceValue) model.getObject()); + ort.setupReferenceValue(model != null ? (PrismReferenceValue) model.getObject() : new PrismReferenceValue()); panel = new ChooseTypePanel(componentId, ort) { private static final long serialVersionUID = 1L; @@ -152,4 +162,24 @@ public Class getObjectTypeClass() { return panel; } + private void removeItemPerformed(T objectToRemove, AjaxRequestTarget target){ + ConfirmationPanel dialog = new ConfirmationPanel(pageBase.getMainPopupBodyId(), + pageBase.createStringResource("MultiValueExpandablePanel.deleteConfirmationMessage", + objectToRemove.asPrismContainerValue().getPath().last())) { + private static final long serialVersionUID = 1L; + + @Override + public StringResourceModel getTitle() { + return pageBase.createStringResource("pageUsers.message.confirmActionPopupTitle"); + } + + @Override + public void yesPerformed(AjaxRequestTarget target) { + pageBase.hideMainPopup(target); + getModelObject().remove(objectToRemove); + target.add(MultiValueExpandablePanel.this); + } + }; + pageBase.showMainPopup(dialog, target); + } } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/DisplayableValueChoiceRenderer.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/DisplayableValueChoiceRenderer.java index 726beb2a009..51fd4e19c53 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/DisplayableValueChoiceRenderer.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/DisplayableValueChoiceRenderer.java @@ -12,28 +12,28 @@ public class DisplayableValueChoiceRenderer implements IChoiceRenderer { private static final long serialVersionUID = 1L; private List choices; - - + + public DisplayableValueChoiceRenderer(List choices) { this.choices = choices; } - + @Override public String getDisplayValue(T object) { if (object == null) { return null; } - + if (object instanceof DisplayableValue) { return ((DisplayableValue) object).getLabel(); } - + return object.toString(); } @Override public String getIdValue(T object, int index) { - + if (object instanceof String && choices != null) { for (DisplayableValue v : choices) { if (object.equals(v.getValue())) { @@ -42,7 +42,7 @@ public String getIdValue(T object, int index) { } } - + return Integer.toString(index); } @@ -51,7 +51,7 @@ public T getObject(String id, IModel> choices) { if (StringUtils.isBlank(id)){ return null; } - + return choices.getObject().get(Integer.parseInt(id)); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/DropDownChoicePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/DropDownChoicePanel.java index 555f5587b47..4d72262ed00 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/DropDownChoicePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/DropDownChoicePanel.java @@ -55,7 +55,7 @@ protected CharSequence getDefaultChoice(String selectedValue) { public DropDownChoicePanel(String id, IModel model, IModel> choices, IChoiceRenderer renderer) { this(id, model, choices, renderer, false); } - + public DropDownChoicePanel(String id, IModel model, IModel> choices, IChoiceRenderer renderer, boolean allowNull) { super(id); @@ -77,7 +77,7 @@ protected String getNullValidDisplayValue() { public DropDownChoice getBaseFormComponent() { return (DropDownChoice) get("input"); } - + public IModel getModel() { return getBaseFormComponent().getModel(); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/QNameChoiceRenderer.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/QNameChoiceRenderer.java index 57b70892202..7c778885dcd 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/QNameChoiceRenderer.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/QNameChoiceRenderer.java @@ -30,9 +30,9 @@ public class QNameChoiceRenderer implements IChoiceRenderer { private static final long serialVersionUID = 1L; - + private static Map prefixMap; - + static { prefixMap = new HashMap<>(); prefixMap.put(SchemaConstantsGenerated.NS_ICF_SCHEMA, "icfs:"); @@ -43,7 +43,7 @@ public class QNameChoiceRenderer implements IChoiceRenderer { } private boolean usePrefix = false; - + public QNameChoiceRenderer() { this(false); } @@ -70,7 +70,7 @@ public Object getDisplayValue(QName object) { sb.append(prefix); } } - + sb.append(object.getLocalPart()); return sb.toString(); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/RefinedObjectTypeChoicePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/RefinedObjectTypeChoicePanel.java index 4f50c613999..e4ebc72d52b 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/RefinedObjectTypeChoicePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/RefinedObjectTypeChoicePanel.java @@ -38,11 +38,11 @@ public class RefinedObjectTypeChoicePanel extends DropDownChoicePanel { private static final Trace LOGGER = TraceManager.getTrace(RefinedObjectTypeChoicePanel.class); - + public RefinedObjectTypeChoicePanel(String id, IModel model, IModel> resourceModel) { super(id, model, createChoiceModel(resourceModel), createRenderer(), false); } - + private static IModel> createChoiceModel(final IModel> resourceModel) { return new IModel>() { @Override diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/StringChoiceRenderer.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/StringChoiceRenderer.java index 025381adb07..4928a759df8 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/StringChoiceRenderer.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/StringChoiceRenderer.java @@ -10,14 +10,14 @@ public class StringChoiceRenderer implements IChoiceRenderer { private static final long serialVersionUID = 1L; - + private String keyPrefix; private String splitPattern; - + public StringChoiceRenderer(String keyPrefix) { this.keyPrefix = StringUtils.isNotBlank(keyPrefix) ? keyPrefix : ""; } - + public StringChoiceRenderer(String keyPrefix, String splitPattern) { this.keyPrefix = StringUtils.isNotBlank(keyPrefix) ? keyPrefix : ""; this.splitPattern = splitPattern; @@ -34,11 +34,11 @@ public String getDisplayValue(String object) { String[] fields = object.split(splitPattern); object = fields[1]; } - + if (StringUtils.isNotBlank(keyPrefix)){ return Application.get().getResourceSettings().getLocalizer().getString(keyPrefix + object, null); } - + return object; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/UploadDownloadPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/UploadDownloadPanel.java index b3bfa4018b5..09a1d5d0a74 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/UploadDownloadPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/UploadDownloadPanel.java @@ -72,14 +72,14 @@ protected void onError (AjaxRequestTarget target){ add(fileUpload); final AjaxDownloadBehaviorFromStream downloadBehavior = new AjaxDownloadBehaviorFromStream() { - + @Override protected InputStream initStream() { return getStream(); } }; add(downloadBehavior); - + add(new AjaxSubmitButton(ID_BUTTON_DOWNLOAD) { @Override @@ -147,11 +147,11 @@ public void uploadFileFailed(AjaxRequestTarget target) { public void updateValue(byte[] file) { } - + public InputStream getStream() { return null; } - + private void downloadPerformed(AjaxDownloadBehaviorFromStream downloadBehavior, AjaxRequestTarget target) { downloadBehavior.initiate(target); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/validator/NotNullValidator.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/validator/NotNullValidator.java index dd9eccda729..5c192a4be0f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/validator/NotNullValidator.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/validator/NotNullValidator.java @@ -8,21 +8,21 @@ public class NotNullValidator implements INullAcceptingValidator{ private static final long serialVersionUID = 1L; private String key; - + public NotNullValidator(String errorMessageKey) { this.key = errorMessageKey; } - + @Override public void validate(IValidatable validatable) { if (validatable.getValue() == null) { ValidationError err = new ValidationError(); err.addKey(key); validatable.error(err); - + } - + } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/menu/BaseMenuItem.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/menu/BaseMenuItem.java index 516c1d1759e..47d3be417e8 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/menu/BaseMenuItem.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/menu/BaseMenuItem.java @@ -112,6 +112,6 @@ public String toString() { return "BaseMenuItem(nameModel=" + nameModel + ", pageClass=" + pageClass + ", params=" + params + ", visibleEnable=" + visibleEnable + ", aliases=" + Arrays.toString(aliases) + ")"; } - - + + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/menu/MainMenuItem.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/menu/MainMenuItem.java index aa531be7cc9..8643cc3150b 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/menu/MainMenuItem.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/menu/MainMenuItem.java @@ -67,7 +67,7 @@ public List getItems() { } return items; } - + public String getBubbleLabel() { return null; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/menu/UserMenuPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/menu/UserMenuPanel.java index b8164878685..8b5d8c15859 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/menu/UserMenuPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/menu/UserMenuPanel.java @@ -279,11 +279,11 @@ private PasswordQuestionsDto loadModel(PageBase parentPage) { PasswordQuestionsDto dto =new PasswordQuestionsDto(); OperationResult result = new OperationResult(OPERATION_LOAD_USER); - + if (parentPage == null) { parentPage = ((PageBase)getPage()); } - + try { MidPointPrincipal principal = SecurityUtils.getPrincipalUser(); @@ -342,7 +342,7 @@ public List createUsersSecurityQuestionsList(PrismObj continue; } } - + } return secQuestAnswListDTO; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/menu/top/LocalePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/menu/top/LocalePanel.java index 47e92f8ec20..f46e4fcd8db 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/menu/top/LocalePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/menu/top/LocalePanel.java @@ -77,7 +77,7 @@ public IModel getModel(LocaleDescriptor value) { }) { - + @Override protected SelectOption newOption(String text, IModel model) { SelectOption option = super.newOption(" " + text, model); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractFocusTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractFocusTabPanel.java index fd6d74eed66..891accafd2e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractFocusTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractFocusTabPanel.java @@ -36,13 +36,13 @@ public abstract class AbstractFocusTabPanel extends Abstrac private static final long serialVersionUID = 1L; private static final Trace LOGGER = TraceManager.getTrace(AbstractFocusTabPanel.class); - + private LoadableModel> assignmentsModel; private LoadableModel>> projectionModel; - public AbstractFocusTabPanel(String id, Form mainForm, - LoadableModel> focusWrapperModel, - LoadableModel> assignmentsModel, + public AbstractFocusTabPanel(String id, Form mainForm, + LoadableModel> focusWrapperModel, + LoadableModel> assignmentsModel, LoadableModel>> projectionModel, PageBase pageBase) { super(id, mainForm, focusWrapperModel, pageBase); 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 d9ff27762c5..da17b1b2da5 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 @@ -56,9 +56,9 @@ public abstract class AbstractObjectMainPanel extends Pane 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) { @Override @@ -86,7 +86,7 @@ protected void onConfigure() { public LoadableModel> getObjectModel() { return objectModel; } - + public ObjectWrapper getObjectWrapper() { return objectModel.getObject(); } @@ -94,7 +94,7 @@ public ObjectWrapper getObjectWrapper() { public PrismObject getObject() { return objectModel.getObject().getObject(); } - + public Form getMainForm() { return mainForm; } @@ -106,7 +106,7 @@ private void initLayout(PageAdminObjectDetails parentPage) { initLayoutOptions(); initLayoutButtons(parentPage); } - + protected void initLayoutTabs(final PageAdminObjectDetails parentPage) { List tabs = createTabs(parentPage); TabbedPanel tabPanel = WebComponentUtil.createTabPanel(ID_TAB_PANEL, parentPage, tabs, null, @@ -130,7 +130,7 @@ public boolean isVisible() { }); mainForm.add(optionsPanel); } - + protected void initLayoutButtons(PageAdminObjectDetails parentPage) { initLayoutPreviewButton(parentPage); initLayoutSaveButton(parentPage); @@ -226,11 +226,11 @@ protected void initLayoutBackButton(PageAdminObjectDetails parentPage) { public void onClick(AjaxRequestTarget target) { backPerformed(target); } - + }; mainForm.add(back); } - + public ExecuteChangeOptionsDto getExecuteChangeOptionsDto() { return executeOptionsModel.getObject(); } @@ -238,7 +238,7 @@ public ExecuteChangeOptionsDto getExecuteChangeOptionsDto() { private void backPerformed(AjaxRequestTarget target) { getDetailsPage().redirectBack(); } - + protected PageAdminObjectDetails getDetailsPage() { return (PageAdminObjectDetails)getPage(); } 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 a19de169d00..ae9581525df 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 @@ -76,7 +76,7 @@ protected PrismContext getPrismContext() { protected PageParameters getPageParameters() { return pageBase.getPageParameters(); } - + public PageBase getPageBase() { return pageBase; } @@ -101,12 +101,12 @@ protected String createComponentPath(String... components) { protected void showResult(OperationResult result) { pageBase.showResult(result); } - + protected void showResult(OperationResult result, boolean showSuccess) { pageBase.showResult(result, false); } - - + + protected WebMarkupContainer getFeedbackPanel() { return pageBase.getFeedbackPanel(); } @@ -137,7 +137,7 @@ protected void showModalWindow(Popupable popupable, AjaxRequestTarget target) { protected void addPrismPropertyPanel(MarkupContainer parentComponent, String id, QName propertyName) { addPrismPropertyPanel(parentComponent, id, new ItemPath(propertyName)); } - + protected void addPrismPropertyPanel(MarkupContainer parentComponent, String id, ItemPath propertyPath) { parentComponent.add( new PrismPropertyPanel(id, 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 89a02c5a664..5685fb04434 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 @@ -74,7 +74,7 @@ */ public abstract class AbstractRoleMainPanel extends FocusMainPanel { private static final long serialVersionUID = 1L; - + private LoadableModel> inducementsModel; private static final Trace LOGGER = TraceManager.getTrace(AbstractRoleMainPanel.class); private static final String DOT_CLASS = AbstractRoleMainPanel.class.getName(); @@ -84,7 +84,7 @@ public abstract class AbstractRoleMainPanel extends private static final String ID_SHOPPING_CART_BUTTON = "shoppingCartButton"; private static final String ID_ITEMS_COUNT = "itemsCount"; - public AbstractRoleMainPanel(String id, LoadableModel> objectModel, + public AbstractRoleMainPanel(String id, LoadableModel> objectModel, CountableLoadableModel assignmentsModel, CountableLoadableModel policyRulesModel, LoadableModel>> projectionModel, @@ -209,7 +209,7 @@ protected List createTabs(final PageAdminObjectDetails parentPage) { tabs.add(new CountablePanelTab(parentPage.createStringResource("FocusType.inducement"), authorization) { private static final long serialVersionUID = 1L; - + @Override public WebMarkupContainer createPanel(String panelId) { return new AssignmentTablePanel(panelId, parentPage.createStringResource("FocusType.inducement"), inducementsModel, parentPage) { @@ -231,7 +231,7 @@ protected boolean ignoreMandatoryAttributes(){ } }; } - + @Override public String getCount() { return Integer.toString(inducementsModel.getObject() == null ? 0 : inducementsModel.getObject().size()); @@ -256,7 +256,7 @@ public boolean isVisible() { isAllowedToReadRoleMembership(getObjectWrapper().getOid(), parentPage); } }); - + return tabs; } @@ -283,5 +283,5 @@ private boolean isAllowedToReadRoleMembershipItemForType(String abstractRoleOid, } public abstract AbstractRoleMemberPanel createMemberPanel(String panelId); - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/BaseAbstractRolePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/BaseAbstractRolePanel.java index f6a771788be..83f3b45a0d1 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/BaseAbstractRolePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/BaseAbstractRolePanel.java @@ -24,18 +24,18 @@ public class BaseAbstractRolePanel extends SimplePanel{ private static final String ID_LABEL_SIZE = "col-md-4"; private static final String ID_INPUT_SIZE = "col-md-6"; - + private AbstractRoleType abstractRole; - + LoadableModel> minAssignmentModel; LoadableModel> maxAssignmentsModel; - + public BaseAbstractRolePanel(String id, AbstractRoleType abstractRole) { super(id); this.abstractRole = abstractRole; // TODO Auto-generated constructor stub } - + private WebMarkupContainer getMinAssignmentsContainer(){ return (WebMarkupContainer) get(StringUtils.join(new String[]{"mainForm", ID_MIN_ASSIGNMENTS}, ":")); } @@ -43,7 +43,7 @@ private WebMarkupContainer getMinAssignmentsContainer(){ private WebMarkupContainer getMaxAssignmentsContainer(){ return (WebMarkupContainer) get(StringUtils.join(new String[]{"mainForm", ID_MAX_ASSIGNMENTS}, ":")); } - + private IModel createMultiplicityPolicyLabel(final IModel model){ return new AbstractReadOnlyModel() { @@ -71,12 +71,12 @@ public String getObject() { }; } - - + + @Override protected void initLayout() { - + minAssignmentModel = new LoadableModel>(false) { @Override @@ -101,7 +101,7 @@ protected List load() { return abstractRole.getPolicyConstraints().getMaxAssignees(); } }; - + GenericMultiValueLabelEditPanel minAssignments = new GenericMultiValueLabelEditPanel(ID_MIN_ASSIGNMENTS, minAssignmentModel, createStringResource("PageRoleEditor.label.minAssignments"), ID_LABEL_SIZE, ID_INPUT_SIZE, true){ diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusAssignmentsTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusAssignmentsTabPanel.java index eb2b8340338..db417a2b644 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusAssignmentsTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusAssignmentsTabPanel.java @@ -48,7 +48,7 @@ */ public class FocusAssignmentsTabPanel 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 = FocusAssignmentsTabPanel.class.getName() + "."; @@ -57,16 +57,16 @@ public class FocusAssignmentsTabPanel extends AbstractObjec private static final String MODAL_ID_ASSIGNMENTS_PREVIEW = "assignmentsPreviewPopup"; private static final Trace LOGGER = TraceManager.getTrace(FocusAssignmentsTabPanel.class); - + private LoadableModel> assignmentsModel; - - public FocusAssignmentsTabPanel(String id, Form mainForm, LoadableModel> focusWrapperModel, + + public FocusAssignmentsTabPanel(String id, Form mainForm, LoadableModel> focusWrapperModel, LoadableModel> assignmentsModel, PageBase page) { super(id, mainForm, focusWrapperModel, page); this.assignmentsModel = assignmentsModel; initLayout(); } - + private void initLayout() { WebMarkupContainer assignments = new WebMarkupContainer(ID_ASSIGNMENTS); @@ -75,9 +75,9 @@ private void initLayout() { Component panel; // if (isEnableExperimentalFeatures()){ - - - + + + panel = new AbstractRoleAssignmentPanel(ID_ASSIGNMENTS_PANEL, assignmentsModel, pageBase); // } else { // panel = new AssignmentTablePanel(ID_ASSIGNMENTS_PANEL, diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusConsentTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusConsentTabPanel.java index 9ceb3360840..442e7aeda3b 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusConsentTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusConsentTabPanel.java @@ -13,29 +13,29 @@ public class FocusConsentTabPanel extends AbstractObjectTabPanel{ private static final long serialVersionUID = 1L; - + private static final String ID_ROLES = "roles"; - + private LoadableModel> consentsModel; - + public FocusConsentTabPanel(String id, Form> mainForm, LoadableModel> objectWrapperModel, LoadableModel> consentsModel, PageBase pageBase) { super(id, mainForm, objectWrapperModel, pageBase); this.consentsModel = consentsModel; - + initLayout(); } - - private void initLayout() { - + + private void initLayout() { + GdprAssignmentPanel consentRoles = new GdprAssignmentPanel(ID_ROLES, consentsModel, getPageBase()); add(consentRoles); consentRoles.setOutputMarkupId(true); - + } - - - + + + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusDetailsTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusDetailsTabPanel.java index b6d4bc474fe..a835a5f5b6f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusDetailsTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusDetailsTabPanel.java @@ -38,20 +38,20 @@ */ public class FocusDetailsTabPanel extends AbstractFocusTabPanel { private static final long serialVersionUID = 1L; - + protected static final String ID_FOCUS_FORM = "focusDetails"; - + private static final Trace LOGGER = TraceManager.getTrace(FocusDetailsTabPanel.class); - public FocusDetailsTabPanel(String id, Form mainForm, - LoadableModel> focusWrapperModel, - LoadableModel> assignmentsModel, + public FocusDetailsTabPanel(String id, Form mainForm, + LoadableModel> focusWrapperModel, + LoadableModel> assignmentsModel, LoadableModel>> projectionModel, PageBase pageBase) { super(id, mainForm, focusWrapperModel, assignmentsModel, projectionModel, pageBase); initLayout(); } - + private void initLayout() { PrismObjectPanel panel = new PrismObjectPanel(ID_FOCUS_FORM, getObjectWrapperModel(), diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusPolicyRulesTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusPolicyRulesTabPanel.java index 653748837bb..281dc62a2b8 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusPolicyRulesTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusPolicyRulesTabPanel.java @@ -49,7 +49,7 @@ public class FocusPolicyRulesTabPanel extends AbstractObje private static final long serialVersionUID = 1L; private LoadableModel> policyRulesModel; - + private static final String ID_POLICY_RULES_CONTAINER = "policyRulesContainer"; private static final String ID_POLICY_RULES_PANEL = "policyRulesPanel"; private static final String DOT_CLASS = FocusAssignmentsTabPanel.class.getName() + "."; @@ -67,11 +67,11 @@ private void initLayout() { WebMarkupContainer policyRules = new WebMarkupContainer(ID_POLICY_RULES_CONTAINER); policyRules.setOutputMarkupId(true); add(policyRules); - + PolicyRulesPanel policyRulesPanel = new PolicyRulesPanel(ID_POLICY_RULES_PANEL, policyRulesModel, pageBase); policyRules.add(policyRulesPanel); } - - + + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusProjectionsTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusProjectionsTabPanel.java index 93fe932da9d..ae75705e1f3 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusProjectionsTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusProjectionsTabPanel.java @@ -85,7 +85,7 @@ public class FocusProjectionsTabPanel extends AbstractObjec private static final String ID_SHADOW_CHECK_ALL = "shadowCheckAll"; private static final String MODAL_ID_RESOURCE = "resourcePopup"; - + private static final String DOT_CLASS = FocusProjectionsTabPanel.class.getName() + "."; private static final String OPERATION_ADD_ACCOUNT = DOT_CLASS + "addShadow"; @@ -321,7 +321,7 @@ public void onClick(AjaxRequestTarget target) { new InlineMenuItemAction() { /** - * + * */ private static final long serialVersionUID = 1L; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusTasksTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusTasksTabPanel.java index 91685109860..03cfef81739 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusTasksTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusTasksTabPanel.java @@ -39,26 +39,26 @@ * @author mederly * @author semancik */ -public class FocusTasksTabPanel +public class FocusTasksTabPanel extends AbstractObjectTabPanel { private static final long serialVersionUID = 1L; - + protected static final String ID_TASK_TABLE = "taskTable"; protected static final String ID_LABEL = "label"; - + private static final Trace LOGGER = TraceManager.getTrace(FocusTasksTabPanel.class); - + private TaskDtoProvider taskDtoProvider; - - public FocusTasksTabPanel(String id, Form mainForm, LoadableModel> focusModel, + + public FocusTasksTabPanel(String id, Form mainForm, LoadableModel> focusModel, TaskDtoProvider taskDtoProvider, PageBase page) { super(id, mainForm, focusModel, page); this.taskDtoProvider = taskDtoProvider; initLayout(page); } - + private void initLayout(final PageBase page) { - + Label label = new Label(ID_LABEL, new AbstractReadOnlyModel() { private static final long serialVersionUID = 1L; @@ -72,7 +72,7 @@ public String getObject() { } }); add(label); - + List> taskColumns = initTaskColumns(); TablePanel taskTable = new TablePanel(ID_TASK_TABLE, taskDtoProvider, taskColumns); add(taskTable); @@ -84,7 +84,7 @@ public boolean isVisible() { } }); } - + private List> initTaskColumns() { List> columns = new ArrayList>(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/RoleMainPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/RoleMainPanel.java index 6283b16d9a8..cab8d124600 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/RoleMainPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/RoleMainPanel.java @@ -47,8 +47,8 @@ */ public class RoleMainPanel extends AbstractRoleMainPanel { private static final long serialVersionUID = 1L; - - public RoleMainPanel(String id, LoadableModel> objectModel, + + public RoleMainPanel(String id, LoadableModel> objectModel, CountableLoadableModel assignmentsModel, CountableLoadableModel policyRulesModel, LoadableModel>> projectionModel, @@ -111,7 +111,7 @@ public WebMarkupContainer createPanel(String panelId) { return tabs; } - + @Override public AbstractRoleMemberPanel createMemberPanel(String panelId) { return new RoleMemberPanel(panelId, new Model(getObject().asObjectable()), getDetailsPage()); @@ -127,6 +127,6 @@ public AbstractRoleMemberPanel createGovernancePanel(String panelId) { relationsList, getDetailsPage()); } - - + + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/AssociationWrapper.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/AssociationWrapper.java index 44287e29cf1..6888f9e70b5 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/AssociationWrapper.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/AssociationWrapper.java @@ -31,7 +31,7 @@ public class AssociationWrapper extends PropertyWrapper container, PrismContainer property, @@ -48,7 +48,7 @@ public ValueWrapper createAddedValue() { return wrapper; } - + @Override public String getDisplayName() { if (assocRDef != null) { @@ -68,5 +68,5 @@ public RefinedAssociationDefinition getRefinedAssociationDefinition() { protected String getDebugName() { return "AssociationWrapper"; } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/CheckTableHeader.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/CheckTableHeader.java index c09e16a9b16..213964a0489 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/CheckTableHeader.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/CheckTableHeader.java @@ -66,7 +66,7 @@ public CheckTableHeader(String id, IModel> model) { } private void initLayout() { - + AjaxCheckBox check = new AjaxCheckBox(ID_CHECK, new PropertyModel(getModel(), ObjectWrapper.F_SELECTED)) { private static final long serialVersionUID = 1L; @@ -151,16 +151,16 @@ public String getObject() { } }); add(description); - + ToggleIconButton expandButton = new ToggleIconButton(ID_EXPAND, GuiStyleConstants.CLASS_ICON_EXPAND, GuiStyleConstants.CLASS_ICON_COLLAPSE) { private static final long serialVersionUID = 1L; - + @Override public void onClick(AjaxRequestTarget target) { onClickPerformed(target); } - + @Override public boolean isOn() { return !CheckTableHeader.this.getModelObject().isMinimalized(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ContainerWrapper.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ContainerWrapper.java index dfb0d3e4b86..9b120771456 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ContainerWrapper.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ContainerWrapper.java @@ -202,7 +202,7 @@ public void computeStripes() { } } } - + public boolean isShowInheritedObjectAttributes() { return showInheritedObjectAttributes; } @@ -375,7 +375,7 @@ public ItemWrapper createItem() { return wrapper.getItem(); } - + public void sort(final PageBase pageBase) { if (objectWrapper.isSorted()){ Collections.sort(properties, new Comparator(){ @@ -424,7 +424,7 @@ public int compare(ItemWrapper pw1, ItemWrapper pw2) { }); } } - + @Override public String debugDump() { return debugDump(0); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ContainerWrapperFactory.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ContainerWrapperFactory.java index 7162be7c0be..d8ad76c1f5f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ContainerWrapperFactory.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ContainerWrapperFactory.java @@ -91,7 +91,7 @@ public ContainerWrapper createContainerWrapper(Object cWrapper.setProperties(properties); cWrapper.computeStripes(); - + return cWrapper; } @@ -103,7 +103,7 @@ public ContainerWrapper createContainerWrapper(T cont List properties = createProperties(cWrapper, result); cWrapper.setProperties(properties); - + cWrapper.computeStripes(); return cWrapper; @@ -214,10 +214,10 @@ private List createProperties(ContainerWrapper cWrapper, OperationR } } else if (isShadowAssociation(cWrapper)) { - + // HACK: this should not be here. Find a better place. cWrapper.setDisplayName("prismContainer.shadow.associations"); - + PrismContext prismContext = objectWrapper.getObject().getPrismContext(); Map> assocMap = new HashMap<>(); PrismContainer associationContainer = cWrapper.getItem(); @@ -280,7 +280,7 @@ private List createProperties(ContainerWrapper cWrapper, OperationR for (Map.Entry> assocEntry : assocMap.entrySet()) { RefinedAssociationDefinition assocRDef = rOcDef.findAssociationDefinition(assocEntry.getKey()); - AssociationWrapper assocWrapper = new AssociationWrapper(cWrapper, assocEntry.getValue(), + AssociationWrapper assocWrapper = new AssociationWrapper(cWrapper, assocEntry.getValue(), cWrapper.isReadonly(), ValueStatus.NOT_CHANGED, assocRDef); properties.add(assocWrapper); } @@ -382,20 +382,20 @@ public ContainerWrapper createAssignmentContainerWrapper(Assignm result = new OperationResult(CREATE_PROPERTIES); PrismContainer assignmentContainer = container.asPrismContainerValue().getContainer(); - + ContainerWrapper cWrapper = new ContainerWrapper(assignmentContainer, status, path, readonly); List properties = createProperties(container, assignmentContainer.getDefinition(), cWrapper); cWrapper.setProperties(properties); - + cWrapper.computeStripes(); return cWrapper; } - + private List createProperties(AssignmentType container, PrismContainerDefinition definition, ContainerWrapper cWrapper) { Collection propertyDefinitions = definition.getDefinitions(); - + List properties = new ArrayList<>(); for (ItemDefinition itemDef : propertyDefinitions) { //TODO temporary decision to hide adminGuiConfiguration attribute (MID-3305) @@ -469,13 +469,13 @@ private List createProperties(AssignmentType container, PrismContai } } - + Collections.sort(properties, new ItemWrapperComparator()); return properties; } - + private boolean isShadowAssociation(ContainerWrapper cWrapper) { ObjectWrapper oWrapper = cWrapper.getObject(); if (oWrapper == null) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/DynamicFieldGroupPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/DynamicFieldGroupPanel.java index f84c08abc6a..d928b0adab5 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/DynamicFieldGroupPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/DynamicFieldGroupPanel.java @@ -45,19 +45,19 @@ public class DynamicFieldGroupPanel extends BasePanel formItems; - + public DynamicFieldGroupPanel(String id, String groupName, IModel> objectWrapper, List formItems, Form mainForm, PageBase parentPage) { super(id,objectWrapper); setParent(parentPage); this.formItems = formItems; initLayout(groupName, formItems, mainForm); } - + public DynamicFieldGroupPanel(String id, IModel> objectWrapper, @NotNull FormDefinitionType formDefinition, Form mainForm, PageBase parentPage) { super(id, objectWrapper); setParent(parentPage); @@ -68,15 +68,15 @@ public DynamicFieldGroupPanel(String id, IModel> objectWrapper, this.formItems = FormTypeUtil.getFormItems(formDefinition.getFormItems()); initLayout(groupName, formItems, mainForm); } - + private void initLayout(String groupName, List formItems, Form mainForm) { - + Label header = new Label(ID_HEADER, groupName); add(header); - + RepeatingView itemView = new RepeatingView(ID_PROPERTY); add(itemView); - + int i = 0; for (AbstractFormItemType formItem : formItems) { @@ -86,9 +86,9 @@ private void initLayout(String groupName, List formItems, itemView.add(dynamicFieldGroupPanel); continue; } - + ItemWrapper itemWrapper = createItemWrapper(formItem, getObjectWrapper()); - + if (itemWrapper instanceof ContainerWrapper) { PrismContainerPanel containerPanel = new PrismContainerPanel(itemView.newChildId(), Model.of((ContainerWrapper) itemWrapper), true, mainForm, getPageBase()); @@ -106,7 +106,7 @@ private void initLayout(String groupName, List formItems, } } - + private ItemWrapper createItemWrapper(AbstractFormItemType formField, ObjectWrapper objectWrapper) { ItemPathType itemPathType = GuiImplUtil.getPathType(formField); @@ -119,9 +119,9 @@ private ItemWrapper createItemWrapper(AbstractFormItemType formField, ObjectWrap ItemPath path = itemPathType.getItemPath(); ItemDefinition itemDef = objectWrapper.getObject().getDefinition().findItemDefinition(path); - + ItemWrapper itemWrapper; - + if (itemDef instanceof PrismContainerDefinition) { itemWrapper = objectWrapper.findContainerWrapper(path); } else { @@ -164,11 +164,11 @@ private void applyFormDefinition(ItemWrapper itemWrapper, AbstractFormItemType f } } - + public ObjectWrapper getObjectWrapper() { return getModelObject(); } - + public List getFormItems() { return formItems; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/DynamicFormPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/DynamicFormPanel.java index a201cc61f18..9cbdc1f2c58 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/DynamicFormPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/DynamicFormPanel.java @@ -105,7 +105,7 @@ private void initialize(final PrismObject prismObject, String formOid, Form objectWrapper = createObjectWrapper(owf, task, prismObject, enforceRequiredFields); wrapperModel = LoadableModel.create(() -> objectWrapper, true); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/H3Header.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/H3Header.java index 7664d5de976..6705aa78b3c 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/H3Header.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/H3Header.java @@ -120,7 +120,7 @@ private String getDisplayName() { if (key == null) { key = ""; } - + return PageBase.createStringResourceStatic(getPage(), key).getString(); // return new StringResourceModel(key, getPage(), null, key).getString(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ItemWrapper.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ItemWrapper.java index de600e88ac0..27525ac2ac3 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ItemWrapper.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ItemWrapper.java @@ -33,20 +33,20 @@ public interface ItemWrapper extends Revivable, DebugDumpable, Serializable { QName getName(); - + String getDisplayName(); void setDisplayName(String name); I getItem(); - + /** * Item definition. * The definition defines how the item will be displayed (type, read-only, read-write or * not displayed at all). This behavior can be overriden by readonly and visible flags. */ ID getItemDefinition(); - + /** * Read only flag. This is an override of the default behavior given by the definition. * If set to TRUE then it overrides the value from the definition. @@ -56,7 +56,7 @@ public interface ItemWrapper extends boolean isEmpty(); boolean hasChanged(); - + List getValues(); /** @@ -64,16 +64,16 @@ public interface ItemWrapper extends * should be displayed or not. */ boolean isVisible(); - + /** * Used to display the form elements with stripe in every other line. */ boolean isStripe(); - + void setStripe(boolean isStripe); - + ContainerWrapper getContainer(); - + void addValue(); boolean checkRequired(PageBase pageBase); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ObjectWrapper.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ObjectWrapper.java index 63b4fc4aa9b..55beaf592ec 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ObjectWrapper.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ObjectWrapper.java @@ -53,7 +53,7 @@ public class ObjectWrapper implements Serializable, Reviva public static final String F_SELECTED = "selected"; private static final Trace LOGGER = TraceManager.getTrace(ObjectWrapper.class); - + public static final String PROPERTY_CONTAINERS = "containers"; private PrismObject object; @@ -75,7 +75,7 @@ public class ObjectWrapper implements Serializable, Reviva private boolean showAssignments = false; // whether to show name and description properties and metadata container private boolean showInheritedObjectAttributes = true; - + // readonly flag is an override. false means "do not override" private boolean readonly = false; @@ -280,7 +280,7 @@ public ContainerWrapper findContainerWrapper(ItemPa return null; } - + public ContainerWrapper findMainContainerWrapper() { for (ContainerWrapper wrapper : getContainers()) { if (wrapper.isMain()) { @@ -289,7 +289,7 @@ public ContainerWrapper findMainContainerWrapper() { } return null; } - + public IW findPropertyWrapper(ItemPath path) { ContainerWrapper containerWrapper; ItemPath propertyPath; @@ -314,7 +314,7 @@ public void normalize() throws SchemaException { delta.applyTo(object); } } - + public void sort(PageBase pageBase) { ContainerWrapper main = findMainContainerWrapper(); if (main != null) { @@ -333,7 +333,7 @@ public ObjectDelta getObjectDelta() throws SchemaException { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Wrapper before creating delta:\n{}", this.debugDump()); } - + if (ContainerStatus.ADDING.equals(getStatus())) { return createAddingObjectDelta(); } @@ -356,11 +356,11 @@ public ObjectDelta getObjectDelta() throws SchemaException { // Make sure we have all the definitions object.getPrismContext().adopt(delta); } - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Creating delta from wrapper {}: existing object, creating delta:\n{}", this, delta.debugDump()); } - + return delta; } @@ -474,7 +474,7 @@ private ObjectDelta createAddingObjectDelta() throws SchemaException { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Creating delta from wrapper {}: adding object, creating complete ADD delta:\n{}", this, delta.debugDump()); } - + if (InternalsConfig.consistencyChecks) { delta.checkConsistence(true, true, true, ConsistencyCheckScope.THOROUGH); } @@ -599,7 +599,7 @@ public PrismContainerDefinition getRefinedAttributeDefinition() { } return null; } - + public void copyRuntimeStateTo(ObjectWrapper newWrapper) { newWrapper.setMinimalized(this.isMinimalized()); newWrapper.setShowEmpty(this.isShowEmpty()); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ObjectWrapperFactory.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ObjectWrapperFactory.java index 832b5f69e84..443a1324fcf 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ObjectWrapperFactory.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ObjectWrapperFactory.java @@ -60,7 +60,7 @@ public class ObjectWrapperFactory { private static final List INHERITED_OBJECT_SUBCONTAINERS = Arrays.asList( ObjectType.F_METADATA, ObjectType.F_EXTENSION); - + private static final List CONTAINERS_TO_IGNORE = Arrays.asList( SubjectedObjectSelectorType.COMPLEX_TYPE, TriggerType.COMPLEX_TYPE, @@ -109,7 +109,7 @@ public ObjectWrapper createObjectWrapper(String displa objectClassDefinitionForEditing = modelServiceLocator.getModelInteractionService().getEditObjectClassDefinition( (PrismObject) object, resource, authorizationPhase); } - + return createObjectWrapper(displayName, description, object, objectDefinitionForEditing, objectClassDefinitionForEditing, status, result); } catch (SchemaException | ConfigurationException | ObjectNotFoundException ex) { @@ -149,11 +149,11 @@ private ObjectWrapper createObjectWrapper(String displ if (LOGGER.isTraceEnabled()) { LOGGER.trace("Created object wrapper:\n{}", objectWrapper.debugDump()); } - + return objectWrapper; } - private List> createContainerWrappers(ObjectWrapper oWrapper, + private List> createContainerWrappers(ObjectWrapper oWrapper, PrismObject object, PrismObjectDefinition objectDefinitionForEditing, ContainerStatus cStatus, OperationResult pResult) { OperationResult result = pResult.createSubresult(CREATE_CONTAINERS); @@ -190,7 +190,7 @@ private List> c return containerWrappers; } - private PrismObjectDefinition getDefinition(PrismObject object, + private PrismObjectDefinition getDefinition(PrismObject object, PrismObjectDefinition objectDefinitionForEditing) { if (objectDefinitionForEditing != null) { return objectDefinitionForEditing; @@ -240,7 +240,7 @@ private void addContainerWrapper if (isIgnoreContainer(def.getTypeName())) { continue; } - + LOGGER.trace("ObjectWrapper.createContainerWrapper processing definition: {}", def); PrismContainerDefinition containerDef = (PrismContainerDefinition) def; @@ -293,15 +293,15 @@ private void addContainerWrapper } } } - - + + private boolean isIgnoreContainer(QName containerDefinitionName) { for (QName container : CONTAINERS_TO_IGNORE) { if (container.equals(containerDefinitionName)){ return true; } } - + return false; } @@ -347,7 +347,7 @@ private void addShadowContainers( ObjectWrapper oWrapper, PrismObject object, PrismObjectDefinition objectDefinitionForEditing, ContainerWrapperFactory cwf, ContainerStatus cStatus, OperationResult result) throws SchemaException { - + PrismContainer attributesContainer = object.findContainer(ShadowType.F_ATTRIBUTES); ContainerStatus status = attributesContainer != null ? cStatus : ContainerStatus.ADDING; if (attributesContainer == null) { @@ -381,7 +381,7 @@ private void addShadowContainers( result.addSubresult(cwf.getResult()); containers.add(attributesContainerWrapper); } - + private void addResourceContainers( List> containers, ObjectWrapper oWrapper, PrismObject object, diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PrismContainerPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PrismContainerPanel.java index 1ad9e3be3b8..4f950198ca4 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PrismContainerPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PrismContainerPanel.java @@ -51,7 +51,7 @@ public PrismContainerPanel(String id, final IModel model, bool this.pageBase = pageBase; LOGGER.trace("Creating container panel for {}", model.getObject()); - + add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; @@ -82,7 +82,7 @@ public boolean isVisible() { initLayout(model, form); } - + private void initLayout(final IModel model, final Form form) { PrismHeaderPanel header = new PrismHeaderPanel(ID_HEADER, model) { private static final long serialVersionUID = 1L; @@ -91,12 +91,12 @@ private void initLayout(final IModel model, final Form form) { protected void onButtonClick(AjaxRequestTarget target) { target.add(PrismContainerPanel.this.findParent(PrismObjectPanel.class)); } - + @Override public boolean isButtonsVisible() { return false; } - + }; header.add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; @@ -137,7 +137,7 @@ protected void populateItem(final ListItem item) { item.add(new PrismPropertyPanel("property", item.getModel(), form, pageBase)); item.add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; - + @Override public boolean isVisible() { return item.getModel().getObject().isVisible(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PrismHeaderPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PrismHeaderPanel.java index ab4e4fe02b9..fe90371ee02 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PrismHeaderPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PrismHeaderPanel.java @@ -32,7 +32,7 @@ /** * @author semancik - * + * * WARNING: super ugly code ahead */ public class PrismHeaderPanel extends BasePanel { @@ -45,15 +45,15 @@ public class PrismHeaderPanel extends BasePanel { private static final Trace LOGGER = TraceManager.getTrace(PrismHeaderPanel.class); - + public PrismHeaderPanel(String id, IModel model) { super(id, model); - + initLayout(model); } private void initLayout(final IModel model) { - + VisibleEnableBehaviour buttonsVisibleBehaviour = new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; @@ -62,7 +62,7 @@ public boolean isVisible() { return PrismHeaderPanel.this.isButtonsVisible(); } }; - + ToggleIconButton showMetadataButton = new ToggleIconButton(ID_SHOW_METADATA, GuiStyleConstants.CLASS_ICON_SHOW_METADATA, GuiStyleConstants.CLASS_ICON_SHOW_METADATA) { private static final long serialVersionUID = 1L; @@ -116,7 +116,7 @@ public boolean isOn() { ToggleIconButton sortPropertiesButton = new ToggleIconButton(ID_SORT_PROPERTIES, GuiStyleConstants.CLASS_ICON_SORT_ALPHA_ASC, GuiStyleConstants.CLASS_ICON_SORT_AMOUNT_ASC) { private static final long serialVersionUID = 1L; - + @Override public void onClick(AjaxRequestTarget target) { ObjectWrapper objectWrapper = getObjectWrapper(model); @@ -125,7 +125,7 @@ public void onClick(AjaxRequestTarget target) { onButtonClick(target); } - + @Override public boolean isOn() { return getObjectWrapper(model).isSorted(); @@ -133,13 +133,13 @@ public boolean isOn() { }; sortPropertiesButton.add(buttonsVisibleBehaviour); add(sortPropertiesButton); - + IModel headerLabelModel = new AbstractReadOnlyModel() { private static final long serialVersionUID = 1L; - + @Override public String getObject() { - + Object wrapper = model.getObject(); String displayName = null; if (wrapper instanceof ContainerWrapper) { @@ -158,10 +158,10 @@ public String getObject() { return getString(displayName, null, displayName); } }; - + add(new Label(ID_LABEL, headerLabelModel)); } - + private ObjectWrapper getObjectWrapper(IModel model) { Object wrapper = model.getObject(); ObjectWrapper objectWrapper = null; @@ -172,11 +172,11 @@ private ObjectWrapper getObjectWrapper(IModel model) { } return null; } - + protected void onButtonClick(AjaxRequestTarget target) { - + } - + public boolean isButtonsVisible() { return true; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PrismObjectPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PrismObjectPanel.java index 96801cd96c3..2c867ecd9ba 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PrismObjectPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PrismObjectPanel.java @@ -46,9 +46,9 @@ */ public class PrismObjectPanel extends Panel { private static final long serialVersionUID = 1L; - + private static final String STRIPED_CLASS = "striped"; - + private static final String ID_HEADER = "header"; private static final String ID_CONTAINERS = "containers"; private static final String ID_CONTAINER = "container"; @@ -67,7 +67,7 @@ public PrismObjectPanel(String id, IModel> model, ResourceRefer this.pageBase = pageBase; initLayout(model, image, form); } - + private void initLayout(final IModel> model, ResourceReference image, final Form> form) { Component headerComponent = createHeader(ID_HEADER, model, form); add(headerComponent); @@ -89,7 +89,7 @@ protected void onButtonClick(AjaxRequestTarget target) { addOrReplaceContainers(model, form, true); target.add(PrismObjectPanel.this); } - + @Override public boolean isButtonsVisible() { return true; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PrismPropertyPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PrismPropertyPanel.java index f901129c4ae..9a4fed41b49 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PrismPropertyPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PrismPropertyPanel.java @@ -52,7 +52,7 @@ */ public class PrismPropertyPanel extends Panel { private static final long serialVersionUID = 1L; - + private static final Trace LOGGER = TraceManager.getTrace(PrismPropertyPanel.class); private static final String ID_HAS_PENDING_MODIFICATION = "hasPendingModification"; private static final String ID_HELP = "help"; @@ -69,7 +69,7 @@ public PrismPropertyPanel(String id, final IModel model, Form form, PageBase this.pageBase = pageBase; LOGGER.trace("Creating property panel for {}", model.getObject()); - + setOutputMarkupId(true); add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; @@ -96,7 +96,7 @@ private void initLayout(final IModel model, final Form form) { labelContainer.setOutputMarkupId(true); labelContainer.add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; - + @Override public boolean isVisible() { return labelContainerVisible; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PrismValuePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PrismValuePanel.java index f7351e9f9b0..3e0c3889da7 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PrismValuePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PrismValuePanel.java @@ -97,7 +97,7 @@ public class PrismValuePanel extends Panel { private static final String ID_ADD_BUTTON = "addButton"; private static final String ID_REMOVE_BUTTON = "removeButton"; private static final String ID_VALUE_CONTAINER = "valueContainer"; - + private static final Trace LOGGER = TraceManager.getTrace(PrismValuePanel.class); private IModel valueWrapperModel; @@ -395,8 +395,8 @@ protected void onUpdate(AjaxRequestTarget target) { // Validation occurs when submitting the form // if (form != null) { -// AjaxFormValidatingBehavior validator = new AjaxFormValidatingBehavior(form, "Blur"); -// +// AjaxFormValidatingBehavior validator = new AjaxFormValidatingBehavior(form, "Blur"); +// // formComponent.add(validator); // } } @@ -407,7 +407,7 @@ protected void onUpdate(AjaxRequestTarget target) { return component; } - + // normally this method returns an InputPanel; // however, for some special readonly types (like ObjectDeltaType) it will return a Panel @@ -415,7 +415,7 @@ private Panel createTypedInputComponent(String id) { // ValueWrapper valueWrapper = model.getObject(); // ItemWrapper itemWrapper = final Item item = valueWrapperModel.getObject().getItem().getItem(); - + Panel panel = null; if (item instanceof PrismProperty) { final PrismProperty property = (PrismProperty) item; @@ -441,16 +441,16 @@ private Panel createTypedInputComponent(String id) { // return WebComponentUtil.createEnumPanel(ActivationStatusType.class, id, new PropertyModel(valueWrapperModel, baseExpression), this); // } // } - + if (DOMUtil.XSD_DATETIME.equals(valueType)) { panel = new DatePanel(id, new PropertyModel(valueWrapperModel, baseExpression)); - + } else if (ProtectedStringType.COMPLEX_TYPE.equals(valueType)) { panel = new PasswordPanel(id, new PropertyModel(valueWrapperModel, baseExpression), valueWrapperModel.getObject().isReadonly()); } else if (DOMUtil.XSD_BOOLEAN.equals(valueType)) { panel = new TriStateComboPanel(id, new PropertyModel(valueWrapperModel, baseExpression)); - + } else if (SchemaConstants.T_POLY_STRING_TYPE.equals(valueType)) { InputPanel inputPanel; PrismPropertyDefinition def = property.getDefinition(); @@ -466,22 +466,22 @@ private Panel createTypedInputComponent(String id) { lookupTableUid, options, pageBase, task, result); if (lookupTable != null) { - + inputPanel = new AutoCompleteTextPanel(id, new LookupPropertyModel(valueWrapperModel, baseExpression + ".orig", lookupTable.asObjectable()), String.class) { - + @Override public Iterator getIterator(String input) { return prepareAutoCompleteList(input, lookupTable).iterator(); } }; - + } else { inputPanel = new TextPanel<>(id, new PropertyModel(valueWrapperModel, baseExpression + ".orig"), String.class); } } else { - + inputPanel = new TextPanel<>(id, new PropertyModel(valueWrapperModel, baseExpression + ".orig"), String.class); } @@ -490,18 +490,18 @@ public Iterator getIterator(String input) { // inputPanel.getBaseFormComponent().setRequired(true); // } panel = inputPanel; - + } else if(DOMUtil.XSD_BASE64BINARY.equals(valueType)) { panel = new UploadDownloadPanel(id, valueWrapperModel.getObject().isReadonly()){ - + @Override public InputStream getStream() { Object object = ((PrismPropertyValue) valueWrapperModel.getObject().getValue()).getValue(); return object != null ? new ByteArrayInputStream((byte[]) object) : new ByteArrayInputStream(new byte[0]); // return super.getStream(); } - + @Override public void updateValue(byte[] file) { ((PrismPropertyValue) valueWrapperModel.getObject().getValue()).setValue(file); @@ -547,7 +547,7 @@ public DeltaDto getObject() { }); } else if (QueryType.COMPLEX_TYPE.equals(valueType) || CleanupPoliciesType.COMPLEX_TYPE.equals(valueType)) { return new TextAreaPanel(id, new AbstractReadOnlyModel() { - + private static final long serialVersionUID = 1L; @Override @@ -578,16 +578,16 @@ public Object getObject() { Class type = XsdTypeMapper.getXsdToJavaMapping(valueType); if (type != null && type.isPrimitive()) { type = ClassUtils.primitiveToWrapper(type); - - } - + + } + if (isEnum(property)) { Class clazz = pageBase.getPrismContext().getSchemaRegistry().determineClassForType(definition.getTypeName()); - + if (clazz != null) { return WebComponentUtil.createEnumPanel(clazz, id, new PropertyModel(valueWrapperModel, baseExpression), this); } - + return WebComponentUtil.createEnumPanel(definition, id, new PropertyModel<>(valueWrapperModel, baseExpression), this); } // // default QName validation is a bit weird, so let's treat QNames as strings [TODO finish this - at the parsing side] @@ -608,11 +608,11 @@ public Object getObject() { lookupTableUid, options, pageBase, task, result); if (lookupTable != null) { - + panel = new AutoCompleteTextPanel(id, new LookupPropertyModel(valueWrapperModel, baseExpression, lookupTable == null ? null : lookupTable.asObjectable()), type) { - - + + @Override public Iterator getIterator(String input) { return prepareAutoCompleteList(input, lookupTable).iterator(); @@ -626,18 +626,18 @@ protected void updateFeedbackPanel(AutoCompleteTextField input, boolean isError, target.add(PrismValuePanel.this.get(ID_FEEDBACK)); } }; - + } else { - + panel = new TextPanel<>(id, new PropertyModel(valueWrapperModel, baseExpression), type); - + } } else { panel = new TextPanel<>(id, new PropertyModel(valueWrapperModel, baseExpression), type); } } - } else if (item instanceof PrismReference) { + } else if (item instanceof PrismReference) { PrismContext prismContext = item.getPrismContext(); if (prismContext == null) { prismContext = pageBase.getPrismContext(); @@ -647,10 +647,10 @@ protected void updateFeedbackPanel(AutoCompleteTextField input, boolean isError, if (targetTypeName != null && prismContext != null) { targetClass = prismContext.getSchemaRegistry().determineCompileTimeClass(targetTypeName); } - final Class typeClass = targetClass != null ? targetClass : + final Class typeClass = targetClass != null ? targetClass : (item.getDefinition().getTypeClassIfKnown() != null ? item.getDefinition().getTypeClassIfKnown() : FocusType.class); Collection typeClasses = new ArrayList(); - + // HACK HACK MID-3201 MID-3231 if (isUserOrgItem(item, typeClass)) { typeClasses.add(UserType.class); @@ -658,23 +658,23 @@ protected void updateFeedbackPanel(AutoCompleteTextField input, boolean isError, } else { typeClasses.add(typeClass); } - + panel = new ValueChoosePanel(id, new PropertyModel<>(valueWrapperModel, "value"), item.getValues(), false, typeClasses); - + } else if (item instanceof PrismContainer) { AssociationWrapper itemWrapper = (AssociationWrapper) valueWrapperModel.getObject().getItem(); final PrismContainer container = (PrismContainer) item; PrismContainerDefinition definition = container.getDefinition(); QName valueType = definition.getTypeName(); - + if (ShadowAssociationType.COMPLEX_TYPE.equals(valueType)) { - + PrismContext prismContext = item.getPrismContext(); if (prismContext == null) { prismContext = pageBase.getPrismContext(); } - + ShadowType shadowType = ((ShadowType)itemWrapper.getContainer().getObject().getObject().asObjectable()); PrismObject resource = shadowType.getResource().asPrismObject(); // HACK. The revive should not be here. Revive is no good. The next use of the resource will @@ -695,12 +695,12 @@ protected void updateFeedbackPanel(AutoCompleteTextField input, boolean isError, } RefinedAssociationDefinition assocDef = itemWrapper.getRefinedAssociationDefinition(); RefinedObjectClassDefinition assocTargetDef = assocDef.getAssociationTarget(); - + ObjectQuery query = getAssociationsSearchQuery(prismContext, resource, assocTargetDef.getTypeName(), assocTargetDef.getKind()); - + List values = item.getValues(); - return new AssociationValueChoicePanel(id, valueWrapperModel, values, false, ShadowType.class, + return new AssociationValueChoicePanel(id, valueWrapperModel, values, false, ShadowType.class, query, assocTargetDef); } } @@ -709,7 +709,7 @@ protected void updateFeedbackPanel(AutoCompleteTextField input, boolean isError, } private boolean isUserOrgItem(Item item, Class referenceType) { - return (referenceType == ObjectType.class || referenceType == FocusType.class) && + return (referenceType == ObjectType.class || referenceType == FocusType.class) && (AbstractRoleType.F_APPROVER_REF.equals(item.getElementName()) || AbstractRoleType.F_OWNER_REF.equals(item.getElementName())); } @@ -744,12 +744,12 @@ private boolean isEnum(PrismProperty property){ //// Object realValue = property.getAnyRealValue(); if (definition == null){ return property.getValueClass().isEnum(); - } -// + } +// // QName defName = definition.getName(); // Class clazz = definition.getPrismContext().getSchemaRegistry().determineCompileTimeClass(defName); -// -// return ((clazz != null && clazz.isEnum()) || ActivationType.F_ADMINISTRATIVE_STATUS.equals(definition.getName()) +// +// return ((clazz != null && clazz.isEnum()) || ActivationType.F_ADMINISTRATIVE_STATUS.equals(definition.getName()) // || ActivationType.F_LOCKOUT_STATUS.equals(definition.getName()) || ); return (definition.getAllowedValues() != null && definition.getAllowedValues().size() > 0); } @@ -789,15 +789,15 @@ private String getAttributeName(ResourceAttribute attr) { if (attr.getDisplayName() != null){ return attr.getDisplayName(); } - + if (attr.getNativeAttributeName() != null){ return attr.getNativeAttributeName(); } - + if (attr.getElementName() != null){ return attr.getElementName().getLocalPart(); } - + return null; //TODO: is this ok?? or better is exception or some default name?? } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PropertyWrapper.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PropertyWrapper.java index c053426728d..a9f1016fb57 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PropertyWrapper.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/PropertyWrapper.java @@ -46,7 +46,7 @@ public PropertyWrapper(@Nullable ContainerWrapper container, I property, boolean && PasswordType.F_VALUE.equals(property.getElementName())) { super.setDisplayName("prismPropertyPanel.name.credentials.password"); } - + values = createValues(); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ValueWrapper.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ValueWrapper.java index cb25056532d..ebc07dd6799 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ValueWrapper.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/prism/ValueWrapper.java @@ -37,7 +37,7 @@ * @author lazyman */ public class ValueWrapper implements Serializable, DebugDumpable { - + private static final Trace LOGGER = TraceManager.getTrace(ValueWrapper.class); private ItemWrapper item; @@ -62,7 +62,7 @@ public ValueWrapper(ItemWrapper property, PrismValue value, PrismValue oldValue, this.item = property; this.status = status; - + if (value != null) { if (value instanceof PrismPropertyValue) { @@ -85,7 +85,7 @@ public ValueWrapper(ItemWrapper property, PrismValue value, PrismValue oldValue, this.value = value.clone(); } } - + if (oldValue == null && value instanceof PrismPropertyValue) { T val = ((PrismPropertyValue) this.value).getValue(); if (val instanceof PolyString) { @@ -94,7 +94,7 @@ public ValueWrapper(ItemWrapper property, PrismValue value, PrismValue oldValue, } oldValue = new PrismPropertyValue(CloneUtil.clone(val), this.value.getOriginType(), this.value.getOriginObject()); } - + this.oldValue = oldValue; } @@ -129,7 +129,7 @@ public void normalize(PrismContext prismContext) { if (prismContext != null){ PrismUtil.recomputePrismPropertyValue(ppVal, prismContext); } - + } else if (ppVal.getValue() instanceof DisplayableValue) { DisplayableValue displayableValue = (DisplayableValue) ppVal.getValue(); ppVal.setValue((T) displayableValue.getValue()); @@ -144,7 +144,7 @@ public boolean hasValueChanged() { public boolean isReadonly() { return item.isReadonly(); } - + public boolean isEmpty() { if (value == null || value.isEmpty()) { return true; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/progress/ProgressPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/progress/ProgressPanel.java index 0c62a3f4a62..fc1d46291f0 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/progress/ProgressPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/progress/ProgressPanel.java @@ -78,7 +78,7 @@ public ProgressPanel(String id, IModel model, ProgressReporter prog private void initLayout(ProgressReportingAwarePage page) { progressForm = new Form<>(ID_PROGRESS_FORM, true); add(progressForm); - + contentsPanel = new WebMarkupContainer(ID_CONTENTS_PANEL); contentsPanel.setOutputMarkupId(true); progressForm.add(contentsPanel); @@ -203,10 +203,10 @@ public String getObject() { } }); contentsPanel.add(executionTime); - + initButtons(progressForm, page); } - + private void initButtons(final Form progressForm, final ProgressReportingAwarePage page) { AjaxSubmitButton abortButton = new AjaxSubmitButton(ID_ABORT, diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/progress/ProgressReportingAwarePage.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/progress/ProgressReportingAwarePage.java index 1f70ac73fa7..3bebe5a8b44 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/progress/ProgressReportingAwarePage.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/progress/ProgressReportingAwarePage.java @@ -40,7 +40,7 @@ public interface ProgressReportingAwarePage { void startProcessing(AjaxRequestTarget target, OperationResult result); - + void finishProcessing(AjaxRequestTarget target, OperationResult result, boolean returningFromAsync); // things from PageBase (todo factor this out eventually) @@ -54,7 +54,7 @@ public interface ProgressReportingAwarePage { Task createSimpleTask(String name); WebApplicationConfiguration getWebApplicationConfiguration(); - + WebMarkupContainer getFeedbackPanel(); void continueEditing(AjaxRequestTarget target); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/sample/HelloObjectTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/sample/HelloObjectTabPanel.java index bdd1edef03e..4c8921cdff9 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/sample/HelloObjectTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/sample/HelloObjectTabPanel.java @@ -29,12 +29,12 @@ /** * Sample showing a custom object form that displays simple greeting. - * + * * @author Radovan Semancik * */ public class HelloObjectTabPanel extends AbstractObjectTabPanel { - + private static final String ID_HELLO_LABEL = "helloLabel"; public HelloObjectTabPanel(String id, Form mainForm, LoadableModel> focusModel, PageBase pageBase) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/sample/SampleFormFocusTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/sample/SampleFormFocusTabPanel.java index bb2d6f78973..f41e6c22304 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/sample/SampleFormFocusTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/sample/SampleFormFocusTabPanel.java @@ -88,7 +88,7 @@ private void initLayout(final LoadableModel> focusModel, Loadab List> availableRoles; try { availableRoles = pageBase.getModelService().searchObjects(RoleType.class, null, null, task, task.getResult()); - } catch (SchemaException | ObjectNotFoundException | SecurityViolationException | CommunicationException | + } catch (SchemaException | ObjectNotFoundException | SecurityViolationException | CommunicationException | ConfigurationException | ExpressionEvaluationException e) { task.getResult().recordFatalError(e); LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load roles", e); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/search/SearchValue.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/search/SearchValue.java index e47cdf02995..80a9700e09a 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/search/SearchValue.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/search/SearchValue.java @@ -64,7 +64,7 @@ public String getLabel() { if (displayName != null) { return displayName; } else if (value != null){ - + return value.toString(); } } @@ -85,11 +85,11 @@ public void setValue(T value) { setLabel(dv.getLabel()); } } - + public String getDisplayName() { return displayName; } - + public void setDisplayName(String displayName) { this.displayName = displayName; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/search/TextPopupPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/search/TextPopupPanel.java index 8ea6fd1c73a..8c9f7386a86 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/search/TextPopupPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/search/TextPopupPanel.java @@ -85,9 +85,9 @@ private TextField initTextField() { if (lookup == null) { return new TextField(ID_TEXT_INPUT, new PropertyModel(getModel(), SearchValue.F_VALUE)); } - + LookupPropertyModel lookupPropertyModel = new LookupPropertyModel(getModel(), SearchValue.F_VALUE, lookup.asObjectable()) { - + private static final long serialVersionUID = 1L; @Override @@ -107,8 +107,8 @@ protected Iterator getChoices(String input) { return prepareAutoCompleteList(input).iterator(); } - - + + }; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/AssignmentListDataProvider.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/AssignmentListDataProvider.java index a844a31e735..c97747d32f9 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/AssignmentListDataProvider.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/AssignmentListDataProvider.java @@ -59,14 +59,14 @@ public AssignmentListDataProvider(Component component, IModel internalIterator(long first, long count) { getAvailableData().clear(); List list = searchThroughList(); - + if (sortable && getSort() != null) { sort(list); } @@ -112,22 +112,22 @@ protected int internalSize() { return list.size(); } - + public List getSelectedData() { return getAvailableData().stream().filter(a -> a.isSelected()).collect(Collectors.toList()); } - + private List searchThroughList() { List list = model.getObject(); - + if (list == null || list.isEmpty()) { return null; } - + if (getQuery() == null || getQuery().getFilter() == null) { return list; } - + List filtered = list.stream().filter(a -> { try { return ObjectQuery.match(a.getAssignment(), getQuery().getFilter(), null); @@ -136,10 +136,10 @@ private List searchThroughList() { } }).collect(Collectors.toList()); return filtered; - + } - - - - + + + + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/ListDataProvider.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/ListDataProvider.java index e159c814ad8..2783b3e812b 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/ListDataProvider.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/ListDataProvider.java @@ -106,6 +106,6 @@ protected int internalSize() { return list.size(); } - - + + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/ListDataProvider2.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/ListDataProvider2.java index a10f10f9872..e68b0b51219 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/ListDataProvider2.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/ListDataProvider2.java @@ -53,7 +53,7 @@ public ListDataProvider2(Component Component, IModel> model) { @Override public Iterator internalIterator(long first, long count) { - + getAvailableData().clear(); List list = model.getObject(); @@ -97,7 +97,7 @@ public List getSelectedObjects() { return allSelected; } - + @SuppressWarnings("unchecked") protected > void sort(List list) { Collections.sort(list, new Comparator() { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/Selectable.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/Selectable.java index d94f285e35f..9dce83024dd 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/Selectable.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/Selectable.java @@ -36,7 +36,7 @@ public boolean isSelected() { public void setSelected(boolean selected) { this.selected = selected; } - + public S getValue() { return (S) this; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/SelectableBean.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/SelectableBean.java index 6ca0fa4656c..6ec67397fb3 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/SelectableBean.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/SelectableBean.java @@ -40,19 +40,19 @@ public class SelectableBean extends Selectable implem private static final long serialVersionUID = 1L; public static final String F_VALUE = "value"; - + private static final Trace LOGGER = TraceManager.getTrace(SelectableBean.class); /** * Value of object that this bean represents. It may be null in case that non-success result is set. */ private T value; - + /** * Result of object retrieval (or attempt of object retrieval). It case that it is not error the result is optional. */ private OperationResult result; - + private List menuItems; public SelectableBean() { @@ -69,7 +69,7 @@ public T getValue() { public void setValue(T value) { this.value = value; } - + public OperationResult getResult() { return result; } @@ -77,7 +77,7 @@ public OperationResult getResult() { public void setResult(OperationResult result) { this.result = result; } - + public void setResult(OperationResultType resultType) throws SchemaException { this.result = OperationResult.createOperationResult(resultType); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/SimplePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/SimplePanel.java index 6375001e048..68d1e83e2f9 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/SimplePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/SimplePanel.java @@ -47,17 +47,17 @@ public SimplePanel(String id, IModel model) { public PageBase getPageBase() { return WebComponentUtil.getPageBase(this); } - + public void setModelObject(T obj){ setDefaultModelObject(obj); } - + protected abstract void initLayout(); // public PrismContext getPrismContext(){ // return getPageBase().getPrismContext(); // } - + // public WebMarkupContainer getFeedbackPanel(){ // return getPageBase().getFeedbackPanel(); // } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/SummaryTag.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/SummaryTag.java index 7938a9e7451..35c1c9dd6a7 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/SummaryTag.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/SummaryTag.java @@ -29,20 +29,20 @@ * */ public abstract class SummaryTag extends Panel { - + private static final String ID_TAG_ICON = "summaryTagIcon"; private static final String ID_TAG_LABEL = "summaryTagLabel"; - + private boolean initialized = false; private String cssClass; private String iconCssClass; private String label; private String color = null; private boolean hideTag = false; - + public SummaryTag(String id, final IModel> model) { super(id, model); - + Label tagIcon = new Label(ID_TAG_ICON, ""); tagIcon.add(new AttributeModifier("class", new SummaryTagWrapperModel(model) { @Override @@ -51,14 +51,14 @@ protected String getValue() { } })); add(tagIcon); - + add(new Label(ID_TAG_LABEL, new SummaryTagWrapperModel(model) { @Override protected String getValue() { return getLabel(); } })); - + add(new AttributeModifier("style", new SummaryTagWrapperModel(model) { @Override protected String getValue() { @@ -68,15 +68,15 @@ protected String getValue() { return "color: " + getColor(); } })); - + add(new AttributeModifier("class", new SummaryTagWrapperModel(model) { @Override protected String getValue() { return getCssClass(); } })); - - add(new VisibleEnableBehaviour(){ + + add(new VisibleEnableBehaviour(){ @Override public boolean isVisible(){ if (!initialized) { @@ -86,7 +86,7 @@ public boolean isVisible(){ } }); } - + public String getCssClass() { return cssClass; } @@ -102,7 +102,7 @@ public String getIconCssClass() { public void setIconCssClass(String iconCssClass) { this.iconCssClass = iconCssClass; } - + public String getLabel() { return label; } @@ -110,7 +110,7 @@ public String getLabel() { public void setLabel(String label) { this.label = label; } - + public String getColor() { return color; } @@ -118,7 +118,7 @@ public String getColor() { public void setColor(String color) { this.color = color; } - + public boolean isHideTag() { return hideTag; } @@ -130,7 +130,7 @@ public void setHideTag(boolean hideTag) { protected abstract void initialize(ObjectWrapper objectWrapper); abstract class SummaryTagWrapperModel extends ReadOnlyWrapperModel { - + public SummaryTagWrapperModel(IModel> wrapperModel) { super(wrapperModel); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/SummaryTagSimple.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/SummaryTagSimple.java index d3b850c1dcb..7d02c94eda5 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/SummaryTagSimple.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/SummaryTagSimple.java @@ -42,7 +42,7 @@ public abstract class SummaryTagSimple extends Panel { public SummaryTagSimple(String id, final IModel model) { super(id, model); - + Label tagIcon = new Label(ID_TAG_ICON, ""); tagIcon.add(new AttributeModifier("class", new SummaryTagModel(model) { @Override @@ -51,14 +51,14 @@ protected String getValue() { } })); add(tagIcon); - + add(new Label(ID_TAG_LABEL, new SummaryTagModel(model) { @Override protected String getValue() { return getLabel(); } })); - + add(new AttributeModifier("style", new SummaryTagModel(model) { @Override protected String getValue() { @@ -68,8 +68,8 @@ protected String getValue() { return "color: " + getColor(); } })); - - add(new VisibleEnableBehaviour(){ + + add(new VisibleEnableBehaviour(){ @Override public boolean isVisible(){ if (!initialized) { @@ -87,7 +87,7 @@ public String getIconCssClass() { public void setIconCssClass(String iconCssClass) { this.iconCssClass = iconCssClass; } - + public String getLabel() { return label; } @@ -95,7 +95,7 @@ public String getLabel() { public void setLabel(String label) { this.label = label; } - + public String getColor() { return color; } @@ -103,7 +103,7 @@ public String getColor() { public void setColor(String color) { this.color = color; } - + public boolean isHideTag() { return hideTag; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/Validatable.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/Validatable.java index b04b894d055..3cd350ff44a 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/Validatable.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/Validatable.java @@ -2,7 +2,7 @@ @FunctionalInterface public interface Validatable { - + public boolean isEmpty(); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/VisibleEnableBehaviour.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/VisibleEnableBehaviour.java index 3ca95054547..ef5546c065f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/VisibleEnableBehaviour.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/util/VisibleEnableBehaviour.java @@ -21,7 +21,7 @@ /** * TODO: move to com.evolveum.midpoint.gui.api.util - * + * * @author lazyman */ public class VisibleEnableBehaviour extends Behavior { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/wizard/resource/NameStep.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/wizard/resource/NameStep.java index 9a0f5acf799..0315869c7ca 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/wizard/resource/NameStep.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/wizard/resource/NameStep.java @@ -308,7 +308,7 @@ public PrismObject getObject(String id, } return choices.getObject().get(Integer.parseInt(id)); } - + @Override public Object getDisplayValue(PrismObject object) { if (object == null) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/wizard/resource/component/schemahandling/ResourceCredentialsEditor.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/wizard/resource/component/schemahandling/ResourceCredentialsEditor.java index 597a04b5930..6a9d96577b5 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/wizard/resource/component/schemahandling/ResourceCredentialsEditor.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/wizard/resource/component/schemahandling/ResourceCredentialsEditor.java @@ -187,7 +187,7 @@ protected void editPerformed(AjaxRequestTarget target, MappingType object){ @Override public List getObject() { return WebModelServiceUtils.createObjectReferenceList(ValuePolicyType.class, getPageBase(), passPolicyMap); - + } }, new ObjectReferenceChoiceRenderer(passPolicyMap)); parentPage.addEditingEnabledBehavior(passwordPolicy); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/wizard/resource/component/schemahandling/ResourceDependencyEditor.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/wizard/resource/component/schemahandling/ResourceDependencyEditor.java index 862c7b49c1c..4f2b5ca2d99 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/wizard/resource/component/schemahandling/ResourceDependencyEditor.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/wizard/resource/component/schemahandling/ResourceDependencyEditor.java @@ -186,7 +186,7 @@ public List getObject() { return WebModelServiceUtils.createObjectReferenceList(ResourceType.class, getPageBase(), resourceMap); } }, new ObjectReferenceChoiceRenderer(resourceMap)); - + resource.add(prepareAjaxOnComponentTagUpdateBehavior()); parentPage.addEditingEnabledBehavior(resource); dependencyBody.add(resource); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/wizard/resource/component/schemahandling/modal/MappingEditorDialog.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/wizard/resource/component/schemahandling/modal/MappingEditorDialog.java index b48bca9ccb5..e60b1325973 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/wizard/resource/component/schemahandling/modal/MappingEditorDialog.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/wizard/resource/component/schemahandling/modal/MappingEditorDialog.java @@ -256,7 +256,7 @@ public List getObject() { @Override protected IChoiceRenderer createRenderer() { return new StringChoiceRenderer("Channel.", "#"); - + } }; form.add(channel); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/wizard/resource/component/synchronization/SynchronizationReactionEditor.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/wizard/resource/component/synchronization/SynchronizationReactionEditor.java index e53fa3d2b01..f5bf1e29302 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/wizard/resource/component/synchronization/SynchronizationReactionEditor.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/wizard/resource/component/synchronization/SynchronizationReactionEditor.java @@ -139,7 +139,7 @@ public List getObject() { @Override protected IChoiceRenderer createRenderer() { return new StringChoiceRenderer("Channel.", "#"); - + } }; add(channel); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/AbstractWrapperModel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/AbstractWrapperModel.java index d75f6546892..a4c674782ca 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/AbstractWrapperModel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/AbstractWrapperModel.java @@ -42,7 +42,7 @@ public IModel> getWrapperModel() { public ObjectWrapper getWrapper() { return wrapperModel.getObject(); } - + public O getObjectType() { return wrapperModel.getObject().getObject().asObjectable(); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/ContainerWrapperFromObjectWrapperModel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/ContainerWrapperFromObjectWrapperModel.java index a8c97f76979..62d617abc2f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/ContainerWrapperFromObjectWrapperModel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/ContainerWrapperFromObjectWrapperModel.java @@ -32,7 +32,7 @@ /** * Model that returns property real values. This implementation works on ObjectWrapper models (not PrismObject). - * + * * Simple implementation, now it can't handle multivalue properties. * * @author lazyman @@ -56,7 +56,7 @@ public ContainerWrapperFromObjectWrapperModel(IModel> model, It this.path = path; } - + @Override public void detach() { } @@ -70,7 +70,7 @@ public ContainerWrapper getObject() { @Override public void setObject(ContainerWrapper arg0) { throw new UnsupportedOperationException("ContainerWrapperFromObjectWrapperModel.setObject called"); - + } } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/LookupPropertyModel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/LookupPropertyModel.java index f6f9e69cec5..304fd06b30d 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/LookupPropertyModel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/LookupPropertyModel.java @@ -49,7 +49,7 @@ public LookupPropertyModel(Object modelObject, String expression, LookupTableTyp this.lookupTable = lookupTable; this.isStrict = isStrict; } - + public boolean isSupportsDisplayName() { return false; } @@ -68,7 +68,7 @@ public T getObject() { final Object target = getInnermostModelOrObject(); if (target != null) { - + Object value = null; if (isSupportsDisplayName()) { value = PropertyResolver.getValue("displayName", target); @@ -76,12 +76,12 @@ public T getObject() { return (T) value; } } - + value = PropertyResolver.getValue(expression, target); if (value == null) { return null; } - String key = value.toString(); + String key = value.toString(); if (lookupTable != null) { for (LookupTableRowType row : lookupTable.getRow()) { @@ -94,7 +94,7 @@ public T getObject() { } return null; } - + @Override public void setObject(T object) { final String expression = propertyExpression(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/PrismPropertyRealValueFromContainerableModel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/PrismPropertyRealValueFromContainerableModel.java index 2ef0ee06b48..37d9887e77d 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/PrismPropertyRealValueFromContainerableModel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/PrismPropertyRealValueFromContainerableModel.java @@ -32,9 +32,9 @@ /** * Model that returns property real values. This implementation works on containerable models (not wrappers). - * + * * Simple implementation, now it can't handle multivalue properties. - * + * * @author lazyman * @author semancik * @author mederly diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/PrismPropertyRealValueFromObjectWrapperModel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/PrismPropertyRealValueFromObjectWrapperModel.java index bbcd3126472..5ba120a50ec 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/PrismPropertyRealValueFromObjectWrapperModel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/PrismPropertyRealValueFromObjectWrapperModel.java @@ -35,7 +35,7 @@ /** * Model that returns property real values. This implementation works on ObjectWrapper models (not PrismObject). - * + * * Simple implementation, now it can't handle multivalue properties. * * @author lazyman @@ -59,7 +59,7 @@ public PrismPropertyRealValueFromObjectWrapperModel(IModel> mod public PrismPropertyRealValueFromObjectWrapperModel(IModel> model, ItemPath path) { this(model, path, null); } - + public PrismPropertyRealValueFromObjectWrapperModel(IModel> model, ItemPath path, T defaltValue) { super(model); Validate.notNull(path, "Item path must not be null."); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/PrismPropertyRealValueFromPrismObjectModel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/PrismPropertyRealValueFromPrismObjectModel.java index 8f72b4e8d06..6e344e34831 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/PrismPropertyRealValueFromPrismObjectModel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/PrismPropertyRealValueFromPrismObjectModel.java @@ -34,9 +34,9 @@ /** * Model that returns property real values. This implementation works on PrismObject models (not wrappers). - * + * * Simple implementation, now it can't handle multivalue properties. - * + * * @author lazyman * @author semancik */ diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/PropertyWrapperFromObjectWrapperModel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/PropertyWrapperFromObjectWrapperModel.java index 03b32701eec..8c66cf3e508 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/PropertyWrapperFromObjectWrapperModel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/PropertyWrapperFromObjectWrapperModel.java @@ -31,7 +31,7 @@ /** * Model that returns property real values. This implementation works on ObjectWrapper models (not PrismObject). - * + * * Simple implementation, now it can't handle multivalue properties. * * @author lazyman diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/ReadOnlyPrismObjectFromObjectWrapperModel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/ReadOnlyPrismObjectFromObjectWrapperModel.java index fc9257913ba..34aa31df34d 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/ReadOnlyPrismObjectFromObjectWrapperModel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/ReadOnlyPrismObjectFromObjectWrapperModel.java @@ -25,7 +25,7 @@ /** * Model that returns property real values. This implementation works on ObjectWrapper models (not PrismObject). - * + * * Simple implementation, now it can't handle multivalue properties. * * @author mederly diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/ReadOnlyWrapperModel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/ReadOnlyWrapperModel.java index a41280a6ed3..dd2337e760b 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/ReadOnlyWrapperModel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/model/ReadOnlyWrapperModel.java @@ -29,7 +29,7 @@ public abstract class ReadOnlyWrapperModel extends Abstr public ReadOnlyWrapperModel(IModel> wrapperModel) { super(wrapperModel); } - + @Override public void setObject(Object object) { throw new UnsupportedOperationException("Model " + getClass() + 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 651aba06623..dfcc3562d2f 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 @@ -66,14 +66,14 @@ protected void prepareObjectDeltaForModify(ObjectDelta focusDelta) throws Sch .findContainerDefinition(AbstractRoleType.F_INDUCEMENT); handleAssignmentDeltas(focusDelta, inducementsModel.getObject(), def); } - - + + @Override protected void prepareObjectForAdd(PrismObject focus) throws SchemaException { super.prepareObjectForAdd(focus); // handleAssignmentForAdd(focus, AbstractRoleType.F_INDUCEMENT, inducementsModel.getObject()); } - + @Override protected void initializeModel(final PrismObject objectToEdit) { super.initializeModel(objectToEdit); 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 617090c01d9..6798bf6cb47 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 @@ -91,7 +91,7 @@ public abstract class PageAdminFocus extends PageAdminObjec @Override protected void initializeModel(final PrismObject objectToEdit) { super.initializeModel(objectToEdit); - + projectionModel = new LoadableModel>>(false) { private static final long serialVersionUID = 1L; @@ -114,7 +114,7 @@ public int countInternal() { return countAssignments(); } }; - + policyRulesModel = new CountableLoadableModel(false) { private static final long serialVersionUID = 1L; @@ -128,11 +128,11 @@ public int countInternal() { return countPolicyRules(); } }; - - + + delegatedToMeModel= new LoadableModel>(false) { - + private static final long serialVersionUID = 1L; @Override protected List load() { @@ -149,11 +149,11 @@ public LoadableModel>> getProjectionModel() public CountableLoadableModel getAssignmentsModel() { return assignmentsModel; } - + public CountableLoadableModel getPolicyRulesModel() { return policyRulesModel; } - + public LoadableModel> getDelegatedToMeModel() { return delegatedToMeModel; } @@ -161,15 +161,15 @@ public LoadableModel> getDelegatedToMeModel() { public List> getFocusShadows() { return projectionModel.getObject(); } - + public boolean isAssignmentsLoaded() { return assignmentsModel.isLoaded() || policyRulesModel.isLoaded(); } - + public List getFocusAssignments() { return assignmentsModel.getObject(); } - + protected void reviveModels() throws SchemaException { super.reviveModels(); WebComponentUtil.revive(projectionModel, getPrismContext()); @@ -259,7 +259,7 @@ private List> loadShadowWrappers() { // The full projection load happens when loadFullShadow() is explicitly invoked. return loadSubwrappers(ShadowType.class, UserType.F_LINK_REF, true); } - + public void loadFullShadow(FocusSubwrapperDto shadowWrapperDto) { ObjectWrapper shadowWrapperOld = shadowWrapperDto.getObject(); Task task = createSimpleTask(OPERATION_LOAD_SHADOW); @@ -318,7 +318,7 @@ private FocusSubwrapperDto loadSubWrapperDto(Class } else { loadOptions = new ArrayList<>(); } - + if (noFetch) { GetOperationOptions rootOptions = SelectorOptions.findRootOptions(loadOptions); if (rootOptions == null) { @@ -367,7 +367,7 @@ private FocusSubwrapperDto loadSubWrapperDto(Class wrapper.initializeContainers(this); subResult.computeStatus(); - + return new FocusSubwrapperDto(wrapper, UserDtoStatus.MODIFY); } catch (Exception ex) { @@ -428,7 +428,7 @@ private List loadAssignments() { return list; } - + protected int countPolicyRules() { int policyRuleCounter = 0; PrismObject focus = getObjectModel().getObject().getObject(); @@ -449,7 +449,7 @@ private List loadPolicyRules() { Collections.sort(list); return list; } - + protected List getPolicyRulesList(List assignments, UserDtoStatus status){ List list = new ArrayList(); for (AssignmentType assignment : assignments) { @@ -459,8 +459,8 @@ protected List getPolicyRulesList(List assignment } return list; } - - + + private boolean isAssignmentRelevant(AssignmentType assignment) { return assignment.getTargetRef() == null || !UserType.COMPLEX_TYPE.equals(assignment.getTargetRef().getType()); @@ -475,17 +475,17 @@ private boolean isConsentAssignment(AssignmentType assignment) { if (assignment.getTargetRef() == null) { return false; } - + return QNameUtil.match(assignment.getTargetRef().getRelation(), SchemaConstants.ORG_CONSENT); } - - + + @Override protected void prepareObjectForAdd(PrismObject focus) throws SchemaException { super.prepareObjectForAdd(focus); F focusType = focus.asObjectable(); // handle added accounts - + List shadowsToAdd = prepareSubobject(getFocusShadows()); if (!shadowsToAdd.isEmpty()) { shadowsToAdd.forEach(shadowType -> addDefaultKindAndIntent(shadowType.asPrismObject())); @@ -498,10 +498,10 @@ protected void prepareObjectForAdd(PrismObject focus) throws SchemaException } handleAssignmentForAdd(focus, UserType.F_ASSIGNMENT, assignmentsModel.getObject()); - + } - - + + protected void handleAssignmentForAdd(PrismObject focus, QName containerName, List assignments) throws SchemaException { PrismObjectDefinition userDef = focus.getDefinition(); @@ -513,7 +513,7 @@ protected void handleAssignmentForAdd(PrismObject focus, QName containerName, if (assignmentContainer != null && !assignmentContainer.isEmpty()){ assignmentContainer.clear(); } - + // List assignments = getFocusAssignments(); for (AssignmentDto assDto : assignments) { if (UserDtoStatus.DELETE.equals(assDto.getStatus())) { @@ -543,7 +543,7 @@ protected void prepareObjectDeltaForModify(ObjectDelta focusDelta) throws Sch if (!refDelta.isEmpty()) { focusDelta.addModification(refDelta); } - + refDef = objectDefinition.findReferenceDefinition(FocusType.F_PARENT_ORG_REF); refDelta = prepareUserOrgsDeltaForModify(refDef); if (!refDelta.isEmpty()) { @@ -563,14 +563,14 @@ protected void prepareObjectDeltaForModify(ObjectDelta focusDelta) throws Sch handleAssignmentExperimentalDeltas(focusDelta, assignmentsList, def, false); } } - + protected PrismObjectDefinition getObjectDefinition() { SchemaRegistry registry = getPrismContext().getSchemaRegistry(); return registry .findObjectDefinitionByCompileTimeClass(getCompileTimeClass()); } - - + + protected ContainerDelta handleAssignmentDeltas(ObjectDelta focusDelta, List assignments, PrismContainerDefinition def) throws SchemaException { return handleAssignmentDeltas(focusDelta, assignments, def, false); @@ -626,7 +626,7 @@ protected ContainerDelta handleAssignmentDeltas(ObjectDelta focusDelta, return assDelta; } - + protected ContainerDelta handleAssignmentExperimentalDeltas(ObjectDelta focusDelta, List assignments, PrismContainerDefinition def, boolean isDelegation) throws SchemaException { @@ -654,7 +654,7 @@ protected ContainerDelta handleAssignmentExperimentalDeltas(Obje if (deltas != null || !deltas.isEmpty()) { focusDelta.addModifications(deltas); } - + break; default: warn(getString("pageAdminUser.message.illegalAssignmentState", assDto.getStatus())); @@ -676,7 +676,7 @@ protected ContainerDelta handleAssignmentExperimentalDeltas(Obje return assDelta; } - + private void handleModifyAssignmentDelta(AssignmentEditorDto assDto, PrismContainerDefinition assignmentDef, PrismContainerValue newValue, ObjectDelta focusDelta) throws SchemaException { @@ -696,7 +696,7 @@ private void handleModifyAssignmentDelta(AssignmentEditorDto assDto, focusDelta.addModification(delta); } } - + @Override protected boolean executeForceDelete(ObjectWrapper userWrapper, Task task, ModelExecuteOptions options, OperationResult parentResult) { @@ -723,7 +723,7 @@ protected boolean executeForceDelete(ObjectWrapper userWrapper, Task task, Model } return false; } - + private ObjectDelta getForceDeleteDelta(ObjectWrapper focusWrapper) throws SchemaException { List> accountDtos = getFocusShadows(); @@ -760,7 +760,7 @@ private ObjectDelta getForceDeleteDelta(ObjectWrapper focusWrapper) throws Schem handleAssignmentExperimentalDeltas(forceDeleteDelta, getFocusAssignments(), def, false); return forceDeleteDelta; } - + private

List

prepareSubobject(List> projections) throws SchemaException{ List

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

projection : projections) { @@ -789,7 +789,7 @@ private

List

prepareSubobject(List> getAdditionalModifyDeltas(OperationResult result) { return getShadowModifyDeltas(result); @@ -846,7 +846,7 @@ private List> getShadowModifyDeltas(OperationR return deltas; } - + /** * remove this method after model is updated - it has to remove resource * from accountConstruction @@ -1153,7 +1153,7 @@ private String nameFromReference(ObjectReferenceType reference, Task task, Opera prismObject = getModelService().getObject(clazz, oid, SelectorOptions.createCollection(GetOperationOptions.createNoFetch()), task, result); } catch (ObjectNotFoundException | SchemaException | SecurityViolationException - | CommunicationException | ConfigurationException | ExpressionEvaluationException + | CommunicationException | ConfigurationException | ExpressionEvaluationException | RuntimeException | Error e) { LoggingUtils.logUnexpectedException(LOGGER, "Couldn't retrieve name for {}: {}", e, clazz.getSimpleName(), oid); @@ -1183,7 +1183,7 @@ private AssignmentsPreviewDto createAssignmentsPreviewDto(EvaluatedConstruction @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()) { @@ -1195,7 +1195,7 @@ protected void performAdditionalValidation(PrismObject object, } } } - + } } 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 17b2c7f9ab9..e2a19e751d1 100644 --- 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 @@ -66,7 +66,7 @@ import org.apache.wicket.util.time.Duration; import org.jetbrains.annotations.NotNull; -/** +/** * @author semancik */ public abstract class PageAdminObjectDetails extends PageAdmin @@ -74,7 +74,7 @@ public abstract class PageAdminObjectDetails extends PageA 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"; @@ -91,13 +91,13 @@ public abstract class PageAdminObjectDetails extends PageA private LoadableModel> objectModel; private LoadableModel>> parentOrgModel; - + private ProgressReporter progressReporter; - + // 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 @@ -155,11 +155,11 @@ public LoadableModel>> getParentOrgModel() { protected AbstractObjectMainPanel getMainPanel() { return mainPanel; } - + public ObjectWrapper getObjectWrapper() { return objectModel.getObject(); } - + public List> getParentOrgs() { return parentOrgModel.getObject(); } @@ -213,16 +213,16 @@ protected List> loadOrgWrappers() { // WRONG!! TODO: fix return null; } - + protected abstract O createNewObject(); - + protected void initLayout() { initLayoutSummaryPanel(); - + mainPanel = createMainPanel(ID_MAIN_PANEL); mainPanel.setOutputMarkupId(true); add(mainPanel); - + progressReporter = createProgressReporter("progressPanel"); add(progressReporter.getProgressPanel()); } @@ -232,7 +232,7 @@ protected ProgressReporter createProgressReporter(String id) { } protected abstract FocusSummaryPanel createSummaryPanel(); - + protected void initLayoutSummaryPanel() { FocusSummaryPanel summaryPanel = createSummaryPanel(); @@ -309,7 +309,7 @@ protected ObjectWrapper loadObjectWrapper(PrismObject objectToEdit) { } showResult(result, false); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Loaded object:\n{}", object.debugDump()); } @@ -334,9 +334,9 @@ protected ObjectWrapper loadObjectWrapper(PrismObject objectToEdit) { wrapper = owf.createObjectWrapper("pageAdminFocus.focusDetails", null, object, null, null, status); } wrapper.setLoadOptions(loadOptions); - + showResult(wrapper.getResult(), false); - + loadParentOrgs(wrapper, task, result); wrapper.setShowEmpty(!isEditingFocus()); @@ -347,7 +347,7 @@ protected ObjectWrapper loadObjectWrapper(PrismObject objectToEdit) { return wrapper; } - + private void loadParentOrgs(ObjectWrapper wrapper, Task task, OperationResult result) { OperationResult subResult = result.createMinorSubresult(OPERATION_LOAD_PARENT_ORGS); PrismObject focus = wrapper.getObject(); @@ -383,7 +383,7 @@ private void loadParentOrgs(ObjectWrapper wrapper, Task task, OperationResult } protected abstract Class getRestartResponsePage(); - + public Object findParam(String param, String oid, OperationResult result) { Object object = null; @@ -427,7 +427,7 @@ public void saveOrPreviewPerformed(AjaxRequestTarget target, OperationResult res ObjectWrapper 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, @@ -436,7 +436,7 @@ public void saveOrPreviewPerformed(AjaxRequestTarget target, OperationResult res delta = null; Task task = createSimpleTask(OPERATION_SEND_TO_SUBMIT); - + ModelExecuteOptions options = getExecuteChangesOptions(); if (previewOnly) { options.getOrCreatePartialProcessing().setApprovals(PartialProcessingTypeType.PROCESS); @@ -504,7 +504,7 @@ public void saveOrPreviewPerformed(AjaxRequestTarget target, OperationResult res delta.revive(getPrismContext()); deltas.add(delta); } - + List> additionalDeltas = getAdditionalModifyDeltas(result); if (additionalDeltas != null) { for (ObjectDelta additionalDelta : additionalDeltas) { @@ -566,7 +566,7 @@ public void saveOrPreviewPerformed(AjaxRequestTarget target, OperationResult res // LOGGER.trace("Result NOT in progress, calling finishProcessing"); // finishProcessing(target, result, false); // } - + LOGGER.trace("returning from saveOrPreviewPerformed"); } @@ -602,17 +602,17 @@ protected ModelExecuteOptions getExecuteChangesOptions() { } protected void prepareObjectForAdd(PrismObject object) throws SchemaException { - + } - + protected void prepareObjectDeltaForModify(ObjectDelta objectDelta) throws SchemaException { - + } - + protected List> getAdditionalModifyDeltas(OperationResult result) { return null; } - + protected boolean executeForceDelete(ObjectWrapper userWrapper, Task task, ModelExecuteOptions options, OperationResult parentResult) { return isForce(); @@ -621,12 +621,12 @@ protected boolean executeForceDelete(ObjectWrapper userWrapper, Task task, Model protected boolean isForce() { return getMainPanel().getExecuteChangeOptionsDto().isForce(); } - + protected boolean isKeepDisplayingResults() { return getMainPanel().getExecuteChangeOptionsDto().isKeepDisplayingResults(); } - - + + protected Collection performCustomValidation(PrismObject object, Collection> deltas) throws SchemaException { Collection errors = null; @@ -637,7 +637,7 @@ protected Collection performCustomValidation(PrismObject< for (ObjectDelta delta : deltas) { // because among deltas there can be also ShadowType deltas - if (UserType.class.isAssignableFrom(delta.getObjectTypeClass())) { + if (UserType.class.isAssignableFrom(delta.getObjectTypeClass())) { delta.applyTo(object); } } @@ -658,12 +658,12 @@ protected Collection performCustomValidation(PrismObject< 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(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/DefinitionBasicPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/DefinitionBasicPanel.java index b64eb117946..2bdc1b490df 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/DefinitionBasicPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/DefinitionBasicPanel.java @@ -70,7 +70,7 @@ public DefinitionBasicPanel(String id, IModel model) { } private void initBasicInfoLayout() { - + final TextField nameField = new TextField(ID_NAME, new PropertyModel<>(getModel(), CertDefinitionDto.F_NAME)); nameField.add(new VisibleEnableBehaviour() { @Override diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/PageCertCampaign.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/PageCertCampaign.java index 80769e3acb2..83ebc01b008 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/PageCertCampaign.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/PageCertCampaign.java @@ -276,7 +276,7 @@ private void initTableLayout(Form mainForm) { private List> initColumns() { List> columns = new ArrayList<>(); - + IColumn column; column = helper.createTypeColumn(OBJECT, this); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/PageCertCampaigns.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/PageCertCampaigns.java index b91af2ee59b..2c3415ca79a 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/PageCertCampaigns.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/PageCertCampaigns.java @@ -460,7 +460,7 @@ public void yesPerformed(AjaxRequestTarget target) { closeSelectedCampaignsConfirmedPerformed(target); } } - + @Override public StringResourceModel getTitle() { return createStringResource("PageCertCampaigns.dialog.title.confirmCloseCampaign"); @@ -488,7 +488,7 @@ public void yesPerformed(AjaxRequestTarget target) { deleteSelectedCampaignsConfirmedPerformed(target); } } - + @Override public StringResourceModel getTitle() { return createStringResource("PageCertCampaigns.dialog.title.confirmDeleteCampaign"); @@ -527,7 +527,7 @@ public void yesPerformed(AjaxRequestTarget target) { closeStageConfirmedPerformed(target, relevantCampaign); } } - + @Override public StringResourceModel getTitle() { return createStringResource("PageCertCampaigns.dialog.title.confirmCloseStage"); @@ -552,7 +552,7 @@ public void yesPerformed(AjaxRequestTarget target) { closeCampaignConfirmedPerformed(target, relevantCampaign); } } - + @Override public StringResourceModel getTitle() { return createStringResource("PageCertCampaigns.dialog.title.confirmCloseCampaign"); @@ -577,7 +577,7 @@ public void yesPerformed(AjaxRequestTarget target) { deleteCampaignConfirmedPerformed(target); } } - + @Override public StringResourceModel getTitle() { return createStringResource("PageCertCampaigns.dialog.title.confirmDeleteCampaign"); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/dto/CertWorkItemDtoProvider.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/dto/CertWorkItemDtoProvider.java index 98db26c153e..6df3df211f7 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/dto/CertWorkItemDtoProvider.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/dto/CertWorkItemDtoProvider.java @@ -73,7 +73,7 @@ public Iterator internalIterator(long first, long count) { try { ObjectPaging paging = createPaging(first, count); Task task = getPage().createSimpleTask(OPERATION_SEARCH_OBJECTS); - + ObjectQuery caseQuery = getQuery(); caseQuery = caseQuery != null ? caseQuery.clone() : new ObjectQuery(); caseQuery.setPaging(paging); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/dto/StageDefinitionDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/dto/StageDefinitionDto.java index 388b6e8be2f..5792d81f4d4 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/dto/StageDefinitionDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/dto/StageDefinitionDto.java @@ -55,7 +55,7 @@ public class StageDefinitionDto implements Serializable { private List stopReviewOnRaw; private List advanceToNextStageOnRaw; private List timedActionsTypes; - + public StageDefinitionDto(AccessCertificationStageDefinitionType stageDefObj, PrismContext prismContext) throws SchemaException { if (stageDefObj != null) { setNumber(stageDefObj.getNumber()); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/handlers/CertGuiHandlerRegistry.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/handlers/CertGuiHandlerRegistry.java index 88c5e2d25d3..c162b61c2ce 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/handlers/CertGuiHandlerRegistry.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/certification/handlers/CertGuiHandlerRegistry.java @@ -44,7 +44,7 @@ public CertGuiHandler getHandler(String uri) { throw new IllegalArgumentException("Unknown handler URI: " + uri); } } - + @SuppressWarnings("unused") private void doNothing() { // no nothing. Just for maven dependency analyze to properly detect the dependency. diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageAccounts.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageAccounts.java index fb2e75a9fd4..2d677cd649a 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageAccounts.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageAccounts.java @@ -263,7 +263,7 @@ protected File initFile() { WebMarkupContainer filesContainer = new WebMarkupContainer(ID_FILES_CONTAINER); filesContainer.setOutputMarkupId(true); accForm.add(filesContainer); - + ModalWindow resultPopup = createModalWindow(ID_RESULT_DIALOG, createStringResource("PageAccounts.result.popoup"), 1100, 560); resultPopup.setContent(new AceEditorDialog(resultPopup.getContentId())); add(resultPopup); @@ -305,8 +305,8 @@ public boolean isVisible() { }); accounts.setItemsPerPage(50); accountsContainer.add(accounts); - - + + } private void initSearchForm(Form searchForm){ @@ -343,7 +343,7 @@ protected void onUpdate(AjaxRequestTarget target) { failedOperationType.setOutputMarkupId(true); failedOperationType.setNullValid(true); searchForm.add(failedOperationType); - + DropDownChoice kind = new DropDownChoice<>(ID_SEARCH_KIND, new PropertyModel(searchModel, AccountDetailsSearchDto.F_KIND), WebComponentUtil.createReadonlyModelFromEnum(ShadowKindType.class), new EnumChoiceRenderer(this)); @@ -642,7 +642,7 @@ private List createAccountsColumns() { // columns.add(new PropertyColumn<>(createStringResource("PageAccounts.accounts.result"), // ShadowType.F_RESULT.getLocalPart(), SelectableBean.F_VALUE + ".result.status")); - + columns.add(new LinkColumn(createStringResource("PageAccounts.accounts.result")){ @Override @@ -665,7 +665,7 @@ public void onClick(AjaxRequestTarget target, IModel rowModel) { showShadowResult(target, rowModel); } }); - + columns.add(new LinkColumn(createStringResource("PageAccounts.accounts.owner")){ @Override @@ -688,14 +688,14 @@ public void onClick(AjaxRequestTarget target, IModel rowModel) { return columns; } - + private void showShadowResult(AjaxRequestTarget target, IModel rowModel){ OperationResultType result = getResult(rowModel); String xml; ModalWindow aceDialog = (ModalWindow) get(createComponentPath(ID_RESULT_DIALOG)); AceEditorDialog aceEditor = (AceEditorDialog) aceDialog.get(aceDialog.getContentId()); - - + + try { xml = getPrismContext().xmlSerializer().serializeRealValue(result, ShadowType.F_RESULT); aceEditor.updateModel(new Model(xml)); @@ -703,10 +703,10 @@ private void showShadowResult(AjaxRequestTarget target, IModel r LoggingUtils.logUnexpectedException(LOGGER, "Couldn't parse result", e); aceEditor.updateModel(new Model("Unable to show result. For more information see logs.")); } - + aceDialog.show(target); target.add(getFeedbackPanel()); - + } private ObjectFilter createResourceAndQueryFilter(){ @@ -1046,18 +1046,18 @@ private void clearSearchPerformed(AjaxRequestTarget target){ target.add(getSearchPanel()); target.add(getAccountsContainer()); } - + private OperationResultType getResult(IModel model){ - + ShadowType shadow = getShadow(model); return shadow.getResult(); } - + private ShadowType getShadow(IModel model){ if(model == null || model.getObject() == null || model.getObject().getValue() == null){ return null; } - + return (ShadowType) model.getObject().getValue(); } @@ -1108,7 +1108,7 @@ private void ownerDetailsPerformed(AjaxRequestTarget targe PageParameters parameters = new PageParameters(); parameters.add(OnePageParameterEncoder.PARAMETER, focus.getOid()); - + if (focus instanceof UserType){ navigateToNext(PageUser.class, parameters); } else if (focus instanceof RoleType){ diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageImportObject.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageImportObject.java index b1390a72f33..aa0d284dd6b 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageImportObject.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageImportObject.java @@ -253,7 +253,7 @@ protected void onError(AjaxRequestTarget target, Form form) { addVisibileForInputType(saveXmlButton, INPUT_XML, inputType); buttonBar.add(saveXmlButton); } - + private FileUpload getUploadedFile() { FileUploadField file = (FileUploadField) get( createComponentPath(ID_MAIN_FORM, ID_INPUT, ID_INPUT_FILE, ID_FILE_INPUT)); @@ -318,10 +318,10 @@ private void clearOldFeedback(){ getSession().getFeedbackMessages().clear(); getFeedbackMessages().clear(); } - + private void savePerformed(boolean raw, String operationName, AjaxRequestTarget target) { clearOldFeedback(); - + OperationResult result = new OperationResult(operationName); if (!validateInput(raw)) { @@ -353,5 +353,5 @@ private void savePerformed(boolean raw, String operationName, AjaxRequestTarget target.add(PageImportObject.this); } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageInternals.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageInternals.java index 91825b1237d..bc28ff9993e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageInternals.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageInternals.java @@ -80,16 +80,16 @@ public class PageInternals extends PageAdminConfiguration { private static final String ID_READ_ENCRYPTION_CHECKS = "readEncryptionChecks"; private static final String ID_TOLERATE_UNDECLARED_PREFIXES = "tolerateUndeclaredPrefixes"; private static final String ID_DETAILED_DEBUG_DUMP = "detailedDebugDump"; - + private static final String ID_TRACES_FORM = "tracesForm"; private static final String ID_TRACES_TABLE = "tracesTable"; private static final String ID_TRACE_TOGGLE = "traceToggle"; private static final String ID_UPDATE_TRACES = "updateTraces"; - + private static final String ID_COUNTERS_TABLE = "countersTable"; private static final String ID_COUNTER_LABEL = "counterLabel"; private static final String ID_COUNTER_VALUE = "counterValue"; - + private static final String LABEL_SIZE = "col-md-4"; private static final String INPUT_SIZE = "col-md-8"; @@ -194,12 +194,12 @@ private void initInternalsConfigForm() { Form form = new Form(ID_INTERNALS_CONFIG_FORM); form.setOutputMarkupId(true); add(form); - + form.add(createCheckbox(ID_CONSISTENCY_CHECKS, InternalsConfigDto.F_CONSISTENCY_CHECKS)); form.add(createCheckbox(ID_ENCRYPTION_CHECKS, InternalsConfigDto.F_ENCRYPTION_CHECKS)); form.add(createCheckbox(ID_READ_ENCRYPTION_CHECKS, InternalsConfigDto.F_READ_ENCRYPTION_CHECKS)); form.add(createCheckbox(ID_TOLERATE_UNDECLARED_PREFIXES, InternalsConfigDto.F_TOLERATE_UNDECLARED_PREFIXES)); - + AjaxSubmitButton update = new AjaxSubmitButton(ID_UPDATE_INTERNALS_CONFIG, createStringResource("PageBase.button.update")) { private static final long serialVersionUID = 1L; @@ -216,12 +216,12 @@ protected void onError(AjaxRequestTarget target, Form form) { }; form.add(update); } - + private void initTraces() { Form form = new Form(ID_TRACES_FORM); form.setOutputMarkupId(true); add(form); - + ListView tracesTable = new ListView(ID_TRACES_TABLE, Arrays.asList(InternalOperationClasses.values())) { private static final long serialVersionUID = 1L; @@ -233,10 +233,10 @@ protected void populateItem(ListItem item) { createStringResource("InternalOperationClasses."+operationClass.getKey()), LABEL_SIZE, INPUT_SIZE); item.add(checkFormGroup); } - + }; form.add(tracesTable); - + AjaxSubmitButton update = new AjaxSubmitButton(ID_UPDATE_TRACES, createStringResource("PageBase.button.update")) { private static final long serialVersionUID = 1L; @@ -253,7 +253,7 @@ protected void onError(AjaxRequestTarget target, Form form) { }; form.add(update); } - + private void updateTraces(AjaxRequestTarget target){ for (Entry entry: tracesMap.entrySet()) { InternalMonitor.setTrace(entry.getKey(), entry.getValue()); @@ -263,15 +263,15 @@ private void updateTraces(AjaxRequestTarget target){ success(getString("PageInternals.message.tracesUpdate")); target.add(getFeedbackPanel(), getInternalsConfigForm()); } - + private CheckFormGroup createCheckbox(String id, String propName) { return new CheckFormGroup(id, new PropertyModel(internalsModel, propName), createStringResource("PageInternals."+propName), LABEL_SIZE, INPUT_SIZE); } - + private void initCounters() { - + ListView countersTable = new ListView(ID_COUNTERS_TABLE, Arrays.asList(InternalCounters.values())) { private static final long serialVersionUID = 1L; @@ -280,7 +280,7 @@ protected void populateItem(ListItem item) { InternalCounters counter = item.getModelObject(); Label label = new Label(ID_COUNTER_LABEL, createStringResource("InternalCounters."+counter.getKey())); item.add(label); - + Label valueLabel = new Label(ID_COUNTER_VALUE, new AbstractReadOnlyModel() { private static final long serialVersionUID = 1L; @@ -292,7 +292,7 @@ public String getObject() { }); item.add(valueLabel); } - + }; add(countersTable); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageSystemConfiguration.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageSystemConfiguration.java index 8c6dd7fa0c0..63ad8362a23 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageSystemConfiguration.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageSystemConfiguration.java @@ -345,7 +345,7 @@ private void saveObjectPolicies(SystemConfigurationType systemConfig) { confList.add(newObjectPolicyConfig); } - + if (confList.isEmpty()){ if (!systemConfig.getDefaultObjectPolicyConfiguration().isEmpty()){ systemConfig.getDefaultObjectPolicyConfiguration().clear(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/AceEditorDialog.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/AceEditorDialog.java index 298df613fc7..f398794782c 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/AceEditorDialog.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/AceEditorDialog.java @@ -29,42 +29,42 @@ public class AceEditorDialog extends BasePanel { private static final Trace LOGGER = TraceManager.getTrace(AceEditorDialog.class); - + private static final String ID_RESULT = "resultAceEditor"; private static final String ID_BUTTON_CLOSE = "closeButton"; - + private IModel xmlModel = new Model(""); - + public AceEditorDialog(String id){ super(id); initLayout(); } protected void initLayout(){ - + add(createAceEditor()); - + // AjaxButton close = new AjaxButton(ID_BUTTON_CLOSE) { // // @Override // public void onClick(AjaxRequestTarget target) { // closePerformed(target); // } -// +// // }; // add(close); - + } - - + + private AceEditor createAceEditor(){ AceEditor acePanel = new AceEditor(ID_RESULT, xmlModel); acePanel.setReadonly(true); acePanel.setMinHeight(500); return acePanel; } - + public void updateModel(IModel model){ xmlModel = model; addOrReplace(createAceEditor()); @@ -74,11 +74,11 @@ public StringResourceModel createStringResource(String resourceKey, Object... ob return PageBase.createStringResourceStatic(this, resourceKey, objects); // return new StringResourceModel(resourceKey, this, new Model(), resourceKey, objects); } - + public void closePerformed(AjaxRequestTarget target){ - + } - - + + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/ChooseTypePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/ChooseTypePanel.java index b613bd615ae..b7b8c2a725b 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/ChooseTypePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/ChooseTypePanel.java @@ -62,20 +62,20 @@ public ChooseTypePanel(String id, IModel> model){ super(id, model); initLayout(); } - + public ChooseTypePanel(String id, ObjectReferenceType ref){ super(id, Model.of(new ObjectViewDto(ref != null ? ref.getOid() : null, ref !=null ? WebComponentUtil.getOrigStringFromPoly(ref.getTargetName()) : null))); initLayout(); } - + protected void initLayout() { final TextField name = new TextField(ID_OBJECT_NAME, new PropertyModel(getModel(), ObjectViewDto.F_NAME)); - - + + // new Model(){ // private static final long serialVersionUID = 1L; -// +// // @Override // public String getObject() { // ObjectViewDto dto = getModel().getObject(); @@ -96,7 +96,7 @@ protected void initLayout() { AjaxLink choose = new AjaxLink(ID_LINK_CHOOSE) { private static final long serialVersionUID = 1L; - + @Override public void onClick(AjaxRequestTarget target) { changeOptionPerformed(target); @@ -152,9 +152,9 @@ private void choosePerformed(AjaxRequestTarget target, T object){ target.add(get(ID_OBJECT_NAME)); executeCustomAction(target, object); } - + protected void executeCustomAction(AjaxRequestTarget target, T object) { - + } private void changeOptionPerformed(AjaxRequestTarget target){ @@ -171,7 +171,7 @@ protected void onSelectPerformed(AjaxRequestTarget target, T focus) { } }; objectBrowserPanel.setOutputMarkupId(true); - + getPageBase().showMainPopup(objectBrowserPanel, target); } @@ -181,9 +181,9 @@ private void setToDefault(AjaxRequestTarget target){ getModel().setObject(dto); executeCustomRemoveAction(target); } - + protected void executeCustomRemoveAction(AjaxRequestTarget target) { - + } public Class getObjectTypeClass(){ diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/LoggingConfigPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/LoggingConfigPanel.java index 7aa71560633..757503ff760 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/LoggingConfigPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/LoggingConfigPanel.java @@ -190,7 +190,7 @@ private void initAudit(){ add(auditAppender); } - + private void addStandardLoggerPerformed(AjaxRequestTarget target){ LoggingDto dto = getModel().getObject(); @@ -595,7 +595,7 @@ private void loggerEditPerformed(AjaxRequestTarget target, IModel extends EditablePropertyColumn { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/NotificationConfigPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/NotificationConfigPanel.java index 9f9be8b7178..96b76dddde9 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/NotificationConfigPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/NotificationConfigPanel.java @@ -45,14 +45,14 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.MailTransportSecurityType; /** - * + * * @author katkav * */ public class NotificationConfigPanel extends SimplePanel { /** - * + * */ private static final long serialVersionUID = 1L; private static final String ID_DEFAULT_FROM = "defaultFrom"; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/ObjectPolicyPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/ObjectPolicyPanel.java index 75f8904600e..d58468263ef 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/ObjectPolicyPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/ObjectPolicyPanel.java @@ -70,7 +70,7 @@ public class ObjectPolicyPanel extends BasePanel implements Popupable{ /** - * + * */ private static final long serialVersionUID = 1L; @@ -114,7 +114,7 @@ protected ObjectPolicyDialogDto load() { return loadModel(config); } }; - + initLayout(config); setOutputMarkupId(true); @@ -167,7 +167,7 @@ public void initLayout(ObjectPolicyConfigurationTypeDto config) { form.add(type); type.getInput().setNullValid(config.getConflictResolution() != null); type.getInput().setRequired(config.getConflictResolution() == null); // traditional template entries still require object type - + TextField fieldSubtype = new TextField<>(ID_SUBTYPE, new PropertyModel(model, ObjectPolicyDialogDto.F_SUBTYPE)); form.add(fieldSubtype); form.add(fieldSubtype); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/ProfilingConfigPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/ProfilingConfigPanel.java index a44f39463d2..b09f3aa0466 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/ProfilingConfigPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/ProfilingConfigPanel.java @@ -37,7 +37,7 @@ import java.util.List; /** - * + * * @author katkav * */ @@ -101,7 +101,7 @@ private void initLayout(PageSystemConfiguration parentPage) { //Subsystem and general profiling init CheckBox requestFilter = WebComponentUtil.createAjaxCheckBox("requestFilter", new PropertyModel(getModel(), "requestFilter")); - + CheckBox performanceStatistics = WebComponentUtil.createAjaxCheckBox("performanceStatistics", new PropertyModel(getModel(), "performanceStatistics")); CheckBox subsystemModel = WebComponentUtil.createAjaxCheckBox("subsystemModel", new PropertyModel(getModel(), "subsystemModel")); CheckBox subsystemRepository = WebComponentUtil.createAjaxCheckBox("subsystemRepository", new PropertyModel(getModel(), "subsystemRepository")); @@ -130,5 +130,5 @@ private void initLayout(PageSystemConfiguration parentPage) { } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/SystemConfigPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/SystemConfigPanel.java index 3174ea1e367..3c1a63d35ed 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/SystemConfigPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/component/SystemConfigPanel.java @@ -53,7 +53,7 @@ public class SystemConfigPanel extends BasePanel { private static final String ID_CLEANUP_CLOSED_TASKS_TOOLTIP = "closedTasksCleanupTooltip"; private static final String ID_EXPERIMENTAL_CODE_CHECKBOX = "experimentalCodeCheckbox"; - + public SystemConfigPanel(String id, IModel model) { super(id, model); @@ -86,26 +86,26 @@ protected void initLayout(){ } aepLevel.add(new EmptyOnChangeAjaxFormUpdatingBehavior()); add(aepLevel); - + TextField auditRecordsField = WebComponentUtil.createAjaxTextField(ID_CLEANUP_AUDIT_RECORDS, new PropertyModel(getModel(), SystemConfigurationDto.F_AUDIT_CLEANUP)); - + TextField closedTasksField = WebComponentUtil.createAjaxTextField(ID_CLEANUP_CLOSED_TASKS, new PropertyModel(getModel(), SystemConfigurationDto.F_TASK_CLEANUP)); - + add(auditRecordsField); add(closedTasksField); createTooltip(ID_CLEANUP_AUDIT_RECORDS_TOOLTIP); createTooltip(ID_CLEANUP_CLOSED_TASKS_TOOLTIP); - + CheckBox experimentalCodeCheck = WebComponentUtil.createAjaxCheckBox(ID_EXPERIMENTAL_CODE_CHECKBOX, new PropertyModel(getModel(), SystemConfigurationDto.F_ENABLE_EXPERIMENTAL_CODE)); add(experimentalCodeCheck); - - + + } - + private void createTooltip(String id) { Label tooltip = new Label(id); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/AccountDetailsSearchDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/AccountDetailsSearchDto.java index 0fe951dc250..726270e280a 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/AccountDetailsSearchDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/AccountDetailsSearchDto.java @@ -83,12 +83,12 @@ public String getObjectClass() { public void setObjectClass(String objectClass) { this.objectClass = objectClass; } - - + + public FailedOperationTypeType getFailedOperationType() { return failedOperationType; } - + public void setFailedOperationType(FailedOperationTypeType failedOperationType) { this.failedOperationType = failedOperationType; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/ClassLogger.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/ClassLogger.java index 7bf6ba42778..3f0b6734797 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/ClassLogger.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/ClassLogger.java @@ -44,8 +44,8 @@ public String getName() { @Override public void setName(String name) { this._package = name; - } - + } + public ClassLoggerConfigurationType toXmlType() { ClassLoggerConfigurationType type = new ClassLoggerConfigurationType(); type.setPackage(_package); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/ComponentLogger.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/ComponentLogger.java index 0d8cc9b08a0..5e29eb37654 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/ComponentLogger.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/ComponentLogger.java @@ -32,7 +32,7 @@ public class ComponentLogger extends LoggerConfiguration { public ComponentLogger(ClassLoggerConfigurationType config) { Validate.notNull(config, "Component logger configuration must not be null."); - + component = LoggingDto.componentMap.get(config.getPackage()); setLevel(config.getLevel()); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/DebugObjectItem.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/DebugObjectItem.java index a61674c05e0..0c216e099a5 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/DebugObjectItem.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/DebugObjectItem.java @@ -36,7 +36,7 @@ public class DebugObjectItem extends Selectable implements InlineMenuable { public static final String F_OID = "oid"; public static final String F_NAME = "name"; - + public static final String F_RESOURCE_NAME = "resourceName"; public static final String F_RESOURCE_TYPE = "resourceType"; public static final String F_FULL_NAME = "fullName"; @@ -62,7 +62,7 @@ public DebugObjectItem(String oid, String name, String description) { public String getName() { return name; } - + public String getOid() { return oid; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/InternalsConfigDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/InternalsConfigDto.java index da798c57260..f1e26996a08 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/InternalsConfigDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/InternalsConfigDto.java @@ -27,7 +27,7 @@ */ public class InternalsConfigDto implements Serializable { private static final long serialVersionUID = 1L; - + public static final String F_CONSISTENCY_CHECKS = "consistencyChecks"; public static final String F_ENCRYPTION_CHECKS = "encryptionChecks"; public static final String F_READ_ENCRYPTION_CHECKS = "readEncryptionChecks"; @@ -50,7 +50,7 @@ public InternalsConfigDto() { detailedDebugDump = DebugUtil.isDetailedDebugDump(); - tolerateUndeclaredPrefixes = QNameUtil.isTolerateUndeclaredPrefixes(); + tolerateUndeclaredPrefixes = QNameUtil.isTolerateUndeclaredPrefixes(); } public boolean isConsistencyChecks() { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/LoggerConfiguration.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/LoggerConfiguration.java index 774058c6643..97159ad059d 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/LoggerConfiguration.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/LoggerConfiguration.java @@ -28,7 +28,7 @@ * @author lazyman */ public abstract class LoggerConfiguration extends Selectable implements Editable { - + private boolean editing; private LoggingLevelType level; private List appenders = new ArrayList<>(); @@ -59,6 +59,6 @@ public boolean isEditing() { public void setEditing(boolean editing) { this.editing = editing; } - + public abstract ClassLoggerConfigurationType toXmlType(); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/LoggingDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/LoggingDto.java index 534420a2277..c647e7f69a4 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/LoggingDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/LoggingDto.java @@ -76,7 +76,7 @@ public class LoggingDto implements Serializable { private boolean advanced; private Boolean debug; - + public LoggingDto() { this(null); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/MailServerConfigurationTypeDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/MailServerConfigurationTypeDto.java index 0f02f248ec9..dce9e52f5aa 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/MailServerConfigurationTypeDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/MailServerConfigurationTypeDto.java @@ -64,7 +64,7 @@ public MailServerConfigurationTypeDto(MailServerConfigurationType config){ public String getName() { return host; } - + public String getHost() { return host; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/NotificationConfigurationDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/NotificationConfigurationDto.java index 590af1b8867..fbd37038a5b 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/NotificationConfigurationDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/NotificationConfigurationDto.java @@ -44,7 +44,7 @@ public class NotificationConfigurationDto implements Serializable{ private List servers; private MailServerConfigurationTypeDto selectedServer; - + public NotificationConfigurationDto(){} public NotificationConfigurationDto(NotificationConfigurationType config){ @@ -67,10 +67,10 @@ public NotificationConfigurationDto(NotificationConfigurationType config){ } } } - + public NotificationConfigurationType getNewObject(SystemConfigurationType systemConfig) { - - + + NotificationConfigurationType notificationConfig = (systemConfig.getNotificationConfiguration() != null) ? systemConfig.getNotificationConfiguration() : new NotificationConfigurationType(); MailConfigurationType mailConfig = (notificationConfig.getMail() != null) ? notificationConfig.getMail() : new MailConfigurationType(); @@ -78,7 +78,7 @@ public NotificationConfigurationType getNewObject(SystemConfigurationType system mailConfig.setDefaultFrom(getDefaultFrom()); mailConfig.setRedirectToFile(getRedirectToFile()); mailConfig.getServer().clear(); - + for (MailServerConfigurationTypeDto serverDto : getServers()) { MailServerConfigurationType newConfig = new MailServerConfigurationType(); newConfig.setHost(serverDto.getHost()); @@ -96,9 +96,9 @@ public NotificationConfigurationType getNewObject(SystemConfigurationType system mailConfig.getServer().add(newConfig); } - + notificationConfig.setMail(mailConfig); - + return notificationConfig; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/ObjectPolicyConfigurationTypeDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/ObjectPolicyConfigurationTypeDto.java index 8d9034325f3..ef96186e9e7 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/ObjectPolicyConfigurationTypeDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/ObjectPolicyConfigurationTypeDto.java @@ -137,5 +137,5 @@ public String toString() { + ")"; } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/ObjectPolicyDialogDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/ObjectPolicyDialogDto.java index 0b2f47caf48..224369ecfbb 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/ObjectPolicyDialogDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/ObjectPolicyDialogDto.java @@ -120,7 +120,7 @@ private String getObjectTemplateName(String oid, PageBase page){ Task task = page.createSimpleTask(OPERATION_LOAD_OBJECT_TEMPLATE); OperationResult result = task.getResult(); - PrismObject templatePrism = WebModelServiceUtils.loadObject(ObjectTemplateType.class, oid, + PrismObject templatePrism = WebModelServiceUtils.loadObject(ObjectTemplateType.class, oid, page, task, result); if(templatePrism != null){ @@ -215,5 +215,5 @@ public String toString() { + config + ", type=" + type + ", subtype=" + subtype + ", templateRef=" + templateRef + ")"; } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/ProfilingDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/ProfilingDto.java index 6d6eeb0a5a1..93d8079a7ff 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/ProfilingDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/ProfilingDto.java @@ -26,7 +26,7 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ProfilingConfigurationType; /** - * + * * @author katkav * */ @@ -120,7 +120,7 @@ public ClassLoggerConfigurationType getProfilingClassLogerConfig() { } public ProfilingConfigurationType getNewObject() { - + ProfilingConfigurationType config = new ProfilingConfigurationType(); if (isProfilingEnabled() || isPerformanceStatistics() || isRequestFilter() diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/StandardLogger.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/StandardLogger.java index 9bb9f36a978..64a3aa962d9 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/StandardLogger.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/dto/StandardLogger.java @@ -64,7 +64,7 @@ public ClassLoggerConfigurationType toXmlType(){ if (!(getAppenders().isEmpty())){ type.getAppender().addAll(getAppenders()); } - + return type; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/dto/ObjectViewDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/dto/ObjectViewDto.java index fe5519fdb1e..794216412aa 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/dto/ObjectViewDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/dto/ObjectViewDto.java @@ -45,7 +45,7 @@ public ObjectViewDto() { this.name = null; this.oid = null; } - + public ObjectViewDto(T object) { this.name = WebComponentUtil.getName(object); this.oid = object.getOid(); @@ -71,11 +71,11 @@ public ObjectViewDto(String oid, String name, PrismObject object, String xml) public PrismObject getObject() { return object; } - + public void setObject(PrismObject object) { this.object = object; } - + public T getObjectType() { if (object == null) { return null; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/PageDashboard.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/PageDashboard.java index f381af26495..55045e0d302 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/PageDashboard.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/PageDashboard.java @@ -74,7 +74,7 @@ public class PageDashboard extends PageAdminHome { private static final String ID_INFO_BOX_SERVICES = "infoBoxServices"; private static final String ID_INFO_BOX_RESOURCES = "infoBoxResources"; private static final String ID_INFO_BOX_TASKS = "infoBoxTasks"; - + private static final String ID_PERSONAL_INFO = "personalInfo"; private static final String ID_SYSTEM_INFO = "systemInfo"; @@ -100,33 +100,33 @@ private void initLayout() { initSystemInfo(); } - + private void initInfoBoxes() { Task task = createSimpleTask("PageDashboard.infobox"); OperationResult result = task.getResult(); - - add(createFocusInfoBoxPanel(ID_INFO_BOX_USERS, UserType.class, "object-user-bg", - GuiStyleConstants.CLASS_OBJECT_USER_ICON, "PageDashboard.infobox.users", PageUsers.class, + + add(createFocusInfoBoxPanel(ID_INFO_BOX_USERS, UserType.class, "object-user-bg", + GuiStyleConstants.CLASS_OBJECT_USER_ICON, "PageDashboard.infobox.users", PageUsers.class, result, task)); - - add(createFocusInfoBoxPanel(ID_INFO_BOX_ORGS, OrgType.class, "object-org-bg", - GuiStyleConstants.CLASS_OBJECT_ORG_ICON, "PageDashboard.infobox.orgs", PageOrgTree.class, + + add(createFocusInfoBoxPanel(ID_INFO_BOX_ORGS, OrgType.class, "object-org-bg", + GuiStyleConstants.CLASS_OBJECT_ORG_ICON, "PageDashboard.infobox.orgs", PageOrgTree.class, result, task)); - - add(createFocusInfoBoxPanel(ID_INFO_BOX_ROLES, RoleType.class, "object-role-bg", - GuiStyleConstants.CLASS_OBJECT_ROLE_ICON, "PageDashboard.infobox.roles", PageRoles.class, + + add(createFocusInfoBoxPanel(ID_INFO_BOX_ROLES, RoleType.class, "object-role-bg", + GuiStyleConstants.CLASS_OBJECT_ROLE_ICON, "PageDashboard.infobox.roles", PageRoles.class, result, task)); - - add(createFocusInfoBoxPanel(ID_INFO_BOX_SERVICES, ServiceType.class, "object-service-bg", - GuiStyleConstants.CLASS_OBJECT_SERVICE_ICON, "PageDashboard.infobox.services", PageServices.class, + + add(createFocusInfoBoxPanel(ID_INFO_BOX_SERVICES, ServiceType.class, "object-service-bg", + GuiStyleConstants.CLASS_OBJECT_SERVICE_ICON, "PageDashboard.infobox.services", PageServices.class, result, task)); - + add(createResourceInfoBoxPanel(result, task)); add(createTaskInfoBoxPanel(result, task)); - + } - private InfoBoxPanel createFocusInfoBoxPanel(String id, Class type, String bgColor, + private InfoBoxPanel createFocusInfoBoxPanel(String id, Class type, String bgColor, String icon, String keyPrefix, Class linkPage, OperationResult result, Task task) { InfoBoxType infoBoxType = new InfoBoxType(bgColor, icon, getString(keyPrefix + ".label")); Integer allCount; @@ -151,25 +151,25 @@ private InfoBoxPanel createFocusInfoBoxPanel(String id, Cl if (archivedCount == null) { archivedCount = 0; } - + int activeCount = allCount - disabledCount - archivedCount; int totalCount = allCount - archivedCount; - + infoBoxType.setNumber(activeCount + " " + getString(keyPrefix + ".number")); - + int progress = 0; if (totalCount != 0) { progress = activeCount * 100 / totalCount; } infoBoxType.setProgress(progress); - + StringBuilder descSb = new StringBuilder(); descSb.append(totalCount).append(" ").append(getString(keyPrefix + ".total")); if (archivedCount != 0) { descSb.append(" ( + ").append(archivedCount).append(" ").append(getString(keyPrefix + ".archived")).append(")"); } infoBoxType.setDescription(descSb.toString()); - + } catch (Exception e) { infoBoxType.setNumber("ERROR: "+e.getMessage()); } @@ -178,9 +178,9 @@ private InfoBoxPanel createFocusInfoBoxPanel(String id, Cl return new InfoBoxPanel(id, boxModel, linkPage); } - + private Component createResourceInfoBoxPanel(OperationResult result, Task task) { - InfoBoxType infoBoxType = new InfoBoxType("object-resource-bg", GuiStyleConstants.CLASS_OBJECT_RESOURCE_ICON, + InfoBoxType infoBoxType = new InfoBoxType("object-resource-bg", GuiStyleConstants.CLASS_OBJECT_RESOURCE_ICON, getString("PageDashboard.infobox.resources.label")); Integer totalCount; try { @@ -196,17 +196,17 @@ private Component createResourceInfoBoxPanel(OperationResult result, Task task) if (activeCount == null) { activeCount = 0; } - + infoBoxType.setNumber(activeCount + " " + getString("PageDashboard.infobox.resources.number")); - + int progress = 0; if (totalCount != 0) { progress = activeCount * 100 / totalCount; } infoBoxType.setProgress(progress); - + infoBoxType.setDescription(totalCount + " " + getString("PageDashboard.infobox.resources.total")); - + } catch (Exception e) { infoBoxType.setNumber("ERROR: "+e.getMessage()); } @@ -215,9 +215,9 @@ private Component createResourceInfoBoxPanel(OperationResult result, Task task) return new InfoBoxPanel(ID_INFO_BOX_RESOURCES, boxModel, PageResources.class); } - + private Component createTaskInfoBoxPanel(OperationResult result, Task task) { - InfoBoxType infoBoxType = new InfoBoxType("object-task-bg", GuiStyleConstants.CLASS_OBJECT_TASK_ICON, + InfoBoxType infoBoxType = new InfoBoxType("object-task-bg", GuiStyleConstants.CLASS_OBJECT_TASK_ICON, getString("PageDashboard.infobox.tasks.label")); Integer totalCount; try { @@ -232,17 +232,17 @@ private Component createTaskInfoBoxPanel(OperationResult result, Task task) { if (activeCount == null) { activeCount = 0; } - + infoBoxType.setNumber(activeCount + " " + getString("PageDashboard.infobox.tasks.number")); - + int progress = 0; if (totalCount != 0) { progress = activeCount * 100 / totalCount; } infoBoxType.setProgress(progress); - + infoBoxType.setDescription(totalCount + " " + getString("PageDashboard.infobox.tasks.total")); - + } catch (Exception e) { infoBoxType.setNumber("ERROR: "+e.getMessage()); } @@ -255,7 +255,7 @@ private Component createTaskInfoBoxPanel(OperationResult result, Task task) { private void initPersonalInfo() { DashboardPanel personalInfo = new DashboardPanel(ID_PERSONAL_INFO, null, - createStringResource("PageDashboard.personalInfo"), GuiStyleConstants.CLASS_OBJECT_USER_BOX_CSS_CLASSES, + createStringResource("PageDashboard.personalInfo"), GuiStyleConstants.CLASS_OBJECT_USER_BOX_CSS_CLASSES, GuiStyleConstants.CLASS_OBJECT_USER_BOX_CSS_CLASSES) { private static final long serialVersionUID = 1L; @@ -269,7 +269,7 @@ protected Component getMainComponent(String componentId) { private void initSystemInfo() { DashboardPanel systemInfo = new DashboardPanel(ID_SYSTEM_INFO, null, - createStringResource("PageDashboard.systemInfo"), + createStringResource("PageDashboard.systemInfo"), GuiStyleConstants.CLASS_ICON_TACHOMETER, GuiStyleConstants.CLASS_OBJECT_RESOURCE_BOX_CSS_CLASSES) { private static final long serialVersionUID = 1L; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/PageMyPasswordQuestions.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/PageMyPasswordQuestions.java index 3b4f2f475c6..e6d63782e57 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/PageMyPasswordQuestions.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/PageMyPasswordQuestions.java @@ -61,9 +61,9 @@ public class PageMyPasswordQuestions extends PageAdminHome { private static final String DOT_CLASS = PageMyPasswordQuestions.class.getName() + "."; private static final String OPERATION_LOAD_USER = DOT_CLASS + "loaduser"; private static final String OPERATION_LOAD_QUESTION_POLICY = DOT_CLASS + "LOAD Question Policy"; - private String ID_PASSWORD_QUESTIONS_PANEL = "pwdQuestionsPanel"; + private String ID_PASSWORD_QUESTIONS_PANEL = "pwdQuestionsPanel"; private static final String OPERATION_SAVE_QUESTIONS="Save Security Questions"; - + private static final String ID_MAIN_FORM = "mainForm"; private static final String ID_BACK = "back"; private static final String ID_SAVE = "save"; @@ -83,7 +83,7 @@ public PageMyPasswordQuestions() { model = new LoadableModel(false) { private static final long serialVersionUID = 1L; - + @Override protected PasswordQuestionsDto load() { return loadPageModel(); @@ -133,7 +133,7 @@ private PasswordQuestionsDto loadPageModel() { } catch (Exception ex) { LoggingUtils.logExceptionOnDebugLevel(LOGGER, "Couldn't get user Questions, Probably not set yet", ex); - + } finally { result.recomputeStatus(); } @@ -181,21 +181,21 @@ public void initLayout(){ Form mainForm = new Form(ID_MAIN_FORM); - //question panel list + //question panel list pqPanels = new ArrayList(); OperationResult result = new OperationResult(OPERATION_LOAD_QUESTION_POLICY); try{ Task task = getPageBase().createSimpleTask(OPERATION_LOAD_QUESTION_POLICY); - OperationResult subResult = result.createSubresult(OPERATION_LOAD_QUESTION_POLICY); + OperationResult subResult = result.createSubresult(OPERATION_LOAD_QUESTION_POLICY); try{ //PrismObject config = getPageBase().getModelService().getObject( // SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, //task, result); - + CredentialsPolicyType credPolicy=getModelInteractionService().getCredentialsPolicy(null, null, result); - + // PrismObject securityPolicy = getModelService().getObject(SecurityPolicyType.class,config.asObjectable().getGlobalSecurityPolicyRef().getOid(), null, task, subResult); //Global Policy set question numbers if (credPolicy != null && credPolicy.getSecurityQuestions() != null) { @@ -209,26 +209,26 @@ public void initLayout(){ } }catch(Exception ex){ ex.printStackTrace(); - + /* List userQuestionList= model.getObject().getSecurityAnswers(); int panelNumber=0; PrismObject user = null; - - + + Collection options = SelectorOptions.createCollection(UserType.F_CREDENTIALS, GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE)); Task taskTwo = createSimpleTask("LOAD USER WRAPPER"); user = getModelService().getObject(UserType.class, SecurityUtils.getPrincipalUser().getOid(), options, taskTwo, result); - + OperationResult parentResult = new OperationResult(OPERATION_LOAD_QUESTION_POLICY); questionNumber = getModelInteractionService().getCredentialsPolicy(user, parentResult).getSecurityQuestions().getQuestionNumber(); - + policyQuestionList=getModelInteractionService().getCredentialsPolicy(user, parentResult).getSecurityQuestions().getQuestion(); if(userQuestionList==null){ - + executeAddingQuestions(questionNumber, 0, policyQuestionList); - + LOGGER.info(getModelInteractionService().getCredentialsPolicy(user, parentResult).getSecurityQuestions().getQuestionNumber().toString()); }else{ @@ -237,13 +237,13 @@ public void initLayout(){ if (userQuestionList.get(userQuestint)!=null){ LOGGER.debug("Questitself"+userQuestionList.get(userQuestint).getQuestionItself()); MyPasswordQuestionsPanel panel=new MyPasswordQuestionsPanel(ID_PASSWORD_QUESTIONS_PANEL+ panelNumber,userQuestionList.get(userQuestint)); - pqPanels.add(panel); + pqPanels.add(panel); panelNumber++; } } //TODO same questions check should be implemented - + } add(mainForm); mainForm.add(getPanels(pqPanels)); @@ -252,62 +252,62 @@ public void initLayout(){ return; */ } - + /*User's Pre-Set Question List*/ - List userQuestionList= model.getObject().getSecurityAnswers(); - - /* check if user's set number of + List userQuestionList= model.getObject().getSecurityAnswers(); + + /* check if user's set number of * questions matches the policy or not*/ - + //Case that policy have more than users's number of numbers if((userQuestionList==null) || (questionNumber>userQuestionList.size())){ if(userQuestionList==null){ executeAddingQuestions(questionNumber, 0, policyQuestionList); //TODO same questions check should be implemented - + }else{ - executePasswordQuestionsAndAnswers(userQuestionList, policyQuestionList, userQuestionList.size()); + executePasswordQuestionsAndAnswers(userQuestionList, policyQuestionList, userQuestionList.size()); //QUESTION NUMBER BIGGER THAN QUESTION LIST - //rest of the questions + //rest of the questions int difference=questionNumber-userQuestionList.size(); executeAddingQuestions(difference, userQuestionList.size(), policyQuestionList); - + } - - + + }else if(questionNumber==userQuestionList.size()){ //QUESTION NUMBER EQUALS TO QUESTION LIST - executePasswordQuestionsAndAnswers(userQuestionList, policyQuestionList, 0); - + executePasswordQuestionsAndAnswers(userQuestionList, policyQuestionList, 0); + //TODO PART2: Case that policy have smaller than users's number of numbers }else if(questionNumber < userQuestionList.size()){ - + //QUESTION NUMBER SMALLER THAN QUESTION LIST executePasswordQuestionsAndAnswers(userQuestionList, policyQuestionList, 0); - - + + //this part will be using at remove operation in the future - /* int diff = userQuestionList.size()-questionNumber; + /* int diff = userQuestionList.size()-questionNumber; for(Iterator iterator = userQuestionList.iterator(); iterator.hasNext();){ - + SecurityQuestionAnswerDTO element = (SecurityQuestionAnswerDTO)iterator.next(); for(int i=0; i u int userQuest =0; LOGGER.debug("executePasswordQuestionsAndAnswers"); for (Iterator iterator = policyQuestionList.iterator(); iterator.hasNext();) { - - - /* Loop for finding the Existing Questions + + + /* Loop for finding the Existing Questions * and Answers according to Policy*/ - + SecurityQuestionDefinitionType securityQuestionDefinitionType = (SecurityQuestionDefinitionType) iterator .next(); //user's question List loop to match the questions for(int i=userQuest;i getPanels(List p){ ListView lw = new ListView(ID_PASSWORD_QUESTIONS_PANEL,p){ @Override protected void populateItem(ListItem item) { - item.add((MyPasswordQuestionsPanel)item.getModelObject()); - } + item.add((MyPasswordQuestionsPanel)item.getModelObject()); + } }; return lw; } @@ -420,7 +420,7 @@ protected void onSubmit(AjaxRequestTarget target, Form form) { } }; mainForm.add(save); - + AjaxButton back = new AjaxButton(ID_BACK, createStringResource("PageBase.button.back")) { @@ -435,7 +435,7 @@ public void onClick(AjaxRequestTarget target) { } private void savePerformed(AjaxRequestTarget target) { - + /* * Oguzhan: added target variable to the updateQuestions method. */ @@ -454,7 +454,7 @@ private ObjectWrapper loadUserWrapper(PrismObject userToEdit) { try { Collection options = SelectorOptions.createCollection(UserType.F_CREDENTIALS, GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE)); - + user = getModelService().getObject(UserType.class, SecurityUtils.getPrincipalUser().getOid(), options, task, result); @@ -465,7 +465,7 @@ private ObjectWrapper loadUserWrapper(PrismObject userToEdit) { } showResult(result, false); - + if (user == null) { throw new RestartResponseException(PageDashboard.class); @@ -483,7 +483,7 @@ private ObjectWrapper loadUserWrapper(PrismObject userToEdit) { } // ObjectWrapper wrapper = new ObjectWrapper("pageUser.userDetails", null, user, status); showResult(wrapper.getResult(), false); - + return wrapper; } @@ -507,15 +507,15 @@ private SecurityQuestionAnswerDTO checkIfQuestionisValid(SecurityQuestionAnswerD } - + return null; } - + private SecurityQuestionAnswerDTO checkIfQuestionisValidSingle(SecurityQuestionAnswerDTO questionIdentifier,SecurityQuestionDefinitionType securityQuestion){ - + if(securityQuestion.getIdentifier().trim().compareTo(questionIdentifier.getPwdQuestion().trim())==0){ questionIdentifier.setQuestionItself(securityQuestion.getQuestionText()); - + //LOGGER.info("\n\n: TRUE QUESTION"); return questionIdentifier; }else{ @@ -541,29 +541,29 @@ private void updateQuestions(String useroid, AjaxRequestTarget target){ SecurityQuestionAnswerType answerType = new SecurityQuestionAnswerType(); ProtectedStringType answer = new ProtectedStringType(); - answer.setClearValue(((TextField)type.get(MyPasswordQuestionsPanel.F_ANSWER)).getModelObject()); + answer.setClearValue(((TextField)type.get(MyPasswordQuestionsPanel.F_ANSWER)).getModelObject()); answerType.setQuestionAnswer(answer); - + //used apache's unescapeHtml method for special chars like \' String results = StringEscapeUtils.unescapeHtml((type.get(MyPasswordQuestionsPanel.F_QUESTION)).getDefaultModelObjectAsString()); - answerType.setQuestionIdentifier(getQuestionIdentifierFromQuestion(results)); + answerType.setQuestionIdentifier(getQuestionIdentifierFromQuestion(results)); answerTypeList[listnum]=answerType; listnum++; - + } - + //if(answerTypeList.length !=) // fill in answerType data here ItemPath path = new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_SECURITY_QUESTIONS, SecurityQuestionsCredentialsType.F_QUESTION_ANSWER); - ObjectDelta objectDelta = ObjectDelta.createModificationReplaceContainer(UserType.class, useroid, + ObjectDelta objectDelta = ObjectDelta.createModificationReplaceContainer(UserType.class, useroid, path, getPrismContext(), answerTypeList); Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); getModelService().executeChanges(deltas, null, task, result); - /* + /* System.out.println("getModel"); Collection> deltas = new ArrayList>(); PasswordQuestionsDto dto = new PasswordQuestionsDto(); @@ -571,7 +571,7 @@ private void updateQuestions(String useroid, AjaxRequestTarget target){ Class type = UserType.class; final ItemPath valuePath = new ItemPath(SchemaConstantsGenerated.C_CREDENTIALS, - CredentialsType.F_SECURITY_QUESTIONS, SecurityQuestionsCredentialsType.F_QUESTION_ANSWER); + CredentialsType.F_SECURITY_QUESTIONS, SecurityQuestionsCredentialsType.F_QUESTION_ANSWER); SecurityQuestionAnswerType secQuesAnsType= new SecurityQuestionAnswerType(); ProtectedStringType protStrType= new ProtectedStringType(); protStrType.setClearValue("deneme"); @@ -592,7 +592,7 @@ private void updateQuestions(String useroid, AjaxRequestTarget target){ success(getString("message.success")); target.add(getFeedbackPanel()); } catch(Exception ex){ - + error(getString("message.error")); target.add(getFeedbackPanel()); ex.printStackTrace(); @@ -610,7 +610,7 @@ private String getQuestionIdentifierFromQuestion(String questionItself){ - } + } return null; } public PageBase getPageBase() { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/component/AsyncDashboardPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/component/AsyncDashboardPanel.java index 9aea7d78204..368f2508c6e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/component/AsyncDashboardPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/component/AsyncDashboardPanel.java @@ -69,7 +69,7 @@ public AsyncDashboardPanel(String id, IModel title, String icon, IModel< public AsyncDashboardPanel(String id, IModel title, String icon, IModel callableParameterModel, Duration durationSecs, String boxCssClasses, boolean noPadding) { super(id, callableParameterModel, durationSecs); - + initLayout(noPadding); WebMarkupContainer dashboardTitle = (WebMarkupContainer) get( diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/component/DashboardPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/component/DashboardPanel.java index ff100d8a666..acc20230a1b 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/component/DashboardPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/component/DashboardPanel.java @@ -31,7 +31,7 @@ */ public abstract class DashboardPanel extends BasePanel { private static final long serialVersionUID = 1L; - + private static final String ID_DASHBOARD_PARENT = "dashboardParent"; private static final String ID_DASHBOARD_TITLE = "dashboardTitle"; private static final String ID_TITLE = "title"; @@ -48,7 +48,7 @@ private void initLayout(IModel titleModel, String icon, String boxCssCla if (boxCssClasses == null) { boxCssClasses = GuiStyleConstants.CLASS_BOX_DEFAULT; } - + WebMarkupContainer dashboardParent = new WebMarkupContainer(ID_DASHBOARD_PARENT); dashboardParent.add(new AttributeAppender("class", " " + boxCssClasses)); add(dashboardParent); @@ -63,7 +63,7 @@ private void initLayout(IModel titleModel, String icon, String boxCssCla WebMarkupContainer dashboardContent = new WebMarkupContainer(ID_DASHBOARD_CONTENT); dashboardContent.add(getMainComponent(ID_CONTENT)); dashboardParent.add(dashboardContent); - + WebMarkupContainer iconI = new WebMarkupContainer(ID_ICON); iconI.add(AttributeModifier.replace("class", icon)); dashboardTitle.add(iconI); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/component/MyPasswordQuestionsPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/component/MyPasswordQuestionsPanel.java index c921d132a04..ddadc6bba60 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/component/MyPasswordQuestionsPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/component/MyPasswordQuestionsPanel.java @@ -46,8 +46,8 @@ public void initLayout() { /* * public void initLayout(){ - * - * + * + * * // final Label question = new Label (F_QUESTION, new * PropertyModel(model,SecurityQuestionAnswerDTO * .F_PASSWORD_QUESTION_ITSELF)); final Label question = new Label @@ -59,7 +59,7 @@ public void initLayout() { * answer = new TextField(F_ANSWER, new PropertyModel(model, * SecurityQuestionAnswerDTO.F_PASSWORD_QUESTION_ANSWER)); * answer.setRequired(true); answer.setOutputMarkupId(true); add(answer); - * + * * } */ @Override diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/dto/AssignmentItemDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/dto/AssignmentItemDto.java index 906b2db1bf9..f8c371d0328 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/dto/AssignmentItemDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/dto/AssignmentItemDto.java @@ -23,7 +23,7 @@ /** * TODO: unify with AssignmentEditorDto - * + * * @author lazyman */ public class AssignmentItemDto implements Serializable, Comparable { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/dto/PasswordAccountDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/dto/PasswordAccountDto.java index 23354be0837..c128e601869 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/dto/PasswordAccountDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/dto/PasswordAccountDto.java @@ -86,11 +86,11 @@ public String getCssClass() { public void setCssClass(String cssClass) { this.cssClass = cssClass; } - + public boolean isPasswordCapabilityEnabled() { return passwordCapabilityEnabled; } - + public void setPasswordCapabilityEnabled(boolean passwordCapabilityEnabled) { this.passwordCapabilityEnabled = passwordCapabilityEnabled; } 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 f0a6225f0ea..38f8ca250db 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 @@ -25,30 +25,30 @@ public class PasswordQuestionsDto implements Serializable{ - + public static final String F_MY_QUESTIONS_ANSWERS="questionAnswers"; public static final String F_MY_QUESTIONS_ANSWER="passwAnswer"; public static final String F_MY_QUESTIONS__QUESTIONITSELF="passwQuestion"; - + private String passwQuestion; private String passwAnswer; - + private List questionAnswers; - + private PrismContainer credentials; - + /*public PasswordQuestionsDto(String passwQuestion){ this.passwQuestion = passwQuestion; }*/ public PasswordQuestionsDto(){ - + }; - + public PasswordQuestionsDto(String passwQuestion, String passAnswer){ this.passwQuestion = passwQuestion; this.passwAnswer = passAnswer; } - + public String getPwdQuestion() { return passwQuestion; } @@ -61,7 +61,7 @@ public String getPwdAnswer() { public void setPwdAnswer(String pwdAnswer) { this.passwAnswer = pwdAnswer; } - + public PrismContainer getCredentials() { return credentials; } @@ -78,6 +78,6 @@ public void setSecurityAnswers(List securityAnswers) this.questionAnswers = securityAnswers; } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/dto/SecurityQuestionAnswerDTO.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/dto/SecurityQuestionAnswerDTO.java index 9365b9b2593..949be952531 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/dto/SecurityQuestionAnswerDTO.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/dto/SecurityQuestionAnswerDTO.java @@ -5,18 +5,18 @@ public class SecurityQuestionAnswerDTO implements Serializable { public static final String F_PASSWORD_QUESTION_IDENTIFIER = "passwQuestionIdentifier"; - - public static final String F_PASSWORD_QUESTION_ANSWER = "passwAnswer"; - - - public static final String F_PASSWORD_QUESTION_ITSELF = "questionItself"; - - - + + public static final String F_PASSWORD_QUESTION_ANSWER = "passwAnswer"; + + + public static final String F_PASSWORD_QUESTION_ITSELF = "questionItself"; + + + private String passwQuestionIdentifier; private String passwAnswer; private String questionItself; - + public SecurityQuestionAnswerDTO(String passwQuestion, String passAnswer){ this.passwQuestionIdentifier = passwQuestion; this.passwAnswer = passAnswer; @@ -26,7 +26,7 @@ public SecurityQuestionAnswerDTO(String passwQuestion, String passAnswer,String this.passwAnswer = passAnswer; this.questionItself=questionitself; } - + public String getPwdQuestion() { return passwQuestionIdentifier; } @@ -39,12 +39,12 @@ public String getPwdAnswer() { public void setPwdAnswer(String pwdAnswer) { this.passwAnswer = pwdAnswer; } - + public String getQuestionItself() { return questionItself; } public void setQuestionItself(String questionItself) { this.questionItself = questionItself; } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/orgs/AbstractOrgTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/orgs/AbstractOrgTabPanel.java index 3fc3b6896d8..622db1017ee 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/orgs/AbstractOrgTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/orgs/AbstractOrgTabPanel.java @@ -51,12 +51,12 @@ public abstract class AbstractOrgTabPanel extends BasePanel { private static final long serialVersionUID = 1L; private static final Trace LOGGER = TraceManager.getTrace(AbstractOrgTabPanel.class); - + public static final String PARAM_ORG_RETURN = "org"; private static final String DOT_CLASS = OrgTreeAssignablePanel.class.getName() + "."; private static final String OPERATION_LOAD_ORG_UNIT = DOT_CLASS + "loadOrgUnit"; - + private String ID_TABS = "tabs"; private List> roots; @@ -65,11 +65,11 @@ public AbstractOrgTabPanel(String id, PageBase pageBase) { setParent(pageBase); initLayout(); } - + private void initLayout() { final IModel> tabModel = new LoadableModel>(false) { private static final long serialVersionUID = 1L; - + @Override protected List load() { LOGGER.debug("Loading org. roots for tabs for tabbed panel."); @@ -86,7 +86,7 @@ protected List load() { public WebMarkupContainer getPanel(String panelId) { add(new AjaxEventBehavior("load") { private static final long serialVersionUID = 1L; - + protected void onEvent(final AjaxRequestTarget target) { SessionStorage storage = getPageBase().getSessionStorage(); storage.getUsers().setSelectedTabId(tabId); @@ -97,8 +97,8 @@ protected void onEvent(final AjaxRequestTarget target) { panel.setOutputMarkupId(true); return panel; } - - + + }); } @@ -118,7 +118,7 @@ protected void onEvent(final AjaxRequestTarget target) { AjaxTabbedPanel tabbedPanel = new AjaxTabbedPanel(ID_TABS, tabModel.getObject(), new Model<>(selectedTab), null){ private static final long serialVersionUID = 1L; - + @Override public TabbedPanel setSelectedTab(int index) { changeTabPerformed(index); @@ -126,17 +126,17 @@ public TabbedPanel setSelectedTab(int index) { } }; tabbedPanel.setOutputMarkupId(true); - + if (tabsList == null || tabsList.size() == 0){ tabbedPanel.setVisible(false); } add(tabbedPanel); } - + protected Panel getPanel(){ return (Panel) get(ID_TABS).get("panel"); } - + public AjaxTabbedPanel getTabbedPanel(){ return (AjaxTabbedPanel) get(ID_TABS); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/orgs/OrgTreePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/orgs/OrgTreePanel.java index 66f59ba7575..dea350e9c4a 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/orgs/OrgTreePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/orgs/OrgTreePanel.java @@ -66,7 +66,7 @@ public class OrgTreePanel extends AbstractTreeTablePanel { private static final long serialVersionUID = 1L; private static final Trace LOGGER = TraceManager.getTrace(OrgTreePanel.class); - + private boolean selectable; private String treeTitleKey = ""; SessionStorage storage; @@ -86,7 +86,7 @@ public OrgTreePanel(String id, IModel rootOid, boolean selectable, Model this.selectable = selectable; selected = new LoadableModel>() { private static final long serialVersionUID = 1L; - + @Override protected SelectableBean load() { TabbedPanel currentTabbedPanel = null; @@ -141,7 +141,7 @@ private void initLayout(ModelServiceLocator serviceLocator) { ISortableTreeProvider provider = new OrgTreeProvider(this, getModel()) { private static final long serialVersionUID = 1L; - + @Override protected List createInlineMenuItems(OrgType org) { return createTreeChildrenMenu(org); @@ -178,7 +178,7 @@ public void renderHead(IHeaderResponse response) { TreeStateModel treeStateMode = new TreeStateModel(this, provider) { private static final long serialVersionUID = 1L; - + @Override public Set> getExpandedItems(){ return OrgTreePanel.this.getExpandedItems(getOrgTreeStateStorage()); @@ -192,7 +192,7 @@ public void setCollapsedItem(SelectableBean item){ OrgTreePanel.this.setCollapsedItem(null, getOrgTreeStateStorage()); } }; - + TableTree, String> tree = new TableTree, String>( ID_TREE, columns, provider, Integer.MAX_VALUE, treeStateMode) { private static final long serialVersionUID = 1L; @@ -219,7 +219,7 @@ protected Item> newRowItem(String id, int index, Item> item = super.newRowItem(id, index, model); item.add(AttributeModifier.append("class", new AbstractReadOnlyModel() { private static final long serialVersionUID = 1L; - + @Override public String getObject() { SelectableBean itemObject = model.getObject(); @@ -337,7 +337,7 @@ private List createTreeMenuInternal(AdminGuiConfigurationType ad InlineMenuItem item = new InlineMenuItem(createStringResource("TreeTablePanel.collapseAll"), new InlineMenuItemAction() { private static final long serialVersionUID = 1L; - + @Override public void onClick(AjaxRequestTarget target) { collapseAllPerformed(target); @@ -349,7 +349,7 @@ public void onClick(AjaxRequestTarget target) { InlineMenuItem item = new InlineMenuItem(createStringResource("TreeTablePanel.expandAll"), new InlineMenuItemAction() { private static final long serialVersionUID = 1L; - + @Override public void onClick(AjaxRequestTarget target) { expandAllPerformed(target); @@ -376,7 +376,7 @@ protected List createTreeChildrenMenu(OrgType org) { protected void selectTreeItemPerformed(SelectableBean selected, AjaxRequestTarget target) { } - + private void collapseAllPerformed(AjaxRequestTarget target) { TableTree, String> tree = getTree(); TreeStateModel model = (TreeStateModel) tree.getDefaultModel(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageCreatedReports.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageCreatedReports.java index b1ea3fd1f69..90bb5feb712 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageCreatedReports.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageCreatedReports.java @@ -118,7 +118,7 @@ public class PageCreatedReports extends PageAdminReports { private static Map reportExportTypeMap = new HashMap<>(); private Map reportTypeMal = new HashMap<>(); - + static { reportExportTypeMap.put(ExportType.CSV, "text/csv; charset=UTF-8"); reportExportTypeMap.put(ExportType.DOCX, "application/vnd.openxmlformats-officedocument.wordprocessingml.document; charset=UTF-8"); @@ -138,13 +138,13 @@ public class PageCreatedReports extends PageAdminReports { public PageCreatedReports(PageParameters pageParameters) { super(pageParameters); - + initReportTypeMap(); initLayout(); - + } - + private void initReportTypeMap() { OperationResult result = new OperationResult(OPERATION_LOAD_REPORTS); List> reports = WebModelServiceUtils.searchObjects(ReportType.class, null, result, this); @@ -166,9 +166,9 @@ private String getReportType(){ private void initLayout() { Form mainForm = new Form<>(ID_MAIN_FORM); add(mainForm); - - - + + + DropDownChoicePanel reportTypeSelect = new DropDownChoicePanel(ID_REPORT_TYPE_SELECT, Model.of(reportTypeMal.get(getReportType())), Model.of(reportTypeMal.values()), @@ -187,9 +187,9 @@ protected void onUpdate(AjaxRequestTarget target) { final AjaxDownloadBehaviorFromStream ajaxDownloadBehavior = new AjaxDownloadBehaviorFromStream() { - + private static final long serialVersionUID = 1L; - + @Override protected InputStream initStream() { return createReport(this); @@ -203,15 +203,15 @@ public String getFileName(){ mainForm.add(ajaxDownloadBehavior); - + MainObjectListPanel table = new MainObjectListPanel(ID_CREATED_REPORTS_TABLE, ReportOutputType.class, UserProfileStorage.TableId.PAGE_CREATED_REPORTS_PANEL, null, this) { - + private static final long serialVersionUID = 1L; @Override protected List createInlineMenu() { return PageCreatedReports.this.initInlineMenu(); } - + @Override protected List, String>> createColumns() { return PageCreatedReports.this.initColumns(ajaxDownloadBehavior); @@ -225,28 +225,28 @@ protected PrismObject getNewObjectListObject(){ @Override protected void objectDetailsPerformed(AjaxRequestTarget target, ReportOutputType object) { // TODO Auto-generated method stub - + } - + @Override protected void newObjectPerformed(AjaxRequestTarget target) { // TODO Auto-generated method stub - + } - + @Override protected boolean isClickable(IModel> rowModel) { return false; } - + @Override protected ObjectQuery addFilterToContentQuery(ObjectQuery query) { return appendTypeFilter(query); } - + @Override protected List createCustomOrdering(SortParam sortParam) { - + if (sortParam != null && sortParam.getProperty() != null) { OrderDirection order = sortParam.isAscending() ? OrderDirection.ASCENDING : OrderDirection.DESCENDING; if (sortParam.getProperty().equals("createTimestamp")) { @@ -257,14 +257,14 @@ protected List createCustomOrdering(SortParam sortParam) return Collections.singletonList( ObjectOrdering.createOrdering( new ItemPath(new QName(SchemaConstantsGenerated.NS_COMMON, sortParam.getProperty())), order)); - - + + } else { return Collections.emptyList(); } } - - }; + + }; table.setOutputMarkupId(true); @@ -284,11 +284,11 @@ private List, String>> initColumns( IColumn, String> column = new PropertyColumn<>(createStringResource("pageCreatedReports.table.description"), "value.description"); columns.add(column); - + column = new AbstractColumn, String>( createStringResource("pageCreatedReports.table.time"), "createTimestamp") { - + private static final long serialVersionUID = 1L; @Override @@ -359,7 +359,7 @@ public void onSubmit(AjaxRequestTarget target, Form form) { headerMenuItems.add(new InlineMenuItem(createStringResource("pageCreatedReports.inlineMenu.deleteSelected"), true, new HeaderMenuAction(this) { - + private static final long serialVersionUID = 1L; @Override @@ -374,7 +374,7 @@ public void onSubmit(AjaxRequestTarget target, Form form) { private IModel createDeleteConfirmString() { return new AbstractReadOnlyModel() { - + private static final long serialVersionUID = 1L; @Override @@ -413,7 +413,7 @@ private void deleteAllPerformed(AjaxRequestTarget target, ReportDeleteDialogDto. private ConfirmationPanel getDeleteDialogPanel(){ ConfirmationPanel dialog = new ConfirmationPanel(getPageBase().getMainPopupBodyId(), createDeleteConfirmString()){ - + private static final long serialVersionUID = 1L; @Override public void yesPerformed(AjaxRequestTarget target) { @@ -461,7 +461,7 @@ private void deleteSelectedConfirmedPerformed(AjaxRequestTarget target, List typeSelect = (DropDownChoicePanel) get(createComponentPath(ID_MAIN_FORM, ID_REPORT_TYPE_SELECT)); String typeRef = (String) typeSelect.getBaseFormComponent().getModelObject(); S_AtomicFilterEntry q = QueryBuilder.queryFor(ReportOutputType.class, getPrismContext()); - + S_AtomicFilterExit refF; if (StringUtils.isNotBlank(typeRef)) { Entry typeRefFilter = reportTypeMal.entrySet().stream().filter(e -> e.getValue().equals(typeRef)).findFirst().get(); @@ -504,7 +504,7 @@ private ObjectQuery appendTypeFilter(ObjectQuery query) { } } } - + return query; } @@ -560,7 +560,7 @@ private void downloadPerformed(AjaxRequestTarget target, ReportOutputType report private String getReportFileName() { return getReportFileName(currentReport); } - + public static String getReportFileName(ReportOutputType currentReport){ try { OperationResult result = new OperationResult(OPERATION_GET_REPORT_FILENAME); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageNewReport.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageNewReport.java index 2cb0cf507c1..e77ba31710a 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageNewReport.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageNewReport.java @@ -66,7 +66,7 @@ public class PageNewReport extends PageAdminReports { private static final Trace LOGGER = TraceManager.getTrace(PageNewReport.class); - + private static final String ID_MAIN_FORM = "mainForm"; private static final String ID_BUTTON_BAR = "buttonBar"; private static final String ID_IMPORT_RADIO_GROUP = "importRadioGroup"; @@ -80,21 +80,21 @@ public class PageNewReport extends PageAdminReports { private static final String ID_INPUT_FILE_LABEL = "inputFileLabel"; private static final String ID_INPUT_FILE = "inputFile"; private static final String ID_FILE_INPUT = "fileInput"; - + private static final String OPERATION_IMPORT_REPORT_XML = "Import Report from XML"; private static final String OPERATION_IMPORT_REPORT = "Import Report from file"; private static final Integer INPUT_FILE = 1; private static final Integer INPUT_XML = 2; - + private Model xmlEditorModel; public PageNewReport() { xmlEditorModel = new Model(null); - + initLayout(); } - + private void initLayout() { Form mainForm = new Form(ID_MAIN_FORM); add(mainForm); @@ -129,7 +129,7 @@ protected void onUpdate(AjaxRequestTarget target) { addVisibileForInputType(inputAce, INPUT_XML, groupModel); input.add(inputAce); - + AceEditor aceEditor = new AceEditor(ID_ACE_EDITOR, xmlEditorModel); aceEditor.setOutputMarkupId(true); inputAce.add(aceEditor); @@ -230,7 +230,7 @@ private void importReportFromFilePerformed(AjaxRequestTarget target) { // reader. stream = new ReaderInputStream(reader, reader.getEncoding()); byte[] reportIn = IOUtils.toByteArray(stream); - + setResponsePage(new PageReport(new ReportDto(Base64.encodeBase64(reportIn)))); } catch (Exception ex) { result.recordFatalError("Couldn't import file.", ex); @@ -260,7 +260,7 @@ private void importReportFromStreamPerformed(AjaxRequestTarget target) { OperationResult result = new OperationResult(OPERATION_IMPORT_REPORT_XML); InputStream stream = null; try { - + setResponsePage(new PageReport(new ReportDto(Base64.encodeBase64(xml.getBytes())))); } catch (Exception ex) { result.recordFatalError("Couldn't import object.", ex); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageReport.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageReport.java index e79427e61fc..4716d90c79a 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageReport.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageReport.java @@ -98,16 +98,16 @@ protected ReportDto load() { initLayout(); } - + public PageReport(final ReportDto reportDto) { model = new LoadableModel(reportDto, false) { - + @Override protected ReportDto load() { // never called return reportDto; } - + }; initLayout(); } @@ -117,14 +117,14 @@ private ReportDto loadReport() { Task task = createSimpleTask(OPERATION_LOAD_REPORT); OperationResult result = task.getResult(); - PrismObject prismReport = WebModelServiceUtils.loadObject(ReportType.class, reportOid.toString(), + PrismObject prismReport = WebModelServiceUtils.loadObject(ReportType.class, reportOid.toString(), this, task, result); - + if (prismReport == null) { LOGGER.error("Couldn't load report."); throw new RestartResponseException(PageReports.class); } - + return new ReportDto(prismReport.asObjectable()); // return prismReport; @@ -307,10 +307,10 @@ protected void onSavePerformed(AjaxRequestTarget target) { getPrismContext().adopt(delta); getModelService().executeChanges(WebComponentUtil.createDeltaCollection(delta), null, task, result); } - + } catch (Exception e) { result.recordFatalError("Couldn't save report.", e); - + } finally { result.computeStatusIfUnknown(); } 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 4768e4d3d56..58ece77ce71 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 @@ -215,9 +215,9 @@ private void reportTypeFilterPerformed(AjaxRequestTarget target, String oid) { } protected void runReportPerformed(AjaxRequestTarget target, ReportType report) { - + RunReportPopupPanel runReportPopupPanel = new RunReportPopupPanel(getMainPopupBodyId(), report) { - + private static final long serialVersionUID = 1L; protected void runConfirmPerformed(AjaxRequestTarget target, ReportType reportType, PrismContainer reportParam) { @@ -236,11 +236,11 @@ protected void runConfirmPerformed(AjaxRequestTarget target, ReportType reportTy showResult(result); target.add(getFeedbackPanel(), get(createComponentPath(ID_MAIN_FORM))); hideMainPopup(target); - + }; }; showMainPopup(runReportPopupPanel, target); - + } private void configurePerformed(AjaxRequestTarget target, ReportType report) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/AceEditorPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/AceEditorPanel.java index fe3ab58cd0c..bf0ad593b61 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/AceEditorPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/AceEditorPanel.java @@ -37,7 +37,7 @@ public AceEditorPanel(String id, IModel title, IModel data) { this.title = title; initLayout(0); } - + public AceEditorPanel(String id, IModel title, IModel data, int minSize) { super(id, data); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/AuditLogViewerPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/AuditLogViewerPanel.java index 256960adbcb..30524b1561c 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/AuditLogViewerPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/AuditLogViewerPanel.java @@ -82,7 +82,7 @@ * Created by honchar. */ public class AuditLogViewerPanel extends BasePanel { - + private static final long serialVersionUID = 1L; private static final String ID_PARAMETERS_PANEL = "parametersPanel"; private static final String ID_TABLE = "table"; @@ -119,9 +119,9 @@ public class AuditLogViewerPanel extends BasePanel { public static final String EVENT_STAGE_COLUMN_VISIBILITY = "eventStageColumn"; public static final String EVENT_STAGE_LABEL_VISIBILITY = "eventStageLabel"; public static final String EVENT_STAGE_FIELD_VISIBILITY = "eventStageField"; - + static final Trace LOGGER = TraceManager.getTrace(AuditLogViewerPanel.class); - + private static final String OPERATION_RESOLVE_REFENRENCE_NAME = AuditLogViewerPanel.class.getSimpleName() + ".resolveReferenceName()"; @@ -211,7 +211,7 @@ private void initParametersPanel(Form mainForm) { PropertyModel changedItemModel = new PropertyModel(auditSearchModel, AuditSearchDto.F_CHANGED_ITEM); - + ItemPathPanel changedItemPanel = new ItemPathPanel(ID_CHANGED_ITEM, changedItemModel, pageBase); // changedItemPanel.getBaseFormComponent().add(new EmptyOnChangeAjaxFormUpdatingBehavior()); // changedItemPanel.getBaseFormComponent().add(new EmptyOnBlurAjaxFormUpdatingBehaviour()); @@ -290,7 +290,7 @@ private void initParametersPanel(Form mainForm) { List> allowedClasses = new ArrayList<>(); allowedClasses.add(UserType.class); MultiValueChoosePanel chooseInitiatorPanel = new SingleValueChoosePanel( - ID_INITIATOR_NAME, allowedClasses, objectReferenceTransformer, + ID_INITIATOR_NAME, allowedClasses, objectReferenceTransformer, new PropertyModel(auditSearchModel, AuditSearchDto.F_INITIATOR_NAME)); parametersPanel.add(chooseInitiatorPanel); @@ -300,10 +300,10 @@ private void initParametersPanel(Form mainForm) { MultiValueChoosePanel chooseTargerOwnerPanel = new SingleValueChoosePanel( ID_TARGET_OWNER_NAME_FIELD, allowedClasses, objectReferenceTransformer, new PropertyModel(auditSearchModel, AuditSearchDto.F_TARGET_OWNER_NAME)); - + chooseTargerOwnerPanel.add(visibilityByKey(visibilityMap, TARGET_OWNER_FIELD_VISIBILITY)); targetOwnerName.add(chooseTargerOwnerPanel); - + WebMarkupContainer targetName = new WebMarkupContainer(ID_TARGET_NAME); targetName.add(visibilityByKey(visibilityMap, TARGET_NAME_LABEL_VISIBILITY)); parametersPanel.add(targetName); @@ -311,7 +311,7 @@ private void initParametersPanel(Form mainForm) { allowedClassesAll.addAll(ObjectTypes.getAllObjectTypes()); MultiValueChoosePanel chooseTargetPanel = new MultiValueChoosePanel( - ID_TARGET_NAME_FIELD, + ID_TARGET_NAME_FIELD, new PropertyModel>(auditSearchModel, AuditSearchDto.F_TARGET_NAMES_OBJECTS), allowedClassesAll); chooseTargetPanel.setOutputMarkupId(true); @@ -366,17 +366,17 @@ protected void onError(AjaxRequestTarget target, Form form){ valueRefTargetNameContainer.add(chooseValueRefTargetNamePanel); } - + // Serializable as it becomes part of panel which is serialized - private Function objectReferenceTransformer = + private Function objectReferenceTransformer = (Function & Serializable) (ObjectType o) -> ObjectTypeUtil.createObjectRef(o); // Serializable as it becomes part of panel which is serialized - private Function stringTransformer = + private Function stringTransformer = (Function & Serializable) (ObjectType o) -> o.getName().getOrig(); - + private VisibleEnableBehaviour visibilityByKey(Map visibilityMap2, String visibilityKey) { return new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; @@ -387,7 +387,7 @@ public boolean isVisible(){ } }; } - + private void addOrReplaceTable(Form mainForm) { AuditEventRecordProvider provider = new AuditEventRecordProvider(AuditLogViewerPanel.this) { private static final long serialVersionUID = 1L; @@ -433,7 +433,7 @@ public Map getParameters() { parameters.put("eventStage", search.getEventStage()); parameters.put("outcome", search.getOutcome()); if(isNotEmpty(search.getvalueRefTargetNames())) { - parameters.put(AuditEventRecordProvider.VALUE_REF_TARGET_NAMES_KEY, + parameters.put(AuditEventRecordProvider.VALUE_REF_TARGET_NAMES_KEY, search.getvalueRefTargetNames().stream() .map(ObjectType::getName) .map(PolyStringType::getOrig) @@ -463,20 +463,20 @@ protected void saveCurrentPage(long from, long count) { @Override protected WebMarkupContainer createButtonToolbar(String id) { CsvDownloadButtonPanel exportDataLink = new CsvDownloadButtonPanel(id) { - + private static final long serialVersionUID = 1L; @Override protected String getFilename() { return "AuditLogViewer_" + createStringResource("MainObjectListPanel.exportFileName").getString(); } - + @Override protected DataTable getDataTable() { return getAuditLogViewerTable().getDataTable(); } }; - + return exportDataLink; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/ConvertingMultiValueChoosePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/ConvertingMultiValueChoosePanel.java index 22a05d3d723..237df9f793f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/ConvertingMultiValueChoosePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/ConvertingMultiValueChoosePanel.java @@ -45,7 +45,7 @@ protected void removePerformedHook(AjaxRequestTarget target, T value) { super.removePerformedHook(target, value); targetModel.getObject().remove(transform(value)); } - + protected U transform(T value) { return transformFunction.apply(value); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/JasperReportConfigurationPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/JasperReportConfigurationPanel.java index 8dd28818ad8..97b688aeb3f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/JasperReportConfigurationPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/JasperReportConfigurationPanel.java @@ -39,7 +39,7 @@ public class JasperReportConfigurationPanel extends BasePanel { private static final long serialVersionUID = 1L; - + private static final String ID_PARAMETERS_TABLE = "parametersTable"; private static final String ID_FIELDS_TABLE = "fieldsTable"; private static final String ID_BUTTON_ADD_PARAMETER = "addParameter"; @@ -54,7 +54,7 @@ public JasperReportConfigurationPanel(String id, IModel model) { initLayout(); } - + protected void initLayout() { AceEditorPanel queryPanel = new AceEditorPanel(ID_QUERY, createStringResource("JasperReportConfigurationPanel.reportQuery"), @@ -216,21 +216,21 @@ private List> initParameterColumns() { buildEditableLinkColumn("JasperReportConfigurationPanel.nestedClass", null, "nestedTypeAsString", true)); columns.add(new LinkColumn(createStringResource("JasperReportConfigurationPanel.properties")) { - + private static final long serialVersionUID = 1L; @Override public void onClick(AjaxRequestTarget target, IModel rowModel) { showPropertiesPopup(target, rowModel); } - + @Override protected IModel createLinkModel(IModel rowModel) { return createStringResource("JasperReportConfigurationPanel.configure"); } - }); - + }); + CheckBoxColumn forPrompting = new CheckBoxColumn( createStringResource("JasperReportConfigurationPanel.forPrompting"), "forPrompting") { @@ -249,13 +249,13 @@ public void populateItem(Item> cellItem return columns; } - + private void showPropertiesPopup(AjaxRequestTarget target, IModel rowModel) { - + ParameterPropertiesPopupPanel propertiesPopup = new ParameterPropertiesPopupPanel(getPageBase().getMainPopupBodyId(), new PropertyModel<>(rowModel, "properties")); getPageBase().showMainPopup(propertiesPopup, target); - + } private EditableLinkColumn buildEditableLinkColumn(String resource, String resourceParam, String property, final Boolean mandatory) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/ParameterPropertiesPopupPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/ParameterPropertiesPopupPanel.java index d5ebed01b47..b4223f7a6c9 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/ParameterPropertiesPopupPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/ParameterPropertiesPopupPanel.java @@ -33,12 +33,12 @@ public class ParameterPropertiesPopupPanel extends BasePanel implements Popupable { private static final long serialVersionUID = 1L; - + private static final String ID_KEY = "propertyKey"; private static final String ID_LABEL = "propertyLabel"; private static final String ID_TARGET_TYPE = "propertyTargetType"; // private static final String ID_MULTIVALUE = "propertyMultivalue"; - + private static final String ID_BUTTON_UPDATE = "update"; // private static final Trace LOGGER = TraceManager.getTrace(ParameterPropertiesPopupPanel.class); @@ -47,17 +47,17 @@ public ParameterPropertiesPopupPanel(String id, IModel(getModel(), "multivalue"), Model.of(Boolean.TRUE)); // add(multivalue); - + AjaxButton update = new AjaxButton(ID_BUTTON_UPDATE) { - + private static final long serialVersionUID = 1L; @Override @@ -67,21 +67,21 @@ public void onClick(AjaxRequestTarget target) { updateProperties(model.getObject(), target); } }; - + add(update); - + } - + private void addTextPanel(String id, String expression){ TextPanel keyPanel = new TextPanel<>(id, new PropertyModel<>(getModel(), expression)); keyPanel.getBaseFormComponent().add(new EmptyOnBlurAjaxFormUpdatingBehaviour()); add(keyPanel); } - + protected void updateProperties(JasperReportParameterPropertiesDto properties, AjaxRequestTarget target) { - + } - + @Override public int getWidth() { return 800; @@ -101,5 +101,5 @@ public StringResourceModel getTitle() { public Component getComponent() { return this; } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/RunReportPopupPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/RunReportPopupPanel.java index 855dee08cee..280d8bd038c 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/RunReportPopupPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/RunReportPopupPanel.java @@ -119,15 +119,15 @@ public class RunReportPopupPanel extends BasePanel implements Popupab private static final String ID_POPUP_FEEDBACK = "popupFeedback"; private static final Integer AUTO_COMPLETE_BOX_SIZE = 10; - + private static final String ID_VALUE_LIST = "valueList"; private static final String ID_ADD_BUTTON = "add"; private static final String ID_REMOVE_BUTTON = "remove"; - + private static final String ID_PARAMETERS = "paramTable"; private IModel reportModel; - + public RunReportPopupPanel(String id, final ReportType reportType) { super(id); @@ -148,8 +148,8 @@ protected void initLayout() { Form mainForm = new Form<>(ID_MAIN_FORM); add(mainForm); - - + + ListView paramListView = new ListView(ID_PARAMETERS, new PropertyModel<>(reportModel, "jasperReportDto.parameters")) { private static final long serialVersionUID = 1L; @@ -157,15 +157,15 @@ protected void initLayout() { @Override protected void populateItem(ListItem paramItem) { paramItem.add(createParameterPanel(paramItem.getModel())); - + } }; paramListView.setOutputMarkupId(true); mainForm.add(paramListView); - + FeedbackAlerts feedback = new FeedbackAlerts(ID_POPUP_FEEDBACK); feedback.setFilter(new ComponentFeedbackMessageFilter(paramListView){ - + private static final long serialVersionUID = 1L; @Override @@ -175,11 +175,11 @@ public boolean accept(FeedbackMessage message) { }); feedback.setOutputMarkupId(true); mainForm.add(feedback); - + AjaxSubmitButton addButton = new AjaxSubmitButton(ID_RUN, createStringResource("runReportPopupContent.button.run")) { private static final long serialVersionUID = 1L; - + @Override protected void onError(AjaxRequestTarget target, Form form) { FeedbackAlerts feedback = (FeedbackAlerts) form.get(ID_POPUP_FEEDBACK); @@ -194,7 +194,7 @@ protected void onSubmit(AjaxRequestTarget target, Form form) { mainForm.add(addButton); } - + private WebMarkupContainer createParameterPanel(final IModel parameterModel) { WebMarkupContainer paramPanel = new WebMarkupContainer("paramPanel"); paramPanel.setOutputMarkupId(true); @@ -209,7 +209,7 @@ private WebMarkupContainer createParameterPanel(final IModel listView = new ListView(ID_VALUE_LIST, new PropertyModel<>(parameterModel, "value")) { private static final long serialVersionUID = 1L; @@ -217,24 +217,24 @@ private WebMarkupContainer createParameterPanel(final IModel item) { item.add(createInputMarkup(item.getModel(), parameterModel.getObject())); - + } }; listView.setOutputMarkupId(true); - + paramPanel.add(listView); return paramPanel; } - + private WebMarkupContainer createInputMarkup(final IModel valueModel, JasperReportParameterDto param) { param.setEditing(true); WebMarkupContainer paramValueMarkup = new WebMarkupContainer("valueMarkup"); paramValueMarkup.setOutputMarkupId(true); - + InputPanel input = createTypedInputPanel("inputValue", valueModel, "value", param); paramValueMarkup.add(input); - + //buttons AjaxLink addButton = new AjaxLink(ID_ADD_BUTTON) { private static final long serialVersionUID = 1L; @@ -273,7 +273,7 @@ public boolean isVisible() { paramValueMarkup.add(removeButton); return paramValueMarkup; } - + private InputPanel createTypedInputPanel(String componentId, IModel model, String expression, JasperReportParameterDto param) { InputPanel panel; Class type; @@ -295,7 +295,7 @@ private InputPanel createTypedInputPanel(String componentId, IModel(componentId, new LookupReportPropertyModel(model, expression, lookup, true), String.class) { - + private static final long serialVersionUID = 1L; @Override @@ -310,17 +310,17 @@ public Iterator getIterator(String input) { for (FormComponent component : components) { component.add(new EmptyOnBlurAjaxFormUpdatingBehaviour()); } - + panel.setOutputMarkupId(true); return panel; } - + private void addValue(WebMarkupContainer paramValueMarkup, JasperReportParameterDto valueModel, AjaxRequestTarget target) { valueModel.addValue(); //reload just current parameter container panel target.add(paramValueMarkup.findParent(ListView.class).findParent(WebMarkupContainer.class)); } - + private ListView getParametersView(){ return (ListView) get(createComponentPath(ID_MAIN_FORM, ID_PARAMETERS)); } @@ -332,18 +332,18 @@ private boolean isAddButtonVisible(JasperReportParameterDto valueDecs) { return false; } } - + private void removeValue(WebMarkupContainer paramValueMarkup, JasperReportParameterDto valueModel, JasperReportValueDto object, AjaxRequestTarget target) { valueModel.removeValue(object); //reload just current parameter container panel target.add(paramValueMarkup.findParent(ListView.class).findParent(WebMarkupContainer.class)); } - + private boolean isRemoveButtonVisible() { return true; } - + private List createLookupTableRows(JasperReportParameterDto param, String input) { ItemPath label = null; ItemPath key = null; @@ -371,7 +371,7 @@ private List createLookupTableRows(Ja targetType = (Class) Class.forName(pTargetType); } catch (ClassNotFoundException e) { error("Error while creating lookup table for input parameter: " + param.getName() + ", " + e.getClass().getSimpleName() + " (" + e.getMessage() + ")"); - + } } @@ -404,7 +404,7 @@ private List createLookupTableRows(Ja continue; } - //TODO: support for single/multivalue value + //TODO: support for single/multivalue value if (!labelItem.isSingleValue()) { continue; } @@ -511,7 +511,7 @@ private void runConfirmPerformed(AjaxRequestTarget target, IModel mod PrismContainerValue reportParamValue = reportParam.asPrismContainerValue(); reportParamValue.revive(getPrismContext()); paramContainer.add(reportParamValue); - + List params = getParametersView().getModelObject(); for (JasperReportParameterDto paramDto : params) { if (paramDto.getValue() == null) { @@ -519,7 +519,7 @@ private void runConfirmPerformed(AjaxRequestTarget target, IModel mod } List values = paramDto.getValue(); Class paramClass = paramDto.getType(); - + boolean multivalue = false; if (List.class.isAssignableFrom(paramClass)) { paramClass = paramDto.getNestedType(); @@ -535,7 +535,7 @@ private void runConfirmPerformed(AjaxRequestTarget target, IModel mod def.setDynamic(true); def.setRuntimeSchema(true); def.setMaxOccurs(multivalue ? -1 : 1); // TODO multivalue is always 'false' here ... - + PrismProperty prop = def.instantiate(); for (JasperReportValueDto paramValue : values) { Object realValue = paramValue.getValue(); @@ -565,7 +565,7 @@ private void runConfirmPerformed(AjaxRequestTarget target, IModel mod runConfirmPerformed(target, reportDto.getObject().asObjectable(), paramContainer); } - + private PrismContext getPrismContext() { return getPageBase().getPrismContext(); } @@ -593,21 +593,21 @@ public StringResourceModel getTitle() { public Component getComponent() { return this; } - + class LookupReportPropertyModel extends LookupPropertyModel { private static final long serialVersionUID = 1L; - - + + public LookupReportPropertyModel(IModel modelObject, String expression, LookupTableType lookupTable, boolean isStrict) { super(modelObject, expression, lookupTable, isStrict); } - + @Override public boolean isSupportsDisplayName() { return true; } - + } } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/SingleValueChoosePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/SingleValueChoosePanel.java index 940b3fe28a1..3d280ddf08b 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/SingleValueChoosePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/component/SingleValueChoosePanel.java @@ -10,7 +10,7 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; public class SingleValueChoosePanel extends ConvertingMultiValueChoosePanel { - + private static final long serialVersionUID = 1L; private IModel singleTargetModel; @@ -23,7 +23,7 @@ public SingleValueChoosePanel(String id, List> types, @Override protected void choosePerformedHook(AjaxRequestTarget target, List selected) { super.choosePerformedHook(target, selected); - + if(selected != null) { U transformedSelectedObject = selected.stream() .findFirst() diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/AuditEventRecordProvider.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/AuditEventRecordProvider.java index b08b687c5f9..8c8cf99645d 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/AuditEventRecordProvider.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/AuditEventRecordProvider.java @@ -90,10 +90,10 @@ protected int internalSize() { // TODO: proper error handling (MID-3536) throw new SystemException(e.getMessage(), e); } - + return ((Long)count).intValue(); } - + private List listRecords(String query, boolean orderBy){ @@ -115,7 +115,7 @@ private List listRecords(String query, boolean orderBy, lo List auditRecords; try { - auditRecords = getAuditService().listRecords(parameterQuery, parameters, + auditRecords = getAuditService().listRecords(parameterQuery, parameters, new OperationResult("listRecords")); } catch (SecurityViolationException | SchemaException e) { // TODO: proper error handling (MID-3536) @@ -152,12 +152,12 @@ private String generateFullQuery(String query, boolean orderBy, boolean isCount) // query += "INNER JOIN aer.changedItems as item on item.record_id = aer.id WHERE 1=1 and " // + "(item.changedItemPath = :changedItem) and "; query += "(item.changedItemPath = :changedItem) and "; - + } else { parameters.remove("changedItem"); // query += "where 1=1 and "; } - + if (parameters.get("from") != null) { query += "(aer.timestamp >= :from) and "; } else { @@ -187,7 +187,7 @@ private String generateFullQuery(String query, boolean orderBy, boolean isCount) query += "(aer.initiatorOid = :initiatorName) and "; } else { parameters.remove("initiatorName"); - } + } if (parameters.get("channel") != null) { query += "(aer.channel = :channel) and "; } else { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/AuditSearchDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/AuditSearchDto.java index b61a15e1570..51ccf3b22e7 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/AuditSearchDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/AuditSearchDto.java @@ -45,7 +45,7 @@ public class AuditSearchDto implements Serializable { public static final String F_HOST_IDENTIFIER = "hostIdentifier"; public static final String F_TARGET_NAME = "targetName"; public static final String F_TARGET_NAMES_OBJECTS = "targetNamesObjects"; - public static final String F_TARGET_OWNER_NAME = "targetOwnerName"; + public static final String F_TARGET_OWNER_NAME = "targetOwnerName"; public static final String F_EVENT_TYPE = "eventType"; public static final String F_EVENT_STAGE = "eventStage"; public static final String F_OUTCOME = "outcome"; @@ -65,22 +65,22 @@ public class AuditSearchDto implements Serializable { private OperationResultStatusType outcome; private ItemPathDto changedItem; private List valueRefTargetNames; - + public AuditSearchDto() { } - + public XMLGregorianCalendar getFrom() { return from; } - + public void setFrom(XMLGregorianCalendar from) { this.from = from; } - + public XMLGregorianCalendar getTo() { return to; } - + public void setTo(XMLGregorianCalendar to) { this.to = to; } @@ -148,7 +148,7 @@ public OperationResultStatusType getOutcome() { public void setOutcome(OperationResultStatusType outcome) { this.outcome = outcome; } - + public ItemPathDto getChangedItem() { if (changedItem == null) { changedItem = new ItemPathDto(); @@ -156,7 +156,7 @@ public ItemPathDto getChangedItem() { } return changedItem; } - + public void setChangedItem(ItemPathDto changedItem) { this.changedItem = changedItem; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportDto.java index df4441b75d5..23609bba4c2 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportDto.java @@ -21,44 +21,44 @@ import com.evolveum.midpoint.util.exception.SchemaException; public class JasperReportDto implements Serializable{ - + private static final long serialVersionUID = 1L; private String query; private List parameters; private List fields; private String detail; private JasperDesign design; - + private byte[] jasperReportXml; - + public JasperReportDto(byte[] jasperReportxml, boolean onlyForPromptingParams) { this.jasperReportXml = jasperReportxml; - + initFileds(onlyForPromptingParams); } - + public JasperReportDto(byte[] jasperReportxml) { this(jasperReportxml, false); } - + private void initFileds(boolean onlyForPromptingParams){ if (jasperReportXml == null){ return; } - + try { design = ReportTypeUtil.loadJasperDesign(jasperReportXml); query = design.getQuery().getText(); - + fields = new ArrayList(); for (JRField field : design.getFieldsList()){ fields.add(new JasperReportFieldDto(field.getName(), field.getValueClass(), field.getValueClassName())); } - + for (JasperReportFieldDto field : fields){ design.removeField(field.getName()); } - + parameters = new ArrayList(); for (JRParameter parameter : design.getParametersList()){ if (parameter.isSystemDefined()){ @@ -66,46 +66,46 @@ private void initFileds(boolean onlyForPromptingParams){ } if (onlyForPromptingParams && !parameter.isForPrompting()){ continue; - + } JasperReportParameterDto p = new JasperReportParameterDto(parameter); parameters.add(p); } - + for (JasperReportParameterDto param : parameters){ design.removeParameter(param.getName()); } - + detail = new String(Base64.decodeBase64(jasperReportXml)); - - + + } catch (SchemaException e) { // TODO Auto-generated catch block throw new IllegalArgumentException(e); } - - + + } - + public List getParameters() { if (parameters == null){ parameters = new ArrayList<>(); } return parameters; } - + public List getFields() { if (fields == null){ fields = new ArrayList<>(); } return fields; } - - + + public String getQuery() { return query; } - + public byte[] getTemplate(){ try{ // design.remadgetFields(). @@ -159,8 +159,8 @@ public byte[] getTemplate(){ } catch (JRException | ClassNotFoundException | SchemaException | UnsupportedEncodingException ex) { throw new IllegalStateException(ex.getMessage(), ex.getCause()); } - + } - - + + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportFieldDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportFieldDto.java index b35db269ff1..ebdade21e81 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportFieldDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportFieldDto.java @@ -13,27 +13,27 @@ public class JasperReportFieldDto extends Selectable implements Serializable, Ed private String name; private Class type; private String typeAsString; - + private boolean editing; - + public JasperReportFieldDto() { // TODO Auto-generated constructor stub } - + public JasperReportFieldDto(String name, Class type, String typeAsString) { this.name = name; this.type = type; this.typeAsString = typeAsString; } - + public String getName() { return name; } - + public Class getType() { return type; } - + public String getTypeAsString() { return typeAsString; } @@ -47,7 +47,7 @@ public boolean isEditing() { public void setEditing(boolean editing) { this.editing = editing; } - + @Override public boolean isEmpty(){ if (StringUtils.isBlank(name) && StringUtils.isBlank(typeAsString)){ diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportParameterDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportParameterDto.java index 5f19b98a73e..420abb7ea6e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportParameterDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportParameterDto.java @@ -31,35 +31,35 @@ public class JasperReportParameterDto extends Selectable implements Serializable public JasperReportParameterDto() { } - + public JasperReportParameterDto(JRParameter param) { this.name = param.getName(); this.typeAsString = param.getValueClassName(); this.type = (Class) param.getValueClass(); this.forPrompting = param.isForPrompting(); - + if (param.getDescription() != null){ this.description = param.getDescription(); } this.nestedType = param.getNestedType(); this.nestedTypeAsString = param.getNestedTypeName(); - - this.value = new ArrayList<>(); + + this.value = new ArrayList<>(); this.value.add(new JasperReportValueDto()); - + this.properties = new JasperReportParameterPropertiesDto(param.getPropertiesMap()); - - + + } - + public List getValue() { return value; } - + public void setValue(List value) { this.value = value; } - + public void addValue() { getValue().add(new JasperReportValueDto()); } @@ -70,7 +70,7 @@ public void removeValue(JasperReportValueDto realValue) { getValue().add(new JasperReportValueDto()); } } - + public boolean isForPrompting() { return forPrompting; @@ -91,7 +91,7 @@ public String getName() { public String getTypeAsString() { return typeAsString; } - + public String getNestedTypeAsString() { return nestedTypeAsString; } @@ -104,23 +104,23 @@ public void setDescription(String description) { this.description = description; } - + public JasperReportParameterPropertiesDto getProperties() { return properties; } - + public JRPropertiesMap getJRProperties() { if (properties == null) { return null; } - + return properties.getPropertiesMap(); } public void setProperties(JasperReportParameterPropertiesDto properties) { this.properties = properties; } - + public Class getType() throws ClassNotFoundException { if (type == null) { if (StringUtils.isNotBlank(typeAsString)) { @@ -131,7 +131,7 @@ public Class getType() throws ClassNotFoundException { } return type; } - + public Class getNestedType() throws ClassNotFoundException { if (StringUtils.isBlank(nestedTypeAsString)) { return null; @@ -139,12 +139,12 @@ public Class getNestedType() throws ClassNotFoundException { nestedType = Class.forName(nestedTypeAsString); return nestedType; } - + public boolean isMultiValue() throws ClassNotFoundException{ if (List.class.isAssignableFrom(getType())){ return true; } - + return false; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportParameterPropertiesDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportParameterPropertiesDto.java index 72c5c2fe7b3..79591bcbe73 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportParameterPropertiesDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportParameterPropertiesDto.java @@ -9,14 +9,14 @@ public class JasperReportParameterPropertiesDto implements Serializable{ private static final String PROPERTY_LABEL = "label"; private static final String PROPERTY_TARGET_TYPE = "targetType"; private static final String PROPERTY_MULTIVALUE = "multivalue"; - - + + private JRPropertiesMap propertiesMap; public JasperReportParameterPropertiesDto(JRPropertiesMap propertiesMap) { this.propertiesMap = propertiesMap; } - + public String getLabel() { if (propertiesMap == null) { return null; @@ -24,12 +24,12 @@ public String getLabel() { return propertiesMap.getProperty(PROPERTY_LABEL); } - + public void setLabel(String label) { if (propertiesMap == null) { propertiesMap = new JRPropertiesMap(); } - + propertiesMap.setProperty(PROPERTY_LABEL, label); } @@ -40,15 +40,15 @@ public void setLabel(String label) { // // return Boolean.parseBoolean(propertiesMap.getProperty(PROPERTY_MULTIVALUE)); // } -// +// // public void setMultivalue(boolean isMultiValue) { // if (propertiesMap == null) { // propertiesMap = new JRPropertiesMap(); // } -// +// // propertiesMap.setProperty(PROPERTY_MULTIVALUE, String.valueOf(isMultiValue)); // } - + public String getTargetType() { if (propertiesMap == null) { return null; @@ -56,16 +56,16 @@ public String getTargetType() { return propertiesMap.getProperty(PROPERTY_TARGET_TYPE); } - + public void setTargetType(String targetType) { if (propertiesMap == null) { propertiesMap = new JRPropertiesMap(); } - + propertiesMap.setProperty(PROPERTY_TARGET_TYPE, targetType); } - + public String getKey() { if (propertiesMap == null) { return null; @@ -73,15 +73,15 @@ public String getKey() { return propertiesMap.getProperty(PROPERTY_KEY); } - + public void setKey(String key) { if (propertiesMap == null) { propertiesMap = new JRPropertiesMap(); } - + propertiesMap.setProperty(PROPERTY_KEY, key); } - + public JRPropertiesMap getPropertiesMap() { return propertiesMap; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportRealValueDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportRealValueDto.java index 686bb6615b8..3b144509d65 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportRealValueDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportRealValueDto.java @@ -5,11 +5,11 @@ public class JasperReportRealValueDto implements Serializable{ private T value; - + public T getValue() { return value; } - + public void setValue(T value) { this.value = value; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportValueDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportValueDto.java index 001d4b652e4..68a63232742 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportValueDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/JasperReportValueDto.java @@ -20,11 +20,11 @@ public Object getValue() { public void setValue(Object value) { this.value = value; } - + public String getDisplayName() { return displayName; } - + public void setDisplayName(String displayName) { this.displayName = displayName; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/ReportDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/ReportDto.java index 6bd571b91ae..76bc904372d 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/ReportDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/ReportDto.java @@ -35,7 +35,7 @@ public class ReportDto implements Serializable { public static final String F_EXPORT_TYPE = "exportType"; public static final String F_VIRTUALIZER = "virtualizer"; public static final String F_VIRTUALIZER_KICKON = "virtualizerKickOn"; - public static final String F_MAXPAGES = "maxPages"; + public static final String F_MAXPAGES = "maxPages"; public static final String F_TIMEOUT = "timeout"; private boolean parent; @@ -116,7 +116,7 @@ public PrismObject getObject() { reportType.setTemplateStyle(templateStyle); reportType.setDescription(description); reportType.setVirtualizer(virtualizer); - reportType.setVirtualizerKickOn(virtualizerKickOn); + reportType.setVirtualizerKickOn(virtualizerKickOn); reportType.setMaxPages(maxPages); reportType.setTimeout(timeout); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/ReportOutputSearchDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/ReportOutputSearchDto.java index a839e2f8fcf..5149adcf96a 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/ReportOutputSearchDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/ReportOutputSearchDto.java @@ -83,7 +83,7 @@ public List getReportTypes() { return list; } - + @Override public String debugDump() { return debugDump(0); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/ReportSearchDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/ReportSearchDto.java index 0ffab0d1f37..4cb1ba7791b 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/ReportSearchDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/dto/ReportSearchDto.java @@ -25,7 +25,7 @@ * */ public class ReportSearchDto implements Serializable, DebugDumpable { private static final long serialVersionUID = 1L; - + public static final String F_SEARCH_TEXT = "text"; public static final String F_PARENT = "parent"; @@ -47,7 +47,7 @@ public Boolean isParent() { public void setParent(Boolean parent) { this.parent = parent; } - + @Override public String debugDump() { return debugDump(0); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/CapabilitiesDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/CapabilitiesDto.java index b3eca2b774f..a856d403625 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/CapabilitiesDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/CapabilitiesDto.java @@ -6,41 +6,41 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; public class CapabilitiesDto implements Serializable { - + private boolean activation; - + private boolean activationLockoutStatus; - + private boolean activationStatus; - + private boolean activationValidity; - + private boolean auxiliaryObjectClasses; - + private boolean countObjects; - + private boolean pagedSearch; - + private boolean password; - + private boolean credentials; - + private boolean liveSync; - + private boolean testConnection; - + private boolean create; - + private boolean update; - + private boolean addRemoveAttributeValues; - + private boolean delete; - + private boolean read; - + private boolean script; - + public CapabilitiesDto(ResourceType resource){ activation = ResourceTypeUtil.isActivationCapabilityEnabled(resource); activationLockoutStatus = ResourceTypeUtil.isActivationLockoutStatusCapabilityEnabled(resource); @@ -196,8 +196,8 @@ public boolean isScript() { public void setScript(boolean script) { this.script = script; } - - - + + + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/PageAdminResources.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/PageAdminResources.java index 6942fa27b27..674ea4d3fc1 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/PageAdminResources.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/PageAdminResources.java @@ -60,7 +60,7 @@ public class PageAdminResources extends PageAdmin { private static final String OPERATION_SAVE_SYNC_TASK = DOT_CLASS + "saveSyncTask"; protected static final Trace LOGGER = TraceManager.getTrace(PageAdminResources.class); - + public static final String AUTH_CONNECTOR_HOSTS_ALL = AuthorizationConstants.AUTZ_UI_CONNECTOR_HOSTS_ALL_URL; public static final String AUTH_CONNECTOR_HOSTS_ALL_LABEL = "PageAdminResources.auth.connectorHostsAll.label"; public static final String AUTH_CONNECTOR_HOSTS_ALL_DESCRIPTION = "PageAdminResources.auth.connectorHostsAll.description"; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/PageResource.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/PageResource.java index 6e1d9ba2a3b..29117971e19 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/PageResource.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/PageResource.java @@ -101,7 +101,7 @@ public PageResource(PageParameters parameters) { resourceOid = parameters.get(OnePageParameterEncoder.PARAMETER).toString(); initialize(); } - + public PageResource() { initialize(); } @@ -266,7 +266,7 @@ private boolean canEdit(LoadableModel> resourceModel) } return true; } - + private void startWizard(boolean configOnly, boolean readOnly) { PageParameters parameters = new PageParameters(); parameters.add(OnePageParameterEncoder.PARAMETER, resourceModel.getObject().getOid()); // compatibility with PageAdminResources @@ -281,7 +281,7 @@ private ResourceSummaryPanel createResourceSummaryPanel(){ resourceSummaryPanel.setOutputMarkupId(true); return resourceSummaryPanel; } - + private AjaxTabbedPanel createTabsPanel(){ List tabs = new ArrayList(); @@ -341,7 +341,7 @@ public WebMarkupContainer createPanel(String panelId) { return new ResourceContentTabPanel(panelId, null, resourceModel, PageResource.this); } }); - + tabs.add(new PanelTab(createStringResource("PageResource.tab.connector")) { private static final long serialVersionUID = 1L; @@ -362,8 +362,8 @@ protected void onTabChange(int index) { resourceTabs.setOutputMarkupId(true); return resourceTabs; } - - + + private void refreshSchemaPerformed(AjaxRequestTarget target) { @@ -421,7 +421,7 @@ public boolean onCloseButtonClicked(AjaxRequestTarget target) { showMainPopup(testConnectionPanel, target); } - + private void refreshStatus(AjaxRequestTarget target) { target.add(addOrReplace(createResourceSummaryPanel())); target.add(addOrReplace(createTabsPanel())); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/PageResources.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/PageResources.java index 018f5cac0ca..b13f8824988 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/PageResources.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/PageResources.java @@ -159,7 +159,7 @@ private void initLayout() { Collection> options = GetOperationOptions.resolveItemsNamed(ResourceType.F_CONNECTOR); options.add(SelectorOptions.create(GetOperationOptions.createNoFetch())); - + MainObjectListPanel resourceListPanel = new MainObjectListPanel(ID_TABLE, ResourceType.class, TableId.TABLE_RESOURCES, options, this) { @@ -194,9 +194,9 @@ protected void objectDetailsPerformed(AjaxRequestTarget target, ResourceType obj @Override protected void newObjectPerformed(AjaxRequestTarget target) { navigateToNext(PageResourceWizard.class); - + } - + }; resourceListPanel.setOutputMarkupId(true); resourceListPanel.setAdditionalBoxCssClasses(GuiStyleConstants.CLASS_OBJECT_RESOURCE_BOX_CSS_CLASSES); @@ -378,7 +378,7 @@ public String getObject() { } else { selected = getResourceTable().getSelectedObjects(); } - + switch (selected.size()) { case 1: Object first = selected.get(0); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceConnectorPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceConnectorPanel.java index 5a78707347b..a8a8244ce1c 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceConnectorPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceConnectorPanel.java @@ -64,19 +64,19 @@ public class ResourceConnectorPanel extends Panel { private static final String ID_POOL_STATUS_NUM_ACTIVE = "poolStatusNumActive"; private PageBase parentPage; - + public ResourceConnectorPanel(String id, ShadowKindType kind, final IModel> model, PageBase parentPage) { super(id, model); this.parentPage = parentPage; - + initLayout(model, parentPage); } - + private void initLayout(final IModel> model, final PageBase parentPage) { setOutputMarkupId(true); - + IModel> statsModel = new AbstractReadOnlyModel>() { private static final long serialVersionUID = 1L; @@ -96,7 +96,7 @@ public List getObject() { return status; } }; - + ListView listview = new ListView(ID_CONNECTOR_LIST, statsModel) { private static final long serialVersionUID = 1L; @@ -119,7 +119,7 @@ protected void populateItem(ListItem item) { add(listview); } - + private Label createLabel(IModel statsModel, String id, String fieldName) { return new Label(id, new PropertyModel(statsModel, fieldName)); } 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 3949c22ed4d..48d95cfb894 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 @@ -121,7 +121,7 @@ /** * Implementation classes : ResourceContentResourcePanel, * ResourceContentRepositoryPanel - * + * * @author katkav * @author semancik */ @@ -247,7 +247,7 @@ private TableId getTableId() { } private void initLayout() { - + WebMarkupContainer totals = new WebMarkupContainer(ID_TOTALS); totals.setOutputMarkupId(true); add(totals); @@ -390,7 +390,7 @@ public boolean isVisible() { } protected abstract void initShadowStatistics(WebMarkupContainer totals); - + private void initButton(String id, String label, String icon, final String category, final List tasks) { @@ -533,10 +533,10 @@ private void createSearchOptions(SelectableBeanObjectDataProvider pr if (addAdditionalOptions() != null) { opts.add(addAdditionalOptions()); } - + provider.setUseObjectCounting(isUseObjectCounting()); provider.setOptions(opts); - + } private StringResourceModel createStringResource(String key) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentRepositoryPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentRepositoryPanel.java index 5890deb9006..7daf050360e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentRepositoryPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentRepositoryPanel.java @@ -51,13 +51,13 @@ public class ResourceContentRepositoryPanel extends ResourceContentPanel { private static final long serialVersionUID = 1L; - + private static final Trace LOGGER = TraceManager.getTrace(ResourceContentRepositoryPanel.class); - + private static final String DOT_CLASS = ResourceContentRepositoryPanel.class.getName() + "."; private static final String OPERATION_GET_TOTALS = DOT_CLASS + "getTotals"; - - + + private static final String ID_TOTAL = "total"; private static final String ID_DELETED = "deleted"; private static final String ID_UNMATCHED = "unmatched"; @@ -65,7 +65,7 @@ public class ResourceContentRepositoryPanel extends ResourceContentPanel { private static final String ID_LINKED = "linked"; private static final String ID_UNLINKED = "unlinked"; private static final String ID_NOTHING = "nothing"; - + private LoadableModel totalModel; private LoadableModel deletedModel; private LoadableModel unmatchedModel; @@ -73,17 +73,17 @@ public class ResourceContentRepositoryPanel extends ResourceContentPanel { private LoadableModel linkedModel; private LoadableModel unlinkedModel; private LoadableModel nothingModel; - + public ResourceContentRepositoryPanel(String id, IModel> resourceModel, QName objectClass, ShadowKindType kind, String intent, String searchMode, PageBase pageBase) { super(id, resourceModel, objectClass, kind, intent, searchMode, pageBase); - - + + } - + protected void initShadowStatistics(WebMarkupContainer totals) { - + totals.add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; @@ -129,7 +129,7 @@ protected Integer load() { } }; } - + private LoadableModel createTotalsModel(final SynchronizationSituationType situation) { return new LoadableModel(false) { private static final long serialVersionUID = 1L; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentResourcePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentResourcePanel.java index 3cd19c86f8e..425b10c8be4 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentResourcePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentResourcePanel.java @@ -93,7 +93,7 @@ private Map createAttributeDefi if (ocDef == null) { return map; } - + ItemPath attributePath = new ItemPath(ShadowType.F_ATTRIBUTES); for (ItemDefinition def : (List) ocDef.getDefinitions()) { @@ -121,7 +121,7 @@ public boolean isVisible() { return false; } }); - + } } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceSummaryPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceSummaryPanel.java index a94c69afd1e..da436b053d8 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceSummaryPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceSummaryPanel.java @@ -38,7 +38,7 @@ public ResourceSummaryPanel(String id, IModel> model, Label summaryTag = new Label(ID_UP_DOWN_TAG, down ? "DOWN" : "UP"); addTag(summaryTag); } - + @Override protected String getIconCssClass() { return GuiStyleConstants.CLASS_OBJECT_RESOURCE_ICON; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceTasksPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceTasksPanel.java index 0b85fd73d0c..d038f3d3f2d 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceTasksPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceTasksPanel.java @@ -59,39 +59,39 @@ public class ResourceTasksPanel extends Panel implements Popupable{ private static final String DOT_CLASS = ResourceTasksPanel.class.getName() + "."; private static final String OPERATION_LOAD_TASKS = DOT_CLASS + "loadTasks"; - + private static final String ID_TASKS_TABLE = "taskTable"; - + private static final String ID_RUN_NOW = "runNow"; private static final String ID_RESUME = "resume"; private static final String ID_SUSPEND = "suspend"; - - + + private PageBase pageBase; - + private boolean editable; - + // private ListModel model; - - + + public ResourceTasksPanel(String id, boolean editable, ListModel tasks, PageBase pageBase) { super(id); this.pageBase = pageBase; this.editable = editable; - - + + initLayout(tasks); } - + public ResourceTasksPanel(String id, boolean editable, final IModel> resourceModel, PageBase pageBase) { super(id); this.pageBase = pageBase; this.editable = editable; - + ListModel model = createTaskModel(resourceModel.getObject()); initLayout(model); } - + private ListModel createTaskModel(PrismObject object) { OperationResult result = new OperationResult(OPERATION_LOAD_TASKS); List> tasks = WebModelServiceUtils @@ -105,18 +105,18 @@ private ListModel createTaskModel(PrismObject object) { tasksType.add(task.asObjectable()); } return new ListModel<>(tasksType); - + } - + private void initLayout(final ListModel tasks){ final MainObjectListPanel tasksPanel = new MainObjectListPanel(ID_TASKS_TABLE, TaskType.class, TableId.PAGE_RESOURCE_TASKS_PANEL, null, pageBase) { private static final long serialVersionUID = 1L; - + @Override protected BaseSortableDataProvider> initProvider() { return new ListDataProvider2(pageBase, tasks); } - + @Override protected List createInlineMenu() { // TODO Auto-generated method stub @@ -140,7 +140,7 @@ public void objectDetailsPerformed(AjaxRequestTarget target, TaskType task) { @Override protected void newObjectPerformed(AjaxRequestTarget target) { getPageBase().navigateToNext(PageTaskAdd.class); - + } @Override @@ -149,17 +149,17 @@ protected List, String>> createColumns() { } }; // final ObjectListPanel tasksPanel = new ObjectListPanel(ID_TASKS_TABLE, TaskType.class, pageBase){ -// +// // @Override // protected BaseSortableDataProvider> getProvider() { // return new ListDataProvider2(pageBase, tasks); // } -// +// // @Override // public boolean isEditable() { // return ResourceTasksPanel.this.editable; // } -// +// // @Override // public void objectDetailsPerformed(AjaxRequestTarget target, TaskType task) { // // TODO Auto-generated method stub @@ -172,10 +172,10 @@ protected List, String>> createColumns() { // tasksPanel.setEditable(false); tasksPanel.setAdditionalBoxCssClasses(GuiStyleConstants.CLASS_OBJECT_TASK_BOX_CSS_CLASSES); add(tasksPanel); - + AjaxButton runNow = new AjaxButton(ID_RUN_NOW, pageBase.createStringResource("pageTaskEdit.button.runNow")) { private static final long serialVersionUID = 1L; - + @Override public void onClick(AjaxRequestTarget target) { List oids = createOidList(getTaskListPanel().getSelectedObjects()); @@ -189,10 +189,10 @@ public void onClick(AjaxRequestTarget target) { } }; add(runNow); - + AjaxButton resume = new AjaxButton(ID_RESUME, pageBase.createStringResource("pageTaskEdit.button.resume")) { private static final long serialVersionUID = 1L; - + @Override public void onClick(AjaxRequestTarget target) { List oids = createOidList(getTaskListPanel().getSelectedObjects()); @@ -206,10 +206,10 @@ public void onClick(AjaxRequestTarget target) { } }; add(resume); - + AjaxButton suspend = new AjaxButton(ID_SUSPEND, pageBase.createStringResource("pageTaskEdit.button.suspend")) { private static final long serialVersionUID = 1L; - + @Override public void onClick(AjaxRequestTarget target) { List oids = createOidList(getTaskListPanel().getSelectedObjects()); @@ -232,7 +232,7 @@ private void noTasksSelected() { private ObjectListPanel getTaskListPanel(){ return (ObjectListPanel) get(ID_TASKS_TABLE); } - + private List createOidList(List tasks){ List oids = new ArrayList<>(); for (TaskType task : tasks){ diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/component/TestConnectionMessagesPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/component/TestConnectionMessagesPanel.java index 5fae91d28bc..54c9cfed73b 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/component/TestConnectionMessagesPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/component/TestConnectionMessagesPanel.java @@ -56,7 +56,7 @@ public class TestConnectionMessagesPanel extends BasePanel { private static final String ID_CONNECTOR_NAME = "connectorName"; private static final String ID_CONNECTOR_MESSAGES = "connectorMessages"; private static final String ID_RESOURCE_MESSAGES = "resourceMessages"; - + private PageBase parentPage; private ListModel modelResourceResults; private ListModel connectorResourceResults; @@ -98,7 +98,7 @@ private void initResultsModel(String resourceOid) { // resource operation resourceResultsDto.add(OpResult.getOpResult(parentPage, subresult)); } - + } if (result.isSuccess()) { @@ -112,7 +112,7 @@ private void initResultsModel(String resourceOid) { private boolean isConnectorResult(OperationResult subresult) { return subresult.getOperation().equals(ConnectorTestOperation.CONNECTOR_TEST.getOperation()); } - + private boolean isKnownResult(OperationResult subresult) { for (ConnectorTestOperation connectorOperation : ConnectorTestOperation.values()) { if (connectorOperation.getOperation().equals(subresult.getOperation())) { @@ -129,7 +129,7 @@ private void initLayout() { WebMarkupContainer messagesPanel = new WebMarkupContainer(ID_MESSAGES_PANEL); messagesPanel.setOutputMarkupId(true); add(messagesPanel); - + ListView connectorView = new ListView(ID_CONNECTOR_MESSAGES_PANEL, connectorResourceResults) { private static final long serialVersionUID = 1L; @Override @@ -143,7 +143,7 @@ protected void populateItem(ListItem item) { } item.add(connectorResultView); } - + }; messagesPanel.add(connectorView); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/content/dto/ResourceContentSearchDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/content/dto/ResourceContentSearchDto.java index 46c269bec90..1c9dd7253d1 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/content/dto/ResourceContentSearchDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/content/dto/ResourceContentSearchDto.java @@ -25,21 +25,21 @@ public class ResourceContentSearchDto implements Serializable, DebugDumpable { private static final long serialVersionUID = 1L; - + private Boolean resourceSearch = Boolean.FALSE; private ShadowKindType kind; private String intent; private QName objectClass; - + private boolean isUseObjectClass = false; - + public ResourceContentSearchDto(ShadowKindType kind) { this.kind = kind; if (kind == null) { this.isUseObjectClass = true; } } - + public Boolean isResourceSearch() { return resourceSearch; } @@ -58,15 +58,15 @@ public String getIntent() { public void setIntent(String intent) { this.intent = intent; } - + public QName getObjectClass() { return objectClass; } - + public void setObjectClass(QName objectClass) { this.objectClass = objectClass; } - + public boolean isUseObjectClass() { return isUseObjectClass; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/dto/ResourceConfigurationDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/dto/ResourceConfigurationDto.java index e5033da3a0f..f92fcf3120e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/dto/ResourceConfigurationDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/dto/ResourceConfigurationDto.java @@ -7,43 +7,43 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; public class ResourceConfigurationDto implements Serializable{ - + private ResourceObjectTypeDefinitionType objectTypeDefinition; - + private boolean sync; private List definedTasks; - + public ResourceConfigurationDto(ResourceObjectTypeDefinitionType obejctTypeDefinition, boolean sync, List definedTasks) { this.objectTypeDefinition = obejctTypeDefinition; this.sync = sync; this.definedTasks = definedTasks; } - + public List getDefinedTasks() { return definedTasks; } - + public ResourceObjectTypeDefinitionType getObjectTypeDefinition() { - + return objectTypeDefinition; } - + public boolean isSync() { return sync; } - + public void setSync(boolean sync) { this.sync = sync; } - + public void setDefinedTasks(List definedTasks) { this.definedTasks = definedTasks; } - + public void setObjectTypeDefinition(ResourceObjectTypeDefinitionType objectTypeDefinition) { this.objectTypeDefinition = objectTypeDefinition; } - - - + + + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/dto/ResourceDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/dto/ResourceDto.java index afe391561a0..fcdc7848591 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/dto/ResourceDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/dto/ResourceDto.java @@ -43,7 +43,7 @@ * @author lazyman */ public class ResourceDto extends Selectable implements InlineMenuable { - + private static final String DOT_CLASS = ResourceDto.class.getName() + "."; private static final String OPERATION_LOAD_RESOURCE_DEFINITION = DOT_CLASS + "ResourceDto - load resource attribute container definition"; @@ -64,7 +64,7 @@ public class ResourceDto extends Selectable implements InlineMenuable { public ResourceDto() { } - + public ResourceDto(PrismObject resource) { oid = resource.getOid(); name = WebComponentUtil.getName(resource); @@ -88,7 +88,7 @@ public ResourceDto(PrismObject resource) { public ResourceDto(PrismObject resource, PrismContext prismContext, ConnectorType connector, List capabilities) { Validate.notNull(resource); - + OperationResult result = new OperationResult(OPERATION_LOAD_RESOURCE_DEFINITION); oid = resource.getOid(); @@ -97,7 +97,7 @@ public ResourceDto(PrismObject resource, PrismContext prismContext version = connector != null ? connector.getConnectorVersion() : null; type = connector != null ? connector.getConnectorType() : null; this.capabilities = capabilities; - + try { ResourceSchema resourceSchema = RefinedResourceSchemaImpl.getResourceSchema(resource, prismContext); Collection definitions = resourceSchema.getObjectClassDefinitions(); @@ -138,51 +138,51 @@ public String getOid() { public String getVersion() { return version; } - + public String getProgress() { return progress; } - + public String getType() { return type; } - + public List getCapabilities() { return capabilities; } - + public ResourceState getState() { if (state == null) { state = new ResourceState(); } return state; } - + public OperationResultStatus getOverallStatus() { if (state == null) { return OperationResultStatus.UNKNOWN; } return state.getOverall(); } - + public AvailabilityStatusType getLastAvailabilityStatus() { return lastAvailabilityStatus; } - + public List getObjectTypes() { if (objectTypes == null) { objectTypes = new ArrayList(); } return objectTypes; } - + public ResourceSyncStatus getSyncStatus() { if (sync == null || !sync.isEnabled()) { return ResourceSyncStatus.DISABLE; } return ResourceSyncStatus.ENABLE; } - + public ResourceImportStatus getResImport() { if (resImport == null || !resImport.isEnabled()) { return ResourceImportStatus.DISABLE; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/dto/ResourceImportDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/dto/ResourceImportDto.java index 87adf9eee5d..e64c516f860 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/dto/ResourceImportDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/dto/ResourceImportDto.java @@ -33,7 +33,7 @@ public class ResourceImportDto implements Serializable { private OperationResult lastError; private long progress; private boolean running; - + public ResourceImportDto(){ //TODO } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/dto/ResourceObjectTypeDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/dto/ResourceObjectTypeDto.java index 029bcebce5f..caba741e096 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/dto/ResourceObjectTypeDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/dto/ResourceObjectTypeDto.java @@ -26,7 +26,7 @@ * @author lazyman */ public class ResourceObjectTypeDto implements Serializable { - + private static final long serialVersionUID = 4664988785770149299L; private String displayName; private String nativeObjectClass; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/dto/ResourceState.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/dto/ResourceState.java index 7c8f91c4378..4c25f19b3fe 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/dto/ResourceState.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/dto/ResourceState.java @@ -120,7 +120,7 @@ public String getExtraName() { public void setExtraName(String extraName) { this.extraName = extraName; } - + public OperationResultStatus getLastAvailability() { if (lastAvailability == null) { return OperationResultStatus.UNKNOWN; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/PageRole.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/PageRole.java index 8d6cbfa8919..a2b7003b186 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/PageRole.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/PageRole.java @@ -60,7 +60,7 @@ public PageRole() { public PageRole(PrismObject roleToEdit) { initialize(roleToEdit); } - + public PageRole(PageParameters parameters) { getPageParameters().overwriteWith(parameters); initialize(null); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/PageRoles.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/PageRoles.java index b779e3ca940..b79ed5fde1c 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/PageRoles.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/PageRoles.java @@ -77,7 +77,7 @@ public class PageRoles extends PageAdminRoles implements FocusListComponent { private static final String ID_MAIN_FORM = "mainForm"; private static final String OPERATION_SEARCH_MEMBERS = DOT_CLASS + "searchMembers"; - + private IModel searchModel; public PageRoles() { @@ -104,7 +104,7 @@ protected IModel getConfirmationMessageModel(ColumnMenuAction action, St private void initLayout() { Form mainForm = new Form(ID_MAIN_FORM); add(mainForm); - + MainObjectListPanel roleListPanel = new MainObjectListPanel(ID_TABLE, RoleType.class, TableId.TABLE_ROLES, null, this) { private static final long serialVersionUID = 1L; @@ -192,8 +192,8 @@ private IModel getConfirmationMessageModel(ColumnMenuAction action, Stri return WebComponentUtil.createAbstractRoleConfirmationMessage(actionName, action, getRoleTable(), this); } - - + + private boolean isShowConfirmationDialog(ColumnMenuAction action){ return action.getRowModel() != null || diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/RoleMemberPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/RoleMemberPanel.java index c8d716ed811..a594921b136 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/RoleMemberPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/RoleMemberPanel.java @@ -81,7 +81,7 @@ public class RoleMemberPanel extends AbstractRoleMem public RoleMemberPanel(String id, IModel model, PageBase pageBase) { super(id, TableId.ROLE_MEMEBER_PANEL, model, pageBase); } - + public RoleMemberPanel(String id, IModel model, List relations, PageBase pageBase) { super(id, TableId.ROLE_MEMEBER_PANEL, model, relations, pageBase); } @@ -133,7 +133,7 @@ protected void refreshTable(AjaxRequestTarget target) { getMemberTable().refreshTable(WebComponentUtil.qnameToClass(getPrismContext(), type, FocusType.class), target); } - + private MainObjectListPanel getMemberTable() { return (MainObjectListPanel) get(createComponentPath(ID_FORM, ID_CONTAINER_MEMBER, ID_MEMBER_TABLE)); @@ -220,14 +220,14 @@ protected void initSearch(Form form) { DropDownChoice typeSelect = createDropDown(ID_OBJECT_TYPE, Model.of(FocusType.COMPLEX_TYPE), allowedTypes, new QNameChoiceRenderer()); add(typeSelect); - + ChooseTypePanel tenant = createParameterPanel(ID_TENANT, true); - + // DropDownChoice tenant = createDropDown(ID_TENANT, new Model(), // createTenantList(), new ObjectTypeChoiceRenderer()); add(tenant); tenant.add(new VisibleEnableBehaviour() { - + private static final long serialVersionUID = 1L; @Override @@ -235,14 +235,14 @@ public boolean isVisible() { return isRole(); } }); - + ChooseTypePanel project = createParameterPanel(ID_PROJECT, false); add(project); - + project.add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; - + @Override public boolean isVisible() { return isRole(); @@ -264,49 +264,49 @@ public void onUpdate(AjaxRequestTarget target) { indirectMembersContainer.add(includeIndirectMembers); } - + 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) { refreshTable(target); } - + @Override protected void executeCustomRemoveAction(AjaxRequestTarget target) { refreshTable(target); } - + @Override protected ObjectQuery getChooseQuery() { ObjectFilter tenantFilter = QueryBuilder.queryFor(OrgType.class, getPrismContext()).item(OrgType.F_TENANT).eq(true).buildFilter(); - + if (isTenant) { return ObjectQuery.createObjectQuery(tenantFilter); - } + } return ObjectQuery.createObjectQuery(NotFilter.createNot(tenantFilter)); - + } - + @Override protected boolean isSearchEnabled() { return true; } - + @Override public Class getObjectTypeClass() { return OrgType.class; } - - + + }; - + return orgSelector; - + } @Override @@ -368,7 +368,7 @@ protected ObjectQuery createContentQuery() { boolean indirect = ((CheckBoxPanel) get(createComponentPath(ID_INDIRECT_MEMBERS_CONTAINER, ID_INDIRECT_MEMBERS))).getValue(); return indirect ? createAllMemberQuery() : createDirectMemberQuery(); - + } protected ObjectQuery createDirectMemberQuery() { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/RoleMemberSearchDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/RoleMemberSearchDto.java index 4cb377fd2bf..f975cd67158 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/RoleMemberSearchDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/RoleMemberSearchDto.java @@ -30,50 +30,50 @@ public class RoleMemberSearchDto implements Serializable, DebugDumpable { public static String F_TYPE = "type"; public static String F_TENANT = "tenant"; public static String F_PROJECT = "project"; - + public static String F_TEXT = "text"; - + private QName type; private OrgType tenant; private OrgType project; private String text; - - + + public void setType(QName type) { this.type = type; } - + public QName getType() { if (type == null){ return UserType.COMPLEX_TYPE; } return type; } - + public OrgType getTenant() { return tenant; } - + public void setTenant(OrgType tenant) { this.tenant = tenant; } - + public OrgType getProject() { return project; } - + public void setProject(OrgType project) { this.project = project; } - + public String getText() { return text; } - + public void setText(String text) { this.text = text; } - + @Override public String debugDump() { return debugDump(0); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/RolePolicyPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/RolePolicyPanel.java index fccaa4be3bf..4e12fd9d9a4 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/RolePolicyPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/RolePolicyPanel.java @@ -22,19 +22,19 @@ public class RolePolicyPanel extends SimplePanel{ private IModel> maxAssignmentsModel; private PrismObject role; - + private static final String ID_MIN_ASSIGNMENTS = "minAssignmentsConfig"; private static final String ID_MAX_ASSIGNMENTS = "maxAssignmentsConfig"; - + private static final String ID_LABEL_SIZE = "col-md-4"; private static final String ID_INPUT_SIZE = "col-md-6"; - + public RolePolicyPanel(String id, PrismObject role) { super(id); this.role = role; } - + @Override protected void initLayout() { minAssignmentModel = new LoadableModel>(false) { @@ -64,7 +64,7 @@ protected List load() { return roleType.getPolicyConstraints().getMaxAssignees(); } }; - + GenericMultiValueLabelEditPanel minAssignments = new GenericMultiValueLabelEditPanel(ID_MIN_ASSIGNMENTS, minAssignmentModel, createStringResource("PageRoleEditor.label.minAssignments"), ID_LABEL_SIZE, ID_INPUT_SIZE, true){ @@ -123,7 +123,7 @@ protected MultiplicityPolicyConstraintType createNewEmptyItem() { add(maxAssignments); } - + private WebMarkupContainer getMinAssignmentsContainer(){ return (WebMarkupContainer) get(ID_MIN_ASSIGNMENTS); } @@ -136,7 +136,7 @@ private IModel createMultiplicityPolicyLabel(final IModel() { @Override - public String getObject() { + public String getObject() { StringBuilder sb = new StringBuilder(); if(model == null || model.getObject() == null || model.getObject().getMultiplicity() == null @@ -158,7 +158,7 @@ public String getObject() { } }; } - - + + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTaskAdd.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTaskAdd.java index f8ba93ae543..ea7f67366b7 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTaskAdd.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTaskAdd.java @@ -117,7 +117,7 @@ public class PageTaskAdd extends PageAdminTasks { private static final long serialVersionUID = 2317887071933841581L; - private static final String ID_DRY_RUN = "dryRun"; + private static final String ID_DRY_RUN = "dryRun"; private static final String ID_FOCUS_TYPE = "focusType"; private static final String ID_KIND = "kind"; private static final String ID_INTENT = "intent"; @@ -162,7 +162,7 @@ protected TaskAddDto load() { }; initLayout(); } - + public PageTaskAdd(final TaskType taskType) { model = new LoadableModel(false) { @@ -177,7 +177,7 @@ protected TaskAddDto load() { private TaskAddDto loadTask() { return new TaskAddDto(); } - + private TaskAddDto loadTask(TaskType taskType) { TaskAddDto taskAdd = new TaskAddDto(); taskAdd.setCategory(taskType.getCategory()); @@ -188,7 +188,7 @@ private TaskAddDto loadTask(TaskType taskType) { } catch (SchemaException e) { warn("Could not set kind for new task : " + e.getMessage()); } - + PrismProperty pIntent; try { pIntent = taskType.asPrismObject().findOrCreateProperty(new ItemPath(TaskType.F_EXTENSION, SchemaConstants.MODEL_EXTENSION_INTENT)); @@ -196,7 +196,7 @@ private TaskAddDto loadTask(TaskType taskType) { } catch (SchemaException e) { warn("Could not set intent for new task : " + e.getMessage()); } - + PrismProperty pObjectClass; try { pObjectClass = taskType.asPrismObject().findOrCreateProperty(new ItemPath(TaskType.F_EXTENSION, SchemaConstants.OBJECTCLASS_PROPERTY_NAME)); @@ -207,8 +207,8 @@ private TaskAddDto loadTask(TaskType taskType) { } catch (SchemaException e) { warn("Could not set obejctClass for new task : " + e.getMessage()); } - - + + ObjectReferenceType ref = taskType.getObjectRef(); if (ref != null) { TaskAddResourcesDto resource= new TaskAddResourcesDto(ref.getOid(), WebComponentUtil.getName(ref)); @@ -272,7 +272,7 @@ public boolean isEnabled() { }); mainForm.add(focusType); - + final DropDownChoice kind = new DropDownChoice<>(ID_KIND, new PropertyModel(model, TaskAddDto.F_KIND), WebComponentUtil.createReadonlyModelFromEnum(ShadowKindType.class), new EnumChoiceRenderer()); @@ -592,7 +592,7 @@ public void onClick(AjaxRequestTarget target) { mainForm.add(backButton); } - + private List createShadowKindTypeList(){ List kindList = new ArrayList<>(); @@ -602,7 +602,7 @@ private List createShadowKindTypeList(){ return kindList; } - + private List createFocusTypeList(){ List focusTypeList = new ArrayList<>(); @@ -741,13 +741,13 @@ private TaskType createTask(TaskAddDto dto) throws SchemaException { if (dto.getFocusType() != null){ PrismObject prismTask = task.asPrismObject(); - + ItemPath path = new ItemPath(TaskType.F_EXTENSION, SchemaConstants.MODEL_EXTENSION_OBJECT_TYPE); PrismProperty focusType = prismTask.findOrCreateProperty(path); focusType.setRealValue(dto.getFocusType()); - + } - + if(dto.getKind() != null){ PrismObject prismTask = task.asPrismObject(); ItemPath path = new ItemPath(TaskType.F_EXTENSION, SchemaConstants.MODEL_EXTENSION_KIND); 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 437683d9ecd..108dcd9ac16 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 @@ -267,18 +267,18 @@ protected WebMarkupContainer createHeader(String headerId) { @Override protected WebMarkupContainer createButtonToolbar(String id) { CsvDownloadButtonPanel exportDataLink = new CsvDownloadButtonPanel(id) { - + private static final long serialVersionUID = 1L; @Override protected DataTable getDataTable() { return getTaskTable().getDataTable(); } - + @Override protected String getFilename() { return "TaskType_" + createStringResource("MainObjectListPanel.exportFileName").getString(); } - + }; return exportDataLink; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskApprovalsTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskApprovalsTabPanel.java index aee7c35d662..33f5215c24c 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskApprovalsTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskApprovalsTabPanel.java @@ -54,7 +54,7 @@ public TaskApprovalsTabPanel(String id, Form mainForm, initLayout(taskDtoModel); setOutputMarkupId(true); } - + private void initLayout(final IModel taskDtoModel) { childPanel = new TaskWfChildPanel(ID_WORKFLOW_CHILD_PANEL, taskDtoModel, parentPage); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskBasicTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskBasicTabPanel.java index 228eb823812..36ffb9e8df1 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskBasicTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskBasicTabPanel.java @@ -97,7 +97,7 @@ public TaskBasicTabPanel(String id, Form mainForm, initLayoutHandler(); setOutputMarkupId(true); } - + private void initLayoutBasic() { // Name 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 7bbbc5b482b..a1f269e3819 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 @@ -51,7 +51,7 @@ public TaskOperationTabPanel(String id, Form mainForm, initLayout(taskDtoModel, pageBase); setOutputMarkupId(true); } - + private void initLayout(final IModel taskDtoModel, PageBase pageBase) { final PropertyModel operationStatusModel = new PropertyModel<>(taskDtoModel, TaskDto.F_MODEL_OPERATION_STATUS); 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 54a236b304c..4682a5d5079 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 @@ -52,7 +52,7 @@ public TaskPerformanceTabPanel(String id, Form mainForm, initLayout(pageBase); setOutputMarkupId(true); } - + private void initLayout(PageBase pageBase) { StatisticsDtoModel statisticsDtoModel = new StatisticsDtoModel(taskDtoModel); StatisticsPanel statisticsPanel = new StatisticsPanel(ID_STATISTICS_PANEL, statisticsDtoModel); 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 513f2ee87a3..bd719d64706 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 @@ -68,7 +68,7 @@ public TaskResultTabPanel(String id, Form mainForm, initLayout(taskDtoModel, pageBase); setOutputMarkupId(true); } - + private void initLayout(final IModel taskDtoModel, final PageBase pageBase) { SortableDataProvider provider = new ListDataProvider<>(this, new PropertyModel>(taskDtoModel, TaskDto.F_OP_RESULT)); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskSchedulingTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskSchedulingTabPanel.java index 2c3416d745a..d4105467cf6 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskSchedulingTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskSchedulingTabPanel.java @@ -277,7 +277,7 @@ public boolean isVisible() { }); add(nextRetryContainer); } - + private void initLayoutForSchedulingTable() { // models @@ -344,7 +344,7 @@ public boolean isEnabled() { protected void onUpdate(AjaxRequestTarget target) { target.add(schedulingTable); } - + @Override public boolean isEnabled() { return parentPage.isEdit() && !parentPage.getTaskDto().isRunnableOrRunning() && parentPage.isEditable(TaskType.F_RECURRENCE); @@ -373,7 +373,7 @@ public boolean isEnabled() { protected void onUpdate(AjaxRequestTarget target) { target.add(schedulingTable); } - + @Override public boolean isEnabled() { return parentPage.isEdit() && !parentPage.getTaskDto().isRunnableOrRunning() && parentPage.isEditable(TaskType.F_BINDING); @@ -413,7 +413,7 @@ public boolean isEnabled() { && parentPage.isEditable(new ItemPath(TaskType.F_SCHEDULE)); } }; - + interval.add(new EmptyOnBlurAjaxFormUpdatingBehaviour()); interval.add(enabledIfEditAndNotRunningRunnableOrLooselyBoundAndScheduleIsEditable); intervalContainer.add(interval); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/dto/SynchronizationInformationDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/dto/SynchronizationInformationDto.java index d61f0c3c81f..87f822cc89e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/dto/SynchronizationInformationDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/dto/SynchronizationInformationDto.java @@ -32,7 +32,7 @@ public class SynchronizationInformationDto { public static final String F_COUNT_LINKED = "countLinked"; public static final String F_COUNT_UNLINKED = "countUnlinked"; public static final String F_COUNT_UNMATCHED = "countUnmatched"; - + private SynchronizationInformationType synchronizationInformationType; private boolean useAfter; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/dto/TaskAddDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/dto/TaskAddDto.java index cd92acd723c..19c3d818aab 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/dto/TaskAddDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/dto/TaskAddDto.java @@ -54,7 +54,7 @@ public class TaskAddDto implements Serializable { private String category; private TaskAddResourcesDto resource; private String name; - + //Scheduling private boolean reccuring; private boolean bound; @@ -62,9 +62,9 @@ public class TaskAddDto implements Serializable { private String cron; private Date notStartBefore; private Date notStartAfter; - + private boolean runUntilNodeDown; - + //Advanced private boolean suspendedState; private ThreadStopActionType threadStop; @@ -76,7 +76,7 @@ public class TaskAddDto implements Serializable { private String intent; private String objectClass; private List objectClassList; - + public String getCategory() { return category; } @@ -84,7 +84,7 @@ public String getCategory() { public void setCategory(String category) { this.category = category; } - + public TaskAddResourcesDto getResource() { return resource; } @@ -164,7 +164,7 @@ public Boolean getSuspendedState() { public void setSuspendedState(Boolean suspendedState) { this.suspendedState = suspendedState; } - + public ThreadStopActionType getThreadStop() { return threadStop; } @@ -188,11 +188,11 @@ public boolean isDryRun() { public void setDryRun(boolean dryRun) { this.dryRun = dryRun; } - + public QName getFocusType() { return focusType; } - + public void setFocusType(QName focusType) { this.focusType = focusType; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/dto/TaskDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/dto/TaskDto.java index 96766cab941..3b5045da3d4 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/dto/TaskDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/dto/TaskDto.java @@ -577,7 +577,7 @@ public void setWorkerThreads(Integer workerThreads) { public String getCategory() { return taskType.getCategory(); } - + public List getHandlerUriList() { return handlerUriList; } @@ -643,7 +643,7 @@ public Long getLastRunFinishTimestampLong() { public String getOid() { return taskType.getOid(); } - + public String getIdentifier() { return taskType.getTaskIdentifier(); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/dto/TasksSearchDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/dto/TasksSearchDto.java index d9791f5f747..498bb528731 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/dto/TasksSearchDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/dto/TasksSearchDto.java @@ -58,7 +58,7 @@ public TaskDtoExecutionStatusFilter getStatus() { public void setStatus(TaskDtoExecutionStatusFilter status) { this.status = status; } - + @Override public String debugDump() { return debugDump(0); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/DefaultHandlerPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/DefaultHandlerPanel.java index 392e81b86eb..4c465a67b98 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/DefaultHandlerPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/DefaultHandlerPanel.java @@ -41,7 +41,7 @@ public DefaultHandlerPanel(String id, IModel model, PageTaskEdit parentPage) initLayout(parentPage); setOutputMarkupId(true); } - + private void initLayout(final PageTaskEdit parentPage) { WebMarkupContainer objectRefContainer = new WebMarkupContainer(ID_OBJECT_REF_CONTAINER); objectRefContainer.add(new VisibleEnableBehaviour() { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/ExecuteChangesHandlerPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/ExecuteChangesHandlerPanel.java index 5ed88f64edb..313db703d86 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/ExecuteChangesHandlerPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/ExecuteChangesHandlerPanel.java @@ -37,7 +37,7 @@ public ExecuteChangesHandlerPanel(String id, IModel mo initLayout(); setOutputMarkupId(true); } - + private void initLayout() { WebMarkupContainer changeContainer = new WebMarkupContainer(ID_CHANGE_CONTAINER); TextArea change = new TextArea<>(ID_CHANGE, new PropertyModel<>(getModel(), ExecuteChangesHandlerDto.F_OBJECT_DELTA_XML)); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/GenericHandlerPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/GenericHandlerPanel.java index c8c827c139f..d2b64fd0a12 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/GenericHandlerPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/GenericHandlerPanel.java @@ -36,7 +36,7 @@ public GenericHandlerPanel(String id, IModel model, PageTaskE initLayout(parentPage); setOutputMarkupId(true); } - + private void initLayout(final PageTaskEdit parentPage) { PrismContainerPanel containerPanel = new PrismContainerPanel( ID_CONTAINER, new PropertyModel<>(getModel(), GenericHandlerDto.F_CONTAINER), diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/LiveSyncHandlerPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/LiveSyncHandlerPanel.java index 3fbedd54f67..2ddf5a706eb 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/LiveSyncHandlerPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/LiveSyncHandlerPanel.java @@ -39,11 +39,11 @@ public class LiveSyncHandlerPanel extends ResourceRelatedHandlerPanel handlerDtoModel, PageTaskEdit parentPage) { super(id, handlerDtoModel, parentPage); initLayout(parentPage); @@ -74,7 +74,7 @@ public boolean isVisible() { deleteTokenPanel.setRenderBodyOnly(true); tokenContainer.add(deleteTokenPanel); add(tokenContainer); - + WebMarkupContainer retryContainer = new WebMarkupContainer(ID_TOKEN_RETRY_CONTAINER); add(retryContainer); WebMarkupContainer retryCheckboxContainer = new WebMarkupContainer(ID_TOKEN_RETRY_CHECKBOX_CONTAINER); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/QueryBasedHandlerPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/QueryBasedHandlerPanel.java index 79489c2f287..6e3d6580b53 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/QueryBasedHandlerPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/QueryBasedHandlerPanel.java @@ -40,7 +40,7 @@ public QueryBasedHandlerPanel(String id, IModel model) { initLayout(); setOutputMarkupId(true); } - + private void initLayout() { WebMarkupContainer objectTypeContainer = new WebMarkupContainer(ID_OBJECT_TYPE_CONTAINER); Label objectType = new Label(ID_OBJECT_TYPE, new AbstractReadOnlyModel() { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/ReportCreateHandlerPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/ReportCreateHandlerPanel.java index 66335902f4d..4b02733fc6e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/ReportCreateHandlerPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/ReportCreateHandlerPanel.java @@ -40,7 +40,7 @@ public class ReportCreateHandlerPanel extends DefaultHandlerPanel { private static final long serialVersionUID = 1L; - + private static final String ID_DOWNLOAD_CONTAINER = "downloadContainer"; private static final String ID_DOWNLOAD = "download"; private static final String ID_REPORT_PARAMETERS_CONTAINER = "reportParametersContainer"; @@ -54,7 +54,7 @@ public ReportCreateHandlerPanel(String id, IModel model, } private void initLayout(final PageTaskEdit parentPage) { - + final AjaxDownloadBehaviorFromStream ajaxDownloadBehavior = new AjaxDownloadBehaviorFromStream() { private static final long serialVersionUID = 1L; @@ -67,8 +67,8 @@ protected InputStream initStream() { return null; } } - - + + @Override public String getFileName() { ReportOutputType reportObject = getReportOutput(parentPage); @@ -85,9 +85,9 @@ public String getFileName() { WebMarkupContainer downloadContainer = new WebMarkupContainer(ID_DOWNLOAD_CONTAINER); AjaxButton download = new AjaxButton(ID_DOWNLOAD) { - + private static final long serialVersionUID = 1L; - + @Override public void onClick(AjaxRequestTarget target) { ajaxDownloadBehavior.initiate(target); @@ -95,9 +95,9 @@ public void onClick(AjaxRequestTarget target) { }; downloadContainer.add(download); downloadContainer.add(new VisibleEnableBehaviour() { - + private static final long serialVersionUID = 1L; - + @Override public boolean isVisible() { ReportOutputType reportObject = getReportOutput(parentPage); @@ -106,16 +106,16 @@ public boolean isVisible() { }); add(downloadContainer); } - + private ReportOutputType getReportOutput(PageTaskEdit parentPage) { String outputOid = getModelObject().getReportOutputOid(); - + if (outputOid == null) { return null; - } + } Task task = parentPage.createSimpleTask(OPERATION_LOAD_REPORT_OUTPUT); PrismObject reportOutput = WebModelServiceUtils.loadObject(ReportOutputType.class, outputOid, parentPage, task, task.getResult()); - + if (reportOutput == null) { return null; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/ResourceRelatedHandlerPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/ResourceRelatedHandlerPanel.java index e102b812548..a09a703c04e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/ResourceRelatedHandlerPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/ResourceRelatedHandlerPanel.java @@ -92,7 +92,7 @@ public ResourceRelatedHandlerPanel(String id, IModel handlerDtoModel, PageTas this.parentPage = parentPage; initLayout(); } - + private void initLayout() { final VisibleEnableBehaviour visibleIfEdit = new VisibleEnableBehaviour() { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/ScannerHandlerPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/ScannerHandlerPanel.java index 385748f995e..7e9dfbc3066 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/ScannerHandlerPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/ScannerHandlerPanel.java @@ -36,7 +36,7 @@ public ScannerHandlerPanel(String id, IModel model) { initLayout(); setOutputMarkupId(true); } - + private void initLayout() { WebMarkupContainer lastScanTimestampContainer = new WebMarkupContainer(ID_LAST_SCAN_TIMESTAMP_CONTAINER); // lastScanTimestampContainer.add(new VisibleEnableBehaviour() { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/ScriptExecutionHandlerPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/ScriptExecutionHandlerPanel.java index 7d94fbd975f..16d4bfa1f97 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/ScriptExecutionHandlerPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/ScriptExecutionHandlerPanel.java @@ -36,7 +36,7 @@ public ScriptExecutionHandlerPanel(String id, IModel initLayout(); setOutputMarkupId(true); } - + private void initLayout() { WebMarkupContainer scriptContainer = new WebMarkupContainer(ID_SCRIPT_CONTAINER); TextArea script = new TextArea<>(ID_SCRIPT, new PropertyModel<>(getModel(), ScriptExecutionHandlerDto.F_SCRIPT)); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/dto/ResourceRelatedHandlerDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/dto/ResourceRelatedHandlerDto.java index 9ec5a84d78b..892771fcbd1 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/dto/ResourceRelatedHandlerDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/handlers/dto/ResourceRelatedHandlerDto.java @@ -95,7 +95,7 @@ private void fillFromExtension(TaskType taskType) { if(objectClassItem != null && objectClassItem.getRealValue() != null){ objectClass = objectClassItem.getRealValue().getLocalPart(); } - + PrismProperty retrySyncItem = task.getExtension().findProperty(SchemaConstants.SYNC_TOKEN_RETRY_UNHANDLED); if (retrySyncItem == null || retrySyncItem.getRealValue() == null) { retryUnhandledErr = true; @@ -111,7 +111,7 @@ public boolean isDryRun() { public void setDryRun(boolean dryRun) { this.dryRun = dryRun; } - + public boolean isRetryUnhandledErr() { return retryUnhandledErr; } @@ -215,16 +215,16 @@ public void setResource(TaskAddResourcesDto resource) { resourceObjectRef.setType(ResourceType.COMPLEX_TYPE); rv.add(DeltaBuilder.deltaFor(TaskType.class, prismContext) .item(TaskType.F_OBJECT_REF).replace(resourceObjectRef.asReferenceValue()).asItemDelta()); - } - + } + if (orig.isDryRun() != curr.isDryRun()) { addExtensionDelta(rv, SchemaConstants.MODEL_EXTENSION_DRY_RUN, curr.isDryRun(), prismContext); - } - + } + if (orig.isRetryUnhandledErr() != curr.isRetryUnhandledErr()) { addExtensionDelta(rv, SchemaConstants.SYNC_TOKEN_RETRY_UNHANDLED, curr.isRetryUnhandledErr(), prismContext); - } - + } + if (orig.getKind() != curr.getKind()) { addExtensionDelta(rv, SchemaConstants.MODEL_EXTENSION_KIND, curr.getKind(), prismContext); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/services/PageAdminServices.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/services/PageAdminServices.java index c1698183a49..e82addf542d 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/services/PageAdminServices.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/services/PageAdminServices.java @@ -29,5 +29,5 @@ public class PageAdminServices extends PageAdmin { public static final String AUTH_SERVICES_ALL_LABEL = "PageAdminServices.auth.servicesAll.label"; public static final String AUTH_SERVICES_ALL_DESCRIPTION = "PageAdminServices.auth.servicesAll.description"; - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/services/PageService.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/services/PageService.java index 8b311bf53a2..21a2b1c7885 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/services/PageService.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/services/PageService.java @@ -41,24 +41,24 @@ public class PageService extends PageAdminAbstractRole implements ProgressReportingAwarePage{ private static final long serialVersionUID = 1L; - + public PageService() { initialize(null); } public PageService(final PrismObject unitToEdit) { initialize(unitToEdit); - } + } public PageService(PageParameters parameters) { getPageParameters().overwriteWith(parameters); initialize(null); } - + @Override protected ServiceType createNewObject() { return new ServiceType(); - } + } @Override public Class getCompileTimeClass() { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageMergeObjects.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageMergeObjects.java index eb5417f2df7..fad1bc2f8af 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageMergeObjects.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageMergeObjects.java @@ -130,17 +130,17 @@ public void detach() { @Override protected AbstractObjectMainPanel createMainPanel(String id){ - + //empty assignments model CountableLoadableModel assignemtns = new CountableLoadableModel() { private static final long serialVersionUID = 1L; - + @Override protected List load() { return new ArrayList<>(); } }; - + //empty projections model CountableLoadableModel policyRules = new CountableLoadableModel() { private static final long serialVersionUID = 1L; @@ -150,7 +150,7 @@ protected List load() { return new ArrayList<>(); } }; - + //empty projections model LoadableModel>> shadows = new LoadableModel>>() { private static final long serialVersionUID = 1L; @@ -159,7 +159,7 @@ protected List> load() { return new ArrayList<>(); } }; - + return new FocusMainPanel(id, getObjectModel(), assignemtns, policyRules, shadows, this) { private static final long serialVersionUID = 1L; @@ -191,7 +191,7 @@ protected boolean getOptionsPanelVisibility() { } }; } - + @Override protected FocusSummaryPanel createSummaryPanel(){ UserSummaryPanel summaryPanel = new UserSummaryPanel(ID_SUMMARY_PANEL, getObjectModel(), this); @@ -203,7 +203,7 @@ protected FocusSummaryPanel createSummaryPanel(){ protected void setSummaryPanelVisibility(FocusSummaryPanel summaryPanel){ summaryPanel.setVisible(false); } - + @Override protected Class getRestartResponsePage() { return PageUsers.class; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageOrgTree.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageOrgTree.java index f603c007a77..048debee008 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageOrgTree.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageOrgTree.java @@ -50,7 +50,7 @@ public class PageOrgTree extends PageAdminUsers { private static final String OPERATION_LOAD_ORG_UNIT = DOT_CLASS + "loadOrgUnit"; private String ID_TABS = "tabs"; - + private String ID_ORG_PANEL = "orgPanel"; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageOrgUnit.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageOrgUnit.java index 5132da67e29..72f89f484e2 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageOrgUnit.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageOrgUnit.java @@ -44,7 +44,7 @@ public class PageOrgUnit extends PageAdminAbstractRole implements ProgressReportingAwarePage { private static final Trace LOGGER = TraceManager.getTrace(PageOrgUnit.class); - + public PageOrgUnit() { initialize(null); } @@ -57,11 +57,11 @@ public PageOrgUnit(PageParameters parameters) { getPageParameters().overwriteWith(parameters); initialize(null); } - + @Override protected OrgType createNewObject() { return new OrgType(); - } + } @Override public Class getCompileTimeClass() { @@ -82,12 +82,12 @@ protected FocusSummaryPanel createSummaryPanel() { protected AbstractObjectMainPanel createMainPanel(String id) { return new AbstractRoleMainPanel(id, getObjectModel(), getAssignmentsModel(), getPolicyRulesModel(), getProjectionModel(), getInducementsModel(), this) { - + @Override public AbstractRoleMemberPanel createMemberPanel(String panelId) { return new OrgMemberPanel(panelId, Model.of(getObject().asObjectable()), PageOrgUnit.this); } }; } - + } 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 fbd97d0f525..3bf81cd7bc9 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 @@ -129,7 +129,7 @@ protected List load() { return getUserPrivilegesList(); } }; - + consentsModel = new CountableLoadableModel(false) { private static final long serialVersionUID = 1L; @@ -137,7 +137,7 @@ protected List load() { protected List load() { return loadConsents(); } - + @Override public int count() { return countConsents(); @@ -169,18 +169,18 @@ protected void cancelPerformed(AjaxRequestTarget target) { // ex); // } } - + @Override protected UserType createNewObject() { return new UserType(); } - + @Override protected Class getRestartResponsePage() { return PageUsers.class; } - + @Override public Class getCompileTimeClass() { return UserType.class; @@ -257,8 +257,8 @@ protected List createAssignmentMenu() { }; } - - + + @Override public String getCount() { @@ -266,8 +266,8 @@ public String getCount() { 0 : getDelegatedToMeModel().getObject().size()); } }); - - + + authorization = new FocusTabVisibleBehavior(unwrapModel(), ComponentConstants.UI_FOCUS_TAB_CONSENTS_URL); tabs.add(new CountablePanelTab(parentPage.createStringResource("FocusType.consents"), authorization) @@ -278,7 +278,7 @@ public String getCount() { public WebMarkupContainer createPanel(String panelId) { return new FocusConsentTabPanel(panelId, getMainForm(), getObjectModel(), consentsModel, parentPage); } - + @Override public String getCount() { return Integer.toString(consentsModel.count()); @@ -367,12 +367,12 @@ private List getUserPrivilegesList(){ } return list; } - + @Override protected void prepareObjectDeltaForModify(ObjectDelta focusDelta) throws SchemaException { - + super.prepareObjectDeltaForModify(focusDelta); - + PrismContainerDefinition def = getObjectDefinition().findContainerDefinition(UserType.F_ASSIGNMENT); if (consentsModel.isLoaded()) { handleAssignmentExperimentalDeltas(focusDelta, consentsModel.getObject(), def, false); @@ -425,7 +425,7 @@ public boolean isLoggedInUserPage(){ StringUtils.isNotEmpty(getObjectWrapper().getObject().asObjectable().getOid()) && getObjectWrapper().getObject().asObjectable().getOid().equals(WebModelServiceUtils.getLoggedInUserOid()); } - + protected int countConsents() { int consentCounter = 0; PrismObject focus = getObjectModel().getObject().getObject(); @@ -446,11 +446,11 @@ private List loadConsents() { Collections.sort(list); return list; } - + 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) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageUsers.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageUsers.java index 7973ca56b14..ab80ceb6ef4 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageUsers.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageUsers.java @@ -208,7 +208,7 @@ protected List createInlineMenu() { protected void objectDetailsPerformed(AjaxRequestTarget target, UserType object) { userDetailsPerformed(target, object.getOid()); } - + @Override protected void newObjectPerformed(AjaxRequestTarget target) { navigateToNext(PageUser.class); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/AbstractRoleMemberPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/AbstractRoleMemberPanel.java index 9f6e925e2f6..a648886ba2a 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/AbstractRoleMemberPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/AbstractRoleMemberPanel.java @@ -570,7 +570,7 @@ protected String getTaskName(String operation, QueryScope scope, boolean manager protected String getTaskName(String operation, QueryScope scope) { return getTaskName(operation, scope, false); } - + private String getMemberObjectDisplayName(ObjectType object){ if (object == null){ return ""; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/AbstractTreeTablePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/AbstractTreeTablePanel.java index a87f21a8ea8..98db073d29e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/AbstractTreeTablePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/AbstractTreeTablePanel.java @@ -98,13 +98,13 @@ public abstract class AbstractTreeTablePanel extends BasePanel { protected static final String SEARCH_SCOPE_SUBTREE = "subtree"; protected static final String SEARCH_SCOPE_ONE = "one"; - + protected static final ObjectTypes OBJECT_TYPES_DEFAULT = ObjectTypes.OBJECT; - + protected static final List SEARCH_SCOPE_VALUES = Arrays.asList( SEARCH_SCOPE_SUBTREE, SEARCH_SCOPE_ONE); - + protected IModel> selected; - + public AbstractTreeTablePanel(String id, IModel rootOid) { super(id, rootOid); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/AssociationValueChoicePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/AssociationValueChoicePanel.java index 952d5bec660..0f996c95d6d 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/AssociationValueChoicePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/AssociationValueChoicePanel.java @@ -78,7 +78,7 @@ public class AssociationValueChoicePanel extends BasePanel private ObjectQuery query = null; private RefinedObjectClassDefinition assocTargetDef; - public AssociationValueChoicePanel(String id, IModel>> model, + public AssociationValueChoicePanel(String id, IModel>> model, List values, boolean required, Class type, ObjectQuery query, RefinedObjectClassDefinition assocTargetDef) { super(id, (IModel)new PropertyModel<>(model, "value")); @@ -89,7 +89,7 @@ public AssociationValueChoicePanel(String id, IModel(model, "value"), values, required, type); } - private void initLayout(final IModel> value, + private void initLayout(final IModel> value, final List values, final boolean required, Class type) { @@ -123,7 +123,7 @@ public void onClick(AjaxRequestTarget target) { }; edit.add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; - + @Override public boolean isVisible() { return model.getObject().isEmpty(); @@ -296,10 +296,10 @@ public String getObject() { PrismReferenceValue shadowRef = cval.findReference(ShadowAssociationType.F_SHADOW_REF).getValue(); if (shadowRef.getObject() == null) { PrismContainer identifiersContainer = cval.findContainer(ShadowAssociationType.F_IDENTIFIERS); - + List> identifiers = (List) identifiersContainer.getValue().getItems(); Collection> secondaryIdentifierDefs = assocTargetDef.getSecondaryIdentifiers(); - + for (RefinedAttributeDefinition secondaryIdentifierDef: secondaryIdentifierDefs) { for (PrismProperty identifier: identifiers) { if (identifier.getElementName().equals(secondaryIdentifierDef.getName())) { @@ -307,11 +307,11 @@ public String getObject() { } } } - + // fallback PrismProperty identifierProp = identifiers.get(0); return identifierProp.getRealValue(); - + } else { return shadowRef.getObject().getName().toString(); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/MergeObjectsPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/MergeObjectsPanel.java index 1774dafe8a8..c285d5cad67 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/MergeObjectsPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/MergeObjectsPanel.java @@ -233,7 +233,7 @@ private List getMergeTypeNames(){ } return mergeTypeNamesList; } - + private PrismObject getMergeObjectsResult() { OperationResult result = new OperationResult(OPERATION_GET_MERGE_OBJECT_PREVIEW); PrismObject mergeResultObject = null; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/OrgMemberPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/OrgMemberPanel.java index 87a3f3dffca..8bc8a919d6f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/OrgMemberPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/OrgMemberPanel.java @@ -230,7 +230,7 @@ public boolean isVisible(){ }); FocusSummaryPanel.addSummaryPanel(managerMarkup, manager, managerWrapper, ID_MANAGER_SUMMARY, serviceLocator); - + link.setOutputMarkupId(true); managerMarkup.setOutputMarkupId(true); managerMarkup.add(link); @@ -268,7 +268,7 @@ public boolean isVisible(){ }); removeManager.setOutputMarkupId(true); managerMarkup.add(removeManager); - + AjaxButton deleteManager = new AjaxButton(ID_DELETE_MANAGER) { @Override @@ -335,7 +335,7 @@ private void removeManagerPerformed(FocusType manager, AjaxRequestTarget target) target.add(getPageBase().getFeedbackPanel()); } - + private void deleteManagerConfirmPerformed(FocusType manager, AjaxRequestTarget target) { getPageBase().hideMainPopup(target); OperationResult parentResult = new OperationResult("Remove manager"); @@ -357,7 +357,7 @@ private void deleteManagerConfirmPerformed(FocusType manager, AjaxRequestTarget target.add(getPageBase().getFeedbackPanel()); } - + private void deleteManagerPerformed(final FocusType manager, final Component summary, AjaxRequestTarget target) { ConfirmationPanel confirmDelete = new ConfirmationPanel(getPageBase().getMainPopupBodyId(), createStringResource("TreeTablePanel.menu.deleteManager.confirm")) { @Override @@ -367,10 +367,10 @@ public void yesPerformed(AjaxRequestTarget target) { target.add(OrgMemberPanel.this); } }; - + getPageBase().showMainPopup(confirmDelete, target); } - + @Override protected boolean isAuthorizedToUnassignMembers(){ return WebComponentUtil.isAuthorized(AuthorizationConstants.AUTZ_UI_ADMIN_UNASSIGN_ORG_MEMBER_ACTION_URI); @@ -441,7 +441,7 @@ public void yesPerformed(AjaxRequestTarget target) { OrgMemberPanel.this.deleteMemberConfirmPerformed(scope, relation, target); } }; - + getPageBase().showMainPopup(confirmDelete, target); } @@ -453,9 +453,9 @@ private void deleteMemberConfirmPerformed(QueryScope scope, QName relation, Ajax return; } executeMemberOperation(operationalTask, FocusType.COMPLEX_TYPE, createQueryForMemberAction(scope, relation, true), delta, TaskCategory.EXECUTE_CHANGES, target); - + } - + private List createManagersHeaderInlineMenu() { List headerMenuItems = new ArrayList<>(); @@ -692,7 +692,7 @@ private ObjectQuery createQueryForMemberAction(QueryScope scope, QName orgRelati query = ObjectQuery.createObjectQuery(InOidFilter.createInOid(oids)); break; case ALL_DIRECT: - case ALL: + case ALL: query = createQueryForAll(scope, isFocus, orgRelation); break; default: @@ -720,7 +720,7 @@ private ObjectQuery createQueryForAll(QueryScope scope, boolean isFocus, QName r .isInScopeOf(org.getOid(), getScope(scope)) .build(); } - + private Scope getScope(QueryScope queryScope) { return QueryScope.ALL == queryScope ? Scope.SUBTREE : Scope.ONE_LEVEL; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/OrgTreeProvider.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/OrgTreeProvider.java index e41ff5ea795..e1649abe65f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/OrgTreeProvider.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/OrgTreeProvider.java @@ -59,7 +59,7 @@ public class OrgTreeProvider extends SortableTreeProvider rootOid; private SelectableBean root; - + private List> availableData; public OrgTreeProvider(Component component, IModel rootOid) { @@ -73,7 +73,7 @@ public List> getAvailableData() { } return availableData; } - + private PageBase getPageBase() { return WebComponentUtil.getPageBase(component); } @@ -157,7 +157,7 @@ private SelectableBean createObjectWrapper(SelectableBean pare protected List createInlineMenuItems(OrgType org){ return null; } - + @Override public Iterator> getRoots() { OperationResult result = null; @@ -187,8 +187,8 @@ public Iterator> getRoots() { list.add(root); if (!getAvailableData().contains(root)){ getAvailableData().add(root); - } - + } + } return list.iterator(); } @@ -202,7 +202,7 @@ public boolean hasChildren(SelectableBean node) { public IModel> model(SelectableBean object) { return new Model<>(object); } - + public List getSelectedObjects(){ List selectedOrgs = new ArrayList<>(); for (SelectableBean selected : getAvailableData()){ @@ -210,7 +210,7 @@ public List getSelectedObjects(){ selectedOrgs.add(selected.getValue()); } } - + return selectedOrgs; } } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/SelectableFolderContent.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/SelectableFolderContent.java index 0180a3172f8..790a94c441f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/SelectableFolderContent.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/SelectableFolderContent.java @@ -52,7 +52,7 @@ protected IModel newLabelModel(final IModel> model) { public String getObject() { SelectableBean dto = model.getObject(); return WebComponentUtil.getEffectiveName(dto.getValue(), OrgType.F_DISPLAY_NAME); - + } }; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/ServiceMemberPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/ServiceMemberPanel.java index 773f32398dd..db666a3559a 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/ServiceMemberPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/ServiceMemberPanel.java @@ -8,10 +8,10 @@ public class ServiceMemberPanel extends RoleMemberPanel{ - + private static final long serialVersionUID = 1L; - + public ServiceMemberPanel(String id, IModel model, PageBase pageBase) { super(id, model, pageBase); } @@ -20,6 +20,6 @@ public ServiceMemberPanel(String id, IModel model, PageBase pageBas protected boolean isRole() { return false; } - - + + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/TreeTablePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/TreeTablePanel.java index a855a16e518..a53da125282 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/TreeTablePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/TreeTablePanel.java @@ -62,7 +62,7 @@ /** * Used as a main component of the Org tree page. - * + * * todo create function computeHeight() in midpoint.js, update height properly * when in "mobile" mode... [lazyman] todo implement midpoint theme for tree * [lazyman] diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/UserSummaryPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/UserSummaryPanel.java index a154f04af0e..10e24f54e2a 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/UserSummaryPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/component/UserSummaryPanel.java @@ -42,13 +42,13 @@ */ public class UserSummaryPanel extends FocusSummaryPanel { private static final long serialVersionUID = -5077637168906420769L; - + private static final String ID_TAG_SECURITY = "summaryTagSecurity"; private static final String ID_TAG_ORG = "summaryTagOrg"; public UserSummaryPanel(String id, IModel> model, ModelServiceLocator serviceLocator) { super(id, UserType.class, model, serviceLocator); - + SummaryTag tagSecurity = new SummaryTag(ID_TAG_SECURITY, model) { private static final long serialVersionUID = 1L; @@ -91,7 +91,7 @@ protected void initialize(ObjectWrapper wrapper) { } }; addTag(tagSecurity); - + SummaryTag tagOrg = new SummaryTag(ID_TAG_ORG, model) { private static final long serialVersionUID = 1L; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/workflow/ProcessInstancesPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/workflow/ProcessInstancesPanel.java index c889e8527bd..a68e8a10851 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/workflow/ProcessInstancesPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/workflow/ProcessInstancesPanel.java @@ -208,7 +208,7 @@ private void itemDetailsPerformed(AjaxRequestTarget target, String pid) { } // copied and adapted from WorkItemsPanel - TODO deduplicate - + IColumn createObjectNameColumn(final String headerKey) { return new LinkColumn(createStringResource(headerKey), ProcessInstanceDto.F_OBJECT_NAME) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/workflow/WorkItemPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/workflow/WorkItemPanel.java index 85ae0c36d6b..449d9cdf274 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/workflow/WorkItemPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/workflow/WorkItemPanel.java @@ -235,14 +235,14 @@ public void onClick(AjaxRequestTarget target) { WebMarkupContainer additionalAttributes = new WebMarkupContainer(ID_ADDITIONAL_ATTRIBUTES); add(additionalAttributes); additionalAttributes.add(new VisibleEnableBehaviour() { - + private static final long serialVersionUID = 1L; public boolean isVisible() { return (level != null && level.getFormRef() != null && level.getFormRef().getOid() != null); }; }); - + if (level != null && level.getFormRef() != null && level.getFormRef().getOid() != null) { String formOid = level.getFormRef().getOid(); ObjectType focus = dto.getFocus(pageBase); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/error/PageOperationResult.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/error/PageOperationResult.java index a303aa1d2c3..7fc205f96b6 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/error/PageOperationResult.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/error/PageOperationResult.java @@ -29,7 +29,7 @@ * Page that displays just the operation result. Comes handy * for places where the operation result cannot be displayed * on the main page (e.g. object list warnings, projection list, etc.) - * + * * @author semancik */ @PageDescriptor(url = "/result") @@ -39,7 +39,7 @@ public class PageOperationResult extends PageBase { private static final String ID_BACK = "back"; private static final Trace LOGGER = TraceManager.getTrace(PageOperationResult.class); - + private OperationResult result = null; public PageOperationResult() { 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 600d0e04f9e..979b96cbd96 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 @@ -365,7 +365,7 @@ private ObjectQuery createStaticFormQuery(Form form) { if (method == null) { passwordResetNotSupported(); } - + switch (method) { case MAIL: return QueryBuilder.queryFor(UserType.class, getPrismContext()).item(UserType.F_EMAIL_ADDRESS) @@ -382,7 +382,7 @@ private ObjectQuery createStaticFormQuery(Form form) { } } - + private void passwordResetNotSupported() { getSession().error(getString("PageForgotPassword.unsupported.reset.type")); throw new RestartResponseException(PageForgotPassword.this); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/PageResetPassword.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/PageResetPassword.java index 5ee6f8acab1..a6d2aa854e8 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/PageResetPassword.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/PageResetPassword.java @@ -26,65 +26,65 @@ label = "PageSelfCredentials.auth.credentials.label", description = "PageSelfCredentials.auth.credentials.description")}) public class PageResetPassword extends PageAbstractSelfCredentials{ - + private static final long serialVersionUID = 1L; - + public PageResetPassword() { // TODO Auto-generated constructor stub } - + @Override protected boolean isSideMenuVisible(boolean visibleIfLoggedIn) { return false; } - - + + @Override protected boolean isCheckOldPassword() { return false; } - + @Override protected void finishChangePassword(final OperationResult result, AjaxRequestTarget target) { - - + + if (result.getStatus() == OperationResultStatus.SUCCESS) { result.setMessage(getString("PageResetPassword.reset.successful")); setResponsePage(PageLogin.class); - + PrismObject user = getUser(); if (user == null) { SecurityContextHolder.getContext().setAuthentication(null); return; } - + UserType userType = user.asObjectable(); - + if (userType.getCredentials() != null && userType.getCredentials().getNonce() != null) { - + try { ObjectDelta deleteNonceDelta = ObjectDelta.createModificationDeleteContainer(UserType.class, userType.getOid(), SchemaConstants.PATH_NONCE, getPrismContext(), userType.getCredentials().getNonce().clone()); WebModelServiceUtils.save(deleteNonceDelta, result, this); } catch (SchemaException e) { - //nothing to do, just let the nonce here.. it will be invalid + //nothing to do, just let the nonce here.. it will be invalid } } - + SecurityContextHolder.getContext().setAuthentication(null); } - + showResult(result); target.add(getFeedbackPanel()); // get(ID_MAIN_FORM).setVisible(false); - - + + } - + @Override protected void createBreadcrumb() { // we don't want breadcrumbs here } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/PageResetPasswordConfirmation.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/PageResetPasswordConfirmation.java index 52eef921d3f..e04aea333d3 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/PageResetPasswordConfirmation.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/PageResetPasswordConfirmation.java @@ -33,15 +33,15 @@ @PageDescriptor(urls = {@Url(mountUrl = SchemaConstants.PASSWORD_RESET_CONFIRMATION_PREFIX)}) public class PageResetPasswordConfirmation extends PageRegistrationBase{ - + private static final Trace LOGGER = TraceManager.getTrace(PageRegistrationConfirmation.class); - + private static final String DOT_CLASS = PageRegistrationConfirmation.class.getName() + "."; - + private static final String ID_LABEL_ERROR = "errorLabel"; private static final String ID_ERROR_PANEL = "errorPanel"; - + private static final String OPERATION_ASSIGN_DEFAULT_ROLES = DOT_CLASS + ".assignDefaultRoles"; private static final String OPERATION_FINISH_REGISTRATION = DOT_CLASS + "finishRegistration"; @@ -63,7 +63,7 @@ private void init(final PageParameters pageParameters) { if (params == null) { params = getPageParameters(); } - + OperationResult result = new OperationResult(OPERATION_FINISH_REGISTRATION); if (params == null) { LOGGER.error("Confirmation link is not valid. No credentials provided in it"); @@ -78,7 +78,7 @@ private void init(final PageParameters pageParameters) { Validate.notEmpty(userNameValue.toString()); StringValue tokenValue = params.get(SchemaConstants.TOKEN); Validate.notEmpty(tokenValue.toString()); - + UsernamePasswordAuthenticationToken token = authenticateUser(userNameValue.toString(), tokenValue.toString(), result); if (token == null) { initLayout(result); @@ -87,7 +87,7 @@ private void init(final PageParameters pageParameters) { // SecurityContextHolder.getContext().setAuthentication(token); MidPointPrincipal principal = (MidPointPrincipal) token.getPrincipal(); Collection authz = principal.getAuthorities(); - + if (authz != null) { Iterator authzIterator = authz.iterator(); while (authzIterator.hasNext()) { @@ -99,11 +99,11 @@ private void init(final PageParameters pageParameters) { actionIterator.remove(); } } - + } - + } - + AuthorizationType authorizationType = new AuthorizationType(); authorizationType.getAction().add(AuthorizationConstants.AUTZ_UI_SELF_CREDENTIALS_URL); Authorization selfServiceCredentialsAuthz = new Authorization(authorizationType); @@ -114,7 +114,7 @@ private void init(final PageParameters pageParameters) { initLayout(result); } - + private UsernamePasswordAuthenticationToken authenticateUser(String username, String nonce, OperationResult result) { ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_GUI_SELF_REGISTRATION_URI); try { @@ -133,10 +133,10 @@ private UsernamePasswordAuthenticationToken authenticateUser(String username, St return null; } } - - - - + + + + private void initLayout(final OperationResult result) { WebMarkupContainer errorPanel = new WebMarkupContainer(ID_ERROR_PANEL); @@ -160,7 +160,7 @@ public boolean isVisible() { errorPanel.add(errorMessage); } - + @Override protected void createBreadcrumb() { // don't create breadcrumb for registration confirmation page diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/PageSecurityQuestions.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/PageSecurityQuestions.java index 0110a44c80e..22d1dde4daf 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/PageSecurityQuestions.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/PageSecurityQuestions.java @@ -148,23 +148,23 @@ protected PasswordQuestionsDto load() { protected void createBreadcrumb() { //don't create breadcrumb for this page } - + public void initLayout() { - + Form mainForm = new Form(ID_MAIN_FORM); - + pqPanels = new ArrayList(); - + PrismObject securityPolicy = getSecurityPolicy(); LOGGER.trace("Found security policy: {}", securityPolicy); - + if (securityPolicy == null) { LOGGER.error("No security policy, cannot process security questions"); // Just log the error, but do not display it. We are still in unprivileged part of the web // we do not want to provide any information to the attacker. throw new RestartResponseException(PageError.class); } - + questionNumber = securityPolicy.asObjectable().getCredentials() != null && securityPolicy.asObjectable().getCredentials().getSecurityQuestions() != null ? securityPolicy.asObjectable().getCredentials().getSecurityQuestions().getQuestionNumber() : 0; @@ -172,33 +172,33 @@ public void initLayout() { securityPolicy.asObjectable().getCredentials().getSecurityQuestions() != null ? securityPolicy.asObjectable().getCredentials().getSecurityQuestions().getQuestion() : new ArrayList(); - + List userQuestionList = model.getObject().getSecurityAnswers(); - + if (userQuestionList == null) { getSession().error(getString("pageForgetPassword.message.ContactAdminQuestionsNotSet")); SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(null); throw new RestartResponseException(PageForgotPassword.class); } - + if (questionNumber <= userQuestionList.size()) { - + // Loop for finding the preset questions from the Policy // Questions for (Iterator iterator = policyQuestionList.iterator(); iterator.hasNext();) { - + SecurityQuestionDefinitionType securityQuestionDefinitionType = (SecurityQuestionDefinitionType) iterator .next(); - + // user's question List loop to match the questions for (int userQuestint = 0; userQuestint < userQuestionList.size(); userQuestint++) { - + // if the question is in the policy check int panelNumber = 0; if (userQuestionList.get(userQuestint).getPwdQuestion() .equalsIgnoreCase(securityQuestionDefinitionType.getIdentifier())) { - + SecurityQuestionAnswerDTO a = new SecurityQuestionAnswerDTO(userQuestionList .get(userQuestint).getPwdQuestion(), "", userQuestionList.get( userQuestint).getQuestionItself()); @@ -207,33 +207,33 @@ public void initLayout() { ID_PASSWORD_QUESTIONS_PANEL + panelNumber, a); pqPanels.add(panel); panelNumber++; - + // This is the Question! - + } } - + } - + } add(mainForm); mainForm.add(getPanels(pqPanels)); initButtons(mainForm); - + } - + private PrismObject getSecurityPolicy() { - + return runPrivileged(new Producer>() { @Override public PrismObject run() { - + Task task = getPageBase().createAnonymousTask(OPERATION_LOAD_QUESTION_POLICY); OperationResult result = task.getResult(); - + PrismObject config; try { config = getPageBase().getModelService().getObject(SystemConfigurationType.class, @@ -243,7 +243,7 @@ public PrismObject run() { LOGGER.error("Error getting system configuration: {}", e.getMessage(), e); return null; } - + if (config.asObjectable().getGlobalSecurityPolicyRef() != null) { try { return getModelService().getObject(SecurityPolicyType.class, @@ -258,14 +258,14 @@ public PrismObject run() { return null; } } - + }); } - + public ListView getPanels(List p) { ListView lw = new ListView(ID_PASSWORD_QUESTIONS_PANEL, p) { private static final long serialVersionUID = 1L; - + @Override protected void populateItem(ListItem item) { @@ -274,7 +274,7 @@ protected void populateItem(ListItem item) { }; return lw; } - + public void initButtons(Form mainForm) { AjaxSubmitButton save = new AjaxSubmitButton(ID_SAVE, createStringResource("PageBase.button.send")) { @@ -330,7 +330,7 @@ private void savePerformed(final AjaxRequestTarget target) { if (questionNumber == correctAnswers) { getSession().removeAttribute(SESSION_ATTRIBUTE_POID); - + runPrivileged(new Producer() { @Override public Object run() { @@ -347,13 +347,13 @@ public Object run() { } } - + private PasswordQuestionsDto loadPageModel() { LOGGER.debug("Loading user."); - + final String userOid = getPageParameters().get(SESSION_ATTRIBUTE_POID).toString(); - + PrismObject user = runPrivileged(new Producer>() { @Override public PrismObject run() { @@ -370,12 +370,12 @@ public PrismObject run() { // we do not want to provide any information to the attacker. return null; } - + } }); - + principalModel.setObject(user); - + PasswordQuestionsDto dto = new PasswordQuestionsDto(); dto.setSecurityAnswers(createUsersSecurityQuestionsList(user)); @@ -459,9 +459,9 @@ private void resetPassword(UserType user, AjaxRequestTarget target) { Task task = createAnonymousTask(OPERATION_RESET_PASSWORD); OperationResult result = task.getResult(); - + LOGGER.debug("Resetting password for {}", user); - + ProtectedStringType password = new ProtectedStringType(); Collection> options = SelectorOptions.createCollection( GetOperationOptions.createResolve(), SystemConfigurationType.F_DEFAULT_USER_TEMPLATE, @@ -627,9 +627,9 @@ protected PasswordAuthentication getPasswordAuthentication() { /* * Session mailSession = Session.getDefaultInstance(props); * MimeMessage message = new MimeMessage(mailSession); - * + * * message.setSubject("Engerek KYS Yeni Şifreniz"); - * + * * message.setText("User Login : " + userLogin + "\n Password : " + * password + "\n"); message.setFrom(new InternetAddress(sender)); * message.addRecipient(Message.RecipientType.TO, new diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/ResetPolicyDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/ResetPolicyDto.java index d4e22363757..cfa74ab38a0 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/ResetPolicyDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/ResetPolicyDto.java @@ -49,7 +49,7 @@ public void initResetPolicyDto(SecurityPolicyType securityPolicyType) throws Sch if (securityPolicyType.getCredentialsReset() == null) { return; } - + MailResetPolicyType mailResetPolicy = securityPolicyType.getCredentialsReset().getMailReset(); if (mailResetPolicy != null) { this.resetMethod = ResetMethod.MAIL; @@ -138,7 +138,7 @@ public NonceCredentialsPolicyType getNoncePolicy() { public void setNoncePolicy(NonceCredentialsPolicyType noncePolicy) { this.noncePolicy = noncePolicy; } - + public ObjectReferenceType getFormRef() { return formRef; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/dto/QuestionDTO.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/dto/QuestionDTO.java index 41830bfd8e4..8d5e05e00fe 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/dto/QuestionDTO.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/dto/QuestionDTO.java @@ -3,13 +3,13 @@ import java.io.Serializable; public class QuestionDTO implements Serializable { - + private String questionItself; private String answerOftheUser; public QuestionDTO(String question,String answer){ setAnswerOftheUser(answer); setQuestionItself(question); - + } private String getQuestionItself() { return questionItself; @@ -23,6 +23,6 @@ private String getAnswerOftheUser() { private void setAnswerOftheUser(String answerOftheUser) { this.answerOftheUser = answerOftheUser; } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/dto/SecretQuestionsDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/dto/SecretQuestionsDto.java index 1eb153cd149..963cc847689 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/dto/SecretQuestionsDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/dto/SecretQuestionsDto.java @@ -4,24 +4,24 @@ import java.util.List; public class SecretQuestionsDto implements Serializable { - + public static final String F_ACCOUNTS = "accounts"; public static final String F_ = "password"; private List secretQuestions; - - + + public List getSecretQuestions() { - + return secretQuestions; } - + public void addToList(QuestionDTO question){ secretQuestions.add(question); } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/login/PageRegistrationBase.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/login/PageRegistrationBase.java index 58844e15a7e..7a1265aa072 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/login/PageRegistrationBase.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/login/PageRegistrationBase.java @@ -22,7 +22,7 @@ public class PageRegistrationBase extends PageBase { private static final long serialVersionUID = 1L; private static final String DOT_CLASS = PageRegistrationBase.class.getName() + "."; private static final String OPERATION_GET_SECURITY_POLICY = DOT_CLASS + "getSecurityPolicy"; - + protected static final String OPERATION_LOAD_DYNAMIC_FORM = DOT_CLASS + "loadDynamicForm"; private static final Trace LOGGER = TraceManager.getTrace(PageRegistrationBase.class); @@ -39,9 +39,9 @@ public PageRegistrationBase() { } private void initSelfRegistrationConfiguration() { - + SecurityPolicyType securityPolicy = resolveSecurityPolicy(); - + this.selfRegistrationDto = new SelfRegistrationDto(); try { this.selfRegistrationDto.initSelfRegistrationDto(securityPolicy); @@ -72,7 +72,7 @@ private void initResetCredentialsConfiguration() { } } - + private SecurityPolicyType resolveSecurityPolicy() { SecurityPolicyType securityPolicy = runPrivileged(new Producer() { @@ -89,7 +89,7 @@ public SecurityPolicyType run() { LOGGER.error("Could not retrieve security policy"); return null; } - + } }); @@ -100,7 +100,7 @@ public SecurityPolicyType run() { .error(createStringResource("PageSelfRegistration.securityPolicy.notFound").getString()); throw new RestartResponseException(PageLogin.class); } - + return securityPolicy; } @@ -114,7 +114,7 @@ public SelfRegistrationDto getSelfRegistrationConfiguration() { return selfRegistrationDto; } - + public ResetPolicyDto getResetPasswordPolicy() { if (resetPasswordPolicy == null) { initResetCredentialsConfiguration(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/login/PageRegistrationConfirmation.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/login/PageRegistrationConfirmation.java index 59ecdf1fdc1..dba297b706a 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/login/PageRegistrationConfirmation.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/login/PageRegistrationConfirmation.java @@ -47,7 +47,7 @@ public class PageRegistrationConfirmation extends PageRegistrationBase { private static final Trace LOGGER = TraceManager.getTrace(PageRegistrationConfirmation.class); - + private static final String DOT_CLASS = PageRegistrationConfirmation.class.getName() + "."; private static final String ID_LABEL_SUCCESS = "successLabel"; @@ -55,7 +55,7 @@ public class PageRegistrationConfirmation extends PageRegistrationBase { private static final String ID_LINK_LOGIN = "linkToLogin"; private static final String ID_SUCCESS_PANEL = "successPanel"; private static final String ID_ERROR_PANEL = "errorPanel"; - + private static final String OPERATION_ASSIGN_DEFAULT_ROLES = DOT_CLASS + ".assignDefaultRoles"; private static final String OPERATION_FINISH_REGISTRATION = DOT_CLASS + "finishRegistration"; @@ -77,7 +77,7 @@ private void init(final PageParameters pageParameters) { if (params == null) { params = getPageParameters(); } - + OperationResult result = new OperationResult(OPERATION_FINISH_REGISTRATION); if (params == null) { LOGGER.error("Confirmation link is not valid. No credentials provided in it"); @@ -92,28 +92,28 @@ private void init(final PageParameters pageParameters) { Validate.notEmpty(userNameValue.toString()); StringValue tokenValue = params.get(SchemaConstants.TOKEN); Validate.notEmpty(tokenValue.toString()); - + UserType userType = checkUserCredentials(userNameValue.toString(), tokenValue.toString(), result); if (userType == null) { initLayout(result); return; } - + result = assignDefaultRoles(userType.getOid()); if (result.getStatus() == OperationResultStatus.FATAL_ERROR) { LOGGER.error("Failed to assign default roles, {}", result.getMessage()); initLayout(result); return; } - + final NonceType nonceClone = userType.getCredentials().getNonce().clone(); - + result = removeNonce(userType.getOid(), nonceClone); result = assignAdditionalRoleIfPresent(userType.getOid(), nonceClone, result); initLayout(result); } - + // private UsernamePasswordAuthenticationToken authenticateUser(String username, String nonce, OperationResult result){ // ConnectionEnvironment connEnv = new ConnectionEnvironment(); // connEnv.setChannel(SchemaConstants.CHANNEL_GUI_SELF_REGISTRATION_URI); @@ -133,7 +133,7 @@ private void init(final PageParameters pageParameters) { // return null; // } // } - + private UserType checkUserCredentials(String username, String nonce, OperationResult result) { ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_GUI_SELF_REGISTRATION_URI); try { @@ -152,7 +152,7 @@ private UserType checkUserCredentials(String username, String nonce, OperationRe return null; } } - + private OperationResult assignDefaultRoles(final String userOid){ List> assignments = new ArrayList<>(); for (ObjectReferenceType defaultRole : getSelfRegistrationConfiguration().getDefaultRoles()) { @@ -165,25 +165,25 @@ private OperationResult assignDefaultRoles(final String userOid){ //nothing to do } } - + final ObjectDelta delta = ObjectDelta.createModifyDelta(userOid, assignments, UserType.class, getPrismContext()); - + return runPrivileged(new Producer() { - + @Override public OperationResult run() { OperationResult result = new OperationResult(OPERATION_ASSIGN_DEFAULT_ROLES); Task task = createAnonymousTask(OPERATION_ASSIGN_DEFAULT_ROLES); WebModelServiceUtils.save(delta, result, task, PageRegistrationConfirmation.this); result.computeStatusIfUnknown(); - + return result; } }); - - + + } - + private OperationResult removeNonce(final String userOid, final NonceType nonce){ return runPrivileged(() -> { OperationResult result = new OperationResult("assignDefaultRoles"); @@ -239,9 +239,9 @@ private OperationResult assignAdditionalRoleIfPresent(String userOid, NonceType return result; }); - + // SecurityContextHolder.getContext().setAuthentication(null); - + } private void initLayout(final OperationResult result) { @@ -298,7 +298,7 @@ public boolean isVisible() { errorPanel.add(errorMessage); } - + @Override protected void createBreadcrumb() { // don't create breadcrumb for registration confirmation page diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/login/PageSelfRegistration.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/login/PageSelfRegistration.java index 4dc71604e99..cb411c8cfa7 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/login/PageSelfRegistration.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/login/PageSelfRegistration.java @@ -332,12 +332,12 @@ public boolean isVisible() { DynamicFormPanel dynamicForm = runPrivileged( () -> { final ObjectReferenceType ort = getSelfRegistrationConfiguration().getFormRef(); - + if (ort == null) { return null; } Task task = createAnonymousTask(OPERATION_LOAD_DYNAMIC_FORM); - + return new DynamicFormPanel(ID_DYNAMIC_FORM_PANEL, userModel, ort.getOid(), mainForm, task, PageSelfRegistration.this, true); }); @@ -573,7 +573,7 @@ private ObjectDelta prepareUserDelta(Task task, OperationResult result } else { delta = getDynamicFormPanel().getObjectDelta(); } - + delta.addModificationReplaceContainer(SchemaConstants.PATH_NONCE, createNonce(getSelfRegistrationConfiguration().getNoncePolicy(), task, result) .asPrismContainerValue()); @@ -677,7 +677,7 @@ private PasswordType createPassword() { return password; } - private String generateNonce(NonceCredentialsPolicyType noncePolicy, + private String generateNonce(NonceCredentialsPolicyType noncePolicy, PrismObject user, Task task, OperationResult result) throws ExpressionEvaluationException, SchemaException, ObjectNotFoundException { ValuePolicyType policy = null; @@ -687,7 +687,7 @@ private String generateNonce(NonceCredentialsPolicyType n policy = valuePolicy.asObjectable(); } - return getModelInteractionService().generateValue(policy != null ? policy.getStringPolicy() : null, + return getModelInteractionService().generateValue(policy != null ? policy.getStringPolicy() : null, 24, false, user, "nonce generation (registration)", task, result); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/login/SelfRegistrationDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/login/SelfRegistrationDto.java index 901e94915d1..f422eb19752 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/login/SelfRegistrationDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/login/SelfRegistrationDto.java @@ -25,7 +25,7 @@ public class SelfRegistrationDto implements Serializable { enum AuthenticationPolicy { MAIL, SMS, NONE; } - + private static final long serialVersionUID = 1L; private String name; @@ -33,10 +33,10 @@ enum AuthenticationPolicy { private MailAuthenticationPolicyType mailAuthenticationPolicy; private SmsAuthenticationPolicyType smsAuthenticationPolicy; private NonceCredentialsPolicyType noncePolicy; - + private String requiredLifecycleState; private String initialLifecycleState; - + private ObjectReferenceType formRef; public void initSelfRegistrationDto(SecurityPolicyType securityPolicy) throws SchemaException { @@ -52,9 +52,9 @@ public void initSelfRegistrationDto(SecurityPolicyType securityPolicy) throws Sc this.defaultRoles = selfRegistration.getDefaultRole(); this.initialLifecycleState = selfRegistration.getInitialLifecycleState(); this.requiredLifecycleState = selfRegistration.getRequiredLifecycleState(); - + this.formRef = selfRegistration.getFormRef(); - + AbstractAuthenticationPolicyType authPolicy = SecurityPolicyUtil.getAuthenticationPolicy( selfRegistration.getAdditionalAuthenticationName(), securityPolicy); @@ -66,7 +66,7 @@ public void initSelfRegistrationDto(SecurityPolicyType securityPolicy) throws Sc noncePolicy = SecurityPolicyUtil.getCredentialPolicy(((SmsAuthenticationPolicyType) authPolicy).getSmsNonce(), securityPolicy); } - + } @@ -74,16 +74,16 @@ public boolean isEmpty() { return StringUtils.isEmpty(name) && CollectionUtils.isEmpty(defaultRoles) && mailAuthenticationPolicy == null && smsAuthenticationPolicy == null && noncePolicy == null; } - + public AuthenticationPolicy getAuthenticationMethod () { if (mailAuthenticationPolicy != null) { return AuthenticationPolicy.MAIL; } - + if (smsAuthenticationPolicy != null) { return AuthenticationPolicy.SMS; } - + return AuthenticationPolicy.NONE; } @@ -261,19 +261,19 @@ public NonceCredentialsPolicyType getNoncePolicy() { public void setNoncePolicy(NonceCredentialsPolicyType noncePolicy) { this.noncePolicy = noncePolicy; } - + public String getInitialLifecycleState() { return initialLifecycleState; } - + public void setInitialLifecycleState(String initialLifecycleState) { this.initialLifecycleState = initialLifecycleState; } - + public String getRequiredLifecycleState() { return requiredLifecycleState; } - + public void setRequiredLifecycleState(String requiredLifecycleState) { this.requiredLifecycleState = requiredLifecycleState; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageAbstractSelfCredentials.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageAbstractSelfCredentials.java index 0676421c758..46a620ca441 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageAbstractSelfCredentials.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageAbstractSelfCredentials.java @@ -73,7 +73,7 @@ public abstract class PageAbstractSelfCredentials extends PageSelf { private static final String ID_TAB_PANEL = "tabPanel"; private static final String ID_SAVE_BUTTON = "save"; private static final String ID_CANCEL_BUTTON = "cancel"; - + private static final Trace LOGGER = TraceManager.getTrace(PageAbstractSelfCredentials.class); private static final String DOT_CLASS = PageSelfCredentials.class.getName() + "."; private static final String OPERATION_LOAD_USER_WITH_ACCOUNTS = DOT_CLASS + "loadUserWithAccounts"; @@ -210,7 +210,7 @@ public WebMarkupContainer getPanel(String panelId) { return new ChangePasswordPanel(panelId, isCheckOldPassword(), model, model.getObject()); } }); - + TabbedPanel credentialsTabPanel = WebComponentUtil.createTabPanel(ID_TAB_PANEL, this, tabs, null); credentialsTabPanel.setOutputMarkupId(true); @@ -225,7 +225,7 @@ private void initButtons(Form mainForm) { AjaxSubmitButton save = new AjaxSubmitButton(ID_SAVE_BUTTON, createStringResource("PageBase.button.save")) { private static final long serialVersionUID = 1L; - + @Override protected void onError(AjaxRequestTarget target, Form form) { target.add(getFeedbackPanel()); @@ -242,7 +242,7 @@ protected void onSubmit(AjaxRequestTarget target, Form form) { AjaxSubmitButton cancel = new AjaxSubmitButton(ID_CANCEL_BUTTON, createStringResource("PageBase.button.back")) { private static final long serialVersionUID = 1L; - + @Override protected void onError(AjaxRequestTarget target, Form form) { onCancelPerformed(target); @@ -272,7 +272,7 @@ private PasswordAccountDto createPasswordAccountDto(PrismObject acco PasswordAccountDto passwordAccountDto = new PasswordAccountDto(account.getOid(), WebComponentUtil.getName(account), resourceName, WebComponentUtil.isActivationEnabled(account)); - + passwordAccountDto.setPasswordOutbound(getPasswordOutbound(account)); passwordAccountDto.setPasswordCapabilityEnabled(hasPasswordCapability(account)); return passwordAccountDto; @@ -367,9 +367,9 @@ protected void setEncryptedPasswordData(EncryptedDataType data){ password.setEncryptedData(data); } } - + protected abstract boolean isCheckOldPassword(); - + protected abstract void finishChangePassword(OperationResult result, AjaxRequestTarget target); private List getSelectedAccountsList(){ @@ -423,7 +423,7 @@ private boolean getPasswordOutbound(PrismObject shadow) { RefinedObjectClassDefinition rOCDef = getModelInteractionService().getEditObjectClassDefinition(shadow, shadow.asObjectable().getResource().asPrismObject(), AuthorizationPhaseType.REQUEST); - + if (rOCDef != null && rOCDef.getPasswordOutbound() != null ){ return true; } @@ -433,11 +433,11 @@ private boolean getPasswordOutbound(PrismObject shadow) { return false; } - + private boolean hasPasswordCapability(PrismObject shadow) { - + return ResourceTypeUtil.isPasswordCapabilityEnabled(shadow.asObjectable().getResource()); - + } public PrismObject getUser() { @@ -460,7 +460,7 @@ private CredentialsPolicyType getPasswordCredentialsPolicy (){ } return credentialsPolicyType; } - + protected MyPasswordsDto getModelObject() { return model.getObject(); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageAccountActivation.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageAccountActivation.java index f65b87668bc..92c975b49c5 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageAccountActivation.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageAccountActivation.java @@ -72,15 +72,15 @@ public class PageAccountActivation extends PageBase { private static final long serialVersionUID = 1L; - + private static final Trace LOGGER = TraceManager.getTrace(PageAccountActivation.class); - + private IModel userModel; - + private static final String DOT_CLASS = PageUser.class.getName() + "."; private static final String LOAD_USER = DOT_CLASS + "loadUser"; private static final String OPERATION_ACTIVATE_SHADOWS = DOT_CLASS + "activateShadows"; - + private static final String ID_MAIN_FORM = "mainForm"; private static final String ID_NAME = "username"; private static final String ID_PASSWORD = "password"; @@ -89,18 +89,18 @@ public class PageAccountActivation extends PageBase { private static final String ID_CONFIRMATION_CONTAINER = "confirmationContainer"; private static final String ID_ACTIVATED_SHADOWS = "activatedShadows"; private static final String ID_LINK_TO_LOGIN = "linkToLogin"; - + private boolean activated = false; - + @SpringBean(name = "passwordAuthenticationEvaluator") private AuthenticationEvaluator authenticationEvaluator; - + public PageAccountActivation(PageParameters params) { - + UserType user = loadUser(params); - + userModel = new LoadableModel(false) { - + private static final long serialVersionUID = 1L; @Override @@ -108,33 +108,33 @@ protected UserType load() { return user; } }; - + initLayout(); - + } - + private UserType loadUser(PageParameters params){ String userOid = getOidFromParameter(params); if (userOid == null) { getSession().error(getString("PageAccountActivation.user.not found")); throw new RestartResponseException(PageLogin.class); } - + Task task = createAnonymousTask(LOAD_USER); OperationResult result = new OperationResult(LOAD_USER); - + return runPrivileged(new Producer() { - + @Override public UserType run() { Collection> options = SelectorOptions.createCollection(UserType.F_LINK_REF, GetOperationOptions.createResolve()); return WebModelServiceUtils.loadObject(UserType.class, userOid, options, PageAccountActivation.this, task, result).asObjectable(); } }); - - + + } - + private void initLayout(){ WebMarkupContainer activationContainer= new WebMarkupContainer(ID_ACTIVATION_CONTAINER); activationContainer.setOutputMarkupId(true); @@ -145,35 +145,35 @@ private void initLayout(){ public boolean isVisible() { return !activated; } - + }); - + Form form = new Form<>(ID_MAIN_FORM); activationContainer.add(form); - + Label usernamePanel = new Label(ID_NAME, createStringResource("PageAccountActivation.activate.accounts.label", new PropertyModel<>(userModel, "name.orig"))); usernamePanel.add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; - + @Override public boolean isEnabled() { return false; } }); form.add(usernamePanel); - + PasswordTextField passwordPanel = new PasswordTextField(ID_PASSWORD, Model.of(new String())); form.add(passwordPanel); - + AjaxSubmitButton confirmPasswrod = new AjaxSubmitButton(ID_CONFIRM) { private static final long serialVersionUID = 1L; - + @Override protected void onSubmit(AjaxRequestTarget target, Form form) { propagatePassword(target, form); } - + @Override protected void onError(AjaxRequestTarget target, Form form) { @@ -181,25 +181,25 @@ protected void onError(AjaxRequestTarget target, target.add(getFeedbackPanel()); } }; - + form.add(confirmPasswrod); - + WebMarkupContainer confirmationContainer = new WebMarkupContainer(ID_CONFIRMATION_CONTAINER); confirmationContainer.setOutputMarkupId(true); confirmationContainer.add(new VisibleEnableBehaviour() { - + private static final long serialVersionUID = 1L; - + @Override public boolean isVisible() { return activated; } }); - + add(confirmationContainer); - + AjaxLink linkToLogin = new AjaxLink(ID_LINK_TO_LOGIN) { - + private static final long serialVersionUID = 1L; @Override @@ -208,11 +208,11 @@ public void onClick(AjaxRequestTarget target) { } }; confirmationContainer.add(linkToLogin); - + RepeatingView activatedShadows = new RepeatingView(ID_ACTIVATED_SHADOWS); confirmationContainer.add(activatedShadows); List shadowsToActivate = getShadowsToActivate(); - + if (shadowsToActivate.isEmpty()) { LOGGER.error("No accounts to validate for user {}", userModel.getObject()); getSession().warn(getString("PageAccountActivation.nothing.to.activate")); @@ -221,37 +221,37 @@ public void onClick(AjaxRequestTarget target) { for (ShadowType shadow : shadowsToActivate) { Label shadowDesc = new Label(activatedShadows.newChildId(), WebComponentUtil.getName(shadow) + " on resource " + WebComponentUtil.getName(shadow.getResourceRef())); activatedShadows.add(shadowDesc); - + } - - + + } - + private String getOidFromParameter(PageParameters params){ - + if (params == null || params.isEmpty()) { LOGGER.error("No page paraeters found for account activation. No user to activate his/her accounts"); return null; } - + StringValue userValue = params.get(SchemaConstants.USER_ID); if (userValue == null || userValue.isEmpty()) { LOGGER.error("No user defined in the page parameter. Expected user=? attribute filled but didmn't find one."); return null; } - + return userValue.toString(); - + } - + private void propagatePassword(AjaxRequestTarget target, Form form) { - + List shadowsToActivate = getShadowsToActivate(); - + PasswordTextField passwordPanel = (PasswordTextField) form.get(createComponentPath(ID_PASSWORD)); String value = passwordPanel.getModelObject(); - + ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_GUI_USER_URI); UsernamePasswordAuthenticationToken token; try { @@ -268,16 +268,16 @@ private void propagatePassword(AjaxRequestTarget target, } ProtectedStringType passwordValue = new ProtectedStringType(); passwordValue.setClearValue(value); - + Collection> passwordDeltas = new ArrayList<>(shadowsToActivate.size()); for (ShadowType shadow : shadowsToActivate) { ObjectDelta shadowDelta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, shadow.getOid(), SchemaConstants.PATH_PASSWORD_VALUE, getPrismContext(), passwordValue); shadowDelta.addModificationReplaceProperty(ShadowType.F_LIFECYCLE_STATE, SchemaConstants.LIFECYCLE_PROPOSED); passwordDeltas.add(shadowDelta); } - + OperationResult result = runPrivileged(new Producer() { - + @Override public OperationResult run() { OperationResult result = new OperationResult(OPERATION_ACTIVATE_SHADOWS); @@ -286,9 +286,9 @@ public OperationResult run() { return result; } }); - + result.recomputeStatus(); - + if (!result.isSuccess()) { getSession().error(getString("PageAccountActivation.account.activation.failed")); LOGGER.error("Failed to acitvate accounts, reason: {} ", result.getMessage()); @@ -298,12 +298,12 @@ public OperationResult run() { target.add(getFeedbackPanel()); activated = true; } - + target.add(PageAccountActivation.this); - - + + } - + private List getShadowsToActivate(){ UserType userType = userModel.getObject(); List shadowsToActivate = userType.getLink(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageSelfConsents.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageSelfConsents.java index f66e3c57a3f..6c26843c0cd 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageSelfConsents.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageSelfConsents.java @@ -42,7 +42,7 @@ @PageDescriptor( urls = { @Url(mountUrl = "/self/consents") - }, + }, action = { @AuthorizationAction(actionUri = PageSelf.AUTH_SELF_ALL_URI, label = PageSelf.AUTH_SELF_ALL_LABEL, @@ -53,27 +53,27 @@ public class PageSelfConsents extends PageBase{ private static final long serialVersionUID = 1L; - + private LoadableModel> consentModel; private static final String DOT_CLASS = PageSelfConsents.class.getSimpleName() + "."; private static final String OPERATION_LOAD_USER = DOT_CLASS + "loadUserSelf"; - + private static final String ID_CONSENTS = "consents"; - + public PageSelfConsents() { - + consentModel = new LoadableModel>() { - + private static final long serialVersionUID = 1L; @Override protected List load() { MidPointPrincipal principal = SecurityUtils.getPrincipalUser(); - + if (principal == null) { return null; } - + Task task = createSimpleTask(OPERATION_LOAD_USER); OperationResult result = task.getResult(); PrismObject userSelf = WebModelServiceUtils.loadObject(UserType.class, principal.getOid(), PageSelfConsents.this, task, result); @@ -81,7 +81,7 @@ protected List load() { if (assignmentContainer == null || assignmentContainer.isEmpty()) { return new ArrayList<>(); } - + Collection assignments = assignmentContainer.getRealValues(); return assignments.stream() .filter(a -> a.getTargetRef()!= null && QNameUtil.match(a.getTargetRef().getRelation(), SchemaConstants.ORG_CONSENT)) @@ -89,12 +89,12 @@ protected List load() { .collect(Collectors.toList()); } }; - + initLayout(); } - + private void initLayout() { - + RepeatingView consents = new RepeatingView(ID_CONSENTS); consents.setOutputMarkupId(true); for (AssignmentDto assignmentDto : consentModel.getObject()) { @@ -102,14 +102,14 @@ private void initLayout() { consentPanel.setOutputMarkupId(true); consents.add(consentPanel); } - + add(consents); - + } - - - - - + + + + + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageSelfCredentials.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageSelfCredentials.java index 5a633a5c1ed..72b1e751199 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageSelfCredentials.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageSelfCredentials.java @@ -26,7 +26,7 @@ protected boolean isCheckOldPassword() { return (getModelObject().getPasswordChangeSecurity() == null) || (getModelObject().getPasswordChangeSecurity() != null && getModelObject().getPasswordChangeSecurity().equals(PasswordChangeSecurityType.OLD_PASSWORD)); } - + @Override protected void finishChangePassword(OperationResult result, AjaxRequestTarget target) { if (!WebComponentUtil.isSuccessOrHandledError(result)) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageSelfDashboard.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageSelfDashboard.java index b717ccd78a1..e215df390c1 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageSelfDashboard.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageSelfDashboard.java @@ -107,7 +107,7 @@ public class PageSelfDashboard extends PageSelf { private static final String ID_REQUESTS_PANEL = "requestPanel"; private static final String ID_ACCOUNTS = "accounts"; private static final String ID_ASSIGNMENTS = "assignments"; - + private static final String DOT_CLASS = PageSelfDashboard.class.getName() + "."; private static final String OPERATION_LOAD_WORK_ITEMS = DOT_CLASS + "loadWorkItems"; private static final String OPERATION_LOAD_REQUESTS = DOT_CLASS + "loadRequests"; @@ -115,7 +115,7 @@ public class PageSelfDashboard extends PageSelf { private static final String OPERATION_LOAD_ASSIGNMENTS = DOT_CLASS + "loadAssignments"; private static final String OPERATION_LOAD_USER = DOT_CLASS + "loadUser"; private static final String OPERATION_GET_SYSTEM_CONFIG = DOT_CLASS + "getSystemConfiguration"; - + private static final int MAX_WORK_ITEMS = 1000; private static final int MAX_REQUESTS = 1000; @@ -247,7 +247,7 @@ protected Component getMainComponent(String markupId) { myRequestsPanel.add(new VisibleEnableBehaviour() { private static final long serialVersionUID = 1L; - + @Override public boolean isVisible() { UserInterfaceElementVisibilityType visibilityType = getComponentVisibility(PredefinedDashboardWidgetId.MY_REQUESTS); @@ -256,7 +256,7 @@ public boolean isVisible() { } }); add(myRequestsPanel); - + initMyAccounts(); initAssignments(); } @@ -361,7 +361,7 @@ private List loadLinksList() { return ((PageBase)getPage()).loadAdminGuiConfiguration().getUserDashboardLink(); } } - + private void initMyAccounts() { AsyncDashboardPanel> accounts = new AsyncDashboardPanel>(ID_ACCOUNTS, createStringResource("PageDashboard.accounts"), @@ -427,7 +427,7 @@ public boolean isVisible() { }); add(accounts); } - + private AccountCallableResult> loadAccounts() throws Exception { LOGGER.debug("Loading accounts."); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageSelfProfile.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageSelfProfile.java index 86d23ba273f..c1717a343a7 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageSelfProfile.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/PageSelfProfile.java @@ -40,7 +40,7 @@ label = "PageSelfProfile.auth.profile.label", description = "PageSelfProfile.auth.profile.description")}) public class PageSelfProfile extends PageUser { - + private static final Trace LOGGER = TraceManager.getTrace(PageSelfProfile.class); @Override 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 df17c6861b2..8e2083ee863 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 @@ -90,7 +90,7 @@ private void initLayout(final boolean oldPasswordVisible) { Label oldPasswordLabel = new Label(ID_OLD_PASSWORD_LABEL, createStringResource("PageSelfCredentials.oldPasswordLabel")); add(oldPasswordLabel); oldPasswordLabel.add(new VisibleEnableBehaviour() { - + private static final long serialVersionUID = 1L; @Override @@ -108,9 +108,9 @@ public boolean isVisible() { oldPasswordField.setResetPassword(false); add(oldPasswordField); oldPasswordField.add(new VisibleEnableBehaviour() { - + private static final long serialVersionUID = 1L; - + public boolean isVisible() { return oldPasswordVisible; }; @@ -136,7 +136,7 @@ public boolean isVisible() { AjaxLink help = new AjaxLink(ID_BUTTON_HELP) { private static final long serialVersionUID = 1L; - + @Override public void onClick(AjaxRequestTarget target) { showHelpPerformed(target); @@ -152,12 +152,12 @@ private List> initColumns() { IColumn column = new IconColumn(new Model()) { private static final long serialVersionUID = 1L; - + @Override protected IModel createIconModel(final IModel rowModel) { return new AbstractReadOnlyModel() { private static final long serialVersionUID = 1L; - + @Override public String getObject() { PasswordAccountDto item = rowModel.getObject(); @@ -184,10 +184,10 @@ public void populateItem(Item> item, String c final ImagePanel imagePanel = (ImagePanel) item.get(0); final PasswordAccountDto passwordAccountDto = rowModel.getObject(); - + imagePanel.add(new AjaxEventBehavior("click") { private static final long serialVersionUID = 1L; - + protected void onEvent(final AjaxRequestTarget target) { if (!passwordAccountDto.isMidpoint()) { if (passwordAccountDto.getCssClass().equals(PROPAGATED_ACCOUNT_ICON_CSS)) { @@ -217,9 +217,9 @@ protected void onEvent(final AjaxRequestTarget target) { } } ); - + imagePanel.add(new VisibleEnableBehaviour() { - + private static final long serialVersionUID = 1L; @Override diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/component/LinksPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/component/LinksPanel.java index 98285dff3d0..a8c36010642 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/component/LinksPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/component/LinksPanel.java @@ -45,9 +45,9 @@ public class LinksPanel extends SimplePanel> { private static final String ID_DESCRIPTION = "descriptionId"; private static final String ID_LINKS_ROW = "linksRow"; private static final String ID_LINKS_COLUMN = "linksColumn"; - + private static final String ICON_DEFAULT_CSS_CLASS = "fa fa-angle-double-right"; - + private static final Trace LOGGER = TraceManager.getTrace(LinksPanel.class); IModel> model; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/MidPointApplication.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/MidPointApplication.java index 315027d9056..2e1398591cb 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/MidPointApplication.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/MidPointApplication.java @@ -16,36 +16,36 @@ package com.evolveum.midpoint.web.security; -import java.io.File; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.net.URI; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - +import com.evolveum.midpoint.common.configuration.api.MidpointConfiguration; +import com.evolveum.midpoint.gui.api.page.PageBase; +import com.evolveum.midpoint.gui.api.util.WebComponentUtil; +import com.evolveum.midpoint.model.api.*; import com.evolveum.midpoint.model.common.SystemObjectCache; +import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.crypto.Protector; import com.evolveum.midpoint.prism.match.MatchingRuleRegistry; import com.evolveum.midpoint.repo.api.RepositoryService; +import com.evolveum.midpoint.repo.common.expression.ExpressionFactory; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.SchemaDebugUtil; +import com.evolveum.midpoint.security.api.AuthorizationConstants; import com.evolveum.midpoint.security.api.SecurityEnforcer; +import com.evolveum.midpoint.task.api.TaskManager; import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.exception.SystemException; +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.DescriptorLoader; +import com.evolveum.midpoint.web.component.GuiComponents; +import com.evolveum.midpoint.web.page.admin.home.PageDashboard; import com.evolveum.midpoint.web.page.error.*; +import com.evolveum.midpoint.web.page.login.PageLogin; +import com.evolveum.midpoint.web.page.self.PageSelfDashboard; +import com.evolveum.midpoint.web.resource.img.ImgResources; +import com.evolveum.midpoint.web.util.Utf8BundleStringResourceLoader; import com.evolveum.midpoint.wf.api.WorkflowManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType; import org.apache.commons.configuration.Configuration; @@ -54,10 +54,6 @@ import org.apache.wicket.authroles.authentication.AbstractAuthenticatedWebSession; import org.apache.wicket.authroles.authentication.AuthenticatedWebApplication; import org.apache.wicket.core.request.mapper.MountedMapper; -import org.apache.wicket.core.util.objects.checker.CheckingObjectOutputStream; -import org.apache.wicket.core.util.objects.checker.IObjectChecker; -import org.apache.wicket.core.util.objects.checker.NotDetachedModelChecker; -import org.apache.wicket.core.util.objects.checker.ObjectSerializationChecker; import org.apache.wicket.markup.head.PriorityFirstComparator; import org.apache.wicket.markup.html.SecurePackageResourceGuard; import org.apache.wicket.markup.html.WebPage; @@ -66,39 +62,25 @@ import org.apache.wicket.request.resource.PackageResourceReference; import org.apache.wicket.request.resource.SharedResourceReference; import org.apache.wicket.resource.loader.IStringResourceLoader; -import org.apache.wicket.serialize.java.JavaSerializer; import org.apache.wicket.settings.ApplicationSettings; import org.apache.wicket.settings.ResourceSettings; import org.apache.wicket.spring.injection.annot.SpringComponentInjector; import org.apache.wicket.util.lang.Bytes; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.stereotype.Component; -import com.evolveum.midpoint.common.configuration.api.MidpointConfiguration; -import com.evolveum.midpoint.repo.common.expression.ExpressionFactory; -import com.evolveum.midpoint.gui.api.page.PageBase; -import com.evolveum.midpoint.gui.api.util.WebComponentUtil; -import com.evolveum.midpoint.model.api.ModelAuditService; -import com.evolveum.midpoint.model.api.ModelInteractionService; -import com.evolveum.midpoint.model.api.ModelService; -import com.evolveum.midpoint.model.api.TaskService; -import com.evolveum.midpoint.model.api.WorkflowService; -import com.evolveum.midpoint.prism.PrismContext; -import com.evolveum.midpoint.prism.crypto.Protector; -import com.evolveum.midpoint.security.api.AuthorizationConstants; -import com.evolveum.midpoint.task.api.TaskManager; -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.DescriptorLoader; -import com.evolveum.midpoint.web.component.GuiComponents; -import com.evolveum.midpoint.web.page.admin.home.PageDashboard; -import com.evolveum.midpoint.web.page.login.PageLogin; -import com.evolveum.midpoint.web.page.self.PageSelfDashboard; -import com.evolveum.midpoint.web.resource.img.ImgResources; -import com.evolveum.midpoint.web.util.Utf8BundleStringResourceLoader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.net.URI; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.*; /** * @author lazyman @@ -115,7 +97,7 @@ public class MidPointApplication extends AuthenticatedWebApplication { public static final List AVAILABLE_LOCALES; - private static final String LOCALIZATION_DESCRIPTOR = "/localization/locale.properties"; + private static final String LOCALIZATION_DESCRIPTOR = "localization/locale.properties"; private static final String PROP_NAME = ".name"; private static final String PROP_FLAG = ".flag"; @@ -128,65 +110,32 @@ public class MidPointApplication extends AuthenticatedWebApplication { } static { + String midpointHome = System.getProperty(WebApplicationConfiguration.MIDPOINT_HOME); + File file = new File(midpointHome, LOCALIZATION_DESCRIPTOR); + + Resource[] localeDescriptorResources = new Resource[]{ + new FileSystemResource(file), + new ClassPathResource(LOCALIZATION_DESCRIPTOR) + }; + List locales = new ArrayList<>(); - try { - ClassLoader classLoader = MidPointApplication.class.getClassLoader(); - Enumeration urls = classLoader.getResources(LOCALIZATION_DESCRIPTOR); - while (urls.hasMoreElements()) { - final URL url = urls.nextElement(); - LOGGER.debug("Found localization descriptor {}.", new Object[]{url.toString()}); - - Properties properties = new Properties(); - Reader reader = null; - try { - reader = new InputStreamReader(url.openStream(), "utf-8"); - properties.load(reader); - - Map> localeMap = new HashMap<>(); - Set keys = (Set) properties.keySet(); - for (String key : keys) { - String[] array = key.split("\\."); - if (array.length != 2) { - continue; - } - - String locale = array[0]; - Map map = localeMap.get(locale); - if (map == null) { - map = new HashMap<>(); - localeMap.put(locale, map); - } - - map.put(key, properties.getProperty(key)); - } - - for (String key : localeMap.keySet()) { - Map localeDefinition = localeMap.get(key); - if (!localeDefinition.containsKey(key + PROP_NAME) - || !localeDefinition.containsKey(key + PROP_FLAG)) { - continue; - } - - LocaleDescriptor descriptor = new LocaleDescriptor( - localeDefinition.get(key + PROP_NAME), - localeDefinition.get(key + PROP_FLAG), - localeDefinition.get(key + PROP_DEFAULT), - WebComponentUtil.getLocaleFromString(key) - ); - locales.add(descriptor); - } - } catch (Exception ex) { - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load localization", ex); - } finally { - IOUtils.closeQuietly(reader); - } + for (Resource resource : localeDescriptorResources) { + if (!resource.isReadable()) { + continue; } - Collections.sort(locales); - } catch (Exception ex) { - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load locales", ex); + try { + LOGGER.debug("Found localization descriptor {}.", new Object[]{resource.getURL()}); + locales = loadLocaleDescriptors(resource); + + break; + } catch (Exception ex) { + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load localization", ex); + } } + Collections.sort(locales); + AVAILABLE_LOCALES = Collections.unmodifiableList(locales); } @@ -198,24 +147,24 @@ public class MidPointApplication extends AuthenticatedWebApplication { transient TaskService taskService; @Autowired transient PrismContext prismContext; - @Autowired - transient ExpressionFactory expressionFactory; + @Autowired + transient ExpressionFactory expressionFactory; @Autowired transient TaskManager taskManager; @Autowired transient ModelAuditService auditService; - @Autowired - transient private RepositoryService repositoryService; // temporary + @Autowired + transient private RepositoryService repositoryService; // temporary @Autowired transient private WorkflowService workflowService; - @Autowired - transient private WorkflowManager workflowManager; + @Autowired + transient private WorkflowManager workflowManager; @Autowired transient MidpointConfiguration configuration; @Autowired transient Protector protector; - @Autowired - transient MatchingRuleRegistry matchingRuleRegistry; + @Autowired + transient MatchingRuleRegistry matchingRuleRegistry; @Autowired transient SecurityEnforcer securityEnforcer; @Autowired @@ -258,14 +207,17 @@ public void init() { SecurePackageResourceGuard guard = (SecurePackageResourceGuard) resourceSettings.getPackageResourceGuard(); guard.addPattern("+*.woff2"); + URL url = buildMidpointHomeLocalizationFolderUrl(); + ClassLoader classLoader = new URLClassLoader(new URL[]{url}); + List resourceLoaders = resourceSettings.getStringResourceLoaders(); - resourceLoaders.add(0, new Utf8BundleStringResourceLoader("localization/Midpoint")); - resourceLoaders.add(1, new Utf8BundleStringResourceLoader(SchemaConstants.SCHEMA_LOCALIZATION_PROPERTIES_RESOURCE_BASE_PATH)); + resourceLoaders.add(0, new Utf8BundleStringResourceLoader("Midpoint", classLoader)); + resourceLoaders.add(1, new Utf8BundleStringResourceLoader(SchemaConstants.BUNDLE_NAME, classLoader)); + resourceLoaders.add(2, new Utf8BundleStringResourceLoader("localization/Midpoint")); + resourceLoaders.add(3, new Utf8BundleStringResourceLoader(SchemaConstants.SCHEMA_LOCALIZATION_PROPERTIES_RESOURCE_BASE_PATH)); resourceSettings.setThrowExceptionOnMissingResource(false); getMarkupSettings().setStripWicketTags(true); -// getMarkupSettings().setDefaultBeforeDisabledLink(""); -// getMarkupSettings().setDefaultAfterDisabledLink(""); if (RuntimeConfigurationType.DEVELOPMENT.equals(getConfigurationType())) { getDebugSettings().setAjaxDebugModeEnabled(true); @@ -294,6 +246,66 @@ public void init() { new DescriptorLoader().loadData(this); } + private static List loadLocaleDescriptors(Resource resource) throws IOException { + List locales = new ArrayList<>(); + + Properties properties = new Properties(); + Reader reader = null; + try { + reader = new InputStreamReader(resource.getInputStream(), "utf-8"); + properties.load(reader); + + Map> localeMap = new HashMap<>(); + Set keys = (Set) properties.keySet(); + for (String key : keys) { + String[] array = key.split("\\."); + if (array.length != 2) { + continue; + } + + String locale = array[0]; + Map map = localeMap.get(locale); + if (map == null) { + map = new HashMap<>(); + localeMap.put(locale, map); + } + + map.put(key, properties.getProperty(key)); + } + + for (String key : localeMap.keySet()) { + Map localeDefinition = localeMap.get(key); + if (!localeDefinition.containsKey(key + PROP_NAME) + || !localeDefinition.containsKey(key + PROP_FLAG)) { + continue; + } + + LocaleDescriptor descriptor = new LocaleDescriptor( + localeDefinition.get(key + PROP_NAME), + localeDefinition.get(key + PROP_FLAG), + localeDefinition.get(key + PROP_DEFAULT), + WebComponentUtil.getLocaleFromString(key) + ); + locales.add(descriptor); + } + } finally { + IOUtils.closeQuietly(reader); + } + + return locales; + } + + private URL buildMidpointHomeLocalizationFolderUrl() { + String midpointHome = System.getProperty(WebApplicationConfiguration.MIDPOINT_HOME); + + File file = new File(midpointHome, "localization"); + try { + return file.toURI().toURL(); + } catch (IOException ex) { + throw new SystemException("Couldn't transform localization folder file to url", ex); + } + } + private void initializeDevelopmentSerializers() { // JavaSerializer javaSerializer = new JavaSerializer( getApplicationKey() ) { // @Override @@ -307,10 +319,10 @@ private void initializeDevelopmentSerializers() { // } // }; // getFrameworkSettings().setSerializer( javaSerializer ); - - } - private void mountFiles(String path, Class clazz) { + } + + private void mountFiles(String path, Class clazz) { try { List list = new ArrayList<>(); String packagePath = clazz.getPackage().getName().replace('.', '/'); @@ -359,9 +371,9 @@ public ModelAuditService getAuditService() { return auditService; } - public RepositoryService getRepositoryService() { - return repositoryService; - } + public RepositoryService getRepositoryService() { + return repositoryService; + } public TaskService getTaskService() { return taskService; @@ -372,8 +384,8 @@ public PrismContext getPrismContext() { } public ExpressionFactory getExpressionFactory() { - return expressionFactory; - } + return expressionFactory; + } public Protector getProtector() { return protector; @@ -393,11 +405,11 @@ public WorkflowService getWorkflowService() { return workflowService; } - public WorkflowManager getWorkflowManager() { - return workflowManager; - } + public WorkflowManager getWorkflowManager() { + return workflowManager; + } - public ModelInteractionService getModelInteractionService() { + public ModelInteractionService getModelInteractionService() { return modelInteractionService; } @@ -425,9 +437,9 @@ public static Locale getDefaultLocale() { return new Locale("en", "US"); } - public MatchingRuleRegistry getMatchingRuleRegistry() { - return matchingRuleRegistry; - } + public MatchingRuleRegistry getMatchingRuleRegistry() { + return matchingRuleRegistry; + } public SystemConfigurationType getSystemConfiguration() throws SchemaException { PrismObject config = systemObjectCache.getSystemConfiguration(new OperationResult("dummy")); @@ -444,18 +456,6 @@ public SystemConfigurationType getSystemConfigurationIfAvailable() { } } - private static class ResourceFileFilter implements FilenameFilter { - - @Override - public boolean accept(File parent, String name) { - if (name.endsWith("png") || name.endsWith("gif")) { - return true; - } - - return false; - } - } - public static MidPointApplication get() { return (MidPointApplication) WebApplication.get(); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/MidPointAuthWebSession.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/MidPointAuthWebSession.java index bee41148135..77ed718bc52 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/MidPointAuthWebSession.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/MidPointAuthWebSession.java @@ -118,7 +118,7 @@ public String debugDump(int indent) { DebugUtil.debugDumpWithLabel(sb, "sessionStorage", sessionStorage, indent+1); return sb.toString(); } - + public String dumpSizeEstimates(int indent) { StringBuilder sb = new StringBuilder(); DebugUtil.dumpObjectSizeEstimate(sb, "MidPointAuthWebSession", this, indent); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/MidPointAuthenticationProvider.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/MidPointAuthenticationProvider.java index d019510a201..2a065fb3f2e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/MidPointAuthenticationProvider.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/MidPointAuthenticationProvider.java @@ -39,18 +39,18 @@ public class MidPointAuthenticationProvider implements AuthenticationProvider { private static final Trace LOGGER = TraceManager.getTrace(MidPointAuthenticationProvider.class); - + @Autowired private transient AuthenticationEvaluator passwordAuthenticationEvaluator; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { - + String enteredUsername = (String) authentication.getPrincipal(); LOGGER.trace("Authenticating username '{}'", enteredUsername); - + ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_GUI_USER_URI); - + Authentication token; if (authentication instanceof UsernamePasswordAuthenticationToken) { String enteredPassword = (String) authentication.getCredentials(); @@ -63,7 +63,7 @@ public Authentication authenticate(Authentication authentication) throws Authent } MidPointPrincipal principal = (MidPointPrincipal)token.getPrincipal(); - + LOGGER.debug("User '{}' authenticated ({}), authorities: {}", authentication.getPrincipal(), authentication.getClass().getSimpleName(), principal.getAuthorities()); return token; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/MidPointObjectChecker.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/MidPointObjectChecker.java index bd2cf76ab72..22feed5b6df 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/MidPointObjectChecker.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/MidPointObjectChecker.java @@ -35,31 +35,31 @@ * */ public class MidPointObjectChecker implements IObjectChecker { - + private static final Trace LOGGER = TraceManager.getTrace(MidPointObjectChecker.class); - + private String label; public MidPointObjectChecker() { this(null); } - + public MidPointObjectChecker(String label) { super(); this.label = label; } - + /* (non-Javadoc) * @see org.apache.wicket.core.util.objects.checker.IObjectChecker#check(java.lang.Object) */ @SuppressWarnings("unchecked") @Override public Result check(Object object) { - + if (label != null) { LOGGER.info("CHECK: {}: {}", label, object); } - + if (object instanceof PrismObject) { return checkObject((PrismObject)object); } else if (object instanceof ObjectType) { @@ -70,25 +70,25 @@ public Result check(Object object) { // } else if (object instanceof Element) { // return new Result( Result.Status.FAILURE, "Storage of DOM elements not allowed: "+object); //// LOGGER.warn("Attempt to serialize DOM element: {}", DOMUtil.getQName((Element)object)); - + // JAXBElement: expression evaluator in expressions, it is JAXBElement even in prism objects // } else if (object instanceof JAXBElement) { // return new Result( Result.Status.FAILURE, "Storage of JAXB elements not allowed: "+object); // LOGGER.warn("Attempt to serialize DOM element: {}", DOMUtil.getQName((Element)object)); } - + return Result.SUCCESS; } - - + + private Result checkObject(PrismObject object) { - + LOGGER.info("Check for serialization of prism object: {}", object); // if (object.canRepresent(ResourceType.class)) { // return new Result( Result.Status.FAILURE, "Storage of ResourceType objects not allowed: "+object); // } - + return Result.SUCCESS; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/WebApplicationConfiguration.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/WebApplicationConfiguration.java index 945da53d0cf..810aded4773 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/WebApplicationConfiguration.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/WebApplicationConfiguration.java @@ -30,7 +30,8 @@ public class WebApplicationConfiguration implements Serializable { private static final Trace LOGGER = TraceManager.getTrace(WebApplicationConfiguration.class); - private static final String MIDPOINT_HOME = "midpoint.home"; //todo move somewhere + public static final String MIDPOINT_HOME = "midpoint.home"; //todo move somewhere + private String importFolder; private String exportFolder; private int progressRefreshInterval; // how often to refresh 'progress table' (in milliseconds; 0 means this feature is disabled) @@ -55,7 +56,7 @@ public WebApplicationConfiguration(Configuration config) { importFolder = "."; } } - + if (exportFolder == null) { if (StringUtils.isNotEmpty(midpointHome)) { exportFolder = midpointHome + "/tmp"; @@ -68,7 +69,7 @@ public WebApplicationConfiguration(Configuration config) { public String getImportFolder() { return importFolder; } - + public String getExportFolder() { return exportFolder; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/ConfigurationStorage.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/ConfigurationStorage.java index 7eb35e7dd7f..923b67f35f3 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/ConfigurationStorage.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/ConfigurationStorage.java @@ -38,7 +38,7 @@ public class ConfigurationStorage implements PageStorage { public Search getSearch() { return debugSearchDto.getSearch(); } - + @Override public void setSearch(Search search) { debugSearchDto.setSearch(search); @@ -47,7 +47,7 @@ public void setSearch(Search search) { public void setDebugSearchDto(DebugSearchDto debugSearchDto) { this.debugSearchDto = debugSearchDto; } - + public DebugSearchDto getDebugSearchDto() { return debugSearchDto; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/PageStorage.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/PageStorage.java index d3e292d4a16..0fc8dcfd21f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/PageStorage.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/PageStorage.java @@ -26,13 +26,13 @@ * @author shood * */ public interface PageStorage extends Serializable, DebugDumpable { - + public Search getSearch(); - + public void setSearch(Search search); - + public void setPaging(ObjectPaging paging); - + public ObjectPaging getPaging(); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/ReportsStorage.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/ReportsStorage.java index a5d74a74ca0..8def27a5107 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/ReportsStorage.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/ReportsStorage.java @@ -95,7 +95,7 @@ public ReportOutputSearchDto getReportOutputSearch() { public void setReportOutputSearch(ReportOutputSearchDto reportOutputSearch) { this.reportOutputSearch = reportOutputSearch; } - + @Override public String debugDump() { return debugDump(0); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/ResourceContentStorage.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/ResourceContentStorage.java index 78e2acd61f5..ac96bf290c3 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/ResourceContentStorage.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/ResourceContentStorage.java @@ -23,19 +23,19 @@ public class ResourceContentStorage implements PageStorage { private static final long serialVersionUID = 1L; - + private ResourceContentSearchDto contentSearch; private Boolean resourceSearch = Boolean.FALSE; private Search attributeSearch; private ObjectPaging paging; - + private ShadowKindType kind; - + public ResourceContentStorage(ShadowKindType kind) { this.kind = kind; } - + @Override public Search getSearch() { return attributeSearch; @@ -57,25 +57,25 @@ public void setResourceSearch(Boolean resourceSearch) { @Override public void setPaging(ObjectPaging paging) { this.paging = paging; - + } @Override public ObjectPaging getPaging() { return paging; } - + public ResourceContentSearchDto getContentSearch() { if (contentSearch == null) { return new ResourceContentSearchDto(kind); } return contentSearch; } - + public void setContentSearch(ResourceContentSearchDto contentSearch) { this.contentSearch = contentSearch; } - + @Override public String debugDump() { return debugDump(0); @@ -93,5 +93,5 @@ public String debugDump(int indent) { DebugUtil.debugDumpWithLabel(sb, "kind", kind==null?null:kind.toString(), indent+1); return sb.toString(); } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/ResourcesStorage.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/ResourcesStorage.java index 2f78b6906e2..543ec839038 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/ResourcesStorage.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/ResourcesStorage.java @@ -40,7 +40,7 @@ public class ResourcesStorage implements PageStorage { * DTO used for search in {@link com.evolveum.midpoint.web.page.admin.resources.content.PageContentAccounts} */ // private AccountContentSearchDto accountContentSearch; - + private ResourceContentSearchDto resourceContentSearch; /** @@ -68,7 +68,7 @@ public void setPaging(ObjectPaging resourcePaging) { this.resourcePaging = resourcePaging; } - + public ObjectPaging getAccountContentPaging() { return accountContentPaging; } @@ -76,11 +76,11 @@ public ObjectPaging getAccountContentPaging() { public void setAccountContentPaging(ObjectPaging accountContentPaging) { this.accountContentPaging = accountContentPaging; } - + public ResourceContentSearchDto getResourceContentSearch() { return resourceContentSearch; } - + public void setResourceContentSearch(ResourceContentSearchDto resourceContentSearch) { this.resourceContentSearch = resourceContentSearch; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/RoleMembersStorage.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/RoleMembersStorage.java index 219f3b5eedc..bbfa176bbb4 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/RoleMembersStorage.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/RoleMembersStorage.java @@ -24,7 +24,7 @@ public class RoleMembersStorage implements PageStorage{ private static final long serialVersionUID = 1L; private RoleMemberSearchDto roleMemberSearch; - + private Search search; /** @@ -49,17 +49,17 @@ public ObjectPaging getPaging() { public void setPaging(ObjectPaging rolesPaging) { this.rolesPaging = rolesPaging; } - + @Override public Search getSearch() { return search; } - + @Override public void setSearch(Search search) { this.search = search; } - + @Override public String debugDump() { return debugDump(0); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/ServicesStorage.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/ServicesStorage.java index 7c8d66a2649..68df354490e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/ServicesStorage.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/ServicesStorage.java @@ -24,7 +24,7 @@ public class ServicesStorage implements PageStorage{ private Search servicesSearch; private ObjectPaging servicesPaging; - + @Override public Search getSearch() { return servicesSearch; @@ -38,7 +38,7 @@ public void setSearch(Search search) { @Override public void setPaging(ObjectPaging paging) { this.servicesPaging = paging; - + } @Override diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/TasksStorage.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/TasksStorage.java index 9945995f164..3e693c7d0a6 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/TasksStorage.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/TasksStorage.java @@ -35,7 +35,7 @@ public class TasksStorage implements PageStorage{ * Paging DTO used in table on page {@link com.evolveum.midpoint.web.page.admin.server.PageTasks} * */ private ObjectPaging tasksPaging; - + private Search search; public TasksSearchDto getTasksSearch() { @@ -55,16 +55,16 @@ public ObjectPaging getPaging() { public void setPaging(ObjectPaging tasksPaging) { this.tasksPaging = tasksPaging; } - + @Override public Search getSearch() { return search; } - + @Override public void setSearch(Search search) { this.search = search; - + } @Override diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/UserProfileStorage.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/UserProfileStorage.java index efdd8181c36..87277836c91 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/UserProfileStorage.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/UserProfileStorage.java @@ -32,7 +32,7 @@ */ public class UserProfileStorage implements Serializable, DebugDumpable { - + private static final long serialVersionUID = 1L; public static final int DEFAULT_PAGING_SIZE = 20; @@ -115,5 +115,5 @@ public String debugDump(int indent) { DebugUtil.debugDumpWithLabel(sb, "tables", tables, indent+1); return sb.toString(); } - + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/UsersStorage.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/UsersStorage.java index 06b8060f9ba..60c1ae652ef 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/UsersStorage.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/session/UsersStorage.java @@ -33,7 +33,7 @@ public class UsersStorage implements PageStorage, DebugDumpable, OrgTreeStateStorage { /** - * + * */ private static final long serialVersionUID = 1L; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/DateValidator.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/DateValidator.java index 52098f53c08..7e80eb4fad0 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/DateValidator.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/DateValidator.java @@ -30,7 +30,7 @@ public class DateValidator extends AbstractFormValidator { private static final long serialVersionUID = 1L; - + private ItemPath identifier; private DateTimeField dateFrom; private DateTimeField dateTo; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/MidPointProfilingServletFilter.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/MidPointProfilingServletFilter.java index 9b94fc18e92..cb9ec9eb4ef 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/MidPointProfilingServletFilter.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/MidPointProfilingServletFilter.java @@ -71,7 +71,7 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha LOGGER.error("Encountered exception: {}: {}", e.getClass().getName(), e.getMessage(), e); throw e; } - + long elapsedTime = System.nanoTime() - startTime; if(request instanceof HttpServletRequest){ diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/StringResourceChoiceRenderer.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/StringResourceChoiceRenderer.java index 99da1d1684f..421ae579138 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/StringResourceChoiceRenderer.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/StringResourceChoiceRenderer.java @@ -45,7 +45,7 @@ public Object getDisplayValue(String object) { public String getIdValue(String object, int index) { return String.valueOf(index); } - + @Override public String getObject(String id, IModel> choices) { return StringUtils.isNotBlank(id) ? choices.getObject().get(Integer.parseInt(id)) : null; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/TaskOperationUtils.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/TaskOperationUtils.java index f3a0e522f4a..f949accd352 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/TaskOperationUtils.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/TaskOperationUtils.java @@ -12,12 +12,12 @@ import com.evolveum.midpoint.web.page.admin.server.PageTasks; public class TaskOperationUtils { - + private static final String DOT_CLASS = TaskOperationUtils.class.getName() + "."; private static final String OPERATION_SUSPEND_TASKS = DOT_CLASS + "suspendTask"; private static final String OPERATION_RESUME_TASK = DOT_CLASS + "resumeTask"; private static final String OPERATION_RUN_NOW_TASK = DOT_CLASS + "runNowTask"; - + public static OperationResult suspendPerformed(TaskService taskService, Collection oids) { OperationResult result = new OperationResult(OPERATION_SUSPEND_TASKS); try { @@ -37,7 +37,7 @@ public static OperationResult suspendPerformed(TaskService taskService, Collecti } return result; - + } public static OperationResult resumePerformed(TaskService taskService, List oids) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/Utf8BundleStringResourceLoader.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/Utf8BundleStringResourceLoader.java index 7593202696b..63946c402da 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/Utf8BundleStringResourceLoader.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/Utf8BundleStringResourceLoader.java @@ -38,8 +38,15 @@ public class Utf8BundleStringResourceLoader implements IStringResourceLoader { private final String bundleName; + private ClassLoader classLoader; + public Utf8BundleStringResourceLoader(String bundleName) { + this(bundleName, null); + } + + public Utf8BundleStringResourceLoader(String bundleName, ClassLoader classLoader) { this.bundleName = bundleName; + this.classLoader = classLoader; } @Override @@ -55,8 +62,16 @@ public String loadStringResource(Component component, String key, Locale locale, ResourceBundle.Control control = new UTF8Control(); try { - return ResourceBundle.getBundle(bundleName, locale, control).getString(key); + if (classLoader == null) { + return ResourceBundle.getBundle(bundleName, locale, control).getString(key); + } else { + return ResourceBundle.getBundle(bundleName, locale, classLoader, control).getString(key); + } } catch (MissingResourceException ex) { + if (classLoader != null) { + return null; + } + try { return ResourceBundle.getBundle(bundleName, locale, Thread.currentThread().getContextClassLoader(), control).getString(key); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/validation/MidpointFormValidatorRegistry.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/validation/MidpointFormValidatorRegistry.java index 6f1de166884..d6db8d6c912 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/validation/MidpointFormValidatorRegistry.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/util/validation/MidpointFormValidatorRegistry.java @@ -26,7 +26,7 @@ */ @Component public class MidpointFormValidatorRegistry { - + private Collection validators = new ArrayList<>(); public void registerValidator(MidpointFormValidator validator) { @@ -36,5 +36,5 @@ public void registerValidator(MidpointFormValidator validator) { public Collection getValidators() { return validators; } - + } diff --git a/gui/admin-gui/src/main/resources/localization/Midpoint.properties b/gui/admin-gui/src/main/resources/localization/Midpoint.properties index c7263cbefbf..ad7c08d66c3 100644 --- a/gui/admin-gui/src/main/resources/localization/Midpoint.properties +++ b/gui/admin-gui/src/main/resources/localization/Midpoint.properties @@ -3756,4 +3756,12 @@ ObjectPolicyConfigurationEditor.conflictResolution=(conflict resolution) PageSelfConsents.title=Consents SelfConsentPanel.button.revoke=Revoke SelfConsentPanel.button.agree=Agree -PageAdmin.menu.consent=Consents \ No newline at end of file +PageAdmin.menu.consent=Consents +MultiValueExpandablePanel.deleteConfirmationMessage=Do you really want to delete {0} item? +PolicyRulePropertiesPanel.exclusionConstraints=Add exclusion +PolicyRulePropertiesPanel.minAssigneesConstraints=minAssignees +PolicyRulePropertiesPanel.maxAssigneesConstraints=maxAssignees +PolicyRulePropertiesPanel.modification=modification +PolicyRulePropertiesPanel.assignmentConstraints=assignment +PolicyRulePropertiesPanel.timeValidityConstraints=timeValidity +PolicyRulePropertiesPanel.situationConstraints=situation \ No newline at end of file diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AbstractGuiIntegrationTest.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AbstractGuiIntegrationTest.java index 2d5c2f469fb..545b584c35b 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AbstractGuiIntegrationTest.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AbstractGuiIntegrationTest.java @@ -60,7 +60,7 @@ public abstract class AbstractGuiIntegrationTest extends AbstractModelIntegratio @Autowired protected PrismContext prismContext; @Autowired protected ExpressionFactory expressionFactory; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -89,15 +89,15 @@ public void afterMethod(Method method) { System.out.println(">>>>>>>>>>>>>>>>>>>>>>>> END TEST" + getClass().getName() + "." + method.getName() + "<<<<<<<<<<<<<<<<<<<<<<<<"); LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>> END {}.{} <<<<<<<<<<<<<<<<<<<<<<<<", new Object[]{getClass().getName(), method.getName()}); } - + protected ModelServiceLocator getServiceLocator(final Task pageTask) { return new ModelServiceLocator() { - + @Override public ModelService getModelService() { return modelService; } - + @Override public ModelInteractionService getModelInteractionService() { return modelInteractionService; @@ -140,23 +140,23 @@ public ExpressionFactory getExpressionFactory() { }; } - + protected void assertUserJack(PrismObject user) { assertUserJack(user, USER_JACK_FULL_NAME, USER_JACK_GIVEN_NAME, USER_JACK_FAMILY_NAME); } - + protected void assertUserJack(PrismObject user, String fullName) { assertUserJack(user, fullName, USER_JACK_GIVEN_NAME, USER_JACK_FAMILY_NAME); } - + protected void assertUserJack(PrismObject user, String fullName, String givenName, String familyName) { assertUserJack(user, fullName, givenName, familyName, "Caribbean"); } - + protected void assertUserJack(PrismObject user, String fullName, String givenName, String familyName, String locality) { assertUserJack(user, USER_JACK_USERNAME, fullName, givenName, familyName, locality); } - + protected void assertUserJack(PrismObject user, String name, String fullName, String givenName, String familyName, String locality) { assertUser(user, USER_JACK_OID, name, fullName, givenName, familyName, locality); UserType userType = user.asObjectable(); @@ -169,5 +169,5 @@ protected void assertUserJack(PrismObject user, String name, String fu PrismAsserts.assertEqualsPolyString("Wrong jack locality", locality, userType.getLocality()); } } - + } diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AbstractGuiUnitTest.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AbstractGuiUnitTest.java index 50999defd82..f1e48e39b2a 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AbstractGuiUnitTest.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AbstractGuiUnitTest.java @@ -43,21 +43,21 @@ public abstract class AbstractGuiUnitTest { private static final Trace LOGGER = TraceManager.getTrace(AbstractGuiUnitTest.class); - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - + protected ModelServiceLocator getServiceLocator() { return new ModelServiceLocator() { - + @Override public ModelService getModelService() { return null; } - + @Override public ModelInteractionService getModelInteractionService() { return null; @@ -94,5 +94,5 @@ public ExpressionFactory getExpressionFactory() { } }; } - + } diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AbstractInitializedGuiIntegrationTest.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AbstractInitializedGuiIntegrationTest.java index b0293362546..80801946675 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AbstractInitializedGuiIntegrationTest.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AbstractInitializedGuiIntegrationTest.java @@ -38,14 +38,14 @@ * */ public abstract class AbstractInitializedGuiIntegrationTest extends AbstractGuiIntegrationTest { - + private static final Trace LOGGER = TraceManager.getTrace(AbstractInitializedGuiIntegrationTest.class); - + protected DummyResource dummyResource; protected DummyResourceContoller dummyResourceCtl; protected ResourceType resourceDummyType; protected PrismObject resourceDummy; - + protected PrismObject userAdministrator; protected String accountJackOid; @@ -60,17 +60,17 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti modelService.postInit(initResult); userAdministrator = repositoryService.getObject(UserType.class, USER_ADMINISTRATOR_OID, null, initResult); login(userAdministrator); - + dummyResourceCtl = DummyResourceContoller.create(null); dummyResourceCtl.extendSchemaPirate(); dummyResource = dummyResourceCtl.getDummyResource(); resourceDummy = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_FILE, RESOURCE_DUMMY_OID, initTask, initResult); resourceDummyType = resourceDummy.asObjectable(); dummyResourceCtl.setResource(resourceDummy); - + repoAddObjectFromFile(USER_JACK_FILE, true, initResult); repoAddObjectFromFile(USER_EMPTY_FILE, true, initResult); - + importObjectFromFile(ROLE_MAPMAKER_FILE); } @@ -82,24 +82,24 @@ public void test000PreparationAndSanity() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(AbstractInitializedGuiIntegrationTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + assertNotNull("No model service", modelService); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignAccount(USER_JACK_OID, RESOURCE_DUMMY_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); IntegrationTestTools.display(result); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); accountJackOid = getSingleLinkOid(userJack); - + } - + } diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AdminGuiTestConstants.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AdminGuiTestConstants.java index 3e2e24941c0..0f6dc50cdd7 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AdminGuiTestConstants.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/AdminGuiTestConstants.java @@ -27,14 +27,14 @@ * */ public class AdminGuiTestConstants { - + public static final String COMMON_DIR_NAME = "common"; public static final File COMMON_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, COMMON_DIR_NAME); public 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"; - + public static final File USER_JACK_FILE = new File(COMMON_DIR, "user-jack.xml"); public static final File USER_JACK_REPO_FILE = new File(COMMON_DIR, "user-jack-repo.xml"); public static final String USER_JACK_OID = "b5541d3c-b2fd-11e5-88c0-4f82a8602266"; @@ -42,23 +42,23 @@ public class AdminGuiTestConstants { public static final String USER_JACK_FULL_NAME = "Jack Sparrow"; public static final String USER_JACK_GIVEN_NAME = "Jack"; public static final String USER_JACK_FAMILY_NAME = "Sparrow"; - + public static final File USER_EMPTY_FILE = new File(COMMON_DIR, "user-empty.xml"); public static final String USER_EMPTY_OID = "50053534-36dc-11e6-86f7-035182a6f678"; public static final String USER_EMPTY_USERNAME = "empty"; - + public static final File RESOURCE_DUMMY_FILE = new File(COMMON_DIR, "resource-dummy.xml"); public static final String RESOURCE_DUMMY_OID = "10000000-0000-0000-0000-000000000004"; public static final String RESOURCE_DUMMY_NAMESPACE = MidPointConstants.NS_RI; public static final File RESOURCE_DUMMY_INITIALIZED_FILE = new File(COMMON_DIR, "resource-dummy-initialized.xml"); protected static final QName RESOURCE_DUMMY_ASSOCIATION_GROUP_QNAME = new QName(RESOURCE_DUMMY_NAMESPACE, "group"); - + public 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"; - + public static final File ROLE_MAPMAKER_FILE = new File(COMMON_DIR, "role-mapmaker.xml"); public static final String ROLE_MAPMAKER_OID = "10000000-0000-0000-0000-000000001605"; - + public static final File SHADOW_ACCOUNT_JACK_DUMMY_FILE = new File(COMMON_DIR, "shadow-account-jack-dummy.xml"); } diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/ObjectWrapperTest.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/ObjectWrapperTest.java index 35cbf350a49..1d4e59c1cab 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/ObjectWrapperTest.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/ObjectWrapperTest.java @@ -49,7 +49,7 @@ public void testEmptyPolyString() throws Exception { PrismObject user = prismContext.parseObject(new File("./src/test/resources/wrapper/user.xml")); Task task = taskManager.createTaskInstance("testEmptyPolyString"); - + ObjectWrapperFactory owf = new ObjectWrapperFactory(null); ObjectWrapper wrapper = owf.createObjectWrapper(null, null, user, ContainerStatus.MODIFYING, task); //simulate change on honorific prefix diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/TestCleanStartup.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/TestCleanStartup.java index 47ab9157379..bc525bad49c 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/TestCleanStartup.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/TestCleanStartup.java @@ -44,13 +44,13 @@ @ContextConfiguration(locations = {"classpath:ctx-admin-gui-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestCleanStartup extends AbstractModelIntegrationTest { - + @Autowired(required=true) private InfraInitialSetup infraInitialSetup; - + @Autowired(required=true) private ModelInitialSetup modelInitialSetup; - + @Autowired(required=true) private InitialDataImport initialDataImport; @@ -62,7 +62,7 @@ public TestCleanStartup() { @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + // The rest of the initialization happens as part of the spring context init } @@ -70,30 +70,30 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test001Logfiles() throws Exception { TestUtil.displayTestTitle("test001Logfiles"); - + // GIVEN - system startup and initialization that has already happened LogfileTestTailer tailer = new LogfileTestTailer(LoggingConfigurationManager.AUDIT_LOGGER_NAME, false); - + // THEN display("Tailing ..."); tailer.tail(); display("... done"); - + display("Errors", tailer.getErrors()); display("Warnings", tailer.getWarnings()); - + assertMessages("Error", tailer.getErrors(), "Unable to find file com/../../keystore.jceks", "Provided Icf connector path /C:/tmp is not a directory", "Provided Icf connector path C:\\tmp is not a directory", "Provided Icf connector path C:\\var\\tmp is not a directory", "Provided Icf connector path D:\\var\\tmp is not a directory"); - + assertMessages("Warning", tailer.getWarnings()); - + tailer.close(); } - + private void assertMessages(String desc, Collection actualMessages, String... expectedSubstrings) { for(String actualMessage: actualMessages) { boolean found = false; diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/TestDescriptorLoader.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/TestDescriptorLoader.java index 5d9040a1951..6078628bb33 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/TestDescriptorLoader.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/TestDescriptorLoader.java @@ -55,150 +55,150 @@ "classpath:ctx-model.xml", "classpath*:ctx-workflow.xml"}) public class TestDescriptorLoader extends AbstractGuiUnitTest { - + private static final Trace LOGGER = TraceManager.getTrace(TestDescriptorLoader.class); @Test(enabled=false) public void testDescriptorLoader() { final String TEST_NAME = "testDescriptorLoader"; TestUtil.displayTestTitle(TEST_NAME); - + MidPointApplication midPointApplication = new MidPointApplication(); ServletContext mockServletContext = new ServletContext() { - + @Override public void setAttribute(String arg0, Object arg1) { } - + @Override public void removeAttribute(String arg0) { } - + @Override public void log(String msg, Throwable e) { LOGGER.error("{}", msg, e); } - + @Override public void log(Exception e, String msg) { LOGGER.error("{}", msg, e); } - + @Override public void log(String msg) { LOGGER.trace("{}", msg); } - + @Override public Enumeration getServlets() { return null; } - + @Override public Enumeration getServletNames() { return null; } - + @Override public String getServletContextName() { return "mock"; } - + @Override public Servlet getServlet(String arg0) throws ServletException { return null; } - + @Override public String getServerInfo() { return null; } - + @Override public Set getResourcePaths(String arg0) { return null; } - + @Override public InputStream getResourceAsStream(String name) { return this.getClass().getClassLoader().getResourceAsStream(name); } - + @Override public URL getResource(String name) throws MalformedURLException { return this.getClass().getClassLoader().getResource(name); } - + @Override public RequestDispatcher getRequestDispatcher(String arg0) { return null; } - + @Override public String getRealPath(String arg0) { return null; } - + @Override public RequestDispatcher getNamedDispatcher(String arg0) { return null; } - + @Override public int getMinorVersion() { return 2; } - + @Override public String getMimeType(String arg0) { return null; } - + @Override public int getMajorVersion() { return 4; } - + @Override public Enumeration getInitParameterNames() { return null; } - + @Override public String getInitParameter(String arg0) { return null; } - + @Override public String getContextPath() { return null; } - + @Override public ServletContext getContext(String arg0) { return this; } - + @Override public Enumeration getAttributeNames() { return null; } - + @Override public Object getAttribute(String arg0) { return null; } }; midPointApplication.setServletContext(mockServletContext); - + DescriptorLoader descriptorLoader = new DescriptorLoader(); - + // TODO: this test does not really work. This needs to be cleaned up // to make it testable - + // WHEN descriptorLoader.loadData(midPointApplication); - + // THEN display("initialized loader", descriptorLoader); } diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/TestIntegrationObjectWrapperFactory.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/TestIntegrationObjectWrapperFactory.java index 6f62eba7261..f029baaeb56 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/TestIntegrationObjectWrapperFactory.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/TestIntegrationObjectWrapperFactory.java @@ -84,76 +84,76 @@ @ContextConfiguration(locations = {"classpath:ctx-admin-gui-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestIntegrationObjectWrapperFactory extends AbstractInitializedGuiIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/wrapper"); - + protected static final File ROLE_PROP_READ_ALL_MODIFY_SOME_USER_FILE = new File(TEST_DIR, "role-prop-read-all-modify-some-user.xml"); protected static final String ROLE_PROP_READ_ALL_MODIFY_SOME_USER_OID = "00000000-0000-0000-0000-00000000ae05"; - + protected static final File ROLE_PROP_READ_SOME_MODIFY_SOME_USER_FILE = new File(TEST_DIR, "role-prop-read-some-modify-some-user.xml"); protected static final String ROLE_PROP_READ_SOME_MODIFY_SOME_USER_OID = "00000000-0000-0000-0000-00000000ae08"; - + private static final String USER_WALLY_NAME = "wally"; private static final String USER_WALLY_FULLNAME = "Wally B. Feed"; - + public static final String GROUP_DUMMY_MAPMAKERS_NAME = "mapmakers"; private String userWallyOid; private String accountWallyOid; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + repoAddObjectFromFile(ROLE_PROP_READ_ALL_MODIFY_SOME_USER_FILE, initResult); repoAddObjectFromFile(ROLE_PROP_READ_SOME_MODIFY_SOME_USER_FILE, initResult); - + } - + @Test public void test100CreateWrapperUserJack() throws Exception { final String TEST_NAME = "test100CreateWrapperUserJack"; TestUtil.displayTestTitle(TEST_NAME); - + PrismObject user = getUser(USER_JACK_OID); - + // WHEN displayWhen(TEST_NAME); - + Task task = taskManager.createTaskInstance(TEST_NAME); - + ObjectWrapperFactory factory = new ObjectWrapperFactory(getServiceLocator(task)); - ObjectWrapper objectWrapper = factory.createObjectWrapper("user display name", "user description", user, + ObjectWrapper objectWrapper = factory.createObjectWrapper("user display name", "user description", user, ContainerStatus.MODIFYING, task); - + // THEN displayThen(TEST_NAME); - + IntegrationTestTools.display("Wrapper after", objectWrapper); - + WrapperTestUtil.assertWrapper(objectWrapper, "user display name", "user description", user, ContainerStatus.MODIFYING); assertEquals("wrong number of containers in "+objectWrapper, 11, objectWrapper.getContainers().size()); - + ContainerWrapper mainContainerWrapper = objectWrapper.findContainerWrapper(null); WrapperTestUtil.assertWrapper(mainContainerWrapper, "prismContainer.mainPanelDisplayName", (ItemPath)null, user, ContainerStatus.MODIFYING); WrapperTestUtil.assertPropertyWrapper(mainContainerWrapper, UserType.F_NAME, PrismTestUtil.createPolyString(USER_JACK_USERNAME)); WrapperTestUtil.assertPropertyWrapper(mainContainerWrapper, UserType.F_TIMEZONE, null); - + ContainerWrapper activationContainerWrapper = objectWrapper.findContainerWrapper(new ItemPath(UserType.F_ACTIVATION)); WrapperTestUtil.assertWrapper(activationContainerWrapper, "ActivationType.activation", UserType.F_ACTIVATION, user, ContainerStatus.MODIFYING); WrapperTestUtil.assertPropertyWrapper(activationContainerWrapper, ActivationType.F_ADMINISTRATIVE_STATUS, ActivationStatusType.ENABLED); WrapperTestUtil.assertPropertyWrapper(activationContainerWrapper, ActivationType.F_LOCKOUT_STATUS, null); - + assertEquals("Wrong main container wrapper readOnly", Boolean.FALSE, (Boolean)mainContainerWrapper.isReadonly()); - + assertItemWrapperFullConrol(mainContainerWrapper, UserType.F_NAME, true); assertItemWrapperFullConrol(mainContainerWrapper, UserType.F_GIVEN_NAME, true); assertItemWrapperFullConrol(mainContainerWrapper, UserType.F_FULL_NAME, true); assertItemWrapperFullConrol(mainContainerWrapper, UserType.F_ADDITIONAL_NAME, false); // not visible, because it is empty assertItemWrapperFullConrol(mainContainerWrapper, UserType.F_LOCALITY, true); - + // WHEN objectWrapper.setShowEmpty(true); - + // THEN assertItemWrapperFullConrol(mainContainerWrapper, UserType.F_NAME, true); assertItemWrapperFullConrol(mainContainerWrapper, UserType.F_GIVEN_NAME, true); // emphasized @@ -161,99 +161,99 @@ public void test100CreateWrapperUserJack() throws Exception { assertItemWrapperFullConrol(mainContainerWrapper, UserType.F_ADDITIONAL_NAME, true); // empty assertItemWrapperFullConrol(mainContainerWrapper, UserType.F_LOCALITY, true); // empty } - + @Test public void test102CreateWrapperUserEmpty() throws Exception { final String TEST_NAME = "test102CreateWrapperUserEmpty"; TestUtil.displayTestTitle(TEST_NAME); - + PrismObject user = getUser(USER_EMPTY_OID); - + // WHEN displayWhen(TEST_NAME); - + Task task = taskManager.createTaskInstance(TEST_NAME); - + ObjectWrapperFactory factory = new ObjectWrapperFactory(getServiceLocator(task)); - ObjectWrapper objectWrapper = factory.createObjectWrapper("user display name", "user description", user, + ObjectWrapper objectWrapper = factory.createObjectWrapper("user display name", "user description", user, ContainerStatus.MODIFYING, task); - + // THEN displayThen(TEST_NAME); - + IntegrationTestTools.display("Wrapper after", objectWrapper); - + WrapperTestUtil.assertWrapper(objectWrapper, "user display name", "user description", user, ContainerStatus.MODIFYING); assertEquals("wrong number of containers in "+objectWrapper, 11, objectWrapper.getContainers().size()); - + ContainerWrapper mainContainerWrapper = objectWrapper.findContainerWrapper(null); WrapperTestUtil.assertWrapper(mainContainerWrapper, "prismContainer.mainPanelDisplayName", (ItemPath)null, user, ContainerStatus.MODIFYING); WrapperTestUtil.assertPropertyWrapper(mainContainerWrapper, UserType.F_NAME, PrismTestUtil.createPolyString(USER_EMPTY_USERNAME)); WrapperTestUtil.assertPropertyWrapper(mainContainerWrapper, UserType.F_TIMEZONE, null); - + // Not sure about this // ContainerWrapper activationContainerWrapper = objectWrapper.findContainerWrapper(new ItemPath(UserType.F_ACTIVATION)); // assertNull("Unexpected activation "+activationContainerWrapper, activationContainerWrapper); - + assertEquals("Wrong main container wrapper readOnly", Boolean.FALSE, (Boolean)mainContainerWrapper.isReadonly()); - + assertItemWrapperFullConrol(mainContainerWrapper, UserType.F_NAME, true); assertItemWrapperFullConrol(mainContainerWrapper, UserType.F_GIVEN_NAME, true); // emphasized assertItemWrapperFullConrol(mainContainerWrapper, UserType.F_FULL_NAME, true); // emphasized assertItemWrapperFullConrol(mainContainerWrapper, UserType.F_ADDITIONAL_NAME, false); // empty assertItemWrapperFullConrol(mainContainerWrapper, UserType.F_LOCALITY, false); // empty - + // WHEN objectWrapper.setShowEmpty(true); - + // THEN assertItemWrapperFullConrol(mainContainerWrapper, UserType.F_NAME, true); assertItemWrapperFullConrol(mainContainerWrapper, UserType.F_GIVEN_NAME, true); // emphasized assertItemWrapperFullConrol(mainContainerWrapper, UserType.F_FULL_NAME, true); // emphasized assertItemWrapperFullConrol(mainContainerWrapper, UserType.F_ADDITIONAL_NAME, true); // empty - assertItemWrapperFullConrol(mainContainerWrapper, UserType.F_LOCALITY, true); // empty + assertItemWrapperFullConrol(mainContainerWrapper, UserType.F_LOCALITY, true); // empty } - + @Test public void test150CreateWrapperShadow() throws Exception { final String TEST_NAME = "test150CreateWrapperShadow"; TestUtil.displayTestTitle(TEST_NAME); - + PrismObject shadow = getShadowModel(accountJackOid); shadow.findReference(ShadowType.F_RESOURCE_REF).getValue().setObject(resourceDummy); // WHEN displayWhen(TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); - + ObjectWrapperFactory factory = new ObjectWrapperFactory(getServiceLocator(task)); - ObjectWrapper objectWrapper = factory.createObjectWrapper("shadow display name", "shadow description", shadow, + ObjectWrapper objectWrapper = factory.createObjectWrapper("shadow display name", "shadow description", shadow, ContainerStatus.MODIFYING, task); - + // THEN displayThen(TEST_NAME); - + display("Wrapper after", objectWrapper); - + WrapperTestUtil.assertWrapper(objectWrapper, "shadow display name", "shadow description", shadow, ContainerStatus.MODIFYING); assertEquals("wrong number of containers in "+objectWrapper, 9, objectWrapper.getContainers().size()); - + ContainerWrapper attributesContainerWrapper = objectWrapper.findContainerWrapper(new ItemPath(ShadowType.F_ATTRIBUTES)); PrismContainer attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES); - WrapperTestUtil.assertWrapper(attributesContainerWrapper, "prismContainer.shadow.mainPanelDisplayName", new ItemPath(ShadowType.F_ATTRIBUTES), + WrapperTestUtil.assertWrapper(attributesContainerWrapper, "prismContainer.shadow.mainPanelDisplayName", new ItemPath(ShadowType.F_ATTRIBUTES), attributesContainer, true, ContainerStatus.MODIFYING); WrapperTestUtil.assertPropertyWrapper(attributesContainerWrapper, dummyResourceCtl.getAttributeFullnameQName(), USER_JACK_FULL_NAME); WrapperTestUtil.assertPropertyWrapper(attributesContainerWrapper, SchemaConstants.ICFS_NAME, USER_JACK_USERNAME); assertEquals("wrong number of items in "+attributesContainerWrapper, 16, attributesContainerWrapper.getItems().size()); - + ContainerWrapper activationContainerWrapper = objectWrapper.findContainerWrapper(new ItemPath(UserType.F_ACTIVATION)); WrapperTestUtil.assertWrapper(activationContainerWrapper, "ShadowType.activation", UserType.F_ACTIVATION, shadow, ContainerStatus.MODIFYING); WrapperTestUtil.assertPropertyWrapper(activationContainerWrapper, ActivationType.F_ADMINISTRATIVE_STATUS, ActivationStatusType.ENABLED); WrapperTestUtil.assertPropertyWrapper(activationContainerWrapper, ActivationType.F_LOCKOUT_STATUS, null); - + assertEquals("Wrong attributes container wrapper readOnly", Boolean.FALSE, (Boolean)attributesContainerWrapper.isReadonly()); - + ItemWrapper fullnameWrapper = attributesContainerWrapper.findPropertyWrapper(dummyResourceCtl.getAttributeFullnameQName()); assertEquals("Wrong attribute fullname readOnly", Boolean.FALSE, (Boolean)fullnameWrapper.isReadonly()); // Is this OK? assertEquals("Wrong attribute fullname visible", Boolean.TRUE, (Boolean)fullnameWrapper.isVisible()); @@ -267,7 +267,7 @@ public void test150CreateWrapperShadow() throws Exception { AssertJUnit.fail("Wrong fullname definition.displayOrder: " + fullNameDefinition.getDisplayOrder()); } assertEquals("Wrong attribute fullname definition.displayName", "Full Name", fullNameDefinition.getDisplayName()); - + } @Test @@ -277,58 +277,58 @@ public void test220AssignRoleLandluberToWally() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + DummyGroup mapmakers = new DummyGroup(GROUP_DUMMY_MAPMAKERS_NAME); dummyResource.addGroup(mapmakers); - + PrismObject user = createUser(USER_WALLY_NAME, USER_WALLY_FULLNAME, true); addObject(user); userWallyOid = user.getOid(); assignRole(userWallyOid, ROLE_MAPMAKER_OID, task, result); - + // preconditions assertSuccess(result); - + PrismObject userAfter = getUser(userWallyOid); display("User after change execution", userAfter); accountWallyOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountWallyOid); shadow.findReference(ShadowType.F_RESOURCE_REF).getValue().setObject(resourceDummy); display("Shadow", shadow); - + DummyGroup dummyGroup = dummyResource.getGroupByName(GROUP_DUMMY_MAPMAKERS_NAME); assertNotNull("No group on dummy resource", dummyGroup); display("Group", dummyGroup); assertGroupMember(dummyGroup, USER_WALLY_NAME); - + // WHEN displayWhen(TEST_NAME); - + ObjectWrapperFactory factory = new ObjectWrapperFactory(getServiceLocator(task)); - ObjectWrapper objectWrapper = factory.createObjectWrapper("shadow display name", "shadow description", shadow, + ObjectWrapper objectWrapper = factory.createObjectWrapper("shadow display name", "shadow description", shadow, ContainerStatus.MODIFYING, task); - + // THEN displayThen(TEST_NAME); - + display("Wrapper after", objectWrapper); - + WrapperTestUtil.assertWrapper(objectWrapper, "shadow display name", "shadow description", shadow, ContainerStatus.MODIFYING); assertEquals("wrong number of containers in "+objectWrapper, 9, objectWrapper.getContainers().size()); - + ContainerWrapper attributesContainerWrapper = objectWrapper.findContainerWrapper(new ItemPath(ShadowType.F_ATTRIBUTES)); WrapperTestUtil.assertWrapper(attributesContainerWrapper, "prismContainer.shadow.mainPanelDisplayName", new ItemPath(ShadowType.F_ATTRIBUTES), shadow.findContainer(ShadowType.F_ATTRIBUTES), true, ContainerStatus.MODIFYING); WrapperTestUtil.assertPropertyWrapper(attributesContainerWrapper, dummyResourceCtl.getAttributeFullnameQName(), USER_WALLY_FULLNAME); WrapperTestUtil.assertPropertyWrapper(attributesContainerWrapper, SchemaConstants.ICFS_NAME, USER_WALLY_NAME); assertEquals("wrong number of items in "+attributesContainerWrapper, 16, attributesContainerWrapper.getItems().size()); - + ContainerWrapper activationContainerWrapper = objectWrapper.findContainerWrapper(new ItemPath(UserType.F_ACTIVATION)); WrapperTestUtil.assertWrapper(activationContainerWrapper, "ShadowType.activation", UserType.F_ACTIVATION, shadow, ContainerStatus.MODIFYING); WrapperTestUtil.assertPropertyWrapper(activationContainerWrapper, ActivationType.F_ADMINISTRATIVE_STATUS, ActivationStatusType.ENABLED); WrapperTestUtil.assertPropertyWrapper(activationContainerWrapper, ActivationType.F_LOCKOUT_STATUS, null); - + ContainerWrapper associationContainerWrapper = objectWrapper.findContainerWrapper(new ItemPath(ShadowType.F_ASSOCIATION)); assertNotNull("No association container wrapper", associationContainerWrapper); assertEquals("wrong number of items in "+associationContainerWrapper, 2, associationContainerWrapper.getItems().size()); @@ -346,7 +346,7 @@ public void test220AssignRoleLandluberToWally() throws Exception { PrismProperty groupAssociationUidProp = groupAssociationValueIdentifiers.findProperty(new QName(null,"uid")); PrismAsserts.assertPropertyValue(groupAssociationUidProp, GROUP_DUMMY_MAPMAKERS_NAME); } - + /** * MID-3126 */ @@ -363,29 +363,29 @@ public void test800EditSchemaJackPropReadAllModifySomeUser() throws Exception { ObjectWrapperFactory factory = new ObjectWrapperFactory(getServiceLocator(task)); PrismObject user = getUser(USER_JACK_OID); display("user before", user); - + // WHEN displayWhen(TEST_NAME); - - ObjectWrapper objectWrapper = factory.createObjectWrapper("user display name", "user description", user, + + ObjectWrapper objectWrapper = factory.createObjectWrapper("user display name", "user description", user, ContainerStatus.MODIFYING, task); - + // THEN displayThen(TEST_NAME); - + IntegrationTestTools.display("Wrapper after", objectWrapper); assertEquals("Wrong object wrapper readOnly", Boolean.FALSE, (Boolean)objectWrapper.isReadonly()); - + ContainerWrapper mainContainerWrapper = objectWrapper.findMainContainerWrapper(); assertEquals("Wrong main container wrapper readOnly", Boolean.FALSE, (Boolean)mainContainerWrapper.isReadonly()); - + ItemWrapper nameWrapper = mainContainerWrapper.findPropertyWrapper(UserType.F_NAME); assertEquals("Wrong name readOnly", Boolean.TRUE, (Boolean)nameWrapper.isReadonly()); // Is this OK? assertEquals("Wrong name visible", Boolean.TRUE, (Boolean)nameWrapper.isVisible()); assertEquals("Wrong name definition.canRead", Boolean.TRUE, (Boolean)nameWrapper.getItemDefinition().canRead()); assertEquals("Wrong name definition.canAdd", Boolean.FALSE, (Boolean)nameWrapper.getItemDefinition().canAdd()); assertEquals("Wrong name definition.canModify", Boolean.FALSE, (Boolean)nameWrapper.getItemDefinition().canModify()); - + ItemWrapper givenNameWrapper = mainContainerWrapper.findPropertyWrapper(UserType.F_GIVEN_NAME); assertEquals("Wrong givenName readOnly", Boolean.TRUE, (Boolean)givenNameWrapper.isReadonly()); // Is this OK? assertEquals("Wrong givenName visible", Boolean.TRUE, (Boolean)givenNameWrapper.isVisible()); @@ -413,16 +413,16 @@ public void test800EditSchemaJackPropReadAllModifySomeUser() throws Exception { assertEquals("Wrong locality definition.canRead", Boolean.TRUE, (Boolean)localityNameWrapper.getItemDefinition().canRead()); assertEquals("Wrong locality definition.canAdd", Boolean.FALSE, (Boolean)localityNameWrapper.getItemDefinition().canAdd()); assertEquals("Wrong locality definition.canModify", Boolean.FALSE, (Boolean)localityNameWrapper.getItemDefinition().canModify()); - + // WHEN objectWrapper.setShowEmpty(true); - + // THEN additionalNameWrapper = mainContainerWrapper.findPropertyWrapper(UserType.F_ADDITIONAL_NAME); assertEquals("Wrong additionalName visible", Boolean.TRUE, (Boolean)additionalNameWrapper.isVisible()); // not visible, because it is empty } - + /** * MID-3126 */ @@ -439,29 +439,29 @@ public void test802EditSchemaJackPropReadSomeModifySomeUser() throws Exception { ObjectWrapperFactory factory = new ObjectWrapperFactory(getServiceLocator(task)); PrismObject user = getUser(USER_JACK_OID); display("user before", user); - + // WHEN displayWhen(TEST_NAME); - - ObjectWrapper objectWrapper = factory.createObjectWrapper("user display name", "user description", user, + + ObjectWrapper objectWrapper = factory.createObjectWrapper("user display name", "user description", user, ContainerStatus.MODIFYING, task); - + // THEN displayThen(TEST_NAME); - + IntegrationTestTools.display("Wrapper after", objectWrapper); assertEquals("Wrong object wrapper readOnly", Boolean.FALSE, (Boolean)objectWrapper.isReadonly()); - + ContainerWrapper mainContainerWrapper = objectWrapper.findMainContainerWrapper(); assertEquals("Wrong main container wrapper readOnly", Boolean.FALSE, (Boolean)mainContainerWrapper.isReadonly()); - + ItemWrapper nameWrapper = mainContainerWrapper.findPropertyWrapper(UserType.F_NAME); assertEquals("Wrong name readOnly", Boolean.TRUE, (Boolean)nameWrapper.isReadonly()); assertEquals("Wrong name visible", Boolean.TRUE, (Boolean)nameWrapper.isVisible()); assertEquals("Wrong name definition.canRead", Boolean.TRUE, (Boolean)nameWrapper.getItemDefinition().canRead()); assertEquals("Wrong name definition.canAdd", Boolean.FALSE, (Boolean)nameWrapper.getItemDefinition().canAdd()); assertEquals("Wrong name definition.canModify", Boolean.FALSE, (Boolean)nameWrapper.getItemDefinition().canModify()); - + ItemWrapper givenNameWrapper = mainContainerWrapper.findPropertyWrapper(UserType.F_GIVEN_NAME); assertEquals("Wrong givenName readOnly", Boolean.TRUE, (Boolean)givenNameWrapper.isReadonly()); // Emphasized property. But the role given no access to this. Therefore is should not be visible. @@ -470,14 +470,14 @@ public void test802EditSchemaJackPropReadSomeModifySomeUser() throws Exception { assertEquals("Wrong givenName definition.canRead", Boolean.FALSE, (Boolean)givenNameWrapper.getItemDefinition().canRead()); assertEquals("Wrong givenName definition.canAdd", Boolean.FALSE, (Boolean)givenNameWrapper.getItemDefinition().canAdd()); assertEquals("Wrong givenName definition.canModify", Boolean.FALSE, (Boolean)givenNameWrapper.getItemDefinition().canModify()); - + ItemWrapper fullNameWrapper = mainContainerWrapper.findPropertyWrapper(UserType.F_FULL_NAME); assertEquals("Wrong fullName readOnly", Boolean.FALSE, (Boolean)fullNameWrapper.isReadonly()); assertEquals("Wrong fullName visible", Boolean.TRUE, (Boolean)fullNameWrapper.isVisible()); assertEquals("Wrong fullName definition.canRead", Boolean.TRUE, (Boolean)fullNameWrapper.getItemDefinition().canRead()); assertEquals("Wrong fullName definition.canAdd", Boolean.FALSE, (Boolean)fullNameWrapper.getItemDefinition().canAdd()); assertEquals("Wrong fullName definition.canModify", Boolean.TRUE, (Boolean)fullNameWrapper.getItemDefinition().canModify()); - + ItemWrapper additionalNameWrapper = mainContainerWrapper.findPropertyWrapper(UserType.F_ADDITIONAL_NAME); assertEquals("Wrong additionalName readOnly", Boolean.FALSE, (Boolean)additionalNameWrapper.isReadonly()); assertEquals("Wrong additionalName visible", Boolean.FALSE, (Boolean)additionalNameWrapper.isVisible()); @@ -502,7 +502,7 @@ private void assertItemWrapperFullConrol(ContainerWrap assertEquals("Wrong "+propName+" definition.canAdd", Boolean.TRUE, (Boolean)itemWrapper.getItemDefinition().canAdd()); assertEquals("Wrong "+propName+" definition.canModify", Boolean.TRUE, (Boolean)itemWrapper.getItemDefinition().canModify()); } - + private void cleanupAutzTest(String userOid) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException, IOException { login(userAdministrator); unassignAllRoles(userOid); diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/TestUnitObjectWrapperFactory.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/TestUnitObjectWrapperFactory.java index 4f499cbeb87..c979c4a4ec8 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/TestUnitObjectWrapperFactory.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/TestUnitObjectWrapperFactory.java @@ -39,41 +39,41 @@ * */ public class TestUnitObjectWrapperFactory extends AbstractGuiUnitTest { - + @Test public void testCreateWrapperUser() throws Exception { final String TEST_NAME = "testCreateWrapperUser"; TestUtil.displayTestTitle(TEST_NAME); - + PrismObject user = PrismTestUtil.parseObject(USER_JACK_REPO_FILE); PrismObjectDefinition objDef = user.getDefinition(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + ObjectWrapperFactory factory = new ObjectWrapperFactory(getServiceLocator()); - ObjectWrapper objectWrapper = factory.createObjectWrapper("user display name", "user description", user, + ObjectWrapper objectWrapper = factory.createObjectWrapper("user display name", "user description", user, objDef, null, ContainerStatus.MODIFYING); - + // THEN TestUtil.displayThen(TEST_NAME); - + IntegrationTestTools.display("Wrapper after", objectWrapper); - + WrapperTestUtil.assertWrapper(objectWrapper, "user display name", "user description", user, ContainerStatus.MODIFYING); assertEquals("wrong number of containers in "+objectWrapper, 11, objectWrapper.getContainers().size()); - + ContainerWrapper mainContainerWrapper = objectWrapper.findContainerWrapper(null); WrapperTestUtil.assertWrapper(mainContainerWrapper, "prismContainer.mainPanelDisplayName", (ItemPath)null, user, ContainerStatus.MODIFYING); WrapperTestUtil.assertPropertyWrapper(mainContainerWrapper, UserType.F_NAME, PrismTestUtil.createPolyString("jack")); WrapperTestUtil.assertPropertyWrapper(mainContainerWrapper, UserType.F_TIMEZONE, null); - + ContainerWrapper activationContainerWrapper = objectWrapper.findContainerWrapper(new ItemPath(UserType.F_ACTIVATION)); WrapperTestUtil.assertWrapper(activationContainerWrapper, "ActivationType.activation", UserType.F_ACTIVATION, user, ContainerStatus.MODIFYING); WrapperTestUtil.assertPropertyWrapper(activationContainerWrapper, ActivationType.F_ADMINISTRATIVE_STATUS, ActivationStatusType.ENABLED); WrapperTestUtil.assertPropertyWrapper(activationContainerWrapper, ActivationType.F_LOCKOUT_STATUS, null); } - + // We cannot unit test shadow wrapper. It requires initialized resource, resource schema, capabilities, working model service, etc. diff --git a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/WrapperTestUtil.java b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/WrapperTestUtil.java index 258e8ad704f..ea9dafa45a0 100644 --- a/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/WrapperTestUtil.java +++ b/gui/admin-gui/src/test/java/com/evolveum/midpoint/web/WrapperTestUtil.java @@ -46,14 +46,14 @@ * */ public class WrapperTestUtil { - + public static void assertPropertyWrapper(ContainerWrapper containerWrapper, QName itemName, T... expectedValues) { ItemWrapper itemWrapper = containerWrapper.findPropertyWrapper(itemName); assertNotNull("No item wrapper "+itemName+" in "+containerWrapper, itemWrapper); List valueWrappers = itemWrapper.getValues(); assertPropertyWrapperValues("item wrapper "+itemName+" in "+containerWrapper, valueWrappers, expectedValues); } - + public static void assertPropertyWrapperValues(String desc, List valueWrappers, T... expectedValues) { if (expectedValues == null) { expectedValues = (T[]) new Object[] { null }; @@ -78,16 +78,16 @@ public static void assertPropertyWrapperValues(Strin } else { AssertJUnit.fail("expected PrismPropertyValue in value wrapper in "+desc+", but got "+actualPval.getClass()); } - + } } - public static void assertWrapper(ContainerWrapper containerWrapper, String displayName, + public static void assertWrapper(ContainerWrapper containerWrapper, String displayName, QName itemName, PrismObject object, ContainerStatus status) { assertWrapper(containerWrapper, displayName, itemName==null?null:new ItemPath(itemName), object, status); } - - public static void assertWrapper(ContainerWrapper containerWrapper, String displayName, + + public static void assertWrapper(ContainerWrapper containerWrapper, String displayName, ItemPath expectedPath, PrismObject object, ContainerStatus status) { PrismContainer container; if (expectedPath == null) { @@ -97,8 +97,8 @@ public static void assertWrapper } assertWrapper(containerWrapper, displayName, expectedPath, container, expectedPath==null, status); } - - public static void assertWrapper(ContainerWrapper containerWrapper, String displayName, ItemPath expectedPath, + + public static void assertWrapper(ContainerWrapper containerWrapper, String displayName, ItemPath expectedPath, PrismContainer container, boolean isMain, ContainerStatus status) { assertNotNull("null wrapper", containerWrapper); assertEquals("Wrong main flag in wrapper "+containerWrapper, expectedPath, containerWrapper.getPath()); diff --git a/icf-connectors/dummy-connector-fake/src/main/java/com/evolveum/icf/dummy/connector/DummyConfiguration.java b/icf-connectors/dummy-connector-fake/src/main/java/com/evolveum/icf/dummy/connector/DummyConfiguration.java index 0cd88dfe7aa..5ae6b07d34f 100644 --- a/icf-connectors/dummy-connector-fake/src/main/java/com/evolveum/icf/dummy/connector/DummyConfiguration.java +++ b/icf-connectors/dummy-connector-fake/src/main/java/com/evolveum/icf/dummy/connector/DummyConfiguration.java @@ -30,7 +30,7 @@ public class DummyConfiguration extends AbstractConfiguration { private String instanceId; private String fakeName; - + @ConfigurationProperty(displayMessageKey = "UI_INSTANCE_ID", helpMessageKey = "UI_INSTANCE_ID_HELP") public String getInstanceId() { @@ -50,7 +50,7 @@ public String getFakeName() { public void setFakeName(String config) { this.fakeName = config; } - + /** * {@inheritDoc} */ @@ -63,6 +63,6 @@ public void validate() { log.info("end"); } - + } - + diff --git a/icf-connectors/dummy-connector-fake/src/main/java/com/evolveum/icf/dummy/connector/DummyConnector.java b/icf-connectors/dummy-connector-fake/src/main/java/com/evolveum/icf/dummy/connector/DummyConnector.java index e85c0bcde27..876d57cf593 100644 --- a/icf-connectors/dummy-connector-fake/src/main/java/com/evolveum/icf/dummy/connector/DummyConnector.java +++ b/icf-connectors/dummy-connector-fake/src/main/java/com/evolveum/icf/dummy/connector/DummyConnector.java @@ -28,7 +28,7 @@ /** * Fake Dummy Connector. - * + * * This is connector that is using the same ICF parameters and class names as Dummy Connector. It has a different * version. It is used to test that we can have two completely different versions of the same connector both in * the system at the same time. I mean really different. Different code, different config schema, different behavior. @@ -38,11 +38,11 @@ configurationClass = DummyConfiguration.class) public class DummyConnector implements Connector, AuthenticateOp, ResolveUsernameOp, CreateOp, DeleteOp, SchemaOp, ScriptOnConnectorOp, ScriptOnResourceOp, SearchOp, SyncOp, TestOp, UpdateAttributeValuesOp { - + private static final Log log = Log.getLog(DummyConnector.class); private static final String FAKE_ATTR_NAME = "fakeAttr"; - + /** * Place holder for the {@link Configuration} passed into the init() method */ @@ -80,10 +80,10 @@ public void dispose() { * Implement the following operations using the contract and * description found in the Javadoc for these methods. ******************/ - + /** * {@inheritDoc} - */ + */ /** * {@inheritDoc} @@ -116,7 +116,7 @@ public Uid removeAttributeValues(ObjectClass objectClass, Uid uid, Set createFilterTranslator(ObjectClass objectClass, public void executeQuery(ObjectClass objectClass, String query, ResultsHandler handler, OperationOptions options) { log.info("executeQuery::begin"); // Lets be stupid and just return everything. That means our single account. ICF will filter it. - handler.handle(getFooConnectorObject()); + handler.handle(getFooConnectorObject()); log.info("executeQuery::end"); } @@ -222,7 +222,7 @@ public void sync(ObjectClass objectClass, SyncToken token, SyncResultsHandler ha */ public SyncToken getLatestSyncToken(ObjectClass objectClass) { log.info("getLatestSyncToken::begin"); - + throw new UnsupportedOperationException("Sync is not supported in this shamefull fake"); } @@ -238,18 +238,18 @@ public void test() { log.info("Test configuration was successful."); log.info("test::end"); } - + private ConnectorObject getFooConnectorObject() { ConnectorObjectBuilder builder = new ConnectorObjectBuilder(); builder.setUid("foo"); builder.addAttribute(Name.NAME, "foo"); - + builder.addAttribute(FAKE_ATTR_NAME, "fake foo"); - + GuardedString gs = new GuardedString("sup3rS3cr3tFak3".toCharArray()); builder.addAttribute(OperationalAttributes.PASSWORD_NAME,gs); - + builder.addAttribute(OperationalAttributes.ENABLE_NAME, true); return builder.build(); diff --git a/icf-connectors/dummy-connector-fake/src/main/java/com/evolveum/icf/dummy/connector/DummyFilterTranslator.java b/icf-connectors/dummy-connector-fake/src/main/java/com/evolveum/icf/dummy/connector/DummyFilterTranslator.java index b56bcf704ae..547410cbd20 100644 --- a/icf-connectors/dummy-connector-fake/src/main/java/com/evolveum/icf/dummy/connector/DummyFilterTranslator.java +++ b/icf-connectors/dummy-connector-fake/src/main/java/com/evolveum/icf/dummy/connector/DummyFilterTranslator.java @@ -29,15 +29,15 @@ public class DummyFilterTranslator implements FilterTranslator { private static final Log log = Log.getLog(DummyFilterTranslator.class); - + /* (non-Javadoc) * @see org.identityconnectors.framework.common.objects.filter.FilterTranslator#translate(org.identityconnectors.framework.common.objects.filter.Filter) */ public List translate(Filter filter) { log.info("translate::begin"); - + log.info("translate::filter: {0}",filter == null ? "null" : filter.toString()); - + log.info("translate::end"); return new ArrayList(); } diff --git a/icf-connectors/dummy-connector/src/main/java/com/evolveum/icf/dummy/connector/DummyConfiguration.java b/icf-connectors/dummy-connector/src/main/java/com/evolveum/icf/dummy/connector/DummyConfiguration.java index 9cd3fa67cb6..8e871899f04 100644 --- a/icf-connectors/dummy-connector/src/main/java/com/evolveum/icf/dummy/connector/DummyConfiguration.java +++ b/icf-connectors/dummy-connector/src/main/java/com/evolveum/icf/dummy/connector/DummyConfiguration.java @@ -31,11 +31,11 @@ public class DummyConfiguration extends AbstractConfiguration { public static final String UID_MODE_NAME = "name"; public static final String UID_MODE_UUID = "uuid"; - + public static final String PASSWORD_READABILITY_MODE_UNREADABLE = "unreadable"; public static final String PASSWORD_READABILITY_MODE_INCOMPLETE = "incomplete"; public static final String PASSWORD_READABILITY_MODE_READABLE = "readable"; - + private static final Log log = Log.getLog(DummyConfiguration.class); private String instanceId; @@ -52,7 +52,7 @@ public class DummyConfiguration extends AbstractConfiguration { private boolean generateDefaultValues = false; private boolean tolerateDuplicateValues = true; private boolean varyLetterCase = false; - private boolean referentialIntegrity = false; + private boolean referentialIntegrity = false; private String uselessString; private GuardedString uselessGuardedString; private boolean requireUselessString = false; @@ -80,7 +80,7 @@ public String getInstanceId() { public void setInstanceId(String config) { this.instanceId = config; } - + /** * If set to false the connector will return UnsupportedOperationException when trying to * get the schema. @@ -94,9 +94,9 @@ public boolean getSupportSchema() { public void setSupportSchema(boolean supportSchema) { this.supportSchema = supportSchema; } - + /** - * If set to true the connector will expose activation special attribute (ENABLED). True is the default. + * If set to true the connector will expose activation special attribute (ENABLED). True is the default. */ @ConfigurationProperty(displayMessageKey = "UI_SUPPORT_ACTIVATION", helpMessageKey = "UI_SUPPORT_ACTIVATION_HELP") @@ -107,9 +107,9 @@ public boolean getSupportActivation() { public void setSupportActivation(boolean supportActivation) { this.supportActivation = supportActivation; } - + /** - * If set to true the connector will expose the validity ICF special attributes. + * If set to true the connector will expose the validity ICF special attributes. */ @ConfigurationProperty(displayMessageKey = "UI_SUPPORT_VALIDITY", helpMessageKey = "UI_SUPPORT_VALIDITY_HELP") @@ -120,7 +120,7 @@ public boolean getSupportValidity() { public void setSupportValidity(boolean supportValidity) { this.supportValidity = supportValidity; } - + @ConfigurationProperty(displayMessageKey = "UI_UID_MODE", helpMessageKey = "UI_UID_MODE_HELP") public String getUidMode() { @@ -140,7 +140,7 @@ public boolean isEnforceUniqueName() { public void setEnforceUniqueName(boolean enforceUniqueName) { this.enforceUniqueName = enforceUniqueName; } - + /** * If set to true then the password can be read from the resource. */ @@ -166,7 +166,7 @@ public boolean getRequireExplicitEnable() { public void setRequireExplicitEnable(boolean requireExplicitEnable) { this.requireExplicitEnable = requireExplicitEnable; } - + /** * If set to true then the identifiers will be considered case-insensitive */ @@ -179,7 +179,7 @@ public boolean getCaseIgnoreId() { public void setCaseIgnoreId(boolean caseIgnoreId) { this.caseIgnoreId = caseIgnoreId; } - + /** * If set to true then the "home dir" will be generated */ @@ -188,7 +188,7 @@ public void setCaseIgnoreId(boolean caseIgnoreId) { public boolean isGenerateDefaultValues() { return generateDefaultValues; } - + public void setGenerateDefaultValues(boolean generateDefaultValues) { this.generateDefaultValues = generateDefaultValues; } @@ -256,7 +256,7 @@ public GuardedString getUselessGuardedString() { public void setUselessGuardedString(GuardedString uselessGuardedString) { this.uselessGuardedString = uselessGuardedString; } - + @ConfigurationProperty(displayMessageKey = "UI_REQUIRE_USELESS_STRING", helpMessageKey = "UI_REQUIRE_USELESS_STRING_HELP") public boolean isRequireUselessString() { @@ -370,7 +370,7 @@ public boolean isRequireNameHint() { public void setRequireNameHint(boolean requireNameHint) { this.requireNameHint = requireNameHint; } - + @ConfigurationProperty public boolean isMonsterized() { return monsterized; @@ -390,7 +390,7 @@ public void validate() { if (uidMode.equals(UID_MODE_NAME) && !enforceUniqueName) { throw new IllegalArgumentException("Cannot use name UID mode without enforceUniqueName"); } - + log.info("uselessString: {0}", uselessString); if (requireUselessString && StringUtils.isBlank(uselessString)) { throw new ConfigurationException("No useless string"); @@ -399,6 +399,6 @@ public void validate() { log.info("end"); } - + } - + diff --git a/icf-connectors/dummy-connector/src/main/java/com/evolveum/icf/dummy/connector/DummyConnector.java b/icf-connectors/dummy-connector/src/main/java/com/evolveum/icf/dummy/connector/DummyConnector.java index 82c9892958f..93ab3f6f131 100644 --- a/icf-connectors/dummy-connector/src/main/java/com/evolveum/icf/dummy/connector/DummyConnector.java +++ b/icf-connectors/dummy-connector/src/main/java/com/evolveum/icf/dummy/connector/DummyConnector.java @@ -81,12 +81,12 @@ /** * Connector for the Dummy Resource. - * + * * Dummy resource is a simple Java object that pretends to be a resource. It has accounts and * account schema. It has operations to manipulate accounts, execute scripts and so on - * almost like a real resource. The purpose is to simulate a real resource with a very + * almost like a real resource. The purpose is to simulate a real resource with a very * little overhead. This connector connects the Dummy resource to ICF. - * + * * @see DummyResource * */ @@ -94,29 +94,29 @@ configurationClass = DummyConfiguration.class) public class DummyConnector implements PoolableConnector, AuthenticateOp, ResolveUsernameOp, CreateOp, DeleteOp, SchemaOp, ScriptOnConnectorOp, ScriptOnResourceOp, SearchOp, SyncOp, TestOp, UpdateAttributeValuesOp { - + // We want to see if the ICF framework logging works properly private static final Log log = Log.getLog(DummyConnector.class); // We also want to see if the libraries that use JUL are logging properly private static final java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(DummyConnector.class.getName()); - + // Marker used in logging tests public static final String LOG_MARKER = "_M_A_R_K_E_R_"; - + private static final String OBJECTCLASS_ACCOUNT_NAME = "account"; private static final String OBJECTCLASS_GROUP_NAME = "group"; private static final String OBJECTCLASS_PRIVILEGE_NAME = "privilege"; private static final String OBJECTCLASS_ORG_NAME = "org"; - + /** * Place holder for the {@link Configuration} passed into the init() method */ private DummyConfiguration configuration; - + private DummyResource resource; - + private boolean connected = false; - + private static String staticVal; /** @@ -136,13 +136,13 @@ public Configuration getConfiguration() { public void init(Configuration configuration) { notNullArgument(configuration, "configuration"); this.configuration = (DummyConfiguration) configuration; - + String instanceName = this.configuration.getInstanceId(); if (instanceName == null || instanceName.isEmpty()) { instanceName = null; } resource = DummyResource.getInstance(instanceName); - + resource.setCaseIgnoreId(this.configuration.getCaseIgnoreId()); resource.setCaseIgnoreValues(this.configuration.getCaseIgnoreValues()); resource.setEnforceUniqueName(this.configuration.isEnforceUniqueName()); @@ -167,18 +167,18 @@ public void init(Configuration configuration) { uselessGuardedString.access(chars -> resource.setUselessGuardedString(new String(chars))); } resource.setMonsterization(this.configuration.isMonsterized()); - + if (connected) { throw new IllegalStateException("Double connect in "+this); } connected = true; - + resource.connect(); - + if (staticVal == null) { staticVal = this.toString(); } - + log.info("Connected to dummy resource instance {0} ({1} connections open)", resource, resource.getConnectionCount()); } @@ -192,7 +192,7 @@ public void dispose() { resource.disconnect(); log.info("Disconnected from dummy resource instance {0} ({1} connections still open)", resource, resource.getConnectionCount()); } - + @Override public void checkAlive() { if (!connected) { @@ -206,10 +206,10 @@ public void checkAlive() { * Implement the following operations using the contract and * description found in the Javadoc for these methods. ******************/ - + /** * {@inheritDoc} - */ + */ /** * {@inheritDoc} @@ -217,47 +217,47 @@ public void checkAlive() { public Uid create(final ObjectClass objectClass, final Set createAttributes, final OperationOptions options) { log.info("create::begin attributes {0}", createAttributes); validate(objectClass); - + DummyObject newObject; try { - + if (ObjectClass.ACCOUNT.is(objectClass.getObjectClassValue())) { // Convert attributes to account DummyAccount newAccount = convertToAccount(createAttributes); - + log.ok("Adding dummy account:\n{0}", newAccount.debugDump()); - + resource.addAccount(newAccount); newObject = newAccount; - + } else if (ObjectClass.GROUP.is(objectClass.getObjectClassValue())) { DummyGroup newGroup = convertToGroup(createAttributes); - + log.ok("Adding dummy group:\n{0}", newGroup.debugDump()); - + resource.addGroup(newGroup); newObject = newGroup; - + } else if (objectClass.is(OBJECTCLASS_PRIVILEGE_NAME)) { DummyPrivilege newPriv = convertToPriv(createAttributes); - + log.ok("Adding dummy privilege:\n{0}", newPriv.debugDump()); - + resource.addPrivilege(newPriv); newObject = newPriv; - + } else if (objectClass.is(OBJECTCLASS_ORG_NAME)) { DummyOrg newOrg = convertToOrg(createAttributes); - + log.ok("Adding dummy org:\n{0}", newOrg.debugDump()); - + resource.addOrg(newOrg); newObject = newOrg; } else { throw new ConnectorException("Unknown object class "+objectClass); } - + } catch (ObjectAlreadyExistsException e) { // Note: let's do the bad thing and add exception loaded by this classloader as inner exception here // The framework should deal with it ... somehow @@ -271,7 +271,7 @@ public Uid create(final ObjectClass objectClass, final Set createAttr } catch (ConflictException e) { throw new AlreadyExistsException(e); } - + String id; if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_NAME)) { id = newObject.getName(); @@ -281,7 +281,7 @@ public Uid create(final ObjectClass objectClass, final Set createAttr throw new IllegalStateException("Unknown UID mode "+configuration.getUidMode()); } Uid uid = new Uid(id); - + log.info("create::end"); return uid; } @@ -293,11 +293,11 @@ public Uid update(ObjectClass objectClass, Uid uid, Set replaceAttrib log.info("update::begin"); validate(objectClass); validate(uid); - + try { - + if (ObjectClass.ACCOUNT.is(objectClass.getObjectClassValue())) { - + final DummyAccount account; if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_NAME)) { account = resource.getAccountByUsername(uid.getUidValue(), false); @@ -312,7 +312,7 @@ public Uid update(ObjectClass objectClass, Uid uid, Set replaceAttrib // we do this before setting attribute values, in case when description itself would be changed resource.changeDescriptionIfNeeded(account); - + for (Attribute attr : replaceAttributes) { if (attr.is(Name.NAME)) { String newName = (String)attr.getValue().get(0); @@ -358,9 +358,9 @@ public Uid update(ObjectClass objectClass, Uid uid, Set replaceAttrib } } } - + } else if (ObjectClass.GROUP.is(objectClass.getObjectClassValue())) { - + final DummyGroup group; if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_NAME)) { group = resource.getGroupByName(uid.getUidValue(), false); @@ -372,7 +372,7 @@ public Uid update(ObjectClass objectClass, Uid uid, Set replaceAttrib if (group == null) { throw new UnknownUidException("Group with UID "+uid+" does not exist on resource"); } - + for (Attribute attr : replaceAttributes) { if (attr.is(Name.NAME)) { String newName = (String)attr.getValue().get(0); @@ -387,10 +387,10 @@ public Uid update(ObjectClass objectClass, Uid uid, Set replaceAttrib uid = new Uid(newName); } else if (attr.is(OperationalAttributes.PASSWORD_NAME)) { throw new IllegalArgumentException("Attempt to change password on group"); - + } else if (attr.is(OperationalAttributes.ENABLE_NAME)) { group.setEnabled(getBooleanNotNull(attr)); - + } else { String name = attr.getName(); List values = attr.getValue(); @@ -408,9 +408,9 @@ public Uid update(ObjectClass objectClass, Uid uid, Set replaceAttrib } } } - + } else if (objectClass.is(OBJECTCLASS_PRIVILEGE_NAME)) { - + final DummyPrivilege priv; if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_NAME)) { priv = resource.getPrivilegeByName(uid.getUidValue(), false); @@ -422,7 +422,7 @@ public Uid update(ObjectClass objectClass, Uid uid, Set replaceAttrib if (priv == null) { throw new UnknownUidException("Privilege with UID "+uid+" does not exist on resource"); } - + for (Attribute attr : replaceAttributes) { if (attr.is(Name.NAME)) { String newName = (String)attr.getValue().get(0); @@ -437,10 +437,10 @@ public Uid update(ObjectClass objectClass, Uid uid, Set replaceAttrib uid = new Uid(newName); } else if (attr.is(OperationalAttributes.PASSWORD_NAME)) { throw new IllegalArgumentException("Attempt to change password on privilege"); - + } else if (attr.is(OperationalAttributes.ENABLE_NAME)) { throw new IllegalArgumentException("Attempt to change enable on privilege"); - + } else { String name = attr.getName(); try { @@ -450,9 +450,9 @@ public Uid update(ObjectClass objectClass, Uid uid, Set replaceAttrib } } } - + } else if (objectClass.is(OBJECTCLASS_ORG_NAME)) { - + final DummyOrg org; if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_NAME)) { org = resource.getOrgByName(uid.getUidValue(), false); @@ -464,7 +464,7 @@ public Uid update(ObjectClass objectClass, Uid uid, Set replaceAttrib if (org == null) { throw new UnknownUidException("Org with UID "+uid+" does not exist on resource"); } - + for (Attribute attr : replaceAttributes) { if (attr.is(Name.NAME)) { String newName = (String)attr.getValue().get(0); @@ -479,10 +479,10 @@ public Uid update(ObjectClass objectClass, Uid uid, Set replaceAttrib uid = new Uid(newName); } else if (attr.is(OperationalAttributes.PASSWORD_NAME)) { throw new IllegalArgumentException("Attempt to change password on org"); - + } else if (attr.is(OperationalAttributes.ENABLE_NAME)) { throw new IllegalArgumentException("Attempt to change enable on org"); - + } else { String name = attr.getName(); try { @@ -492,12 +492,12 @@ public Uid update(ObjectClass objectClass, Uid uid, Set replaceAttrib } } } - - + + } else { throw new ConnectorException("Unknown object class "+objectClass); } - + } catch (ConnectException e) { log.info("update::exception "+e); throw new ConnectionFailedException(e.getMessage(), e); @@ -511,7 +511,7 @@ public Uid update(ObjectClass objectClass, Uid uid, Set replaceAttrib log.info("update::exception "+e); throw new AlreadyExistsException(e); } - + log.info("update::end"); return uid; } @@ -524,9 +524,9 @@ public Uid addAttributeValues(ObjectClass objectClass, Uid uid, Set v validate(uid); try { - + if (ObjectClass.ACCOUNT.is(objectClass.getObjectClassValue())) { - + DummyAccount account; if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_NAME)) { account = resource.getAccountByUsername(uid.getUidValue()); @@ -541,18 +541,18 @@ public Uid addAttributeValues(ObjectClass objectClass, Uid uid, Set v // we could change the description here, but don't do that not to collide with ADD operation // TODO add the functionality if needed - + for (Attribute attr : valuesToAdd) { - + if (attr.is(OperationalAttributeInfos.PASSWORD.getName())) { if (account.getPassword() != null) { throw new IllegalArgumentException("Attempt to add value for password while password is already set"); } changePassword(account,attr); - + } else if (attr.is(OperationalAttributes.ENABLE_NAME)) { throw new IllegalArgumentException("Attempt to add value for enable attribute"); - + } else if (PredefinedAttributes.AUXILIARY_OBJECT_CLASS_NAME.equalsIgnoreCase(attr.getName())) { account.addAuxiliaryObjectClassNames(attr.getValue()); @@ -570,9 +570,9 @@ public Uid addAttributeValues(ObjectClass objectClass, Uid uid, Set v } } } - + } else if (ObjectClass.GROUP.is(objectClass.getObjectClassValue())) { - + DummyGroup group; if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_NAME)) { group = resource.getGroupByName(uid.getUidValue()); @@ -584,15 +584,15 @@ public Uid addAttributeValues(ObjectClass objectClass, Uid uid, Set v if (group == null) { throw new UnknownUidException("Group with UID "+uid+" does not exist on resource"); } - + for (Attribute attr : valuesToAdd) { - + if (attr.is(OperationalAttributeInfos.PASSWORD.getName())) { throw new IllegalArgumentException("Attempt to change password on group"); - + } else if (attr.is(OperationalAttributes.ENABLE_NAME)) { throw new IllegalArgumentException("Attempt to add value for enable attribute"); - + } else { String name = attr.getName(); List values = attr.getValue(); @@ -615,9 +615,9 @@ public Uid addAttributeValues(ObjectClass objectClass, Uid uid, Set v } } } - + } else if (objectClass.is(OBJECTCLASS_PRIVILEGE_NAME)) { - + DummyPrivilege priv; if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_NAME)) { priv = resource.getPrivilegeByName(uid.getUidValue()); @@ -629,15 +629,15 @@ public Uid addAttributeValues(ObjectClass objectClass, Uid uid, Set v if (priv == null) { throw new UnknownUidException("Privilege with UID "+uid+" does not exist on resource"); } - + for (Attribute attr : valuesToAdd) { - + if (attr.is(OperationalAttributeInfos.PASSWORD.getName())) { throw new IllegalArgumentException("Attempt to change password on privilege"); - + } else if (attr.is(OperationalAttributes.ENABLE_NAME)) { throw new IllegalArgumentException("Attempt to add value for enable attribute"); - + } else { String name = attr.getName(); try { @@ -652,9 +652,9 @@ public Uid addAttributeValues(ObjectClass objectClass, Uid uid, Set v } } } - + } else if (objectClass.is(OBJECTCLASS_ORG_NAME)) { - + DummyOrg org; if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_NAME)) { org = resource.getOrgByName(uid.getUidValue()); @@ -666,15 +666,15 @@ public Uid addAttributeValues(ObjectClass objectClass, Uid uid, Set v if (org == null) { throw new UnknownUidException("Org with UID "+uid+" does not exist on resource"); } - + for (Attribute attr : valuesToAdd) { - + if (attr.is(OperationalAttributeInfos.PASSWORD.getName())) { throw new IllegalArgumentException("Attempt to change password on org"); - + } else if (attr.is(OperationalAttributes.ENABLE_NAME)) { throw new IllegalArgumentException("Attempt to add value for enable org"); - + } else { String name = attr.getName(); try { @@ -689,11 +689,11 @@ public Uid addAttributeValues(ObjectClass objectClass, Uid uid, Set v } } } - + } else { throw new ConnectorException("Unknown object class "+objectClass); } - + } catch (ConnectException e) { log.info("addAttributeValues::exception "+e); throw new ConnectionFailedException(e.getMessage(), e); @@ -707,7 +707,7 @@ public Uid addAttributeValues(ObjectClass objectClass, Uid uid, Set v log.info("addAttributeValues::exception "+e); throw new AlreadyExistsException(e); } - + return uid; } @@ -719,9 +719,9 @@ public Uid removeAttributeValues(ObjectClass objectClass, Uid uid, Set attributesToGet = getAttrsToGet(options); log.ok("attributesToGet={0}", attributesToGet); - + if (configuration.getRequiredBaseContextOrgName() != null && shouldRequireBaseContext(objectClass, query, options)) { if (options == null || options.getContainer() == null) { throw new ConnectorException("No container option while base context is required"); @@ -1202,37 +1202,37 @@ public void executeQuery(ObjectClass objectClass, Filter query, ResultsHandler h +"' is required, but got '"+container.getUid().getUidValue()+"'"); } } - + try { if (ObjectClass.ACCOUNT.is(objectClass.getObjectClassValue())) { - - search(objectClass, query, handler, options, + + search(objectClass, query, handler, options, resource::listAccounts, resource::getAccountByUsername, resource::getAccountById, this::convertToConnectorObject, null); - + } else if (ObjectClass.GROUP.is(objectClass.getObjectClassValue())) { - - search(objectClass, query, handler, options, - resource::listGroups, resource::getGroupByName, resource::getGroupById, this::convertToConnectorObject, + + search(objectClass, query, handler, options, + resource::listGroups, resource::getGroupByName, resource::getGroupById, this::convertToConnectorObject, object -> { if (attributesToGetHasAttribute(attributesToGet, DummyGroup.ATTR_MEMBERS_NAME)) { resource.recordGroupMembersReadCount(); } }); - + } else if (objectClass.is(OBJECTCLASS_PRIVILEGE_NAME)) { - - search(objectClass, query, handler, options, + + search(objectClass, query, handler, options, resource::listPrivileges, resource::getPrivilegeByName, resource::getPrivilegeById, this::convertToConnectorObject, null); - + } else if (objectClass.is(OBJECTCLASS_ORG_NAME)) { - - search(objectClass, query, handler, options, + + search(objectClass, query, handler, options, resource::listOrgs, resource::getOrgByName, resource::getOrgById, this::convertToConnectorObject, null); - + } else { throw new ConnectorException("Unknown object class "+objectClass); } - + } catch (ConnectException e) { log.info("executeQuery::exception "+e); throw new ConnectionFailedException(e.getMessage(), e); @@ -1246,15 +1246,15 @@ public void executeQuery(ObjectClass objectClass, Filter query, ResultsHandler h log.info("executeQuery::exception "+e); throw new AlreadyExistsException(e); } - + log.info("executeQuery::end"); } - - private void search(ObjectClass objectClass, Filter query, ResultsHandler handler, OperationOptions options, + + private void search(ObjectClass objectClass, Filter query, ResultsHandler handler, OperationOptions options, Lister lister, Getter nameGetter, Getter idGetter, Converter converter, Consumer recorder) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { Collection attributesToGet = getAttrsToGet(options); log.ok("attributesToGet={0}", attributesToGet); - + if (isEqualsFilter(query, Name.NAME) && resource.isEnforceUniqueName()) { Attribute nameAttribute = ((EqualsFilter)query).getAttribute(); String name = (String)nameAttribute.getValue().get(0); @@ -1264,7 +1264,7 @@ private void search(ObjectClass objectClass, Filter quer } return; } - + if (isEqualsFilter(query, Uid.NAME)) { Attribute uidAttribute = ((EqualsFilter)query).getAttribute(); String uid = (String)uidAttribute.getValue().get(0); @@ -1281,7 +1281,7 @@ private void search(ObjectClass objectClass, Filter quer } return; } - + // Brute force: list all, filter out Collection allObjects = lister.list(); for (T object : allObjects) { @@ -1291,12 +1291,12 @@ private void search(ObjectClass objectClass, Filter quer } } } - + private void handleObject(T object, ResultsHandler handler, OperationOptions options, Collection attributesToGet, Converter converter, Consumer recorder) throws SchemaViolationException { ConnectorObject co = converter.convert(object, attributesToGet); handleConnectorObject(object, co, handler, options, attributesToGet, recorder); } - + private void handleConnectorObject(T object, ConnectorObject co, ResultsHandler handler, OperationOptions options, Collection attributesToGet, Consumer recorder) { if (recorder != null) { recorder.accept(object); @@ -1308,17 +1308,17 @@ private void handleConnectorObject(T object, ConnectorOb private boolean isEqualsFilter(Filter icfFilter, String icfAttrname) { return icfFilter != null && (icfFilter instanceof EqualsFilter) && icfAttrname.equals(((EqualsFilter)icfFilter).getName()); } - + @FunctionalInterface interface Lister { Collection list() throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException; } - + @FunctionalInterface interface Getter { T get(String id) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException; } - + @FunctionalInterface interface Converter { ConnectorObject convert(T object, Collection attributesToGet) throws SchemaViolationException; @@ -1363,7 +1363,7 @@ private ConnectorObject normalize(ConnectorObject co) { } return cob.build(); } - + private Filter normalize(Filter filter) { if (filter instanceof ContainsFilter) { AttributeFilter afilter = (AttributeFilter) filter; @@ -1405,7 +1405,7 @@ private Filter normalize(Filter filter) { return filter; } } - + private Attribute normalize(Attribute attr) { if (configuration.getCaseIgnoreValues()) { AttributeBuilder ab = new AttributeBuilder(); @@ -1458,14 +1458,14 @@ private boolean containsAttribute(Collection attrs, String attrName) { public void sync(ObjectClass objectClass, SyncToken token, SyncResultsHandler handler, final OperationOptions options) { log.info("sync::begin"); validate(objectClass); - + Collection attributesToGet = getAttrsToGet(options); try { int syncToken = (Integer)token.getValue(); List deltas = resource.getDeltasSince(syncToken); for (DummyDelta delta: deltas) { - + Class deltaObjectClass = delta.getObjectClass(); if (objectClass.is(ObjectClass.ALL_NAME)) { // take all changes @@ -1480,7 +1480,7 @@ public void sync(ObjectClass objectClass, SyncToken token, SyncResultsHandler ha continue; } } - + SyncDeltaBuilder deltaBuilder = new SyncDeltaBuilder(); if (deltaObjectClass == DummyAccount.class) { deltaBuilder.setObjectClass(ObjectClass.ACCOUNT); @@ -1493,7 +1493,7 @@ public void sync(ObjectClass objectClass, SyncToken token, SyncResultsHandler ha } else { throw new IllegalArgumentException("Unknown delta objectClass "+deltaObjectClass); } - + SyncDeltaType deltaType; if (delta.getType() == DummyDeltaType.ADD || delta.getType() == DummyDeltaType.MODIFY) { if (resource.getSyncStyle() == DummySyncStyle.DUMB) { @@ -1535,9 +1535,9 @@ public void sync(ObjectClass objectClass, SyncToken token, SyncResultsHandler ha throw new IllegalStateException("Unknown delta type "+delta.getType()); } deltaBuilder.setDeltaType(deltaType); - + deltaBuilder.setToken(new SyncToken(delta.getSyncToken())); - + Uid uid; if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_NAME)) { uid = new Uid(delta.getObjectName()); @@ -1551,12 +1551,12 @@ public void sync(ObjectClass objectClass, SyncToken token, SyncResultsHandler ha throw new IllegalStateException("Unknown UID mode "+configuration.getUidMode()); } deltaBuilder.setUid(uid); - + SyncDelta syncDelta = deltaBuilder.build(); log.info("sync::handle {0}",syncDelta); handler.handle(syncDelta); } - + } catch (ConnectException e) { log.info("sync::exception "+e); throw new ConnectionFailedException(e.getMessage(), e); @@ -1570,7 +1570,7 @@ public void sync(ObjectClass objectClass, SyncToken token, SyncResultsHandler ha log.info("sync::exception "+e); throw new AlreadyExistsException(e); } - + log.info("sync::end"); } @@ -1601,22 +1601,22 @@ public SyncToken getLatestSyncToken(ObjectClass objectClass) { */ public void test() { log.info("test::begin"); - + if (!connected) { throw new IllegalStateException("Attempt to test non-connected connector instance "+this); } - + log.info("Validating configuration."); configuration.validate(); - + // Produce log messages on all levels. The tests may check if they are really logged. log.error(LOG_MARKER + " DummyConnectorIcfError"); log.info(LOG_MARKER + " DummyConnectorIcfInfo"); log.warn(LOG_MARKER + " DummyConnectorIcfWarn"); log.ok(LOG_MARKER + " DummyConnectorIcfOk"); - + log.info("Dummy Connector JUL logger as seen by the connector: " + julLogger + "; classloader " + julLogger.getClass().getClassLoader()); - + // Same thing using JUL julLogger.severe(LOG_MARKER + " DummyConnectorJULsevere"); julLogger.warning(LOG_MARKER + " DummyConnectorJULwarning"); @@ -1624,15 +1624,15 @@ public void test() { julLogger.fine(LOG_MARKER + " DummyConnectorJULfine"); julLogger.finer(LOG_MARKER + " DummyConnectorJULfiner"); julLogger.finest(LOG_MARKER + " DummyConnectorJULfinest"); - + log.info("Test configuration was successful."); log.info("test::end"); } - + private ConnectorObjectBuilder createConnectorObjectBuilderCommon(DummyObject dummyObject, DummyObjectClass objectClass, Collection attributesToGet, boolean supportActivation) { ConnectorObjectBuilder builder = new ConnectorObjectBuilder(); - + if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_NAME)) { builder.setUid(dummyObject.getName()); } else if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_UUID)) { @@ -1640,9 +1640,9 @@ private ConnectorObjectBuilder createConnectorObjectBuilderCommon(DummyObject du } else { throw new IllegalStateException("Unknown UID mode "+configuration.getUidMode()); } - + builder.addAttribute(Name.NAME, dummyObject.getName()); - + for (String name : dummyObject.getAttributeNames()) { DummyAttributeDefinition attrDef = dummyObject.getAttributeDefinition(name); if (attrDef == null) { @@ -1662,23 +1662,23 @@ private ConnectorObjectBuilder createConnectorObjectBuilderCommon(DummyObject du builder.addAttribute(name, values); } } - + if (supportActivation) { if (attributesToGet == null || attributesToGet.contains(OperationalAttributes.ENABLE_NAME)) { builder.addAttribute(OperationalAttributes.ENABLE_NAME, dummyObject.isEnabled()); } - + if (dummyObject.getValidFrom() != null && (attributesToGet == null || attributesToGet.contains(OperationalAttributes.ENABLE_DATE_NAME))) { builder.addAttribute(OperationalAttributes.ENABLE_DATE_NAME, convertToLong(dummyObject.getValidFrom())); } - + if (dummyObject.getValidTo() != null && (attributesToGet == null || attributesToGet.contains(OperationalAttributes.DISABLE_DATE_NAME))) { builder.addAttribute(OperationalAttributes.DISABLE_DATE_NAME, convertToLong(dummyObject.getValidTo())); } } - + if (configuration.isAddConnectorStateAttributes()) { builder.addAttribute(DummyResource.ATTRIBUTE_CONNECTOR_TO_STRING, this.toString()); builder.addAttribute(DummyResource.ATTRIBUTE_CONNECTOR_STATIC_VAL, staticVal); @@ -1714,7 +1714,7 @@ private Long convertToLong(Date date) { } private ConnectorObject convertToConnectorObject(DummyAccount account, Collection attributesToGet) throws SchemaViolationException { - + DummyObjectClass objectClass; try { objectClass = resource.getAccountObjectClass(); @@ -1728,10 +1728,10 @@ private ConnectorObject convertToConnectorObject(DummyAccount account, Collectio log.error(e, e.getMessage()); throw new AlreadyExistsException(e); } - + ConnectorObjectBuilder builder = createConnectorObjectBuilderCommon(account, objectClass, attributesToGet, true); builder.setObjectClass(ObjectClass.ACCOUNT); - + // Password is not returned by default (hardcoded ICF specification) if (account.getPassword() != null && attributesToGet != null && attributesToGet.contains(OperationalAttributes.PASSWORD_NAME)) { switch (configuration.getPasswordReadabilityMode()) { @@ -1749,14 +1749,14 @@ private ConnectorObject convertToConnectorObject(DummyAccount account, Collectio // nothing to do } } - + if (account.isLockout() != null) { builder.addAttribute(OperationalAttributes.LOCK_OUT_NAME, account.isLockout()); } return builder.build(); } - + private ConnectorObject convertToConnectorObject(DummyGroup group, Collection attributesToGet) { ConnectorObjectBuilder builder = createConnectorObjectBuilderCommon(group, resource.getGroupObjectClass(), attributesToGet, true); @@ -1777,7 +1777,7 @@ private ConnectorObject convertToConnectorObject(DummyOrg org, Collection createAttributes) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { log.ok("Create attributes: {0}", createAttributes); String userName = Utils.getMandatoryStringAttribute(createAttributes, Name.NAME); @@ -1786,42 +1786,42 @@ private DummyAccount convertToAccount(Set createAttributes) throws Co } log.ok("Username {0}", userName); final DummyAccount newAccount = new DummyAccount(userName); - + Boolean enabled = null; boolean hasPassword = false; for (Attribute attr : createAttributes) { if (attr.is(Uid.NAME)) { throw new IllegalArgumentException("UID explicitly specified in the account attributes"); - + } else if (attr.is(Name.NAME)) { // Skip, already processed } else if (attr.is(OperationalAttributeInfos.PASSWORD.getName())) { changePassword(newAccount,attr); hasPassword = true; - + } else if (attr.is(OperationalAttributeInfos.ENABLE.getName())) { enabled = getBoolean(attr); newAccount.setEnabled(enabled); - + } else if (attr.is(OperationalAttributeInfos.ENABLE_DATE.getName())) { if (configuration.getSupportValidity()) { newAccount.setValidFrom(getDate(attr)); } else { throw new IllegalArgumentException("ENABLE_DATE specified in the account attributes while not supporting it"); } - + } else if (attr.is(OperationalAttributeInfos.DISABLE_DATE.getName())) { if (configuration.getSupportValidity()) { newAccount.setValidTo(getDate(attr)); } else { throw new IllegalArgumentException("DISABLE_DATE specified in the account attributes while not supporting it"); } - + } else if (attr.is(OperationalAttributeInfos.LOCK_OUT.getName())) { Boolean lockout = getBooleanNotNull(attr); newAccount.setLockout(lockout); - + } else { String name = attr.getName(); try { @@ -1834,18 +1834,18 @@ private DummyAccount convertToAccount(Set createAttributes) throws Co } } } - + if (!hasPassword) { checkPasswordPolicies(null); } - + if (configuration.getRequireExplicitEnable() && enabled == null) { throw new IllegalArgumentException("Explicit value for ENABLE attribute was not provided and the connector is set to require it"); } - + return newAccount; } - + private DummyGroup convertToGroup(Set createAttributes) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { String icfName = Utils.getMandatoryStringAttribute(createAttributes,Name.NAME); if (configuration.getUpCaseName()) { @@ -1857,31 +1857,31 @@ private DummyGroup convertToGroup(Set createAttributes) throws Connec for (Attribute attr : createAttributes) { if (attr.is(Uid.NAME)) { throw new IllegalArgumentException("UID explicitly specified in the group attributes"); - + } else if (attr.is(Name.NAME)) { // Skip, already processed } else if (attr.is(OperationalAttributeInfos.PASSWORD.getName())) { throw new IllegalArgumentException("Password specified for a group"); - + } else if (attr.is(OperationalAttributeInfos.ENABLE.getName())) { enabled = getBooleanNotNull(attr); newGroup.setEnabled(enabled); - + } else if (attr.is(OperationalAttributeInfos.ENABLE_DATE.getName())) { if (configuration.getSupportValidity()) { newGroup.setValidFrom(getDate(attr)); } else { throw new IllegalArgumentException("ENABLE_DATE specified in the group attributes while not supporting it"); } - + } else if (attr.is(OperationalAttributeInfos.DISABLE_DATE.getName())) { if (configuration.getSupportValidity()) { newGroup.setValidTo(getDate(attr)); } else { throw new IllegalArgumentException("DISABLE_DATE specified in the group attributes while not supporting it"); } - + } else { String name = attr.getName(); try { @@ -1894,7 +1894,7 @@ private DummyGroup convertToGroup(Set createAttributes) throws Connec return newGroup; } - + private DummyPrivilege convertToPriv(Set createAttributes) throws ConnectException, FileNotFoundException, ConflictException { String icfName = Utils.getMandatoryStringAttribute(createAttributes,Name.NAME); if (configuration.getUpCaseName()) { @@ -1905,16 +1905,16 @@ private DummyPrivilege convertToPriv(Set createAttributes) throws Con for (Attribute attr : createAttributes) { if (attr.is(Uid.NAME)) { throw new IllegalArgumentException("UID explicitly specified in the group attributes"); - + } else if (attr.is(Name.NAME)) { // Skip, already processed } else if (attr.is(OperationalAttributeInfos.PASSWORD.getName())) { throw new IllegalArgumentException("Password specified for a privilege"); - + } else if (attr.is(OperationalAttributeInfos.ENABLE.getName())) { throw new IllegalArgumentException("Unsupported ENABLE attribute in privilege"); - + } else { String name = attr.getName(); try { @@ -1927,7 +1927,7 @@ private DummyPrivilege convertToPriv(Set createAttributes) throws Con return newPriv; } - + private DummyOrg convertToOrg(Set createAttributes) throws ConnectException, FileNotFoundException, ConflictException { String icfName = Utils.getMandatoryStringAttribute(createAttributes,Name.NAME); if (configuration.getUpCaseName()) { @@ -1938,16 +1938,16 @@ private DummyOrg convertToOrg(Set createAttributes) throws ConnectExc for (Attribute attr : createAttributes) { if (attr.is(Uid.NAME)) { throw new IllegalArgumentException("UID explicitly specified in the org attributes"); - + } else if (attr.is(Name.NAME)) { // Skip, already processed } else if (attr.is(OperationalAttributeInfos.PASSWORD.getName())) { throw new IllegalArgumentException("Password specified for a org"); - + } else if (attr.is(OperationalAttributeInfos.ENABLE.getName())) { throw new IllegalArgumentException("Unsupported ENABLE attribute in org"); - + } else { String name = attr.getName(); try { @@ -1971,7 +1971,7 @@ private Boolean getBoolean(Attribute attr) { } return ((Boolean)object).booleanValue(); } - + private boolean getBooleanNotNull(Attribute attr) { if (attr.getValue() == null || attr.getValue().isEmpty()) { throw new IllegalArgumentException("Empty "+attr.getName()+" attribute was provided"); @@ -1982,17 +1982,17 @@ private boolean getBooleanNotNull(Attribute attr) { } return ((Boolean)object).booleanValue(); } - + private Date getDate(Attribute attr) { if (attr.getValue() == null || attr.getValue().isEmpty()) { throw new IllegalArgumentException("Empty date attribute was provided"); } Object object = attr.getValue().get(0); - + if (object == null){ return null; } - + if (!(object instanceof Long)) { throw new IllegalArgumentException("Date attribute was provided as "+object.getClass().getName()+" while expecting long"); } @@ -2022,7 +2022,7 @@ public void access(char[] passwdChars) { } account.setPassword(passwdArray[0]); } - + private void checkPasswordPolicies(String password) { if (configuration.getMinPasswordLength() != null) { if (password == null || password.isEmpty()) { @@ -2033,7 +2033,7 @@ private void checkPasswordPolicies(String password) { } } } - + private boolean attributesToGetHasAttribute(Collection attributesToGet, String attrName) { if (attributesToGet == null) { return true; @@ -2046,7 +2046,7 @@ public void validate(ObjectClass oc) { throw new IllegalArgumentException("Object class must not be null."); } } - + public void validate(Uid uid) { if (uid == null) { throw new IllegalArgumentException("Uid must not be null."); @@ -2060,29 +2060,29 @@ public void validate(Uid uid) { } } } - + private void validate(Filter filter) { if (filter == null) { return; } if (nameHintChecksEnabled()) { filter.accept(new FilterVisitor() { - + @Override public String visitAndFilter(String p, AndFilter filter) { return null; } - + @Override public String visitContainsFilter(String p, ContainsFilter filter) { return null; } - + @Override public String visitContainsAllValuesFilter(String p, ContainsAllValuesFilter filter) { return null; } - + @Override public String visitEqualsFilter(String p, EqualsFilter filter) { if (filter.getAttribute().is(Uid.NAME)) { @@ -2096,56 +2096,56 @@ public String visitEqualsFilter(String p, EqualsFilter filter) { } return null; } - + @Override public String visitExtendedFilter(String p, Filter filter) { return null; } - + @Override public String visitGreaterThanFilter(String p, GreaterThanFilter filter) { return null; } - + @Override public String visitGreaterThanOrEqualFilter(String p, GreaterThanOrEqualFilter filter) { return null; } - + @Override public String visitLessThanFilter(String p, LessThanFilter filter) { return null; } - + @Override public String visitLessThanOrEqualFilter(String p, LessThanOrEqualFilter filter) { return null; } - + @Override public String visitNotFilter(String p, NotFilter filter) { return null; } - + @Override public String visitOrFilter(String p, OrFilter filter) { return null; } - + @Override public String visitStartsWithFilter(String p, StartsWithFilter filter) { return null; } - + @Override public String visitEndsWithFilter(String p, EndsWithFilter filter) { return null; } - + }, null); } } - + private boolean nameHintChecksEnabled() { return configuration.isRequireNameHint() && !resource.isDisableNameHintChecks(); } diff --git a/icf-connectors/dummy-connector/src/main/java/com/evolveum/icf/dummy/connector/DummyFilterTranslator.java b/icf-connectors/dummy-connector/src/main/java/com/evolveum/icf/dummy/connector/DummyFilterTranslator.java index a14662c8b1b..49c5921bba1 100644 --- a/icf-connectors/dummy-connector/src/main/java/com/evolveum/icf/dummy/connector/DummyFilterTranslator.java +++ b/icf-connectors/dummy-connector/src/main/java/com/evolveum/icf/dummy/connector/DummyFilterTranslator.java @@ -29,7 +29,7 @@ public class DummyFilterTranslator implements FilterTranslator { private static final Log log = Log.getLog(DummyFilterTranslator.class); - + /* (non-Javadoc) * @see org.identityconnectors.framework.common.objects.filter.FilterTranslator#translate(org.identityconnectors.framework.common.objects.filter.Filter) */ diff --git a/icf-connectors/dummy-connector/src/main/java/com/evolveum/icf/dummy/connector/Utils.java b/icf-connectors/dummy-connector/src/main/java/com/evolveum/icf/dummy/connector/Utils.java index d13f3cb3508..3e83f2a4604 100644 --- a/icf-connectors/dummy-connector/src/main/java/com/evolveum/icf/dummy/connector/Utils.java +++ b/icf-connectors/dummy-connector/src/main/java/com/evolveum/icf/dummy/connector/Utils.java @@ -24,10 +24,10 @@ * * @author lazyman * @author Radovan Semancik - * + * */ public class Utils { - + public static String getMandatoryStringAttribute(Set attributes, String attributeName) { String value = getAttributeSingleValue(attributes, attributeName, String.class); if (value == null) { @@ -35,7 +35,7 @@ public static String getMandatoryStringAttribute(Set attributes, Stri } return value; } - + @SuppressWarnings("unchecked") public static T getAttributeSingleValue(Set attributes, String attributeName, Class type) { for (Attribute attr : attributes) { diff --git a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/BreakMode.java b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/BreakMode.java index 22c45cd5fcd..53c7cc3b3cd 100644 --- a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/BreakMode.java +++ b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/BreakMode.java @@ -20,7 +20,7 @@ * */ public enum BreakMode { - + NONE, NETWORK, IO, 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 a5490622867..95c759c98e3 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 @@ -25,13 +25,13 @@ * */ public class DummyAccount extends DummyObject { - + public static final String ATTR_FULLNAME_NAME = "fullname"; public static final String ATTR_DESCRIPTION_NAME = "description"; public static final String ATTR_INTERESTS_NAME = "interests"; public static final String ATTR_PRIVILEGES_NAME = "privileges"; public static final String ATTR_INTERNAL_ID = "internalId"; - + private String password = null; private Boolean lockout = null; @@ -42,7 +42,7 @@ public DummyAccount() { public DummyAccount(String username) { super(username); } - + public String getPassword() { return password; } @@ -51,7 +51,7 @@ public void setPassword(String password) throws ConnectException, FileNotFoundEx checkModifyBreak(); this.password = password; } - + public Boolean isLockout() { return lockout; } @@ -78,7 +78,7 @@ public String getShortTypeName() { @Override public String toStringContent() { - return super.toStringContent() + ", password=" + password; + return super.toStringContent() + ", password=" + password; } @Override @@ -92,5 +92,5 @@ protected void extendDebugDump(StringBuilder sb, int indent) { DebugUtil.debugDumpWithLabelToStringLn(sb, "Password", password, indent + 1); DebugUtil.debugDumpWithLabelToString(sb, "Lockout", lockout, indent + 1); } - + } diff --git a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyAttributeDefinition.java b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyAttributeDefinition.java index 5a41ba4803a..2bbcc373e2d 100644 --- a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyAttributeDefinition.java +++ b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyAttributeDefinition.java @@ -20,13 +20,13 @@ * */ public class DummyAttributeDefinition { - + private String attributeName; private Class attributeType; private boolean isRequired; private boolean isMulti; private boolean isReturnedByDefault = true; - + public DummyAttributeDefinition(String attributeName, Class attributeType) { super(); this.attributeName = attributeName; @@ -43,35 +43,35 @@ public DummyAttributeDefinition(String attributeName, Class attributeType, bo this.isRequired = isRequired; this.isMulti = isMulti; } - + public String getAttributeName() { return attributeName; } - + public void setAttributeName(String attributeName) { this.attributeName = attributeName; } - + public Class getAttributeType() { return attributeType; } - + public void setAttributeType(Class attributeType) { this.attributeType = attributeType; } - + public boolean isRequired() { return isRequired; } - + public void setRequired(boolean isRequired) { this.isRequired = isRequired; } - + public boolean isMulti() { return isMulti; } - + public void setMulti(boolean isMulti) { this.isMulti = isMulti; } diff --git a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyDelta.java b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyDelta.java index 5342f18ca6e..55496bb2cee 100644 --- a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyDelta.java +++ b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyDelta.java @@ -20,13 +20,13 @@ * */ public class DummyDelta { - + private int syncToken; private Class objectClass; private String objectId; private String objectName; private DummyDeltaType type; - + DummyDelta(int syncToken, Class objectClass, String objectId, String objectName, DummyDeltaType type) { this.syncToken = syncToken; this.objectClass = objectClass; @@ -38,11 +38,11 @@ public class DummyDelta { public int getSyncToken() { return syncToken; } - + public void setSyncToken(int syncToken) { this.syncToken = syncToken; } - + public Class getObjectClass() { return objectClass; } @@ -54,7 +54,7 @@ public void setObjectClass(Class objectClass) { public String getObjectId() { return objectId; } - + public void setObjectId(String accountId) { this.objectId = accountId; } diff --git a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyDeltaType.java b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyDeltaType.java index fdf7f10224e..310554ce969 100644 --- a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyDeltaType.java +++ b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyDeltaType.java @@ -20,11 +20,11 @@ * */ public enum DummyDeltaType { - + ADD, - + MODIFY, - + DELETE; } 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 525487184bc..6ad08e3ed09 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 @@ -26,7 +26,7 @@ * */ public class DummyGroup extends DummyObject { - + public static final String ATTR_MEMBERS_NAME = "members"; public DummyGroup() { @@ -36,11 +36,11 @@ public DummyGroup() { public DummyGroup(String username) { super(username); } - + public Collection getMembers() { return getAttributeValues(ATTR_MEMBERS_NAME, String.class); } - + public void addMember(String newMember) throws SchemaViolationException, ConnectException, FileNotFoundException, ConflictException { addAttributeValue(ATTR_MEMBERS_NAME, newMember); } @@ -56,7 +56,7 @@ public boolean containsMember(String member) { public void removeMember(String newMember) throws SchemaViolationException, ConnectException, FileNotFoundException, ConflictException { removeAttributeValue(ATTR_MEMBERS_NAME, newMember); } - + @Override protected DummyObjectClass getObjectClass() { return resource.getGroupObjectClass(); @@ -74,7 +74,7 @@ public String getShortTypeName() { @Override public String toStringContent() { - return super.toStringContent() + ", members=" + getMembers(); + return super.toStringContent() + ", members=" + getMembers(); } @Override @@ -87,5 +87,5 @@ protected void extendDebugDump(StringBuilder sb, int indent) { sb.append("\n"); DebugUtil.debugDumpWithLabelToStringLn(sb, "Members", getMembers(), indent + 1); } - + } diff --git a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyObject.java b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyObject.java index 382725f2f9c..d8425ba90a7 100644 --- a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyObject.java +++ b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyObject.java @@ -39,7 +39,7 @@ * */ public abstract class DummyObject implements DebugDumpable { - + private String id; // private int internalId = -1; private String name; @@ -55,7 +55,7 @@ public abstract class DummyObject implements DebugDumpable { public DummyObject() { } - + public String getId() { return id; } @@ -63,11 +63,11 @@ public String getId() { public void setId(String id) { this.id = id; } - + public DummyObject(String name) { this.name = name; } - + public DummyResource getResource() { return resource; } @@ -83,7 +83,7 @@ public String getName() { public void setName(String username) { this.name = username; } - + public Boolean isEnabled() { return enabled; } @@ -92,6 +92,7 @@ public void setEnabled(Boolean enabled) throws ConnectException, FileNotFoundExc checkModifyBreak(); delayOperation(); this.enabled = enabled; + recordModify(); } public Date getValidFrom() { @@ -102,6 +103,7 @@ public void setValidFrom(Date validFrom) throws ConnectException, FileNotFoundEx checkModifyBreak(); delayOperation(); this.validFrom = validFrom; + recordModify(); } public Date getValidTo() { @@ -112,6 +114,7 @@ public void setValidTo(Date validTo) throws ConnectException, FileNotFoundExcept checkModifyBreak(); delayOperation(); this.validTo = validTo; + recordModify(); } public BreakMode getModifyBreakMode() { @@ -125,12 +128,12 @@ public void setModifyBreakMode(BreakMode modifyBreakMode) { public Set getAttributeNames() { return attributes.keySet(); } - + public Set getAttributeValues(String attrName, Class type) { Set values = attributes.get(attrName); return (Set)values; } - + public T getAttributeValue(String attrName, Class type) { Set values = getAttributeValues(attrName, type); if (values == null || values.isEmpty()) { @@ -141,7 +144,7 @@ public T getAttributeValue(String attrName, Class type) { } return values.iterator().next(); } - + public String getAttributeValue(String attrName) { return getAttributeValue(attrName,String.class); } @@ -151,7 +154,7 @@ public void replaceAttributeValue(String name, Object value) throws SchemaViolat values.add(value); replaceAttributeValues(name, values); } - + public void replaceAttributeValues(String name, Collection values) throws SchemaViolationException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { checkModifyBreak(); delayOperation(); @@ -166,7 +169,7 @@ public void replaceAttributeValues(String name, Collection values) throw checkSchema(name, values, "replace"); recordModify(); } - + public void replaceAttributeValues(String name, Object... values) throws SchemaViolationException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { checkModifyBreak(); delayOperation(); @@ -185,7 +188,7 @@ public void replaceAttributeValues(String name, Object... values) throws SchemaV } recordModify(); } - + public void addAttributeValue(String name, Object value) throws SchemaViolationException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { Collection values = new ArrayList(1); values.add(value); @@ -205,7 +208,7 @@ public void addAttributeValues(String name, Collection valuesToAdd) thro } recordModify(); } - + public void addAttributeValues(String name, String... valuesToAdd) throws SchemaViolationException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { checkModifyBreak(); delayOperation(); @@ -219,7 +222,7 @@ public void addAttributeValues(String name, String... valuesToAdd) throws Schema } recordModify(); } - + private void addAttributeValue(String attrName, Set currentValues, Object valueToAdd) throws SchemaViolationException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { checkModifyBreak(); delayOperation(); @@ -235,7 +238,7 @@ private void addAttributeValue(String attrName, Set currentValues, Objec } } } - + if (resource != null && resource.isMonsterization() && DummyResource.VALUE_MONSTER.equals(valueToAdd)) { Iterator iterator = currentValues.iterator(); while (iterator.hasNext()) { @@ -244,15 +247,15 @@ private void addAttributeValue(String attrName, Set currentValues, Objec } } } - + Set valuesToCheck = new HashSet(); valuesToCheck.addAll(currentValues); valuesToCheck.add(valueToAdd); checkSchema(attrName, valuesToCheck, "add"); - + currentValues.add(valueToAdd); } - + public void removeAttributeValue(String name, Object value) throws SchemaViolationException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { Collection values = new ArrayList(); values.add(value); @@ -267,19 +270,19 @@ public void removeAttributeValues(String name, Collection values) throws currentValues = new HashSet(); attributes.put(name, currentValues); } - + Set valuesToCheck = new HashSet(); valuesToCheck.addAll(currentValues); valuesToCheck.removeAll(values); checkSchema(name, valuesToCheck, "remove"); - + Iterator iterator = currentValues.iterator(); boolean foundMember = false; - + if (name.equals(DummyGroup.ATTR_MEMBERS_NAME) && !resource.isTolerateDuplicateValues()){ checkIfExist(values, currentValues); } - + while(iterator.hasNext()) { Object currentValue = iterator.next(); boolean found = false; @@ -299,9 +302,9 @@ public void removeAttributeValues(String name, Collection values) throws if (found) { iterator.remove(); } - + } - + recordModify(); } @@ -346,7 +349,7 @@ private void checkIfExist(Collection valuesToDelete, Set current } } } - + if (!found){ throw new SchemaViolationException("no such member: " + valueToDelete + " in " + currentValues); } @@ -390,7 +393,7 @@ private void recordModify() { resource.recordModify(this); } } - + private void delayOperation() { if (resource != null) { resource.delayOperation(); @@ -447,12 +450,12 @@ public DummyAttributeDefinition getAttributeDefinition(String attrName) { abstract protected DummyObjectClass getObjectClassNoExceptions(); public abstract String getShortTypeName(); - + @Override public String toString() { return getClass().getSimpleName()+"(" + toStringContent() + ")"; } - + protected String toStringContent() { return "name=" + name + ", attributes=" + attributes + ", enabled=" + enabled; } diff --git a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyObjectClass.java b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyObjectClass.java index 5244784eed3..61e8f3cb392 100644 --- a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyObjectClass.java +++ b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyObjectClass.java @@ -23,7 +23,7 @@ * */ public class DummyObjectClass { - + private Collection attributeDefinitions; public DummyObjectClass() { @@ -33,7 +33,7 @@ public DummyObjectClass() { public Collection getAttributeDefinitions() { return attributeDefinitions; } - + public DummyAttributeDefinition getAttributeDefinition(String attrName) { for (DummyAttributeDefinition attrDef: attributeDefinitions) { if (attrName.equals(attrDef.getAttributeName())) { @@ -46,11 +46,11 @@ public DummyAttributeDefinition getAttributeDefinition(String attrName) { public void add(DummyAttributeDefinition attrDef) { attributeDefinitions.add(attrDef); } - + public void clear() { attributeDefinitions.clear(); } - + public void addAttributeDefinition(String attributeName) { addAttributeDefinition(attributeName,String.class,false,false); } @@ -68,5 +68,5 @@ public void addAttributeDefinition(String attributeName, Class attributeType, DummyAttributeDefinition attrDef = new DummyAttributeDefinition(attributeName,attributeType,isRequired,isMulti); add(attrDef); } - + } diff --git a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyOrg.java b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyOrg.java index 62f43725bdf..cfee87033d8 100644 --- a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyOrg.java +++ b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyOrg.java @@ -23,7 +23,7 @@ * */ public class DummyOrg extends DummyObject { - + public DummyOrg() { super(); } @@ -31,7 +31,7 @@ public DummyOrg() { public DummyOrg(String username) { super(username); } - + @Override protected DummyObjectClass getObjectClass() throws ConnectException, FileNotFoundException, SchemaViolationException { return resource.getPrivilegeObjectClass(); @@ -46,5 +46,5 @@ protected DummyObjectClass getObjectClassNoExceptions() { public String getShortTypeName() { return "org"; } - + } diff --git a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyPrivilege.java b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyPrivilege.java index 90a4a521451..2d2c7429ca4 100644 --- a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyPrivilege.java +++ b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyPrivilege.java @@ -21,7 +21,7 @@ * */ public class DummyPrivilege extends DummyObject { - + public DummyPrivilege() { super(); } @@ -29,7 +29,7 @@ public DummyPrivilege() { public DummyPrivilege(String username) { super(username); } - + @Override protected DummyObjectClass getObjectClass() { return resource.getPrivilegeObjectClass(); @@ -47,8 +47,8 @@ public String getShortTypeName() { @Override public String toStringContent() { - return super.toStringContent(); + return super.toStringContent(); } - + } 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 04e6222c466..e27cf326409 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 @@ -39,40 +39,40 @@ /** * Resource for use with dummy ICF connector. - * + * * This is a simple Java object that pretends to be a resource. It has accounts and * account schema. It has operations to manipulate accounts, execute scripts and so on - * almost like a real resource. The purpose is to simulate a real resource with a very + * almost like a real resource. The purpose is to simulate a real resource with a very * little overhead. - * + * * The resource is a singleton, therefore the resource instance can be shared by * the connector and the test code. The usual story is like this: - * + * * 1) test class fetches first instance of the resource (getInstance). This will cause * loading of the resource class in the test (parent) classloader. - * + * * 2) test class configures the connector (e.g. schema) usually by calling the populateWithDefaultSchema() method. - * + * * 3) test class initializes IDM. This will cause connector initialization. The connector will fetch * the instance of dummy resource. As it was loaded by the parent classloader, it will get the same instance * as the test class. - * + * * 4) test class invokes IDM operation. That will invoke connector and change the resource. - * + * * 5) test class will access resource directly to see if the operation went OK. - * + * * The dummy resource is a separate package (JAR) from the dummy connector. Connector has its own * classloader. If the resource would be the same package as connector, it will get loaded by the * connector classloader regardless whether it is already loaded by the parent classloader. - * + * * @author Radovan Semancik * */ public class DummyResource implements DebugDumpable { - + private static final Trace LOGGER = TraceManager.getTrace(DummyResource.class); private static final Random RND = new Random(); - + public static final String ATTRIBUTE_CONNECTOR_TO_STRING = "connectorToString"; public static final String ATTRIBUTE_CONNECTOR_STATIC_VAL = "connectorStaticVal"; public static final String ATTRIBUTE_CONNECTOR_CONFIGURATION_TO_STRING = "connectorConfigurationToString"; @@ -113,7 +113,7 @@ public class DummyResource implements DebugDumpable { * MID-3727 */ private boolean monsterization = false; - + public static final String VALUE_MONSTER = "monster"; public static final String VALUE_COOKIE = "cookie"; @@ -122,18 +122,18 @@ public class DummyResource implements DebugDumpable { public static final String POWERFAIL_ARG_ERROR_GENERIC = "generic"; public static final String POWERFAIL_ARG_ERROR_RUNTIME = "runtime"; public static final String POWERFAIL_ARG_ERROR_IO = "io"; - + private BreakMode schemaBreakMode = BreakMode.NONE; private BreakMode getBreakMode = BreakMode.NONE; private BreakMode addBreakMode = BreakMode.NONE; private BreakMode modifyBreakMode = BreakMode.NONE; private BreakMode deleteBreakMode = BreakMode.NONE; - + private boolean blockOperations = false; private boolean generateAccountDescriptionOnCreate = false; // simulates volatile behavior (on create) private boolean generateAccountDescriptionOnUpdate = false; // simulates volatile behavior (on update) - + private boolean disableNameHintChecks = false; // Following two properties are just copied from the connector @@ -141,9 +141,9 @@ public class DummyResource implements DebugDumpable { // completely useless. private String uselessString; private String uselessGuardedString; - + private static Map instances = new HashMap(); - + DummyResource() { allObjects = Collections.synchronizedMap(new LinkedHashMap()); accounts = Collections.synchronizedMap(new LinkedHashMap()); @@ -158,7 +158,7 @@ public class DummyResource implements DebugDumpable { deltas = Collections.synchronizedList(new ArrayList()); latestSyncToken = 0; } - + /** * Clears everything, just like the resouce was just created. */ @@ -179,11 +179,11 @@ public void reset() { operationDelayRange = 0; resetBreakMode(); } - + public static DummyResource getInstance() { return getInstance(null); } - + public static DummyResource getInstance(String instanceName) { DummyResource instance = instances.get(instanceName); if (instance == null) { @@ -193,7 +193,7 @@ public static DummyResource getInstance(String instanceName) { } return instance; } - + public String getInstanceName() { return instanceName; } @@ -213,11 +213,11 @@ public void setTolerateDuplicateValues(boolean tolerateDuplicateValues) { public boolean isGenerateDefaultValues() { return generateDefaultValues; } - + public void setGenerateDefaultValues(boolean generateDefaultValues) { this.generateDefaultValues = generateDefaultValues; } - + public boolean isEnforceUniqueName() { return enforceUniqueName; } @@ -249,7 +249,7 @@ public BreakMode getAddBreakMode() { public void setAddBreakMode(BreakMode addBreakMode) { this.addBreakMode = addBreakMode; } - + public BreakMode getGetBreakMode() { return getBreakMode; } @@ -281,7 +281,7 @@ public void setBreakMode(BreakMode breakMode) { this.modifyBreakMode = breakMode; this.deleteBreakMode = breakMode; } - + public void resetBreakMode() { setBreakMode(BreakMode.NONE); } @@ -381,15 +381,15 @@ public int getConnectionCount() { public synchronized void connect() { connectionCount++; } - + public synchronized void disconnect() { connectionCount--; } - + public void assertNoConnections() { assert connectionCount == 0 : "Dummy resource: "+connectionCount+" connections still open"; } - + public synchronized void recordWriteOperation(String operation) { writeOperationCount++; } @@ -405,7 +405,7 @@ public int getGroupMembersReadCount() { public void setGroupMembersReadCount(int groupMembersReadCount) { this.groupMembersReadCount = groupMembersReadCount; } - + public void recordGroupMembersReadCount() { groupMembersReadCount++; traceOperation("groupMembersRead", groupMembersReadCount); @@ -424,7 +424,7 @@ public DummyObjectClass getAccountObjectClassNoExceptions() { public DummyObjectClass getGroupObjectClass() { return groupObjectClass; } - + public DummyObjectClass getPrivilegeObjectClass() { return privilegeObjectClass; } @@ -440,14 +440,14 @@ public void addAuxiliaryObjectClass(String name, DummyObjectClass objectClass) { public int getNumberOfObjectclasses() { return 4 + auxiliaryObjectClassMap.size(); } - + public Collection listAccounts() throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { checkBlockOperations(); breakIt(getBreakMode, "get"); delayOperation(); return accounts.values(); } - + private T getObjectByName(Map map, String name, boolean checkBreak) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { if (!enforceUniqueName) { throw new IllegalStateException("Attempt to search object by name while resource is in non-unique name mode"); @@ -459,39 +459,39 @@ private T getObjectByName(Map map, String name } return map.get(normalize(name)); } - + public DummyAccount getAccountByUsername(String username) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { return getObjectByName(accounts, username, true); } - + public DummyAccount getAccountByUsername(String username, boolean checkBreak) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { return getObjectByName(accounts, username, checkBreak); } - + public DummyGroup getGroupByName(String name) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { return getObjectByName(groups, name, true); } - + public DummyGroup getGroupByName(String name, boolean checkBreak) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { return getObjectByName(groups, name, checkBreak); } - + public DummyPrivilege getPrivilegeByName(String name) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { return getObjectByName(privileges, name, true); } - + public DummyPrivilege getPrivilegeByName(String name, boolean checkBreak) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { return getObjectByName(privileges, name, checkBreak); } - + public DummyOrg getOrgByName(String name) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { return getObjectByName(orgs, name, true); } - + public DummyOrg getOrgByName(String name, boolean checkBreak) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { return getObjectByName(orgs, name, checkBreak); } - + private T getObjectById(Class expectedClass, String id, boolean checkBreak) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { checkBlockOperations(); if (checkBreak) { @@ -507,35 +507,35 @@ private T getObjectById(Class expectedClass, String i } return (T)dummyObject; } - + public DummyAccount getAccountById(String id) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { return getObjectById(DummyAccount.class, id, true); } - + public DummyAccount getAccountById(String id, boolean checkBreak) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { return getObjectById(DummyAccount.class, id, checkBreak); } - + public DummyGroup getGroupById(String id) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { return getObjectById(DummyGroup.class, id, true); } - + public DummyGroup getGroupById(String id, boolean checkBreak) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { return getObjectById(DummyGroup.class, id, checkBreak); } - + public DummyPrivilege getPrivilegeById(String id) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { return getObjectById(DummyPrivilege.class, id, true); } - + public DummyPrivilege getPrivilegeById(String id, boolean checkBreak) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { return getObjectById(DummyPrivilege.class, id, checkBreak); } - + public DummyOrg getOrgById(String id) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { return getObjectById(DummyOrg.class, id, true); } - + public DummyOrg getOrgById(String id, boolean checkBreak) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { return getObjectById(DummyOrg.class, id, checkBreak); } @@ -546,27 +546,27 @@ public Collection listGroups() throws ConnectException, FileNotFound delayOperation(); return groups.values(); } - + public Collection listPrivileges() throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { checkBlockOperations(); breakIt(getBreakMode, "get"); delayOperation(); return privileges.values(); } - + public Collection listOrgs() throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { checkBlockOperations(); breakIt(getBreakMode, "get"); delayOperation(); return orgs.values(); } - + private synchronized String addObject(Map map, T newObject) throws ObjectAlreadyExistsException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { checkBlockOperations(); recordWriteOperation("add"); breakIt(addBreakMode, "add"); delayOperation(); - + Class type = newObject.getClass(); String normalName = normalize(newObject.getName()); if (normalName != null && forbiddenNames != null && forbiddenNames.contains(normalName)) { @@ -578,52 +578,52 @@ private synchronized String addObject(Map map, if (allObjects.containsKey(newId)) { throw new IllegalStateException("The hell is frozen over. The impossible has happened. ID "+newId+" already exists ("+ type.getSimpleName()+" with identifier "+normalName+")"); } - + //this is "resource-generated" attribute (used to simulate resource which generate by default attributes which we need to sync) if (generateDefaultValues){ // int internalId = allObjects.size(); newObject.addAttributeValue(DummyAccount.ATTR_INTERNAL_ID, new Random().nextInt()); } - - + + String mapKey; if (enforceUniqueName) { mapKey = normalName; } else { mapKey = newId; } - + if (map.containsKey(mapKey)) { throw new ObjectAlreadyExistsException(type.getSimpleName()+" with name '"+normalName+"' already exists"); } - + newObject.setResource(this); map.put(mapKey, newObject); allObjects.put(newId, newObject); - + if (syncStyle != DummySyncStyle.NONE) { int syncToken = nextSyncToken(); DummyDelta delta = new DummyDelta(syncToken, type, newId, newObject.getName(), DummyDeltaType.ADD); deltas.add(delta); } - + return newObject.getName(); } - + private synchronized void deleteObjectByName(Class type, Map map, String name) throws ObjectDoesNotExistException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { checkBlockOperations(); recordWriteOperation("delete"); breakIt(deleteBreakMode, "delete"); delayOperation(); - + String normalName = normalize(name); T existingObject; - + if (!enforceUniqueName) { throw new IllegalStateException("Whoops! got into deleteObjectByName without enforceUniqueName"); } - + if (map.containsKey(normalName)) { existingObject = map.get(normalName); map.remove(normalName); @@ -631,14 +631,14 @@ private synchronized void deleteObjectByName(Class ty } else { throw new ObjectDoesNotExistException(type.getSimpleName()+" with name '"+normalName+"' does not exist"); } - + if (syncStyle != DummySyncStyle.NONE) { int syncToken = nextSyncToken(); DummyDelta delta = new DummyDelta(syncToken, type, existingObject.getId(), name, DummyDeltaType.DELETE); deltas.add(delta); } } - + public void deleteAccountById(String id) throws ConnectException, FileNotFoundException, ObjectDoesNotExistException, SchemaViolationException, ConflictException { deleteObjectById(DummyAccount.class, accounts, id); } @@ -650,7 +650,7 @@ public void deleteGroupById(String id) throws ConnectException, FileNotFoundExce public void deletePrivilegeById(String id) throws ConnectException, FileNotFoundException, ObjectDoesNotExistException, SchemaViolationException, ConflictException { deleteObjectById(DummyPrivilege.class, privileges, id); } - + public void deleteOrgById(String id) throws ConnectException, FileNotFoundException, ObjectDoesNotExistException, SchemaViolationException, ConflictException { deleteObjectById(DummyOrg.class, orgs, id); } @@ -660,7 +660,7 @@ private synchronized void deleteObjectById(Class type recordWriteOperation("delete"); breakIt(deleteBreakMode, "delete"); delayOperation(); - + DummyObject object = allObjects.get(id); if (object == null) { throw new ObjectDoesNotExistException(type.getSimpleName()+" with id '"+id+"' does not exist"); @@ -670,22 +670,22 @@ private synchronized void deleteObjectById(Class type } T existingObject = (T)object; String normalName = normalize(object.getName()); - + allObjects.remove(id); - + String mapKey; if (enforceUniqueName) { mapKey = normalName; } else { mapKey = id; } - + if (map.containsKey(mapKey)) { map.remove(mapKey); } else { throw new ObjectDoesNotExistException(type.getSimpleName()+" with name '"+normalName+"' does not exist"); } - + if (syncStyle != DummySyncStyle.NONE) { int syncToken = nextSyncToken(); DummyDelta delta = new DummyDelta(syncToken, type, id, object.getName(), DummyDeltaType.DELETE); @@ -698,7 +698,7 @@ private void renameObject(Class type, Map m recordWriteOperation("modify"); breakIt(modifyBreakMode, "modify"); delayOperation(); - + T existingObject; if (enforceUniqueName) { String normalOldName = normalize(oldName); @@ -727,7 +727,7 @@ public String addAccount(DummyAccount newAccount) throws ObjectAlreadyExistsExce } return addObject(accounts, newAccount); } - + public void deleteAccountByName(String id) throws ObjectDoesNotExistException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { deleteObjectByName(DummyAccount.class, accounts, id); } @@ -755,7 +755,7 @@ public void changeDescriptionIfNeeded(DummyAccount account) throws SchemaViolati public String addGroup(DummyGroup newGroup) throws ObjectAlreadyExistsException, ConnectException, FileNotFoundException, SchemaViolationException, SchemaViolationException, ConflictException { return addObject(groups, newGroup); } - + public void deleteGroupByName(String id) throws ObjectDoesNotExistException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { deleteObjectByName(DummyGroup.class, groups, id); } @@ -763,11 +763,11 @@ public void deleteGroupByName(String id) throws ObjectDoesNotExistException, Con public void renameGroup(String id, String oldName, String newName) throws ObjectDoesNotExistException, ObjectAlreadyExistsException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { renameObject(DummyGroup.class, groups, id, oldName, newName); } - + public String addPrivilege(DummyPrivilege newGroup) throws ObjectAlreadyExistsException, ConnectException, FileNotFoundException, SchemaViolationException, SchemaViolationException, ConflictException { return addObject(privileges, newGroup); } - + public void deletePrivilegeByName(String id) throws ObjectDoesNotExistException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { deleteObjectByName(DummyPrivilege.class, privileges, id); } @@ -775,11 +775,11 @@ public void deletePrivilegeByName(String id) throws ObjectDoesNotExistException, public void renamePrivilege(String id, String oldName, String newName) throws ObjectDoesNotExistException, ObjectAlreadyExistsException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { renameObject(DummyPrivilege.class, privileges, id, oldName, newName); } - + public String addOrg(DummyOrg newGroup) throws ObjectAlreadyExistsException, ConnectException, FileNotFoundException, SchemaViolationException, SchemaViolationException, ConflictException { return addObject(orgs, newGroup); } - + public void deleteOrgByName(String id) throws ObjectDoesNotExistException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { deleteObjectByName(DummyOrg.class, orgs, id); } @@ -787,7 +787,7 @@ public void deleteOrgByName(String id) throws ObjectDoesNotExistException, Conne public void renameOrg(String id, String oldName, String newName) throws ObjectDoesNotExistException, ObjectAlreadyExistsException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { renameObject(DummyOrg.class, orgs, id, oldName, newName); } - + void recordModify(DummyObject dObject) { recordWriteOperation("modify"); if (syncStyle != DummySyncStyle.NONE) { @@ -804,19 +804,19 @@ void recordModify(DummyObject dObject) { public List getScriptHistory() { return scriptHistory; } - + /** * Clears the script history. */ public void purgeScriptHistory() { scriptHistory.clear(); } - + /** * Pretend to run script on the resource. * The script is actually not executed, it is only recorded in the script history * and can be fetched by getScriptHistory(). - * + * * @param scriptCode code of the script */ public void runScript(String language, String scriptCode, Map params) throws FileNotFoundException { @@ -834,7 +834,7 @@ public void runScript(String language, String scriptCode, Map pa } } } - + /** * Populates the resource with some kind of "default" schema. This is a schema that should suit * majority of basic test cases. @@ -866,7 +866,7 @@ private synchronized int nextSyncToken() { public int getLatestSyncToken() { return latestSyncToken; } - + private String normalize(String id) { if (caseIgnoreId) { return StringUtils.lowerCase(id); @@ -875,7 +875,7 @@ private String normalize(String id) { } } - + public List getDeltasSince(int syncToken) { List result = new ArrayList(); for (DummyDelta delta: deltas) { @@ -885,7 +885,7 @@ public List getDeltasSince(int syncToken) { } return result; } - + void breakIt(BreakMode breakMode, String operation) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { if (breakMode == BreakMode.NONE) { return; @@ -910,7 +910,7 @@ void breakIt(BreakMode breakMode, String operation) throws ConnectException, Fil throw new RuntimeException("Unknown "+operation+" break mode "+getBreakMode); } } - + void delayOperation() { if (operationDelayRange == 0) { return; @@ -924,7 +924,7 @@ void delayOperation() { LOGGER.debug("Operation delay on dummy {} interrupted: {}", instanceName, e.getMessage()); } } - + private synchronized void checkBlockOperations() { if (blockOperations) { try { @@ -936,17 +936,17 @@ private synchronized void checkBlockOperations() { } } } - + public synchronized void unblock() { LOGGER.info("Unblocking"); this.notify(); } - + public synchronized void unblockAll() { LOGGER.info("Unblocking all"); this.notifyAll(); } - + private void traceOperation(String opName, long counter) { LOGGER.info("MONITOR dummy '{}' {} ({})", instanceName, opName, counter); if (LOGGER.isDebugEnabled()) { @@ -972,12 +972,12 @@ 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/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummySyncStyle.java b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummySyncStyle.java index fa471934779..bfc89d7b43a 100644 --- a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummySyncStyle.java +++ b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummySyncStyle.java @@ -20,11 +20,11 @@ * */ public enum DummySyncStyle { - + NONE, - + DUMB, - + SMART; } diff --git a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/ScriptHistoryEntry.java b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/ScriptHistoryEntry.java index 6c2a58c3308..8b81d19adc5 100644 --- a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/ScriptHistoryEntry.java +++ b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/ScriptHistoryEntry.java @@ -22,12 +22,12 @@ * */ public class ScriptHistoryEntry { - + private String language; private String code; private Map params; private long timestamp; - + public ScriptHistoryEntry(String language, String code, Map params) { super(); this.language = language; @@ -39,23 +39,23 @@ public ScriptHistoryEntry(String language, String code, Map para public String getLanguage() { return language; } - + public void setLanguage(String language) { this.language = language; } - + public String getCode() { return code; } - + public void setCode(String code) { this.code = code; } - + public Map getParams() { return params; } - + public void setParams(Map params) { this.params = params; } diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/ActivationComputer.java b/infra/common/src/main/java/com/evolveum/midpoint/common/ActivationComputer.java index e12a75dec44..165ec39afe6 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/ActivationComputer.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/ActivationComputer.java @@ -28,14 +28,14 @@ * */ public class ActivationComputer { - + private Clock clock; public ActivationComputer() { super(); } - + public ActivationComputer(Clock clock) { super(); this.clock = clock; @@ -50,28 +50,28 @@ public Clock getClock() { public void setClock(Clock clock) { this.clock = clock; } - + public ActivationStatusType getEffectiveStatus(String lifecycleStatus, ActivationType activationType) { return getEffectiveStatus(lifecycleStatus, activationType, getValidityStatus(activationType)); } - + public ActivationStatusType getEffectiveStatus(String lifecycleStatus, ActivationType activationType, TimeIntervalStatusType validityStatus) { - + if (SchemaConstants.LIFECYCLE_ARCHIVED.equals(lifecycleStatus)) { return ActivationStatusType.ARCHIVED; } - - if (lifecycleStatus != null && + + if (lifecycleStatus != null && !lifecycleStatus.equals(SchemaConstants.LIFECYCLE_ACTIVE) && !lifecycleStatus.equals(SchemaConstants.LIFECYCLE_DEPRECATED)) { return ActivationStatusType.DISABLED; } - + if (activationType == null) { return ActivationStatusType.ENABLED; } ActivationStatusType administrativeStatus = activationType.getAdministrativeStatus(); if (administrativeStatus != null) { - // Explicit administrative status overrides everything + // Explicit administrative status overrides everything return administrativeStatus; } if (validityStatus == null) { @@ -88,11 +88,11 @@ public ActivationStatusType getEffectiveStatus(String lifecycleStatus, Activatio // This should not happen return null; } - + public TimeIntervalStatusType getValidityStatus(ActivationType activationType) { return getValidityStatus(activationType, clock.currentTimeXMLGregorianCalendar()); } - + public TimeIntervalStatusType getValidityStatus(ActivationType activationType, XMLGregorianCalendar referenceTime) { if (activationType == null || referenceTime == null) { return null; @@ -111,29 +111,29 @@ public TimeIntervalStatusType getValidityStatus(ActivationType activationType, X } return status; } - + public void computeEffective(String lifecycleStatus, ActivationType activationType) { computeEffective(lifecycleStatus, activationType, clock.currentTimeXMLGregorianCalendar()); } - + public void computeEffective(String lifecycleStatus, ActivationType activationType, XMLGregorianCalendar referenceTime) { ActivationStatusType effectiveStatus = null; - - if (lifecycleStatus != null && + + if (lifecycleStatus != null && !lifecycleStatus.equals(SchemaConstants.LIFECYCLE_ACTIVE) && !lifecycleStatus.equals(SchemaConstants.LIFECYCLE_DEPRECATED)) { effectiveStatus = ActivationStatusType.DISABLED; } - + if (SchemaConstants.LIFECYCLE_ARCHIVED.equals(lifecycleStatus)) { effectiveStatus = ActivationStatusType.ARCHIVED; } - + ActivationStatusType administrativeStatus = activationType.getAdministrativeStatus(); if (effectiveStatus == null && administrativeStatus != null) { - // Explicit administrative status overrides everything + // Explicit administrative status overrides everything effectiveStatus = administrativeStatus; } - + TimeIntervalStatusType validityStatus = getValidityStatus(activationType); if (effectiveStatus == null) { if (validityStatus == null) { @@ -169,7 +169,7 @@ public boolean isActive(String lifecycleStatus, ActivationType activationType) { } return effectiveStatus == ActivationStatusType.ENABLED; } - + public boolean lifecycleHasActiveAssignments(String lifecycleStatus) { return lifecycleIsActive(lifecycleStatus); } diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/Clock.java b/infra/common/src/main/java/com/evolveum/midpoint/common/Clock.java index 6c42b2ea639..e90cf1c27f0 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/Clock.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/Clock.java @@ -29,13 +29,13 @@ * test time-based behavior. Using the Clock avoids changing the actual system time (or JVM's perception * of time) therefore the tests are easier to use and usual tools still make sense (e.g. log record timestamps * are correct). - * + * * @author Radovan Semancik */ public class Clock { - + private static final Trace LOGGER = TraceManager.getTrace(Clock.class); - + private Long override = null; // TODO: more sophisticated functions @@ -45,7 +45,7 @@ public long currentTimeMillis() { } return System.currentTimeMillis(); } - + public XMLGregorianCalendar currentTimeXMLGregorianCalendar() { long millis = currentTimeMillis(); return XmlTypeConverter.createXMLGregorianCalendar(millis); @@ -58,8 +58,8 @@ public boolean isPast(long date) { public boolean isPast(XMLGregorianCalendar date) { return isPast(XmlTypeConverter.toMillis(date)); } - - + + public boolean isFuture(long date) { return currentTimeMillis() < date; } @@ -67,7 +67,7 @@ public boolean isFuture(long date) { public boolean isFuture(XMLGregorianCalendar date) { return isFuture(XmlTypeConverter.toMillis(date)); } - + public void override(long overrideTimestamp) { LOGGER.info("Clock override: {}", override); this.override = overrideTimestamp; @@ -75,11 +75,11 @@ public void override(long overrideTimestamp) { LOGGER.debug("Clock current time: {}", currentTimeXMLGregorianCalendar()); } } - + public void override(XMLGregorianCalendar overrideTimestamp) { override(XmlTypeConverter.toMillis(overrideTimestamp)); } - + public void overrideDuration(String durationString) { overrideDuration(XmlTypeConverter.createDuration(durationString)); } diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/LoggingConfigurationManager.java b/infra/common/src/main/java/com/evolveum/midpoint/common/LoggingConfigurationManager.java index ac13de54dbc..89cac4c8662 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/LoggingConfigurationManager.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/LoggingConfigurationManager.java @@ -135,11 +135,10 @@ public static void configure(LoggingConfigurationType config, String version, Op if (!StringUtils.isEmpty(internalLog)) { //Parse internal log res.recordSuccess(); - String internalLogLines[] = internalLog.split("\n"); - for (int i = 0; i < internalLogLines.length; i++) { - if (internalLogLines[i].contains("|-ERROR")) - res.recordPartialError(internalLogLines[i]); - res.appendDetail(internalLogLines[i]); + for (String internalLogLine : internalLog.split("\n")) { + if (internalLogLine.contains("|-ERROR")) + res.recordPartialError(internalLogLine); + res.appendDetail(internalLogLine); } LOGGER.trace("LogBack internal log:\n{}",internalLog); } else { @@ -332,7 +331,7 @@ private static void appendProp(StringBuilder sb, String name, Object value) { private static void prepareCommonAppenderHeader(StringBuilder sb, AppenderConfigurationType appender, LoggingConfigurationType config, String appenderClass) { - sb.append("\t\n"); + sb.append("\t\n"); //Apply profiling appender filter if necessary if(IDM_PROFILE_APPENDER.equals(appender.getName())){ diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/ResourceObjectPattern.java b/infra/common/src/main/java/com/evolveum/midpoint/common/ResourceObjectPattern.java index a3aa8b3f96b..a8c7bf75f9d 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/ResourceObjectPattern.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/ResourceObjectPattern.java @@ -40,22 +40,22 @@ * */ public class ResourceObjectPattern implements Serializable { - + private Collection> identifiers; private RefinedObjectClassDefinition rOcDef; private ObjectFilter objectFilter; - + public ResourceObjectPattern(RefinedObjectClassDefinition rOcDef) { this.rOcDef = rOcDef; } - + public Collection> getIdentifiers() { if (identifiers == null) { identifiers = new ArrayList>(); } return identifiers; } - + public void addIdentifier(ResourceAttribute identifier) { getIdentifiers().add(identifier); } diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/StaticExpressionUtil.java b/infra/common/src/main/java/com/evolveum/midpoint/common/StaticExpressionUtil.java index b3fdcfa2e22..e6c11e3ec4a 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/StaticExpressionUtil.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/StaticExpressionUtil.java @@ -42,16 +42,16 @@ * intended for a general public usage. It is used to set and get pre-computed * values in expressions and mappings, e.g. when used between model and provisioning * in provisioning scripts. - * + * * @author Radovan Semancik * */ public class StaticExpressionUtil { - + /** - * Returns either Object (if result is supposed to be single-value) or Collection (if result is supposed to be multi-value) + * Returns either Object (if result is supposed to be single-value) or Collection (if result is supposed to be multi-value) */ - public static Object getStaticOutput(ExpressionType expressionType, PrismPropertyDefinition outputDefinition, + public static Object getStaticOutput(ExpressionType expressionType, PrismPropertyDefinition outputDefinition, String contextDescription, ExpressionReturnMultiplicityType preferredMultiplicity, PrismContext prismContext) throws SchemaException { PrismProperty output = getPropertyStatic(expressionType, outputDefinition, contextDescription, prismContext); ExpressionReturnMultiplicityType multiplicity = preferredMultiplicity; @@ -75,25 +75,25 @@ public static Object getStaticOutput(ExpressionType expressionType, PrismPropert } } - public static PrismProperty getPropertyStatic(ExpressionType expressionType, PrismPropertyDefinition outputDefinition, + public static PrismProperty getPropertyStatic(ExpressionType expressionType, PrismPropertyDefinition outputDefinition, String contextDescription, PrismContext prismContext) throws SchemaException { Collection> expressionEvaluatorElement = expressionType.getExpressionEvaluator(); return (PrismProperty) parseValueElements(expressionEvaluatorElement, outputDefinition, contextDescription, prismContext); } - + /** - * Always returns collection, even for single-valued results. + * Always returns collection, even for single-valued results. */ - public static Collection getPropertyStaticRealValues(ExpressionType expressionType, PrismPropertyDefinition outputDefinition, + public static Collection getPropertyStaticRealValues(ExpressionType expressionType, PrismPropertyDefinition outputDefinition, String contextDescription, PrismContext prismContext) throws SchemaException { PrismProperty output = getPropertyStatic(expressionType, outputDefinition, contextDescription, prismContext); return output.getRealValues(); } - - public static Item parseValueElements(Collection valueElements, ID outputDefinition, + + public static Item parseValueElements(Collection valueElements, ID outputDefinition, String contextDescription, PrismContext prismContext) throws SchemaException { - + Item output = null; for (Object valueElement: valueElements) { @@ -105,16 +105,16 @@ public static Item pars if (!valueElementName.equals(SchemaConstants.C_VALUE)) { throw new SchemaException("Literal expression cannot handle element <"+valueElementName + "> in "+ contextDescription); } - + JAXBElement jaxbElement = (JAXBElement)valueElement; // not checking declaredType because it may be Object.class instead ... but actual type must be of RawType if (jaxbElement.getValue() != null && !(jaxbElement.getValue() instanceof RawType)) { throw new SchemaException("Literal expression cannot handle JAXBElement value type "+jaxbElement.getValue().getClass()+" in " +contextDescription); } - + RawType rawType = (RawType)jaxbElement.getValue(); - + //Item elementItem = xnodeProcessor.parseItem(rawType.getXnode(), outputDefinition.getName(), outputDefinition); Item elementItem = rawType.getParsedItem(outputDefinition); if (output == null) { diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/Utils.java b/infra/common/src/main/java/com/evolveum/midpoint/common/Utils.java index 9b7e86069a2..c954d2a71b0 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/Utils.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/Utils.java @@ -25,10 +25,10 @@ import com.evolveum.midpoint.util.logging.TraceManager; /** - * + * * @author Igor Farinic * @author Radovan Semancik - * + * */ public class Utils { @@ -49,11 +49,11 @@ public static Element fillPropertyReference(String resolve) { /** * Removing non-printable UTF characters from the string. - * + * * This is not really used now. It was done as a kind of prototype for * filters. But may come handy and it in fact tests that the pattern is * doing what expected, so it may be useful. - * + * * @param bad * string with bad chars * @return string without bad chars @@ -75,7 +75,7 @@ public static String cleanupUtf(String bad) { /** * According to XML specification, section 2.2: * http://www.w3.org/TR/REC-xml/ - * + * * @param c * @return */ diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/crypto/CryptoUtil.java b/infra/common/src/main/java/com/evolveum/midpoint/common/crypto/CryptoUtil.java index cd1bf0cd61e..ab259af5489 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/crypto/CryptoUtil.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/crypto/CryptoUtil.java @@ -53,7 +53,7 @@ * */ public class CryptoUtil { - + private static final Trace LOGGER = TraceManager.getTrace(CryptoUtil.class); /** @@ -153,7 +153,7 @@ private static void encryptProtectedStringType(Protector protector, ProtectedStr } } } - + // Checks that everything is encrypted public static void checkEncrypted(final PrismObject object) { Visitor visitor = new Visitor() { @@ -173,7 +173,7 @@ public void visit(Visitable visitable){ } } - + // Checks that everything is encrypted public static void checkEncrypted(final ObjectDelta delta) { Visitor visitor = new Visitor() { @@ -192,7 +192,7 @@ public void visit(Visitable visitable){ throw new IllegalStateException(e.getMessage() + " in delta " + delta, e); } } - + private static void checkEncrypted(PrismPropertyValue pval) { Itemable item = pval.getParent(); if (item == null) { @@ -258,10 +258,10 @@ public void visit(Visitable visitable){ (byte) 0x51,(byte) 0x65,(byte) 0x22,(byte) 0x23, (byte) 0x64,(byte) 0x05,(byte) 0x6A,(byte) 0xBE, }; - + public static void securitySelfTest(OperationResult parentTestResult) { OperationResult result = parentTestResult.createSubresult(CryptoUtil.class.getName()+".securitySelfTest"); - + // Providers for (Provider provider: Security.getProviders()) { String providerName = provider.getName(); @@ -278,7 +278,7 @@ public static void securitySelfTest(OperationResult parentTestResult) { providerResult.recordFatalError(e); } } - + securitySelfTestAlgorithm("AES", "AES/CBC/PKCS5Padding", null, false, result); OperationResult cryptoResult = result.getLastSubresult(); if (cryptoResult.isError()) { @@ -291,11 +291,11 @@ public static void securitySelfTest(OperationResult parentTestResult) { cryptoResult.setStatus(OperationResultStatus.HANDLED_ERROR); } } - + result.computeStatus(); } - private static void securitySelfTestAlgorithm(String algorithmName, String transformationName, + private static void securitySelfTestAlgorithm(String algorithmName, String transformationName, Integer keySize, boolean critical, OperationResult parentResult) { OperationResult subresult = parentResult.createSubresult(CryptoUtil.class.getName()+".securitySelfTest.algorithm."+algorithmName); try { @@ -306,17 +306,17 @@ private static void securitySelfTestAlgorithm(String algorithmName, String trans subresult.addReturn("keyGeneratorProvider", keyGenerator.getProvider().getName()); subresult.addReturn("keyGeneratorAlgorithm", keyGenerator.getAlgorithm()); subresult.addReturn("keyGeneratorKeySize", keySize); - + SecretKey key = keyGenerator.generateKey(); subresult.addReturn("keyAlgorithm", key.getAlgorithm()); subresult.addReturn("keyLength", key.getEncoded().length*8); subresult.addReturn("keyFormat", key.getFormat()); subresult.recordSuccess(); - + IvParameterSpec iv = new IvParameterSpec(DEFAULT_IV_BYTES); - + String plainString = "Scurvy seadog"; - + Cipher cipher = Cipher.getInstance(transformationName); subresult.addReturn("cipherAlgorithmName", algorithmName); subresult.addReturn("cipherTansfromationName", transformationName); @@ -326,26 +326,26 @@ private static void securitySelfTestAlgorithm(String algorithmName, String trans subresult.addReturn("cipherMaxAllowedKeyLength", cipher.getMaxAllowedKeyLength(transformationName)); cipher.init(Cipher.ENCRYPT_MODE, key, iv); byte[] encryptedBytes = cipher.doFinal(plainString.getBytes()); - + cipher = Cipher.getInstance(transformationName); cipher.init(Cipher.DECRYPT_MODE, key, iv); byte[] decryptedBytes = cipher.doFinal(encryptedBytes); String decryptedString = new String(decryptedBytes); - + if (!plainString.equals(decryptedString)) { subresult.recordFatalError("Encryptor roundtrip failed; encrypted="+plainString+", decrypted="+decryptedString); } else { subresult.recordSuccess(); } - LOGGER.debug("Security self test (algorithmName={}, transformationName={}, keySize={}) success", + LOGGER.debug("Security self test (algorithmName={}, transformationName={}, keySize={}) success", new Object[] {algorithmName, transformationName, keySize}); } catch (Throwable e) { if (critical) { - LOGGER.error("Security self test (algorithmName={}, transformationName={}, keySize={}) failed: {}", + LOGGER.error("Security self test (algorithmName={}, transformationName={}, keySize={}) failed: {}", new Object[] {algorithmName, transformationName, keySize, e.getMessage() ,e}); subresult.recordFatalError(e); } else { - LOGGER.warn("Security self test (algorithmName={}, transformationName={}, keySize={}) failed: {} (failure is expected in some cases)", + LOGGER.warn("Security self test (algorithmName={}, transformationName={}, keySize={}) failed: {} (failure is expected in some cases)", new Object[] {algorithmName, transformationName, keySize, e.getMessage() ,e}); subresult.recordWarning(e); } diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/filter/Filter.java b/infra/common/src/main/java/com/evolveum/midpoint/common/filter/Filter.java index 6fd0aa06563..f0a658af670 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/filter/Filter.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/filter/Filter.java @@ -20,9 +20,9 @@ import com.evolveum.midpoint.prism.PrismPropertyValue; /** - * + * * @author Igor Farinic - * + * */ public interface Filter { diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/filter/FilterManager.java b/infra/common/src/main/java/com/evolveum/midpoint/common/filter/FilterManager.java index 02945036d6c..1aedb5ef26f 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/filter/FilterManager.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/filter/FilterManager.java @@ -20,7 +20,7 @@ import java.util.Map; /** - * + * * @author Igor Farinic */ public interface FilterManager { diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/filter/FilterManagerImpl.java b/infra/common/src/main/java/com/evolveum/midpoint/common/filter/FilterManagerImpl.java index ab1b7535047..949ff465e84 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/filter/FilterManagerImpl.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/filter/FilterManagerImpl.java @@ -25,9 +25,9 @@ import com.evolveum.midpoint.util.logging.TraceManager; /** - * + * * @author Igor Farinic - * + * */ public class FilterManagerImpl implements FilterManager { diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/CompositeRefinedObjectClassDefinition.java b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/CompositeRefinedObjectClassDefinition.java index 8006644fdab..aebbcd6c2d2 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/CompositeRefinedObjectClassDefinition.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/CompositeRefinedObjectClassDefinition.java @@ -21,7 +21,7 @@ /** * Used to represent combined definition of structural and auxiliary object classes. - * + * * @author semancik * */ 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 25681c22903..a2d7f8acf65 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 @@ -40,7 +40,7 @@ /** * Used to represent combined definition of structural and auxiliary object classes. - * + * * @author semancik * */ @@ -205,7 +205,7 @@ public Collection> getPrimaryIdentifiers public Collection> getSecondaryIdentifiers() { return structuralObjectClassDefinition.getSecondaryIdentifiers(); } - + @Override public Collection> getAllIdentifiers() { return structuralObjectClassDefinition.getAllIdentifiers(); @@ -275,7 +275,7 @@ public ObjectClassComplexTypeDefinition getObjectClassDefinition() { public ResourceObjectReferenceType getBaseContext() { return structuralObjectClassDefinition.getBaseContext(); } - + @Override public ResourceObjectVolatilityType getVolatility() { return structuralObjectClassDefinition.getVolatility(); @@ -384,7 +384,7 @@ public Collection> getAttributeDefinitio } return defs; } - + @Override public PrismContext getPrismContext() { return structuralObjectClassDefinition.getPrismContext(); @@ -461,7 +461,7 @@ public Collection getNamesOfAssociationsWithOutboundExpressions .map(a -> a.getName()) .collect(Collectors.toCollection(HashSet::new)); } - + @Override public ResourceBidirectionalMappingAndDefinitionType getAuxiliaryObjectClassMappings() { return structuralObjectClassDefinition.getAuxiliaryObjectClassMappings(); @@ -611,7 +611,7 @@ public boolean equals(Object obj) { public String debugDump() { return debugDump(0); } - + @Override public String debugDump(int indent) { return debugDump(indent, null); @@ -630,7 +630,7 @@ protected String debugDump(int indent, LayerType layer) { DebugUtil.debugDumpWithLabel(sb, "auxiliary", auxiliaryObjectClassDefinitions, indent + 1); return sb.toString(); } - + /** * Return a human readable name of this class suitable for logs. */ @@ -646,7 +646,7 @@ public String getHumanReadableName() { return getKind()+":"+getIntent(); } } - + @Override public String toString() { if (auxiliaryObjectClassDefinitions.isEmpty()) { diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/LayerRefinedAttributeDefinitionImpl.java b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/LayerRefinedAttributeDefinitionImpl.java index df7ac43771a..4f8c369d413 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/LayerRefinedAttributeDefinitionImpl.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/LayerRefinedAttributeDefinitionImpl.java @@ -41,7 +41,7 @@ * */ public class LayerRefinedAttributeDefinitionImpl implements LayerRefinedAttributeDefinition { - + private RefinedAttributeDefinition refinedAttributeDefinition; private LayerType layer; private Boolean overrideCanRead = null; @@ -59,7 +59,7 @@ static LayerRefinedAttributeDefinition wrap(RefinedAttributeDefinition } return new LayerRefinedAttributeDefinitionImpl(rAttrDef, layer); } - + static List> wrapCollection( Collection defs, LayerType layer) { List outs = new ArrayList>(defs.size()); @@ -185,7 +185,7 @@ public boolean equals(Object obj) { return false; return true; } - + @Override public String debugDump() { return debugDump(0); @@ -199,7 +199,7 @@ public String debugDump(int indent) { sb.append(refinedAttributeDefinition.debugDump(indent+1, layer)); return sb.toString(); } - + /** * Return a human readable name of this class suitable for logs. */ diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/LayerRefinedObjectClassDefinitionImpl.java b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/LayerRefinedObjectClassDefinitionImpl.java index c969072f499..1e2e2e28d39 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/LayerRefinedObjectClassDefinitionImpl.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/LayerRefinedObjectClassDefinitionImpl.java @@ -54,19 +54,19 @@ public class LayerRefinedObjectClassDefinitionImpl implements LayerRefinedObject * This list is lazily evaluated. */ private List> layerRefinedAttributeDefinitions; - + private LayerRefinedObjectClassDefinitionImpl(RefinedObjectClassDefinition refinedAccountDefinition, LayerType layer) { this.refinedObjectClassDefinition = refinedAccountDefinition; this.layer = layer; } - + static LayerRefinedObjectClassDefinition wrap(RefinedObjectClassDefinition rOCD, LayerType layer) { if (rOCD == null) { return null; } return new LayerRefinedObjectClassDefinitionImpl(rOCD, layer); } - + static List wrapCollection(Collection rOCDs, LayerType layer) { return(rOCDs.stream() .map(rAccountDef -> wrap(rAccountDef, layer)) @@ -189,7 +189,7 @@ public String getHelp() { public Collection> getPrimaryIdentifiers() { return substituteLayerRefinedAttributeDefinitionCollection(refinedObjectClassDefinition.getPrimaryIdentifiers()); } - + @Override public Collection> getAllIdentifiers() { return substituteLayerRefinedAttributeDefinitionCollection(refinedObjectClassDefinition.getAllIdentifiers()); @@ -521,7 +521,7 @@ public boolean equals(Object obj) { return false; return true; } - + @Override public String debugDump() { return debugDump(0); @@ -538,9 +538,9 @@ public String debugDump(int indent) { } // Do NOT override&delegate debugDump(int indent, LayerType layer) here. - // We want to use code in the context of this class so things like + // We want to use code in the context of this class so things like // getDebugDumpClassName() will be correct. - + /** * Return a human readable name of this class suitable for logs. */ 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 9e1b99491be..f1cfe93e41d 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 @@ -26,40 +26,40 @@ * */ public class PropertyLimitations implements DebugDumpable, Serializable { - + private boolean ignore; private int minOccurs; private int maxOccurs; private PropertyAccessType access = new PropertyAccessType(); - + public boolean isIgnore() { return ignore; } - + public void setIgnore(boolean ignore) { this.ignore = ignore; } - + public int getMinOccurs() { return minOccurs; } - + public void setMinOccurs(int minOccurs) { this.minOccurs = minOccurs; } - + public int getMaxOccurs() { return maxOccurs; } - + public void setMaxOccurs(int maxOccurs) { this.maxOccurs = maxOccurs; } - + public PropertyAccessType getAccess() { return access; } - + public void setAccess(PropertyAccessType access) { this.access = access; } @@ -76,7 +76,7 @@ public String debugDump(int indent) { sb.append(toString()); return sb.toString(); } - + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedAssociationDefinition.java b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedAssociationDefinition.java index 29c1713c514..dbfc66a44bc 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedAssociationDefinition.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedAssociationDefinition.java @@ -31,7 +31,7 @@ public class RefinedAssociationDefinition implements Serializable { private static final long serialVersionUID = 1L; - + private ResourceObjectAssociationType resourceObjectAssociationType; private RefinedObjectClassDefinition associationTarget; @@ -55,15 +55,15 @@ public void setAssociationTarget(RefinedObjectClassDefinition associationTarget) public QName getName() { return ItemPathUtil.getOnlySegmentQName(resourceObjectAssociationType.getRef()); } - + public ShadowKindType getKind() { return resourceObjectAssociationType.getKind(); } - + public Collection getIntents() { return resourceObjectAssociationType.getIntent(); } - + public QName getAuxiliaryObjectClass() { return resourceObjectAssociationType.getAuxiliaryObjectClass(); } @@ -71,7 +71,7 @@ public QName getAuxiliaryObjectClass() { public MappingType getOutboundMappingType() { return resourceObjectAssociationType.getOutbound(); } - + public boolean isExclusiveStrong() { return BooleanUtils.isTrue(resourceObjectAssociationType.isExclusiveStrong()); } @@ -101,11 +101,11 @@ public boolean requiresExplicitReferentialIntegrity() { public QName getMatchingRule() { return getResourceObjectAssociationType().getMatchingRule(); } - + public String getDisplayName() { return resourceObjectAssociationType.getDisplayName(); } - + public RefinedAssociationDefinition clone() { RefinedAssociationDefinition clone = new RefinedAssociationDefinition(resourceObjectAssociationType); copyValues(clone); diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedAttributeDefinitionImpl.java b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedAttributeDefinitionImpl.java index 1d081e798b2..c85dea3ac9c 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedAttributeDefinitionImpl.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedAttributeDefinitionImpl.java @@ -51,7 +51,7 @@ public class RefinedAttributeDefinitionImpl extends ResourceAttributeDefinitionImpl implements RefinedAttributeDefinition { private static LayerType DEFAULT_LAYER = LayerType.MODEL; - + private String displayName; private String description; private boolean tolerant = true; @@ -89,21 +89,21 @@ public boolean isTolerant() { public void setTolerant(boolean tolerant) { this.tolerant = tolerant; } - + @Override public boolean isSecondaryIdentifier() { return secondaryIdentifier; } - + public void setSecondaryIdentifier(boolean secondaryIdentifier) { this.secondaryIdentifier = secondaryIdentifier; } - + @Override public boolean canAdd() { return canAdd(DEFAULT_LAYER); } - + @Override public boolean canAdd(LayerType layer) { if (accessOverride.isAdd() != null) { @@ -129,7 +129,7 @@ public boolean canRead(LayerType layer) { public boolean canModify() { return canModify(DEFAULT_LAYER); } - + @Override public boolean canModify(LayerType layer) { if (accessOverride.isModify() != null) { @@ -177,7 +177,7 @@ public void setCanAdd(boolean create) { public boolean isIgnored() { return isIgnored(DEFAULT_LAYER); } - + @Override public boolean isIgnored(LayerType layer) { return limitationsMap.get(layer).isIgnore(); @@ -202,7 +202,7 @@ public String getDisplayName() { public void setDisplayName(String displayName) { this.displayName = displayName; } - + @Override public String getDescription() { return description; @@ -229,7 +229,7 @@ public MappingType getOutboundMappingType() { public void setOutboundMappingType(MappingType outboundMappingType) { this.outboundMappingType = outboundMappingType; } - + @Override public boolean hasOutboundMapping() { return outboundMappingType != null; @@ -257,7 +257,7 @@ public QName getTypeName() { public String getNativeAttributeName() { return attributeDefinition.getNativeAttributeName(); } - + public String getFrameworkAttributeName() { return attributeDefinition.getFrameworkAttributeName(); } @@ -265,7 +265,7 @@ public String getFrameworkAttributeName() { public Collection> getAllowedValues() { return attributeDefinition.getAllowedValues(); } - + public boolean isReturnedByDefault() { return attributeDefinition.isReturnedByDefault(); } @@ -278,7 +278,7 @@ public void setReturnedByDefault(Boolean returnedByDefault) { public int getMaxOccurs() { return getMaxOccurs(DEFAULT_LAYER); } - + @Override public int getMaxOccurs(LayerType layer) { return limitationsMap.get(layer).getMaxOccurs(); @@ -293,7 +293,7 @@ public int getMinOccurs() { public int getMinOccurs(LayerType layer) { return limitationsMap.get(layer).getMinOccurs(); } - + @Override public boolean isOptional(LayerType layer) { return limitationsMap.get(layer).getMinOccurs() == 0; @@ -303,13 +303,13 @@ public boolean isOptional(LayerType layer) { public boolean isMandatory(LayerType layer) { return limitationsMap.get(layer).getMinOccurs() > 0; } - + @Override public boolean isMultiValue(LayerType layer) { int maxOccurs = limitationsMap.get(layer).getMaxOccurs(); return maxOccurs < 0 || maxOccurs > 1; } - + @Override public boolean isSingleValue(LayerType layer) { return limitationsMap.get(layer).getMaxOccurs() == 1; @@ -349,12 +349,12 @@ public QName getMatchingRuleQName() { public void setMatchingRuleQName(QName matchingRuleQName) { this.matchingRuleQName = matchingRuleQName; } - + @Override public List getTolerantValuePattern(){ return tolerantValuePattern; } - + @Override public List getIntolerantValuePattern(){ return intolerantValuePattern; @@ -383,7 +383,7 @@ static RefinedAttributeDefinition parse(ResourceAttributeDefinition sc rAttrDef.setDisplayName(schemaAttrDef.getDisplayName()); } } - + if (schemaHandlingAttrDefType != null && schemaHandlingAttrDefType.getDisplayOrder() != null) { rAttrDef.setDisplayOrder(schemaHandlingAttrDefType.getDisplayOrder()); } else { @@ -443,7 +443,7 @@ static RefinedAttributeDefinition parse(ResourceAttributeDefinition sc rAttrDef.setModificationPriority(schemaHandlingAttrDefType.getModificationPriority()); rAttrDef.setReadReplaceMode(schemaHandlingAttrDefType.isReadReplaceMode()); // may be null at this point - + if (schemaHandlingAttrDefType.isDisplayNameAttribute() != null && schemaHandlingAttrDefType.isDisplayNameAttribute()) { rAttrDef.isDisplayNameAttribute = true; } @@ -502,7 +502,7 @@ private static void applyLimitationsType(PropertyLimitations limitations, Proper limitations.getAccess().setModify(accessType.isModify()); } } - + } private static PropertyLimitations getOrCreateLimitations(Map limitationsMap, @@ -529,7 +529,7 @@ static boolean isIgnored(ResourceAttributeDefinitionType attrDefType) throws Sch } return limitationsType.isIgnore(); } - + @NotNull @Override public RefinedAttributeDefinition clone() { @@ -588,7 +588,7 @@ public String toString() { } return sb.toString(); } - + /** * Return a human readable name of this class suitable for logs. */ @@ -601,7 +601,7 @@ protected String getDebugDumpClassName() { public String debugDump(int indent) { return debugDump(indent, null); } - + @Override public String debugDump(int indent, LayerType layer) { StringBuilder sb = new StringBuilder(); diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedConnectorSchemaImpl.java b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedConnectorSchemaImpl.java index e68664ee4a7..6d2e15840b6 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedConnectorSchemaImpl.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedConnectorSchemaImpl.java @@ -43,7 +43,7 @@ public static ConnectorSchema getConnectorSchema(ConnectorType connectorType, Pr PrismObject connector = connectorType.asPrismObject(); return getConnectorSchema(connector, prismContext); } - + public static ConnectorSchema getConnectorSchema(PrismObject connector, PrismContext prismContext) throws SchemaException { Element connectorXsdSchema = ConnectorTypeUtil.getConnectorXsdSchema(connector); if (connectorXsdSchema == null) { @@ -68,7 +68,7 @@ public static ConnectorSchema getConnectorSchema(PrismObject conn return parsedSchema; } } - + public static void setParsedConnectorSchemaConditional(ConnectorType connectorType, ConnectorSchema parsedSchema) { if (hasParsedSchema(connectorType)) { return; diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedObjectClassDefinition.java b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedObjectClassDefinition.java index 056c46bad3e..aca798afec8 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedObjectClassDefinition.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedObjectClassDefinition.java @@ -121,7 +121,7 @@ default Collection> getAllIdentifiers() ResourceObjectReferenceType getBaseContext(); String getHumanReadableName(); - + ResourceObjectVolatilityType getVolatility(); //endregion @@ -147,7 +147,7 @@ default PrismObject createBlankShadow() { Collection getAuxiliaryObjectClassDefinitions(); boolean hasAuxiliaryObjectClass(QName expectedObjectClassName); - + ResourceBidirectionalMappingAndDefinitionType getAuxiliaryObjectClassMappings(); Collection getProtectedObjectPatterns(); 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 0ef502db2be..6f8450fb5b4 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 @@ -299,7 +299,7 @@ public ShadowKindType getKind() { public void setKind(ShadowKindType kind) { this.kind = kind; } - + @Override public ResourceObjectVolatilityType getVolatility() { if (schemaHandlingObjectTypeDefinitionType == null) { @@ -409,7 +409,7 @@ public boolean hasAuxiliaryObjectClass(QName expectedObjectClassName) { return auxiliaryObjectClassDefinitions.stream() .anyMatch(def -> QNameUtil.match(def.getTypeName(), expectedObjectClassName)); } - + @Override public ResourceBidirectionalMappingAndDefinitionType getAuxiliaryObjectClassMappings() { if (schemaHandlingObjectTypeDefinitionType == null) { @@ -624,7 +624,7 @@ public boolean isAuxiliary() { public PrismContext getPrismContext() { return originalObjectClassDefinition.getPrismContext(); } - + @Nullable @Override public Class getCompileTimeClass() { @@ -778,7 +778,7 @@ public boolean isListMarker() { static RefinedObjectClassDefinition parse(ResourceObjectTypeDefinitionType entTypeDefType, ResourceType resourceType, RefinedResourceSchema rSchema, ShadowKindType impliedKind, PrismContext prismContext, String contextDescription) throws SchemaException { - + ShadowKindType kind = entTypeDefType.getKind(); if (kind == null) { kind = impliedKind; @@ -790,7 +790,7 @@ static RefinedObjectClassDefinition parse(ResourceObjectTypeDefinitionType entTy if (intent == null) { intent = SchemaConstants.INTENT_DEFAULT; } - RefinedObjectClassDefinition rObjectClassDef = parseRefinedObjectClass(entTypeDefType, + RefinedObjectClassDefinition rObjectClassDef = parseRefinedObjectClass(entTypeDefType, resourceType, rSchema, prismContext, kind, intent, kind.value(), kind.value() + " type definition '"+intent+"' in " + contextDescription); if (entTypeDefType.getPagedSearches() != null) { @@ -805,7 +805,7 @@ private static void parseProtected(RefinedObjectClassDefinition rAccountDef, Res rAccountDef.getProtectedObjectPatterns().add(protectedPattern); } } - + private static ResourceObjectPattern convertToPattern(ResourceObjectPatternType patternType, RefinedObjectClassDefinition rAccountDef) throws SchemaException { ResourceObjectPattern resourceObjectPattern = new ResourceObjectPattern(rAccountDef); SearchFilterType filterType = patternType.getFilter(); @@ -814,7 +814,7 @@ private static ResourceObjectPattern convertToPattern(ResourceObjectPatternType resourceObjectPattern.addFilter(filter); return resourceObjectPattern; } - + // Deprecated if (patternType.getName() != null) { RefinedAttributeDefinition attributeDefinition = rAccountDef.findAttributeDefinition(new QName(SchemaConstants.NS_ICF_SCHEMA,"name")); @@ -831,7 +831,7 @@ private static ResourceObjectPattern convertToPattern(ResourceObjectPatternType } ResourceAttribute attr = attributeDefinition.instantiate(); attr.setRealValue(patternType.getUid()); - resourceObjectPattern.addIdentifier(attr); + resourceObjectPattern.addIdentifier(attr); } else { throw new SchemaException("No filter and no deprecated name/uid in resource object pattern"); } @@ -873,11 +873,11 @@ public static RefinedObjectClassDefinition parseFromSchema(ObjectClassComplexTyp return rOcDef; } - + private static RefinedObjectClassDefinition parseRefinedObjectClass(ResourceObjectTypeDefinitionType schemaHandlingObjDefType, ResourceType resourceType, RefinedResourceSchema rSchema, PrismContext prismContext, @NotNull ShadowKindType kind, @NotNull String intent, String typeDesc, String contextDescription) throws SchemaException { - + ObjectClassComplexTypeDefinition objectClassDef; if (schemaHandlingObjDefType.getObjectClass() != null) { QName objectClass = schemaHandlingObjDefType.getObjectClass(); @@ -888,13 +888,13 @@ private static RefinedObjectClassDefinition parseRefinedObjectClass(ResourceObje } else { throw new SchemaException("Definition of "+typeDesc+" type " + schemaHandlingObjDefType.getIntent() + " does not have objectclass, in " + contextDescription); } - + RefinedObjectClassDefinitionImpl rOcDef = new RefinedObjectClassDefinitionImpl(resourceType.getOid(), objectClassDef); rOcDef.setKind(kind); rOcDef.setIntent(intent); // clone here to disassociate this definition from the resource. So this definition can be serialized without the need to serialize // entire resource. If we do not clone then the resource will be present here through parent in the schemaHandlingObjDefType - rOcDef.schemaHandlingObjectTypeDefinitionType = schemaHandlingObjDefType.clone(); + rOcDef.schemaHandlingObjectTypeDefinitionType = schemaHandlingObjDefType.clone(); if (rOcDef.schemaHandlingObjectTypeDefinitionType.getDisplayName() != null) { rOcDef.setDisplayName(rOcDef.schemaHandlingObjectTypeDefinitionType.getDisplayName()); @@ -917,7 +917,7 @@ private static RefinedObjectClassDefinition parseRefinedObjectClass(ResourceObje if (rOcDef.schemaHandlingObjectTypeDefinitionType.getBaseContext() != null) { rOcDef.setBaseContext(rOcDef.schemaHandlingObjectTypeDefinitionType.getBaseContext()); } - + return rOcDef; } @@ -933,7 +933,7 @@ void parseAssociations(RefinedResourceSchema rSchema) throws SchemaException { associationDefinitions.add(rAssocDef); } } - + void parseAuxiliaryObjectClasses(RefinedResourceSchema rSchema) throws SchemaException { if (schemaHandlingObjectTypeDefinitionType == null) { return; @@ -953,7 +953,7 @@ void parseAttributes(RefinedResourceSchema rSchema, String contextDescription) t // this is definition from schema. We already have all we need. return; } - + parseAttributesFrom(rSchema, getObjectClassDefinition(), false, contextDescription); for (RefinedObjectClassDefinition auxiliaryObjectClassDefinition: auxiliaryObjectClassDefinitions) { parseAttributesFrom(rSchema, auxiliaryObjectClassDefinition, true, contextDescription); @@ -966,10 +966,10 @@ void parseAttributes(RefinedResourceSchema rSchema, String contextDescription) t .getTypeName() + " as defined in " + contextDescription); } } - + parseProtected(this, schemaHandlingObjectTypeDefinitionType); } - + private void parseAttributesFrom(RefinedResourceSchema rSchema, ObjectClassComplexTypeDefinition ocDef, boolean auxiliary, String contextDescription) throws SchemaException { if (schemaHandlingObjectTypeDefinitionType == null) { @@ -1000,14 +1000,14 @@ private void parseAttributesFrom(RefinedResourceSchema rSchema, ObjectClassCompl } } add(rAttrDef); - + if (rAttrDef.isDisplayNameAttribute()) { displayNameAttributeDefinition = rAttrDef; } } - + } private void processIdentifiers(RefinedAttributeDefinition rAttrDef, ObjectClassComplexTypeDefinition objectClassDef) { @@ -1017,9 +1017,9 @@ private void processIdentifiers(RefinedAttributeDefinition rAttrDef, ObjectClass } if (objectClassDef.isSecondaryIdentifier(attrName) || rAttrDef.isSecondaryIdentifier()) { ((Collection)getSecondaryIdentifiers()).add(rAttrDef); - } + } } - + private ResourceAttributeDefinitionType findAttributeDefinitionType(QName attrName, ResourceObjectTypeDefinitionType rOcDefType, String contextDescription) throws SchemaException { ResourceAttributeDefinitionType foundAttrDefType = null; @@ -1051,7 +1051,7 @@ private void add(RefinedAttributeDefinition refinedAttributeDefinition) { public String debugDump() { return debugDump(0); } - + @Override public String debugDump(int indent) { return debugDump(indent, null, this); @@ -1084,7 +1084,7 @@ public static String debugDump(int indent, LayerType layer, RefinedObjectClassDe } return sb.toString(); } - + /** * Return a human readable name of this class suitable for logs. */ @@ -1102,7 +1102,7 @@ public String getHumanReadableName() { return getTypeName().getLocalPart(); } } - + @Override public String toString() { if (getKind() == null) { diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedObjectClassDefinitionKey.java b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedObjectClassDefinitionKey.java index 7b34dc27de4..fc4f5068917 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedObjectClassDefinitionKey.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedObjectClassDefinitionKey.java @@ -25,7 +25,7 @@ class RefinedObjectClassDefinitionKey { private QName typeName; private String intent; - + public RefinedObjectClassDefinitionKey(RefinedObjectClassDefinition rObjectClassDefinition) { typeName = rObjectClassDefinition.getTypeName(); intent = rObjectClassDefinition.getIntent(); diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedResourceSchemaImpl.java b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedResourceSchemaImpl.java index fb7291498e3..5d5fcae089e 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedResourceSchemaImpl.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedResourceSchemaImpl.java @@ -38,28 +38,28 @@ /** * TODO: this whole class would benefit from more refactoring. * TODO: especially the parsing part. - * + * * @author semancik * @author mederly */ public class RefinedResourceSchemaImpl implements RefinedResourceSchema { - + private static final String USER_DATA_KEY_PARSED_RESOURCE_SCHEMA = RefinedResourceSchema.class.getName()+".parsedResourceSchema"; private static final String USER_DATA_KEY_REFINED_SCHEMA = RefinedResourceSchema.class.getName()+".refinedSchema"; - // Original resource schema is there to make parsing easier. + // Original resource schema is there to make parsing easier. // But it is also useful in some cases, e.g. we do not need to pass both refined schema and // original schema as a method parameter. private ResourceSchema originalResourceSchema; - + // This object contains the real data of the refined schema private ResourceSchema resourceSchema; - + private RefinedResourceSchemaImpl(@NotNull ResourceSchema originalResourceSchema) { this.originalResourceSchema = originalResourceSchema; this.resourceSchema = new ResourceSchemaImpl(originalResourceSchema.getNamespace(), originalResourceSchema.getPrismContext()); } - + @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public Collection getObjectClassDefinitions() { @@ -70,7 +70,7 @@ public Collection getObjectClassDefinitions() public List getRefinedDefinitions() { return resourceSchema.getDefinitions(RefinedObjectClassDefinition.class); } - + @Override public List getRefinedDefinitions(ShadowKindType kind) { List rv = new ArrayList<>(); @@ -81,12 +81,12 @@ public List getRefinedDefinitions(Shadow } return rv; } - + @Override public ResourceSchema getOriginalResourceSchema() { return originalResourceSchema; } - + @Override public RefinedObjectClassDefinition getRefinedDefinition(ShadowKindType kind, String intent) { for (RefinedObjectClassDefinition acctDef: getRefinedDefinitions(kind)) { @@ -102,7 +102,7 @@ public RefinedObjectClassDefinition getRefinedDefinition(ShadowKindType kind, St } return null; } - + @Override public CompositeRefinedObjectClassDefinition determineCompositeObjectClassDefinition(ResourceShadowDiscriminator discriminator) { if (discriminator.getKind() == null && discriminator.getObjectClass() == null) { @@ -120,26 +120,26 @@ public CompositeRefinedObjectClassDefinition determineCompositeObjectClassDefini Collection auxiliaryObjectClassDefinitions = structuralObjectClassDefinition.getAuxiliaryObjectClassDefinitions(); return new CompositeRefinedObjectClassDefinitionImpl(structuralObjectClassDefinition, auxiliaryObjectClassDefinitions); } - + @Override public CompositeRefinedObjectClassDefinition determineCompositeObjectClassDefinition(PrismObject shadow) throws SchemaException { return determineCompositeObjectClassDefinition(shadow, null); } - + @Override public CompositeRefinedObjectClassDefinition determineCompositeObjectClassDefinition(PrismObject shadow, Collection additionalAuxiliaryObjectClassQNames) throws SchemaException { ShadowType shadowType = shadow.asObjectable(); - + RefinedObjectClassDefinition structuralObjectClassDefinition = null; ShadowKindType kind = shadowType.getKind(); String intent = shadowType.getIntent(); QName structuralObjectClassQName = shadowType.getObjectClass(); - + if (kind != null) { structuralObjectClassDefinition = getRefinedDefinition(kind, intent); } - + if (structuralObjectClassDefinition == null) { // Fallback to objectclass only if (structuralObjectClassQName == null) { @@ -147,9 +147,9 @@ public CompositeRefinedObjectClassDefinition determineCompositeObjectClassDefini } structuralObjectClassDefinition = getRefinedDefinition(structuralObjectClassQName); } - + if (structuralObjectClassDefinition == null) { - return null; + return null; } List auxiliaryObjectClassQNames = shadowType.getAuxiliaryObjectClass(); if (additionalAuxiliaryObjectClassQNames != null) { @@ -163,10 +163,10 @@ public CompositeRefinedObjectClassDefinition determineCompositeObjectClassDefini } auxiliaryObjectClassDefinitions.add(auxiliaryObjectClassDef); } - + return new CompositeRefinedObjectClassDefinitionImpl(structuralObjectClassDefinition, auxiliaryObjectClassDefinitions); } - + @Override public CompositeRefinedObjectClassDefinition determineCompositeObjectClassDefinition(QName structuralObjectClassQName, ShadowKindType kind, String intent) { @@ -174,7 +174,7 @@ public CompositeRefinedObjectClassDefinition determineCompositeObjectClassDefini Collection auxiliaryObjectClassDefinitions; if (kind != null) { structuralObjectClassDefinition = getRefinedDefinition(kind, intent); - } + } if (structuralObjectClassDefinition == null) { // Fallback to objectclass only if (structuralObjectClassQName == null) { @@ -182,13 +182,13 @@ public CompositeRefinedObjectClassDefinition determineCompositeObjectClassDefini } structuralObjectClassDefinition = getRefinedDefinition(structuralObjectClassQName); } - + if (structuralObjectClassDefinition == null) { return null; - } + } auxiliaryObjectClassDefinitions = structuralObjectClassDefinition.getAuxiliaryObjectClassDefinitions(); - + return new CompositeRefinedObjectClassDefinitionImpl(structuralObjectClassDefinition, auxiliaryObjectClassDefinitions); } @@ -236,7 +236,7 @@ public RefinedObjectClassDefinition getRefinedDefinition(QName objectClassName) } return null; } - + @Override public RefinedObjectClassDefinition findRefinedDefinitionByObjectClassQName(ShadowKindType kind, QName objectClass) { if (objectClass == null) { @@ -257,13 +257,13 @@ public RefinedObjectClassDefinition findRefinedDefinitionByObjectClassQName(Shad } return null; } - + @Override public LayerRefinedResourceSchema forLayer(LayerType layer) { return new LayerRefinedResourceSchemaImpl(this, layer); } - + @Override public String toString() { return "rSchema(ns=" + getNamespace() + ")"; @@ -587,9 +587,9 @@ public Collection findTypeDefinitionsB //endregion public static void validateRefinedSchema(RefinedResourceSchema refinedSchema, PrismObject resource) throws SchemaException { - + Set discrs = new HashSet<>(); - + for (RefinedObjectClassDefinition rObjectClassDefinition: refinedSchema.getRefinedDefinitions()) { QName typeName = rObjectClassDefinition.getTypeName(); RefinedObjectClassDefinitionKey key = new RefinedObjectClassDefinitionKey(rObjectClassDefinition); @@ -597,10 +597,10 @@ public static void validateRefinedSchema(RefinedResourceSchema refinedSchema, Pr throw new SchemaException("Duplicate definition of object class "+key+" in resource schema of "+resource); } discrs.add(key); - + ResourceTypeUtil.validateObjectClassDefinition(rObjectClassDefinition, resource); } } - - + + } diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/ShadowDiscriminatorObjectDelta.java b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/ShadowDiscriminatorObjectDelta.java index f61bfdc8a00..5091704ea1e 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/ShadowDiscriminatorObjectDelta.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/ShadowDiscriminatorObjectDelta.java @@ -30,11 +30,11 @@ public class ShadowDiscriminatorObjectDelta extends ObjectDelta { private ResourceShadowDiscriminator discriminator; - + public ShadowDiscriminatorObjectDelta(Class objectTypeClass, ChangeType changeType, PrismContext prismContext) { super(objectTypeClass, changeType, prismContext); } - + public ResourceShadowDiscriminator getDiscriminator() { return discriminator; } @@ -52,9 +52,9 @@ protected void checkIdentifierConsistence(boolean requireOid) { /** * Convenience method for quick creation of object deltas that replace a single object property. This is used quite often - * to justify a separate method. + * to justify a separate method. */ - public static ShadowDiscriminatorObjectDelta createModificationReplaceProperty(Class type, + public static ShadowDiscriminatorObjectDelta createModificationReplaceProperty(Class type, String resourceOid, ShadowKindType kind, String intent, ItemPath propertyPath, PrismContext prismContext, X... propertyValues) { ShadowDiscriminatorObjectDelta objectDelta = new ShadowDiscriminatorObjectDelta(type, ChangeType.MODIFY, prismContext); objectDelta.setDiscriminator(new ResourceShadowDiscriminator(resourceOid, kind, intent)); @@ -71,5 +71,5 @@ protected String debugName() { protected String debugIdentifiers() { return discriminator == null ? "null" : discriminator.toString(); } - + } 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 e289d144482..3056303b966 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 @@ -25,7 +25,7 @@ /** * Set of callback methods used to convey information from the validator to the "working" code. - * + * * It is used e.g. to connect validator to the code that executes import. It makes validator quite a generic tool. * E.g. it can be used as the base of the import in the system and the same validator can be used in tests to * check the validity of samples. @@ -37,32 +37,32 @@ public interface EventHandler { /** * Call-back called after deserializing to DOM and static schema validation but before unmarshall to JAXB. * It can be used for extra DOM-based checks or transformations of the object. - * + * * @param objectElement DOM tree parsed from file * @param postValidationTree post-validation DOM tree * @param objectResult Operation result for this object * @return true if the process should continue, false if it should stop */ public EventResult preMarshall(Element objectElement, Node postValidationTree, OperationResult objectResult); - + /** * Call-back called after the object is unmarshalled. - * + * * The compliance with static schemas should already be checked. This is the "main" call-back as it is expected that * this call-back will do the primary part of work such storing the object to repository during import. - * + * * @param object unmarshalled JAXB object * @param objectElement DOM tree parsed from the fil * @param objectResult Operation result for this object * @return true if the process should continue, false if it should stop */ public EventResult postMarshall(PrismObject object, Element objectElement, OperationResult objectResult); - + /** * Call-back to handle global errors. - * + * * This callback will be called with any error that cannot be attributed to any particular object. - * + * * @param currentResult Operation result pointing to the particular error. * @return true if the process should continue, false if it should stop */ diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/validator/EventResult.java b/infra/common/src/main/java/com/evolveum/midpoint/common/validator/EventResult.java index c0a1e5c1b9f..c68987df205 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/validator/EventResult.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/validator/EventResult.java @@ -22,40 +22,40 @@ public class EventResult { public enum EventResultStatus { - + /** * Continue normal processing. */ CONTINUE, - + /** * Skip the rest of processing of this object, continue with the next object. */ SKIP_OBJECT, - + /** * Stop processing. */ STOP; } - + private EventResultStatus status; private String reason; - + private EventResult(EventResultStatus status, String reason) { super(); this.status = status; this.reason = reason; } - + public static EventResult cont() { return new EventResult(EventResultStatus.CONTINUE,null); } - + public static EventResult skipObject() { return new EventResult(EventResultStatus.SKIP_OBJECT,null); } - + public static EventResult skipObject(String reason) { return new EventResult(EventResultStatus.SKIP_OBJECT, reason); } @@ -63,7 +63,7 @@ public static EventResult skipObject(String reason) { public static EventResult stop() { return new EventResult(EventResultStatus.STOP,null); } - + public static EventResult stop(String reason) { return new EventResult(EventResultStatus.STOP,reason); } @@ -75,11 +75,11 @@ public EventResultStatus getStatus() { public String getReason() { return reason; } - + public boolean isCont() { return status==EventResultStatus.CONTINUE; } - + public boolean isStop() { return status==EventResultStatus.STOP; } diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/validator/ValidationMessage.java b/infra/common/src/main/java/com/evolveum/midpoint/common/validator/ValidationMessage.java index 45d7e22252c..9db9fd1927e 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/validator/ValidationMessage.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/validator/ValidationMessage.java @@ -17,7 +17,7 @@ package com.evolveum.midpoint.common.validator; /** - * + * * @author semancik */ public class ValidationMessage { @@ -53,7 +53,7 @@ public ValidationMessage(Type type, String message, String oid, String name, Str /** * Get the value of type - * + * * @return the value of type */ public Type getType() { @@ -62,7 +62,7 @@ public Type getType() { /** * Set the value of type - * + * * @param type * new value of type */ @@ -72,7 +72,7 @@ public void setType(Type type) { /** * Get the value of message - * + * * @return the value of message */ public String getMessage() { @@ -81,7 +81,7 @@ public String getMessage() { /** * Set the value of message - * + * * @param message * new value of message */ @@ -99,7 +99,7 @@ public void setName(String name) { /** * Get the value of oid - * + * * @return the value of oid */ public String getOid() { @@ -108,7 +108,7 @@ public String getOid() { /** * Set the value of oid - * + * * @param oid * new value of oid */ @@ -118,7 +118,7 @@ public void setOid(String oid) { /** * Get the value of property - * + * * @return the value of property */ public String getProperty() { @@ -127,7 +127,7 @@ public String getProperty() { /** * Set the value of property - * + * * @param property * new value of property */ diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/validator/Validator.java b/infra/common/src/main/java/com/evolveum/midpoint/common/validator/Validator.java index 66654002432..a080a299e34 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/validator/Validator.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/validator/Validator.java @@ -57,10 +57,10 @@ import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; /** - * - * + * + * * @author Radovan Semancik - * + * */ public class Validator { @@ -177,7 +177,7 @@ public void validate(InputStream inputStream, OperationResult validatorResult, S XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); stream = xmlInputFactory.createXMLStreamReader(inputStream); - + int eventType = stream.nextTag(); if (eventType == XMLStreamConstants.START_ELEMENT) { if (!QNameUtil.match(stream.getName(), SchemaConstants.C_OBJECTS)) { @@ -245,7 +245,7 @@ public void validate(InputStream inputStream, OperationResult validatorResult, S if (objectResult.isError()) { errors++; } - + objectResult.cleanupResult(); validatorResult.summarize(); @@ -314,13 +314,13 @@ private EventResult readFromStreamAndValidate(XMLStreamReader stream, OperationR return validateObjectInternal(objectElement, objectResult, validatorResult); } - + public EventResult validateObject(String stringXml, OperationResult objectResult) { Document objectDoc = DOMUtil.parseDocument(stringXml); Element objectElement = DOMUtil.getFirstChildElement(objectDoc); return validateObjectInternal(objectElement, objectResult, objectResult); } - + public EventResult validateObject(Element objectElement, OperationResult objectResult) { return validateObjectInternal(objectElement, objectResult, objectResult); } @@ -363,20 +363,20 @@ private EventResult validateObjectInternal(Element objectElement, OperationResul } PrismObject object = prismContext.parserFor(objectElement).parse(); - + try { object.checkConsistence(); } catch (RuntimeException e) { objectResult.recordFatalError("Internal object inconsistence, probably a parser bug: "+e.getMessage(), e); return EventResult.skipObject(e.getMessage()); } - + Objectable objectType = null; if (object != null) { objectType = object.asObjectable(); objectResult.addContext(OperationResult.CONTEXT_OBJECT, object.toString()); } - + if (verbose) { LOGGER.trace("Processing OID " + objectType.getOid()); } @@ -436,7 +436,7 @@ private EventResult validateObjectInternal(Element objectElement, OperationResul objectResult.recordFatalError(ex); return EventResult.skipObject(ex.getMessage()); } - + } // this was made public to allow validation of pre-parsed non-prism documents diff --git a/infra/common/src/test/java/com/evolveum/midpoint/common/CommonTestConstants.java b/infra/common/src/test/java/com/evolveum/midpoint/common/CommonTestConstants.java index 1ccfd41cebc..ced76967ba2 100644 --- a/infra/common/src/test/java/com/evolveum/midpoint/common/CommonTestConstants.java +++ b/infra/common/src/test/java/com/evolveum/midpoint/common/CommonTestConstants.java @@ -24,7 +24,7 @@ * */ public class CommonTestConstants { - + public static final String USER_JACK_OID = "c0c010c0-d34d-b33f-f00d-111111111111"; public static final File USER_JACK_FILE = new File(MidPointTestConstants.OBJECTS_DIR, USER_JACK_OID + ".xml"); diff --git a/infra/common/src/test/java/com/evolveum/midpoint/common/TestActivationComputer.java b/infra/common/src/test/java/com/evolveum/midpoint/common/TestActivationComputer.java index e6c6a2f7b30..a4b95e37779 100644 --- a/infra/common/src/test/java/com/evolveum/midpoint/common/TestActivationComputer.java +++ b/infra/common/src/test/java/com/evolveum/midpoint/common/TestActivationComputer.java @@ -41,14 +41,14 @@ * */ public class TestActivationComputer { - + private static final XMLGregorianCalendar YEAR_START = XmlTypeConverter.createXMLGregorianCalendar(2013, 1, 1, 0, 0, 0); private static final XMLGregorianCalendar SPRING_EQUINOX = XmlTypeConverter.createXMLGregorianCalendar(2013, 3, 20, 11, 2, 00); private static final XMLGregorianCalendar SUMMER_SOLSTICE = XmlTypeConverter.createXMLGregorianCalendar(2013, 6, 21, 5, 4, 00); private static final XMLGregorianCalendar AUTUMN_EQUINOX = XmlTypeConverter.createXMLGregorianCalendar(2013, 9, 22, 20, 4, 00); private static final XMLGregorianCalendar WINTER_SOLSTICE = XmlTypeConverter.createXMLGregorianCalendar(2013, 12, 21, 17, 11, 00); private static final XMLGregorianCalendar YEAR_END = XmlTypeConverter.createXMLGregorianCalendar(2013, 12, 31, 23, 59, 59); - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); @@ -58,47 +58,47 @@ public void setup() throws SchemaException, SAXException, IOException { @Test public void testGetAdministrativeEnabled() throws Exception { System.out.println("\n===[ testGetAdministrativeEnabled ]===\n"); - + // GIVEN Clock clock = createClock(YEAR_START); - ActivationComputer activationComputer = createActivationComputer(clock); + ActivationComputer activationComputer = createActivationComputer(clock); ActivationType activationType = createActivationType(ActivationStatusType.ENABLED, SPRING_EQUINOX, AUTUMN_EQUINOX); - + // WHEN ActivationStatusType effectiveStatus = activationComputer.getEffectiveStatus(null, activationType); - + // THEN assertEquals("Unexpected effective status", ActivationStatusType.ENABLED, effectiveStatus); } - + @Test public void testGetAdministrativeDisabled() throws Exception { System.out.println("\n===[ testGetAdministrativeDisabled ]===\n"); - + // GIVEN Clock clock = createClock(SUMMER_SOLSTICE); - ActivationComputer activationComputer = createActivationComputer(clock); + ActivationComputer activationComputer = createActivationComputer(clock); ActivationType activationType = createActivationType(ActivationStatusType.DISABLED, SPRING_EQUINOX, AUTUMN_EQUINOX); - + // WHEN ActivationStatusType effectiveStatus = activationComputer.getEffectiveStatus(null, activationType); - + // THEN assertEquals("Unexpected effective status", ActivationStatusType.DISABLED, effectiveStatus); } - + @Test public void testGetAdministrativeArchived() throws Exception { System.out.println("\n===[ testGetAdministrativeArchived ]===\n"); - + // GIVEN Clock clock = createClock(SUMMER_SOLSTICE); - ActivationComputer activationComputer = createActivationComputer(clock); + ActivationComputer activationComputer = createActivationComputer(clock); ActivationType activationType = createActivationType(ActivationStatusType.ARCHIVED, SPRING_EQUINOX, AUTUMN_EQUINOX); - + // WHEN ActivationStatusType effectiveStatus = activationComputer.getEffectiveStatus(null, activationType); - + // THEN assertEquals("Unexpected effective status", ActivationStatusType.ARCHIVED, effectiveStatus); } @@ -106,15 +106,15 @@ public void testGetAdministrativeArchived() throws Exception { @Test public void testGetDraftAdministrativeEnabled() throws Exception { System.out.println("\n===[ testGetDraftAdministrativeEnabled ]===\n"); - + // GIVEN Clock clock = createClock(YEAR_START); - ActivationComputer activationComputer = createActivationComputer(clock); + ActivationComputer activationComputer = createActivationComputer(clock); ActivationType activationType = createActivationType(ActivationStatusType.DISABLED, SPRING_EQUINOX, AUTUMN_EQUINOX); - + // WHEN ActivationStatusType effectiveStatus = activationComputer.getEffectiveStatus(SchemaConstants.LIFECYCLE_DRAFT, activationType); - + // THEN assertEquals("Unexpected effective status", ActivationStatusType.DISABLED, effectiveStatus); } @@ -122,15 +122,15 @@ public void testGetDraftAdministrativeEnabled() throws Exception { @Test public void testGetProposedAdministrativeEnabled() throws Exception { System.out.println("\n===[ testGetProposedAdministrativeEnabled ]===\n"); - + // GIVEN Clock clock = createClock(YEAR_START); - ActivationComputer activationComputer = createActivationComputer(clock); + ActivationComputer activationComputer = createActivationComputer(clock); ActivationType activationType = createActivationType(ActivationStatusType.DISABLED, SPRING_EQUINOX, AUTUMN_EQUINOX); - + // WHEN ActivationStatusType effectiveStatus = activationComputer.getEffectiveStatus(SchemaConstants.LIFECYCLE_PROPOSED, activationType); - + // THEN assertEquals("Unexpected effective status", ActivationStatusType.DISABLED, effectiveStatus); } @@ -138,215 +138,215 @@ public void testGetProposedAdministrativeEnabled() throws Exception { @Test public void testGetActiveAdministrativeEnabled() throws Exception { System.out.println("\n===[ testGetActiveAdministrativeEnabled ]===\n"); - + // GIVEN Clock clock = createClock(YEAR_START); - ActivationComputer activationComputer = createActivationComputer(clock); + ActivationComputer activationComputer = createActivationComputer(clock); ActivationType activationType = createActivationType(ActivationStatusType.ENABLED, SPRING_EQUINOX, AUTUMN_EQUINOX); - + // WHEN ActivationStatusType effectiveStatus = activationComputer.getEffectiveStatus(SchemaConstants.LIFECYCLE_ACTIVE, activationType); - + // THEN assertEquals("Unexpected effective status", ActivationStatusType.ENABLED, effectiveStatus); } - + @Test public void testGetActiveAdministrativeDisabled() throws Exception { System.out.println("\n===[ testGetActiveAdministrativeDisabled ]===\n"); - + // GIVEN Clock clock = createClock(YEAR_START); - ActivationComputer activationComputer = createActivationComputer(clock); + ActivationComputer activationComputer = createActivationComputer(clock); ActivationType activationType = createActivationType(ActivationStatusType.DISABLED, SPRING_EQUINOX, AUTUMN_EQUINOX); - + // WHEN ActivationStatusType effectiveStatus = activationComputer.getEffectiveStatus(SchemaConstants.LIFECYCLE_ACTIVE, activationType); - + // THEN assertEquals("Unexpected effective status", ActivationStatusType.DISABLED, effectiveStatus); } - + @Test public void testGetDeprecatedAdministrativeDisabled() throws Exception { System.out.println("\n===[ testGetDeprecatedAdministrativeDisabled ]===\n"); - + // GIVEN Clock clock = createClock(SUMMER_SOLSTICE); - ActivationComputer activationComputer = createActivationComputer(clock); + ActivationComputer activationComputer = createActivationComputer(clock); ActivationType activationType = createActivationType(ActivationStatusType.DISABLED, SPRING_EQUINOX, AUTUMN_EQUINOX); - + // WHEN ActivationStatusType effectiveStatus = activationComputer.getEffectiveStatus(SchemaConstants.LIFECYCLE_DEPRECATED, activationType); - + // THEN assertEquals("Unexpected effective status", ActivationStatusType.DISABLED, effectiveStatus); } - + @Test public void testGetDeprecatedAdministrativeEnabled() throws Exception { System.out.println("\n===[ testGetDeprecatedAdministrativeEnabled ]===\n"); - + // GIVEN Clock clock = createClock(SUMMER_SOLSTICE); - ActivationComputer activationComputer = createActivationComputer(clock); + ActivationComputer activationComputer = createActivationComputer(clock); ActivationType activationType = createActivationType(ActivationStatusType.ENABLED, SPRING_EQUINOX, AUTUMN_EQUINOX); - + // WHEN ActivationStatusType effectiveStatus = activationComputer.getEffectiveStatus(SchemaConstants.LIFECYCLE_DEPRECATED, activationType); - + // THEN assertEquals("Unexpected effective status", ActivationStatusType.ENABLED, effectiveStatus); } - + @Test public void testGetActiveAdministrativeArchived() throws Exception { System.out.println("\n===[ testGetAdministrativeArchived ]===\n"); - + // GIVEN Clock clock = createClock(SUMMER_SOLSTICE); - ActivationComputer activationComputer = createActivationComputer(clock); + ActivationComputer activationComputer = createActivationComputer(clock); ActivationType activationType = createActivationType(ActivationStatusType.ARCHIVED, SPRING_EQUINOX, AUTUMN_EQUINOX); - + // WHEN ActivationStatusType effectiveStatus = activationComputer.getEffectiveStatus(SchemaConstants.LIFECYCLE_ACTIVE, activationType); - + // THEN assertEquals("Unexpected effective status", ActivationStatusType.ARCHIVED, effectiveStatus); } - + @Test public void testGetArchivedAdministrativeEnabled() throws Exception { System.out.println("\n===[ testGetArchivedAdministrativeEnabled ]===\n"); - + // GIVEN Clock clock = createClock(SUMMER_SOLSTICE); - ActivationComputer activationComputer = createActivationComputer(clock); + ActivationComputer activationComputer = createActivationComputer(clock); ActivationType activationType = createActivationType(ActivationStatusType.ENABLED, SPRING_EQUINOX, AUTUMN_EQUINOX); - + // WHEN ActivationStatusType effectiveStatus = activationComputer.getEffectiveStatus(SchemaConstants.LIFECYCLE_ARCHIVED, activationType); - + // THEN assertEquals("Unexpected effective status", ActivationStatusType.ARCHIVED, effectiveStatus); } - + @Test public void testGetBeforeValidity() throws Exception { System.out.println("\n===[ testGetBeforeValidity ]===\n"); - + // GIVEN Clock clock = createClock(YEAR_START); - ActivationComputer activationComputer = createActivationComputer(clock); + ActivationComputer activationComputer = createActivationComputer(clock); ActivationType activationType = createActivationType(null, SPRING_EQUINOX, AUTUMN_EQUINOX); - + // WHEN ActivationStatusType effectiveStatus = activationComputer.getEffectiveStatus(null, activationType); - + // THEN assertEquals("Unexpected effective status", ActivationStatusType.DISABLED, effectiveStatus); } - + @Test public void testGetInValidity() throws Exception { System.out.println("\n===[ testGetInValidity ]===\n"); - + // GIVEN Clock clock = createClock(SUMMER_SOLSTICE); - ActivationComputer activationComputer = createActivationComputer(clock); + ActivationComputer activationComputer = createActivationComputer(clock); ActivationType activationType = createActivationType(null, SPRING_EQUINOX, AUTUMN_EQUINOX); - + // WHEN ActivationStatusType effectiveStatus = activationComputer.getEffectiveStatus(null, activationType); - + // THEN assertEquals("Unexpected effective status", ActivationStatusType.ENABLED, effectiveStatus); } - + @Test public void testGetAfterValidity() throws Exception { System.out.println("\n===[ testGetAfterValidity ]===\n"); - + // GIVEN Clock clock = createClock(WINTER_SOLSTICE); - ActivationComputer activationComputer = createActivationComputer(clock); + ActivationComputer activationComputer = createActivationComputer(clock); ActivationType activationType = createActivationType(null, SPRING_EQUINOX, AUTUMN_EQUINOX); - + // WHEN ActivationStatusType effectiveStatus = activationComputer.getEffectiveStatus(null, activationType); - + // THEN assertEquals("Unexpected effective status", ActivationStatusType.DISABLED, effectiveStatus); } - + @Test public void testComputeAdministrativeEnabledBefore() throws Exception { - testCompute("testComputeAdministrativeEnabledBefore", YEAR_START, - ActivationStatusType.ENABLED, SPRING_EQUINOX, AUTUMN_EQUINOX, + testCompute("testComputeAdministrativeEnabledBefore", YEAR_START, + ActivationStatusType.ENABLED, SPRING_EQUINOX, AUTUMN_EQUINOX, ActivationStatusType.ENABLED, TimeIntervalStatusType.BEFORE); } - + @Test public void testComputeAdministrativeEnabledIn() throws Exception { - testCompute("testComputeAdministrativeEnabledIn", SUMMER_SOLSTICE, - ActivationStatusType.ENABLED, SPRING_EQUINOX, AUTUMN_EQUINOX, + testCompute("testComputeAdministrativeEnabledIn", SUMMER_SOLSTICE, + ActivationStatusType.ENABLED, SPRING_EQUINOX, AUTUMN_EQUINOX, ActivationStatusType.ENABLED, TimeIntervalStatusType.IN); } - + @Test public void testComputeAdministrativeEnabledAfter() throws Exception { - testCompute("testComputeAdministrativeEnabledBefore", WINTER_SOLSTICE, - ActivationStatusType.ENABLED, SPRING_EQUINOX, AUTUMN_EQUINOX, + testCompute("testComputeAdministrativeEnabledBefore", WINTER_SOLSTICE, + ActivationStatusType.ENABLED, SPRING_EQUINOX, AUTUMN_EQUINOX, ActivationStatusType.ENABLED, TimeIntervalStatusType.AFTER); } - + @Test public void testComputeAdministrativeArchivedBefore() throws Exception { - testCompute("testComputeAdministrativeArchivedBefore", YEAR_START, - ActivationStatusType.ARCHIVED, SPRING_EQUINOX, AUTUMN_EQUINOX, + testCompute("testComputeAdministrativeArchivedBefore", YEAR_START, + ActivationStatusType.ARCHIVED, SPRING_EQUINOX, AUTUMN_EQUINOX, ActivationStatusType.ARCHIVED, TimeIntervalStatusType.BEFORE); } - + @Test public void testComputeAdministrativeDisabledIn() throws Exception { - testCompute("testComputeAdministrativeDisabledIn", SUMMER_SOLSTICE, - ActivationStatusType.DISABLED, SPRING_EQUINOX, AUTUMN_EQUINOX, + testCompute("testComputeAdministrativeDisabledIn", SUMMER_SOLSTICE, + ActivationStatusType.DISABLED, SPRING_EQUINOX, AUTUMN_EQUINOX, ActivationStatusType.DISABLED, TimeIntervalStatusType.IN); } - + @Test public void testComputeAdministrativeDisabledAfter() throws Exception { - testCompute("testComputeAdministrativeDisabledAfter", WINTER_SOLSTICE, - ActivationStatusType.DISABLED, SPRING_EQUINOX, AUTUMN_EQUINOX, + testCompute("testComputeAdministrativeDisabledAfter", WINTER_SOLSTICE, + ActivationStatusType.DISABLED, SPRING_EQUINOX, AUTUMN_EQUINOX, ActivationStatusType.DISABLED, TimeIntervalStatusType.AFTER); } - + @Test public void testComputeBefore() throws Exception { - testCompute("testComputeAdministrativeEnabledBefore", YEAR_START, - null, SPRING_EQUINOX, AUTUMN_EQUINOX, + testCompute("testComputeAdministrativeEnabledBefore", YEAR_START, + null, SPRING_EQUINOX, AUTUMN_EQUINOX, ActivationStatusType.DISABLED, TimeIntervalStatusType.BEFORE); } - + @Test public void testComputeIn() throws Exception { - testCompute("testComputeAdministrativeEnabledIn", SUMMER_SOLSTICE, - null, SPRING_EQUINOX, AUTUMN_EQUINOX, + testCompute("testComputeAdministrativeEnabledIn", SUMMER_SOLSTICE, + null, SPRING_EQUINOX, AUTUMN_EQUINOX, ActivationStatusType.ENABLED, TimeIntervalStatusType.IN); } - + @Test public void testComputeAfter() throws Exception { - testCompute("testComputeAdministrativeEnabledBefore", WINTER_SOLSTICE, - null, SPRING_EQUINOX, AUTUMN_EQUINOX, + testCompute("testComputeAdministrativeEnabledBefore", WINTER_SOLSTICE, + null, SPRING_EQUINOX, AUTUMN_EQUINOX, ActivationStatusType.DISABLED, TimeIntervalStatusType.AFTER); } - + void testCompute(final String TEST_NAME, XMLGregorianCalendar now, ActivationStatusType administrativeStatus, XMLGregorianCalendar validFrom, XMLGregorianCalendar validTo, ActivationStatusType expectedEffective, TimeIntervalStatusType expectedValidity) { System.out.println("\n===[ "+TEST_NAME+" ]===\n"); - + testCompute(TEST_NAME, null, now, administrativeStatus, validFrom, validTo, expectedEffective, expectedValidity); testCompute(TEST_NAME, SchemaConstants.LIFECYCLE_DRAFT, now, administrativeStatus, validFrom, validTo, ActivationStatusType.DISABLED, expectedValidity); testCompute(TEST_NAME, SchemaConstants.LIFECYCLE_PROPOSED, now, administrativeStatus, validFrom, validTo, ActivationStatusType.DISABLED, expectedValidity); @@ -355,18 +355,18 @@ void testCompute(final String TEST_NAME, XMLGregorianCalendar now, ActivationSta testCompute(TEST_NAME, SchemaConstants.LIFECYCLE_FAILED, now, administrativeStatus, validFrom, validTo, ActivationStatusType.DISABLED, expectedValidity); testCompute(TEST_NAME, SchemaConstants.LIFECYCLE_ARCHIVED, now, administrativeStatus, validFrom, validTo, ActivationStatusType.ARCHIVED, expectedValidity); } - + void testCompute(final String TEST_NAME, String lifecycleState, XMLGregorianCalendar now, ActivationStatusType administrativeStatus, XMLGregorianCalendar validFrom, XMLGregorianCalendar validTo, ActivationStatusType expectedEffective, TimeIntervalStatusType expectedValidity) { - + // GIVEN Clock clock = createClock(now); - ActivationComputer activationComputer = createActivationComputer(clock); + ActivationComputer activationComputer = createActivationComputer(clock); ActivationType activationType = createActivationType(administrativeStatus, validFrom, validTo); - + // WHEN activationComputer.computeEffective(lifecycleState, activationType); - + // THEN assertEquals("Unexpected effective status", expectedEffective, activationType.getEffectiveStatus()); assertEquals("Unexpected validity status", expectedValidity, activationType.getValidityStatus()); diff --git a/infra/common/src/test/java/com/evolveum/midpoint/common/TestStaticValues.java b/infra/common/src/test/java/com/evolveum/midpoint/common/TestStaticValues.java index bf04742b3db..4ba66ca810a 100644 --- a/infra/common/src/test/java/com/evolveum/midpoint/common/TestStaticValues.java +++ b/infra/common/src/test/java/com/evolveum/midpoint/common/TestStaticValues.java @@ -43,7 +43,7 @@ * @author semancik */ public class TestStaticValues { - + private static final QName PROP_NAME = new QName("http://whatever.com/", "foo"); @BeforeSuite @@ -56,7 +56,7 @@ public void setup() throws SchemaException, SAXException, IOException { public void testValueElementsRoundtripString() throws Exception { final String TEST_NAME = "testValueElementsRoundtripString"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); PrismPropertyDefinitionImpl propDef = new PrismPropertyDefinitionImpl(PROP_NAME, DOMUtil.XSD_STRING, prismContext); @@ -64,15 +64,15 @@ public void testValueElementsRoundtripString() throws Exception { PrismProperty origProperty = propDef.instantiate(); origProperty.addRealValue("FOO"); origProperty.addRealValue("BAR"); - + doRoundtrip(origProperty, propDef, prismContext); } - + @Test public void testValueElementsRoundtripInt() throws Exception { final String TEST_NAME = "testValueElementsRoundtripInt"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); PrismPropertyDefinitionImpl propDef = new PrismPropertyDefinitionImpl(PROP_NAME, DOMUtil.XSD_INT, prismContext); @@ -81,14 +81,14 @@ public void testValueElementsRoundtripInt() throws Exception { origProperty.addRealValue(42); origProperty.addRealValue(123); origProperty.addRealValue(321); - + doRoundtrip(origProperty, propDef, prismContext); } private void doRoundtrip(PrismProperty origProperty, ItemDefinition propDef, PrismContext prismContext) throws SchemaException, JAXBException { // WHEN List> valueElements = StaticExpressionUtil.serializeValueElements(origProperty, "here somewhere"); - + for (Object element: valueElements) { if (element instanceof JAXBElement) { System.out.println(PrismTestUtil.serializeJaxbElementToString((JAXBElement) element)); diff --git a/infra/common/src/test/java/com/evolveum/midpoint/common/refinery/TestRefinedSchema.java b/infra/common/src/test/java/com/evolveum/midpoint/common/refinery/TestRefinedSchema.java index bdfd1d1f4fe..428eb663361 100644 --- a/infra/common/src/test/java/com/evolveum/midpoint/common/refinery/TestRefinedSchema.java +++ b/infra/common/src/test/java/com/evolveum/midpoint/common/refinery/TestRefinedSchema.java @@ -78,13 +78,13 @@ public class TestRefinedSchema { private static final File RESOURCE_COMPLEX_FILE = new File(TEST_DIR_NAME, "resource-complex.xml"); private static final File RESOURCE_SIMPLE_FILE = new File(TEST_DIR_NAME, "resource-simple.xml"); private static final File RESOURCE_POSIX_FILE = new File(TEST_DIR_NAME, "resource-ldap-posix.xml"); - + private static final String ENTITLEMENT_GROUP_INTENT = "group"; private static final String ENTITLEMENT_LDAP_GROUP_INTENT = "ldapGroup"; private static final String ENTITLEMENT_UNIX_GROUP_INTENT = "unixGroup"; - + private static final QName OBJECT_CLASS_INETORGPERSON_QNAME = new QName(MidPointConstants.NS_RI, "inetOrgPerson"); - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); @@ -95,7 +95,7 @@ public void setup() throws SchemaException, SAXException, IOException { public void test010ParseFromResourceComplex() throws Exception { final String TEST_NAME = "test010ParseFromResourceComplex"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN PrismContext prismContext = createInitializedPrismContext(); @@ -112,11 +112,11 @@ public void test010ParseFromResourceComplex() throws Exception { System.out.println("Refined schema"); System.out.println(rSchema.debugDump()); assertRefinedSchema(resourceType, rSchema, null, LayerType.MODEL, true, true); - + assertLayerRefinedSchema(resourceType, rSchema, LayerType.SCHEMA, LayerType.SCHEMA, true, true); assertLayerRefinedSchema(resourceType, rSchema, LayerType.MODEL, LayerType.MODEL, true, true); assertLayerRefinedSchema(resourceType, rSchema, LayerType.PRESENTATION, LayerType.PRESENTATION, true, true); - + RefinedObjectClassDefinition rAccount = rSchema.getRefinedDefinition(ShadowKindType.ACCOUNT, (String)null); RefinedAttributeDefinition userPasswordAttribute = rAccount.findAttributeDefinition("userPassword"); assertNotNull("No userPassword attribute", userPasswordAttribute); @@ -135,7 +135,7 @@ private void assertLayerRefinedSchema(ResourceType resourceType, RefinedResource public void test020ParseFromResourceSimple() throws Exception { final String TEST_NAME = "test020ParseFromResourceSimple"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN PrismContext prismContext = createInitializedPrismContext(); @@ -149,92 +149,92 @@ public void test020ParseFromResourceSimple() throws Exception { assertNotNull("Refined schema is null", rSchema); System.out.println("Refined schema"); System.out.println(rSchema.debugDump()); - + assertRefinedSchema(resourceType, rSchema, null, LayerType.SCHEMA, false, false); } - - private void assertRefinedSchema(ResourceType resourceType, RefinedResourceSchema rSchema, + + private void assertRefinedSchema(ResourceType resourceType, RefinedResourceSchema rSchema, LayerType sourceLayer, LayerType validationLayer, boolean assertEntitlements, boolean assertPasswordPolicy) { - + assertEquals("Unexpected number of object classes in refined schema", 2, rSchema.getDefinitions().size()); - + for (Definition def: rSchema.getDefinitions()) { if (!(def instanceof RefinedObjectClassDefinition)) { AssertJUnit.fail("Non-refined definition sneaked into resource schema: "+def); } } - + assertFalse("No account definitions", rSchema.getRefinedDefinitions(ShadowKindType.ACCOUNT).isEmpty()); - + RefinedObjectClassDefinition rAccountDef = rSchema.getRefinedDefinition(ShadowKindType.ACCOUNT, (String)null); - + RefinedObjectClassDefinition accountDefByNullObjectclass = rSchema.findRefinedDefinitionByObjectClassQName(ShadowKindType.ACCOUNT, null); assertEquals("findAccountDefinitionByObjectClass(null) returned wrong value", rAccountDef, accountDefByNullObjectclass); - - RefinedObjectClassDefinition accountDefByIcfAccountObjectclass = rSchema.findRefinedDefinitionByObjectClassQName(ShadowKindType.ACCOUNT, + + RefinedObjectClassDefinition accountDefByIcfAccountObjectclass = rSchema.findRefinedDefinitionByObjectClassQName(ShadowKindType.ACCOUNT, new QName(resourceType.getNamespace(), SchemaTestConstants.ICF_ACCOUNT_OBJECT_CLASS_LOCAL_NAME)); assertEquals("findAccountDefinitionByObjectClass(ICF account) returned wrong value", rAccountDef, accountDefByIcfAccountObjectclass); assertRObjectClassDef(rAccountDef, resourceType, sourceLayer, validationLayer); System.out.println("Refined account definitionn:"); System.out.println(rAccountDef.debugDump()); - + assertEquals("Wrong kind", ShadowKindType.ACCOUNT, rAccountDef.getKind()); - + Collection accAttrsDef = rAccountDef.getAttributeDefinitions(); assertNotNull("Null attributeDefinitions", accAttrsDef); assertFalse("Empty attributeDefinitions", accAttrsDef.isEmpty()); assertEquals("Unexpected number of attributeDefinitions", 55, accAttrsDef.size()); - + RefinedAttributeDefinition disabledAttribute = rAccountDef.findAttributeDefinition("ds-pwp-account-disabled"); assertNotNull("No ds-pwp-account-disabled attribute", disabledAttribute); assertTrue("ds-pwp-account-disabled not ignored", disabledAttribute.isIgnored()); - + RefinedAttributeDefinition displayNameAttributeDef = rAccountDef.getDisplayNameAttribute(); assertNotNull("No account displayNameAttribute", displayNameAttributeDef); assertEquals("Wrong account displayNameAttribute", new QName(resourceType.getNamespace(), "uid"), displayNameAttributeDef.getName()); - + // This is compatibility with PrismContainerDefinition, it should work well Collection propertyDefinitions = rAccountDef.getDefinitions(); assertNotNull("Null propertyDefinitions", propertyDefinitions); assertFalse("Empty propertyDefinitions", propertyDefinitions.isEmpty()); assertEquals("Unexpected number of propertyDefinitions", 55, propertyDefinitions.size()); - + if (assertPasswordPolicy) { ObjectReferenceType passwordPolicyRef = rAccountDef.getPasswordPolicy(); assertNotNull("Expected password policy for account definition not found", passwordPolicyRef); } - - if (assertEntitlements) { + + if (assertEntitlements) { assertFalse("No entitlement definitions", rSchema.getRefinedDefinitions(ShadowKindType.ENTITLEMENT).isEmpty()); RefinedObjectClassDefinition rEntDef = rSchema.getRefinedDefinition(ShadowKindType.ENTITLEMENT, (String)null); assertNotNull("No entitlement definition for null intent", rEntDef); RefinedObjectClassDefinition rEntDefGroup = rSchema.getRefinedDefinition(ShadowKindType.ENTITLEMENT, ENTITLEMENT_GROUP_INTENT); assertNotNull("No entitlement for intent '"+ENTITLEMENT_GROUP_INTENT+"'", rEntDefGroup); - + assertEquals("Wrong kind", ShadowKindType.ENTITLEMENT, rEntDef.getKind()); - + Collection entAttrDefs = rEntDef.getAttributeDefinitions(); assertNotNull("Null attributeDefinitions", entAttrDefs); assertFalse("Empty attributeDefinitions", entAttrDefs.isEmpty()); assertEquals("Unexpected number of attributeDefinitions", 11, entAttrDefs.size()); // TODO - + RefinedAttributeDefinition entDisplayNameAttributeDef = rEntDef.getDisplayNameAttribute(); assertNotNull("No entitlement displayNameAttribute", entDisplayNameAttributeDef); assertEquals("Wrong entitlement displayNameAttribute", new QName(resourceType.getNamespace(), "cn"), entDisplayNameAttributeDef.getName()); - + assertEquals("Unexpected number of entitlement associations", 1, rAccountDef.getAssociationDefinitions().size()); } - + assertRefinedToLayer(rAccountDef, sourceLayer); - + ResourceAttributeContainerDefinition resAttrContainerDef = rAccountDef.toResourceAttributeContainerDefinition(); assertNotNull("No ResourceAttributeContainerDefinition", resAttrContainerDef); System.out.println("\nResourceAttributeContainerDefinition ("+sourceLayer+")"); System.out.println(resAttrContainerDef.debugDump()); - + ObjectClassComplexTypeDefinition rComplexTypeDefinition = resAttrContainerDef.getComplexTypeDefinition(); System.out.println("\nResourceAttributeContainerDefinition ComplexTypeDefinition ("+sourceLayer+")"); System.out.println(rComplexTypeDefinition.debugDump()); @@ -244,17 +244,17 @@ private void assertRefinedSchema(ResourceType resourceType, RefinedResourceSchem assertNotNull("No ri:uid def in ResourceAttributeContainerDefinition", riUidAttrDef); System.out.println("\nri:uid def "+riUidAttrDef.getClass()+" ("+sourceLayer+")"); System.out.println(riUidAttrDef.debugDump()); - + assertRefinedToLayer(riUidAttrDef, sourceLayer); - + if (validationLayer == LayerType.PRESENTATION) { - assertFalse("Can update "+riUidAttrDef+" from ResourceAttributeContainerDefinition ("+sourceLayer+")", + assertFalse("Can update "+riUidAttrDef+" from ResourceAttributeContainerDefinition ("+sourceLayer+")", riUidAttrDef.canModify()); } else { - assertTrue("Cannot update "+riUidAttrDef+" from ResourceAttributeContainerDefinition ("+sourceLayer+")", + assertTrue("Cannot update "+riUidAttrDef+" from ResourceAttributeContainerDefinition ("+sourceLayer+")", riUidAttrDef.canModify()); } - + Collection definitionsFromResAttrContainerDef = resAttrContainerDef.getDefinitions(); for (ResourceAttributeDefinition definitionFromResAttrContainerDef: definitionsFromResAttrContainerDef) { assertRefinedToLayer(definitionFromResAttrContainerDef, sourceLayer); @@ -301,7 +301,7 @@ public void test100ParseAccount() throws Exception { RefinedResourceSchema rSchema = RefinedResourceSchemaImpl.parse(resourceType, prismContext); RefinedObjectClassDefinition defaultAccountDefinition = rSchema.getDefaultRefinedDefinition(ShadowKindType.ACCOUNT); assertNotNull("No refined default account definition in "+rSchema, defaultAccountDefinition); - + PrismObject accObject = prismContext.parseObject(new File(TEST_DIR_NAME, "account-jack.xml")); @@ -321,7 +321,7 @@ public void test100ParseAccount() throws Exception { assertAccountShadow(accObject, resource, prismContext); } - + @Test public void test110ApplyAttributeDefinition() throws Exception { final String TEST_NAME = "test110ApplyAttributeDefinition"; @@ -331,7 +331,7 @@ public void test110ApplyAttributeDefinition() throws Exception { PrismContext prismContext = createInitializedPrismContext(); PrismObject resource = prismContext.parseObject(RESOURCE_COMPLEX_FILE); - + RefinedResourceSchema rSchema = RefinedResourceSchemaImpl.parse(resource, prismContext); System.out.println("Refined schema:"); System.out.println(rSchema.debugDump(1)); @@ -344,7 +344,7 @@ public void test110ApplyAttributeDefinition() throws Exception { PrismContainer attributesContainer = accObject.findContainer(ShadowType.F_ATTRIBUTES); System.out.println("Attributes container:"); System.out.println(attributesContainer.debugDump(1)); - + // WHEN attributesContainer.applyDefinition((PrismContainerDefinition)defaultAccountDefinition.toResourceAttributeContainerDefinition(), true); @@ -354,7 +354,7 @@ public void test110ApplyAttributeDefinition() throws Exception { assertAccountShadow(accObject, resource, prismContext); } - + private void assertAccountShadow(PrismObject accObject, PrismObject resource, PrismContext prismContext) throws SchemaException, JAXBException { ResourceType resourceType = resource.asObjectable(); QName objectClassQName = new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "AccountObjectClass"); @@ -374,7 +374,7 @@ private void assertAccountShadow(PrismObject accObject, PrismObject< PrismAsserts.assertPropertyValue(attributes, getAttrQName(resource, "uid"), "jack"); assertEquals("JAXB class name doesn't match (1)", ShadowType.class, accObject.getCompileTimeClass()); - + accObject.checkConsistence(); ShadowType accObjectType = accObject.asObjectable(); @@ -388,13 +388,13 @@ private void assertAccountShadow(PrismObject accObject, PrismObject< TestUtil.assertElement(attributeElements, getAttrQName(resource, "givenName"), "Jack"); TestUtil.assertElement(attributeElements, getAttrQName(resource, "sn"), "Sparrow"); TestUtil.assertElement(attributeElements, getAttrQName(resource, "uid"), "jack"); - + String accString = PrismTestUtil.serializeObjectToString(accObjectType.asPrismObject()); System.out.println("Result of JAXB marshalling:\n"+accString); - + accObject.checkConsistence(true, true, ConsistencyCheckScope.THOROUGH); } - + private QName getAttrQName(PrismObject resource, String localPart) { return new QName(ResourceTypeUtil.getResourceNamespace(resource), localPart); } @@ -414,10 +414,10 @@ public void test120CreateShadow() throws Exception { assertNotNull("Refined schema is null", rSchema); assertFalse("No account definitions", rSchema.getRefinedDefinitions(ShadowKindType.ACCOUNT).isEmpty()); RefinedObjectClassDefinition rAccount = rSchema.getRefinedDefinition(ShadowKindType.ACCOUNT, (String)null); - + // WHEN PrismObject blankShadow = rAccount.createBlankShadow(); - + // THEN assertNotNull("No blank shadow", blankShadow); assertNotNull("No prism context in blank shadow", blankShadow.getPrismContext()); @@ -426,9 +426,9 @@ public void test120CreateShadow() throws Exception { PrismContainerDefinition attrDef = objectDef.findContainerDefinition(ShadowType.F_ATTRIBUTES); assertNotNull("Blank shadow has no definition for attributes", attrDef); assertTrue("Wrong class for attributes definition: "+attrDef.getClass(), attrDef instanceof ResourceAttributeContainerDefinition); - + } - + @Test public void test130ProtectedAccount() throws Exception { final String TEST_NAME = "test130ProtectedAccount"; @@ -445,7 +445,7 @@ public void test130ProtectedAccount() throws Exception { // WHEN Collection protectedAccounts = rAccount.getProtectedObjectPatterns(); - + // THEN assertNotNull("Null protectedAccounts", protectedAccounts); assertFalse("Empty protectedAccounts", protectedAccounts.isEmpty()); @@ -463,7 +463,7 @@ private void assertAttributeDefs(ResourceAttributeContainerDefinition attrsDef, RefinedObjectClassDefinition rAccount = (RefinedObjectClassDefinition) attrsDef.getComplexTypeDefinition(); assertRObjectClassDef(rAccount, resourceType, sourceLayer, validationLayer); } - + private void assertRObjectClassDef(RefinedObjectClassDefinition rAccount, ResourceType resourceType, LayerType sourceLayer, LayerType validationLayer) { assertTrue(rAccount.isDefault()); @@ -471,31 +471,31 @@ private void assertRObjectClassDef(RefinedObjectClassDefinition rAccount, Resour assertFalse(attrs.isEmpty()); assertAttributeDef(attrs, SchemaTestConstants.ICFS_NAME, DOMUtil.XSD_STRING, 1, 1, "Distinguished Name", 110, - true, false, + true, false, true, true, validationLayer == LayerType.SCHEMA, // Access: create, read, update sourceLayer, validationLayer); - + assertAttributeDef(attrs, SchemaTestConstants.ICFS_UID, DOMUtil.XSD_STRING, 1, 1, "Entry UUID", 100, false, false, false, true, false, // Access: create, read, update sourceLayer, validationLayer); - - assertAttributeDef(attrs, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "cn"), DOMUtil.XSD_STRING, - 1, (validationLayer == LayerType.MODEL || validationLayer == LayerType.PRESENTATION) ? 1 : -1, "Common Name", 1, - true, validationLayer == LayerType.PRESENTATION, + + assertAttributeDef(attrs, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "cn"), DOMUtil.XSD_STRING, + 1, (validationLayer == LayerType.MODEL || validationLayer == LayerType.PRESENTATION) ? 1 : -1, "Common Name", 1, + true, validationLayer == LayerType.PRESENTATION, true, true, true, // Access: create, read, update sourceLayer, validationLayer); - - assertAttributeDef(attrs, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "uid"), - DOMUtil.XSD_STRING, - validationLayer == LayerType.SCHEMA ? 0 : 1 , // minOccurs + + assertAttributeDef(attrs, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "uid"), + DOMUtil.XSD_STRING, + validationLayer == LayerType.SCHEMA ? 0 : 1 , // minOccurs validationLayer == LayerType.SCHEMA ? -1 : 1, // maxOccurs "Login Name", 2, true, false, true, true, validationLayer != LayerType.PRESENTATION, // Access: create, read, update sourceLayer, validationLayer); - - assertAttributeDef(attrs, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "employeeNumber"), + + assertAttributeDef(attrs, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "employeeNumber"), DOMUtil.XSD_STRING, 0, 1, null, null, false, false, true, true, true, // Access: create, read, update @@ -504,7 +504,7 @@ private void assertRObjectClassDef(RefinedObjectClassDefinition rAccount, Resour private void assertAttributeDef(Collection attrDefs, QName name, QName typeName, int minOccurs, int maxOccurs, String displayName, Integer displayOrder, - boolean hasOutbound, boolean ignore, boolean canCreate, boolean canRead, boolean canUpdate, + boolean hasOutbound, boolean ignore, boolean canCreate, boolean canRead, boolean canUpdate, LayerType sourceLayer, LayerType validationLayer) { for (RefinedAttributeDefinition def : attrDefs) { if (def.getName().equals(name)) { @@ -525,7 +525,7 @@ private void assertAttributeDef(Collection } Assert.fail("Attribute " + name + " not found"); } - + private void assertDeprecatedProtectedAccount(String message, ResourceObjectPattern protectedPattern, String identifierValue, RefinedObjectClassDefinition rAccount) throws SchemaException { Collection> identifiers = protectedPattern.getIdentifiers(); assertNotNull("Null identifiers in "+message, identifiers); @@ -533,8 +533,8 @@ private void assertDeprecatedProtectedAccount(String message, ResourceObjectPatt ResourceAttribute identifier = identifiers.iterator().next(); assertNotNull("Null identifier in "+message, identifier); assertEquals("Wrong identifier value in "+message, identifier.getRealValue(), identifierValue); - - // Try matching + + // Try matching PrismObject shadow = rAccount.getObjectDefinition().instantiate(); ResourceAttributeContainer attributesContainer = ShadowUtil.getOrCreateAttributesContainer(shadow, rAccount); ResourceAttribute confusingAttr1 = createStringAttribute(new QName("http://whatever.com","confuseMe"), "HowMuchWoodWouldWoodchuckChuckIfWoodchuckCouldChudkWood"); @@ -543,7 +543,7 @@ private void assertDeprecatedProtectedAccount(String message, ResourceObjectPatt attributesContainer.add(nameAttr); ResourceAttribute confusingAttr2 = createStringAttribute(new QName("http://whatever.com","confuseMeAgain"), "WoodchuckWouldChuckNoWoodAsWoodchuckCannotChuckWood"); attributesContainer.add(confusingAttr2); - + assertTrue("Test attr not matched in "+message, protectedPattern.matches(shadow, null)); nameAttr.setRealValue("huhulumululul"); assertFalse("Test attr nonsense was matched in "+message, protectedPattern.matches(shadow, null)); @@ -560,7 +560,7 @@ private ResourceAttribute createStringAttribute(QName attrName, String v public void test140ParseFromResourcePosix() throws Exception { final String TEST_NAME = "test140ParseFromResourcePosix"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN PrismContext prismContext = createInitializedPrismContext(); @@ -576,104 +576,104 @@ public void test140ParseFromResourcePosix() throws Exception { assertNotNull("Refined schema is null", rSchema); System.out.println("Refined schema"); System.out.println(rSchema.debugDump()); - + assertFalse("No account definitions", rSchema.getRefinedDefinitions(ShadowKindType.ACCOUNT).isEmpty()); - + // ### default account objectType - + RefinedObjectClassDefinition rAccountDef = rSchema.getRefinedDefinition(ShadowKindType.ACCOUNT, (String)null); assertNotNull("No default account definition", rAccountDef); - + RefinedObjectClassDefinition accountDefByIcfAccountObjectclass = rSchema.findRefinedDefinitionByObjectClassQName(ShadowKindType.ACCOUNT, OBJECT_CLASS_INETORGPERSON_QNAME); assertTrue("findAccountDefinitionByObjectClass("+OBJECT_CLASS_INETORGPERSON_QNAME+") returned wrong value", rAccountDef.equals(accountDefByIcfAccountObjectclass)); - + assertTrue(rAccountDef.isDefault()); Collection rAccountAttrs = rAccountDef.getAttributeDefinitions(); assertFalse(rAccountAttrs.isEmpty()); - assertAttributeDef(rAccountAttrs, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "dn"), + assertAttributeDef(rAccountAttrs, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "dn"), DOMUtil.XSD_STRING, 1, 1, "Distinguished Name", 110, - true, false, + true, false, true, true, true, // Access: create, read, update LayerType.SCHEMA, LayerType.PRESENTATION); - - assertAttributeDef(rAccountAttrs, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "entryUUID"), + + assertAttributeDef(rAccountAttrs, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "entryUUID"), DOMUtil.XSD_STRING, 0, 1, null, 100, false, false, false, true, false, // Access: create, read, update LayerType.SCHEMA, LayerType.PRESENTATION); - - assertAttributeDef(rAccountAttrs, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "cn"), - DOMUtil.XSD_STRING, 1, -1, "Common Name", 590, - true, false, + + assertAttributeDef(rAccountAttrs, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "cn"), + DOMUtil.XSD_STRING, 1, -1, "Common Name", 590, + true, false, true, true, true, // Access: create, read, update LayerType.SCHEMA, LayerType.PRESENTATION); - - assertAttributeDef(rAccountAttrs, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "uid"), + + assertAttributeDef(rAccountAttrs, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "uid"), DOMUtil.XSD_STRING, 0, -1, "Login Name", 300, true, false, true, true, true, // Access: create, read, update LayerType.SCHEMA, LayerType.PRESENTATION); - - assertAttributeDef(rAccountAttrs, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "employeeNumber"), + + assertAttributeDef(rAccountAttrs, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "employeeNumber"), DOMUtil.XSD_STRING, 0, 1, null, 140, false, false, true, true, true, // Access: create, read, update LayerType.SCHEMA, LayerType.PRESENTATION); - + System.out.println("Refined account definitionn:"); System.out.println(rAccountDef.debugDump()); - + assertEquals("Wrong kind", ShadowKindType.ACCOUNT, rAccountDef.getKind()); - + Collection accAttrsDef = rAccountDef.getAttributeDefinitions(); assertNotNull("Null attributeDefinitions", accAttrsDef); assertFalse("Empty attributeDefinitions", accAttrsDef.isEmpty()); assertEquals("Unexpected number of attributeDefinitions", 53, accAttrsDef.size()); - + RefinedAttributeDefinition disabledAttribute = rAccountDef.findAttributeDefinition("ds-pwp-account-disabled"); assertNotNull("No ds-pwp-account-disabled attribute", disabledAttribute); assertTrue("ds-pwp-account-disabled not ignored", disabledAttribute.isIgnored()); - + RefinedAttributeDefinition displayNameAttributeDef = rAccountDef.getDisplayNameAttribute(); assertNotNull("No account displayNameAttribute", displayNameAttributeDef); - assertEquals("Wrong account displayNameAttribute", new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "dn"), + assertEquals("Wrong account displayNameAttribute", new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "dn"), displayNameAttributeDef.getName()); - + // This is compatibility with PrismContainerDefinition, it should work well Collection propertyDefinitions = rAccountDef.getDefinitions(); assertNotNull("Null propertyDefinitions", propertyDefinitions); assertFalse("Empty propertyDefinitions", propertyDefinitions.isEmpty()); assertEquals("Unexpected number of propertyDefinitions", 53, propertyDefinitions.size()); - + assertFalse("No entitlement definitions", rSchema.getRefinedDefinitions(ShadowKindType.ENTITLEMENT).isEmpty()); RefinedObjectClassDefinition rEntDef = rSchema.getRefinedDefinition(ShadowKindType.ENTITLEMENT, (String)null); assertNotNull("No entitlement definition for null intent", rEntDef); RefinedObjectClassDefinition rEntDefGroup = rSchema.getRefinedDefinition(ShadowKindType.ENTITLEMENT, ENTITLEMENT_LDAP_GROUP_INTENT); assertNotNull("No entitlement for intent '"+ENTITLEMENT_LDAP_GROUP_INTENT+"'", rEntDefGroup); - + assertEquals("Wrong kind", ShadowKindType.ENTITLEMENT, rEntDef.getKind()); - + Collection entAttrDefs = rEntDef.getAttributeDefinitions(); assertNotNull("Null attributeDefinitions", entAttrDefs); assertFalse("Empty attributeDefinitions", entAttrDefs.isEmpty()); assertEquals("Unexpected number of attributeDefinitions", 12, entAttrDefs.size()); - + RefinedAttributeDefinition entDisplayNameAttributeDef = rEntDef.getDisplayNameAttribute(); assertNotNull("No entitlement displayNameAttribute", entDisplayNameAttributeDef); assertEquals("Wrong entitlement displayNameAttribute", new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "dn"), entDisplayNameAttributeDef.getName()); - + assertEquals("Unexpected number of entitlement associations", 1, rAccountDef.getAssociationDefinitions().size()); - + ResourceAttributeContainerDefinition resAttrContainerDef = rAccountDef.toResourceAttributeContainerDefinition(); assertNotNull("No ResourceAttributeContainerDefinition", resAttrContainerDef); System.out.println("\nResourceAttributeContainerDefinition"); System.out.println(resAttrContainerDef.debugDump()); - + ObjectClassComplexTypeDefinition rComplexTypeDefinition = resAttrContainerDef.getComplexTypeDefinition(); System.out.println("\nResourceAttributeContainerDefinition ComplexTypeDefinition"); System.out.println(rComplexTypeDefinition.debugDump()); @@ -682,7 +682,7 @@ public void test140ParseFromResourcePosix() throws Exception { assertNotNull("No ri:uid def in ResourceAttributeContainerDefinition", riUidAttrDef); System.out.println("\nri:uid def "+riUidAttrDef.getClass()); System.out.println(riUidAttrDef.debugDump()); - + } - + } diff --git a/infra/common/src/test/java/com/evolveum/midpoint/common/test/UtilsTest.java b/infra/common/src/test/java/com/evolveum/midpoint/common/test/UtilsTest.java index ae8eea8ec9e..eb06a16c704 100644 --- a/infra/common/src/test/java/com/evolveum/midpoint/common/test/UtilsTest.java +++ b/infra/common/src/test/java/com/evolveum/midpoint/common/test/UtilsTest.java @@ -29,7 +29,7 @@ /** * Unit tests for Util class - * + * * @author semancik */ public class UtilsTest { diff --git a/infra/common/src/test/java/com/evolveum/midpoint/validator/test/BasicValidatorTest.java b/infra/common/src/test/java/com/evolveum/midpoint/validator/test/BasicValidatorTest.java index 88a87e930b1..4bd65525b33 100644 --- a/infra/common/src/test/java/com/evolveum/midpoint/validator/test/BasicValidatorTest.java +++ b/infra/common/src/test/java/com/evolveum/midpoint/validator/test/BasicValidatorTest.java @@ -55,7 +55,7 @@ /** * Test few basic cases of validation. - * + * * @author Radovan Semancik */ public class BasicValidatorTest { @@ -65,7 +65,7 @@ public class BasicValidatorTest { public BasicValidatorTest() { } - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); @@ -75,24 +75,24 @@ public void setup() throws SchemaException, SAXException, IOException { @Test public void resource1Valid() throws Exception { System.out.println("\n===[ resource1Valid ]====="); - + OperationResult result = new OperationResult(this.getClass().getName()+".resource1Valid"); - + EventHandler handler = new EventHandler() { - + @Override public EventResult preMarshall(Element objectElement, Node postValidationTree, OperationResult objectResult) { return EventResult.cont(); } - + @Override public EventResult postMarshall(PrismObject object, Element objectElement, OperationResult objectResult) { System.out.println("Validating resorce:"); System.out.println(object.debugDump()); object.checkConsistence(); - + PrismContainer extensionContainer = object.getExtension(); PrismProperty menProp = extensionContainer.findProperty(new QName("http://myself.me/schemas/whatever","menOnChest")); assertNotNull("No men on a dead man chest!", menProp); @@ -101,14 +101,14 @@ public EventResult postMarshall(PrismObject object, El assertNotNull("Men on a dead man chest NOT defined", menPropDef); assertEquals("Wrong type for men on a dead man chest definition", DOMUtil.XSD_INT, menPropDef.getTypeName()); assertTrue("Men on a dead man chest definition not dynamic", menPropDef.isDynamic()); - + return EventResult.cont(); } - + @Override public void handleGlobalError(OperationResult currentResult) { /* nothing */ } }; - + validateFile("resource-1-valid.xml", handler, result); AssertJUnit.assertTrue(result.isSuccess()); @@ -119,7 +119,7 @@ public void handlerTest() throws Exception { System.out.println("\n===[ handlerTest ]====="); OperationResult result = new OperationResult(this.getClass().getName()+".handlerTest"); - + final List postMarshallHandledOids = new ArrayList(); final List preMarshallHandledOids = new ArrayList(); @@ -164,9 +164,9 @@ public void notWellFormed() throws Exception { System.out.println("\n===[ notWellFormed ]====="); OperationResult result = new OperationResult(this.getClass().getName()+".notWellFormed"); - + validateFile("not-well-formed.xml",result); - + System.out.println(result.debugDump()); AssertJUnit.assertFalse(result.isSuccess()); AssertJUnit.assertTrue(result.getMessage().contains("Unexpected close tag")); @@ -178,11 +178,11 @@ public void notWellFormed() throws Exception { @Test public void undeclaredPrefix() throws Exception { System.out.println("\n===[ undeclaredPrefix ]====="); - + OperationResult result = new OperationResult(this.getClass().getName()+".undeclaredPrefix"); - + validateFile("undeclared-prefix.xml",result); - + System.out.println(result.debugDump()); AssertJUnit.assertFalse(result.isSuccess()); AssertJUnit.assertTrue(result.getMessage().contains("Undeclared namespace prefix")); @@ -194,11 +194,11 @@ public void undeclaredPrefix() throws Exception { @Test public void schemaViolation() throws Exception { System.out.println("\n===[ schemaViolation ]====="); - + OperationResult result = new OperationResult(this.getClass().getName()+".schemaViolation"); - + validateFile("three-users-schema-violation.xml",result); - + System.out.println(result.debugDump()); assertFalse(result.isSuccess()); assertTrue(result.getSubresults().get(0).getMessage().contains("Invalid content was found starting with element 'foo'")); @@ -212,26 +212,26 @@ public void schemaViolation() throws Exception { @Test public void testStopOnErrors() throws Exception { System.out.println("\n===[ testStopOnErrors ]====="); - + OperationResult result = new OperationResult(this.getClass().getName()+".testStopOnErrors"); - + Validator validator = new Validator(PrismTestUtil.getPrismContext()); validator.setVerbose(false); validator.setStopAfterErrors(2); - + validateFile("three-users-schema-violation.xml", null, validator, result); - + System.out.println(result.debugDump()); assertFalse(result.isSuccess()); assertEquals(2,result.getSubresults().size()); } - + @Test public void noName() throws Exception { System.out.println("\n===[ noName ]====="); OperationResult result = new OperationResult(this.getClass().getName()+".noName"); - + validateFile("no-name.xml",result); System.out.println(result.debugDump()); @@ -253,7 +253,7 @@ private void validateFile(String filename,EventHandler handler, OperationResult validator.setVerbose(false); validateFile(filename, handler, validator, result); } - + private void validateFile(String filename,EventHandler handler, Validator validator, OperationResult result) throws FileNotFoundException { String filepath = BASE_PATH + filename; diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/ComplexTypeDefinitionImpl.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/ComplexTypeDefinitionImpl.java index 12f4c9378f6..ec8381af609 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/ComplexTypeDefinitionImpl.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/ComplexTypeDefinitionImpl.java @@ -33,9 +33,9 @@ /** * TODO - * + * * @author Radovan Semancik - * + * */ public class ComplexTypeDefinitionImpl extends TypeDefinitionImpl implements ComplexTypeDefinition { @@ -62,13 +62,13 @@ public ComplexTypeDefinitionImpl(@NotNull QName typeName, @NotNull PrismContext protected String getSchemaNamespace() { return getTypeName().getNamespaceURI(); } - + /** * Returns set of item definitions. - * + * * The set contains all item definitions of all types that were parsed. * Order of definitions is insignificant. - * + * * @return set of definitions */ @NotNull @@ -76,7 +76,7 @@ protected String getSchemaNamespace() { public List getDefinitions() { return Collections.unmodifiableList(itemDefinitions); } - + public void add(ItemDefinition definition) { itemDefinitions.add(definition); } @@ -94,7 +94,7 @@ public QName getExtensionForType() { public void setExtensionForType(QName extensionForType) { this.extensionForType = extensionForType; } - + @Override public boolean isContainerMarker() { return containerMarker; @@ -108,7 +108,7 @@ public void setContainerMarker(boolean containerMarker) { public boolean isObjectMarker() { return objectMarker; } - + @Override public boolean isXsdAnyMarker() { return xsdAnyMarker; @@ -157,7 +157,7 @@ public PrismPropertyDefinitionImpl createPropertyDefinition(QName name, QName ty itemDefinitions.add(propDef); return propDef; } - + // Creates reference to other schema // TODO: maybe check if the name is in different namespace // TODO: maybe create entirely new concept of property reference? @@ -297,7 +297,7 @@ public ComplexTypeDefinition deepClone(Map ctdMap) } return clone; } - + protected void copyDefinitionData(ComplexTypeDefinitionImpl clone) { super.copyDefinitionData(clone); clone.containerMarker = this.containerMarker; @@ -327,7 +327,7 @@ public void replaceDefinition(QName propertyName, ItemDefinition newDefinition) } throw new IllegalArgumentException("The definition with name "+propertyName+" was not found in complex type "+getTypeName()); } - + @Override public int hashCode() { final int prime = 31; @@ -412,7 +412,7 @@ protected void extendDumpHeader(StringBuilder sb) { } protected void extendDumpDefinition(StringBuilder sb, ItemDefinition def) { - // Do nothing + // Do nothing } /** diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/Containerable.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/Containerable.java index 67c05055f51..f5c38ef90ed 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/Containerable.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/Containerable.java @@ -22,15 +22,15 @@ * */ public interface Containerable extends Serializable { - - + + PrismContainerValue asPrismContainerValue(); - + /** * Setup value to the containerable representation. This is used to after (empty) containerable is created to * initialize it with a correct prism container value. * Note: This method DOES NOT change the container value parent. */ void setupContainerValue(PrismContainerValue container); - + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/DefinitionImpl.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/DefinitionImpl.java index c7dc4f30e6a..6c692a6d019 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/DefinitionImpl.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/DefinitionImpl.java @@ -28,25 +28,25 @@ /** * Abstract definition in the schema. - * + * * This is supposed to be a superclass for all definitions. It defines common * properties for all definitions. - * + * * The definitions represent data structures of the schema. Therefore instances * of Java objects from this class represent specific definitions from * the schema, not specific properties or objects. E.g the definitions does not * have any value. - * + * * To transform definition to a real property or object use the explicit * instantiate() methods provided in the definition classes. E.g. the * instantiate() method will create instance of Property using appropriate * PropertyDefinition. - * + * * The convenience methods in Schema are using this abstract class to find * appropriate definitions easily. - * + * * @author Radovan Semancik - * + * */ public abstract class DefinitionImpl implements Definition { @@ -59,26 +59,26 @@ public abstract class DefinitionImpl implements Definition { protected String help; protected String documentation; protected boolean deprecated = false; - + /** * whether an item is inherited from a supertype (experimental feature) */ protected boolean inherited = false; - + /** * This means that the item container is not defined by fixed (compile-time) schema. * This in fact means that we need to use getAny in a JAXB types. It does not influence the * processing of DOM that much, as that does not really depend on compile-time/run-time distinction. */ protected boolean isRuntimeSchema; - + /** * Set true for definitions that are more important than others and that should be emphasized * during presentation. E.g. the emphasized definitions will always be displayed in the user * interfaces (even if they are empty), they will always be included in the dumps, etc. */ protected boolean emphasized = false; - + protected transient PrismContext prismContext; DefinitionImpl(@NotNull QName typeName, @NotNull PrismContext prismContext) { @@ -92,7 +92,7 @@ public abstract class DefinitionImpl implements Definition { public QName getTypeName() { return typeName; } - + public void setTypeName(@NotNull QName typeName) { this.typeName = typeName; } @@ -141,11 +141,11 @@ public void setEmphasized(boolean emphasized) { public String getDisplayName() { return displayName; } - - public void setDisplayName(String displayName) { + + public void setDisplayName(String displayName) { this.displayName = displayName; } - + @Override public Integer getDisplayOrder() { return displayOrder; @@ -159,7 +159,7 @@ public void setDisplayOrder(Integer displayOrder) { public String getHelp() { return help; } - + public void setHelp(String help) { this.help = help; } @@ -194,12 +194,12 @@ public boolean isRuntimeSchema() { public void setRuntimeSchema(boolean isRuntimeSchema) { this.isRuntimeSchema = isRuntimeSchema; } - + @Override public PrismContext getPrismContext() { return prismContext; } - + @Override public Class getTypeClassIfKnown() { return XsdTypeMapper.toJavaTypeIfKnown(getTypeName()); @@ -209,7 +209,7 @@ public Class getTypeClassIfKnown() { public Class getTypeClass() { return XsdTypeMapper.toJavaType(getTypeName()); } - + public abstract void revive(PrismContext prismContext); protected void copyDefinitionData(DefinitionImpl clone) { @@ -260,7 +260,7 @@ public boolean equals(Object obj) { public String toString() { return getDebugDumpClassName() + " ("+PrettyPrinter.prettyPrint(getTypeName())+")"; } - + @Override public String debugDump() { return debugDump(0); @@ -275,7 +275,7 @@ public String debugDump(int indent) { sb.append(toString()); return sb.toString(); } - + /** * Return a human readable name of this class suitable for logs. (e.g. "PPD") */ diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/DisplayableValueImpl.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/DisplayableValueImpl.java index 836c25ab6aa..4f354016a34 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/DisplayableValueImpl.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/DisplayableValueImpl.java @@ -20,11 +20,11 @@ import com.evolveum.midpoint.util.DisplayableValue; public class DisplayableValueImpl implements DisplayableValue, Serializable{ - + private T value; private String label; private String description; - + public DisplayableValueImpl(T value, String label, String description) { this.label = label; this.value = value; diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/ExpressionWrapper.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/ExpressionWrapper.java index 3f07207d4be..b1f8f05eced 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/ExpressionWrapper.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/ExpressionWrapper.java @@ -28,7 +28,7 @@ */ public class ExpressionWrapper implements Cloneable, Serializable { private static final long serialVersionUID = 1L; - + private QName elementName; private Object expression; @@ -45,7 +45,7 @@ public QName getElementName() { public Object getExpression() { return expression; } - + public ExpressionWrapper clone() { Object expressionClone = CloneUtil.clone(expression); return new ExpressionWrapper(elementName, expressionClone); @@ -55,6 +55,6 @@ public ExpressionWrapper clone() { public String toString() { return "ExpressionWrapper(" + PrettyPrinter.prettyPrint(elementName) + ":" + PrettyPrinter.prettyPrint(expression); } - - + + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/Item.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/Item.java index 2aa98ed2394..0fe6c53bc15 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/Item.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/Item.java @@ -35,7 +35,7 @@ /** * Item is a common abstraction of Property and PropertyContainer. - *

+ *

* This is supposed to be a superclass for all items. Items are things * that can appear in property containers, which generally means only a property * and property container itself. Therefore this is in fact superclass for those @@ -58,12 +58,12 @@ public abstract class Item imple protected boolean immutable; protected boolean incomplete; - + protected transient PrismContext prismContext; // beware, this one can easily be null /** * This is used for definition-less construction, e.g. in JAXB beans. - * + * * The constructors should be used only occasionally (if used at all). * Use the factory methods in the ResourceObjectDefintion instead. */ @@ -89,10 +89,10 @@ public abstract class Item imple this.definition = definition; this.prismContext = prismContext; } - + /** * Returns applicable property definition. - *

+ *

* May return null if no definition is applicable or the definition is not * know. * @@ -101,7 +101,7 @@ public abstract class Item imple public D getDefinition() { return definition; } - + public boolean hasCompleteDefinition() { return getDefinition() != null; } @@ -109,11 +109,11 @@ public boolean hasCompleteDefinition() { /** * Returns the name of the property. - *

+ *

* The name is a QName. It uniquely defines a property. - *

+ *

* The name may be null, but such a property will not work. - *

+ *

* The name is the QName of XML element in the XML representation. * * @return property name @@ -125,11 +125,11 @@ public QName getElementName() { /** * Sets the name of the property. - *

+ *

* The name is a QName. It uniquely defines a property. - *

+ *

* The name may be null, but such a property will not work. - *

+ *

* The name is the QName of XML element in the XML representation. * * @param elementName the name to set @@ -152,9 +152,9 @@ public void setDefinition(D definition) { /** * Returns a display name for the property type. - *

+ *

* Returns null if the display name cannot be determined. - *

+ *

* The display name is fetched from the definition. If no definition * (schema) is available, the display name will not be returned. * @@ -166,9 +166,9 @@ public String getDisplayName() { /** * Returns help message defined for the property type. - *

+ *

* Returns null if the help message cannot be determined. - *

+ *

* The help message is fetched from the definition. If no definition * (schema) is available, the help message will not be returned. * @@ -177,7 +177,7 @@ public String getDisplayName() { public String getHelp() { return getDefinition() == null ? null : getDefinition().getHelp(); } - + /** * Flag that indicates incomplete item. If set to true then the * values in this item are not complete. If this flag is true @@ -188,7 +188,7 @@ public String getHelp() { * account has a password, but the password value is not revealed. * This may indicate that a user has a photo, but the photo was not * requested and therefore is not returned. This may be used to indicate - * that only part of the attribute values were returned from the search. + * that only part of the attribute values were returned from the search. * And so on. */ public boolean isIncomplete() { @@ -214,7 +214,7 @@ public PrismContext getPrismContext() { public PrismContext getPrismContextLocal() { return prismContext; } - + public void setPrismContext(PrismContext prismContext) { this.prismContext = prismContext; } @@ -222,7 +222,7 @@ public void setPrismContext(PrismContext prismContext) { public PrismValue getParent() { return parent; } - + public void setParent(PrismValue parentValue) { if (this.parent != null && parentValue != null && this.parent != parentValue) { throw new IllegalStateException("Attempt to reset parent of item "+this+" from "+this.parent+" to "+parentValue); @@ -231,14 +231,14 @@ public void setParent(PrismValue parentValue) { // However, if existing parent itself is immutable, adding/removing its child item will cause the exception. this.parent = parentValue; } - + public ItemPath getPath() { if (parent == null) { return new ItemPath(getElementName()); } return parent.getPath().subPath(getElementName()); } - + public Map getUserData() { if (userData == null) { userData = new HashMap<>(); @@ -249,12 +249,12 @@ public Map getUserData() { return userData; } } - + public Object getUserData(String key) { // TODO make returned data immutable (?) return getUserData().get(key); } - + public void setUserData(String key, Object value) { checkMutability(); getUserData().put(key, value); @@ -264,30 +264,30 @@ public void setUserData(String key, Object value) { public List getValues() { return values; } - + public V getValue(int index) { if (index < 0) { index = values.size() + index; } return values.get(index); } - + public abstract X getRealValue(); - + public abstract Collection getRealValues(); - + public boolean hasValue(PrismValue value, boolean ignoreMetadata) { return (findValue(value, ignoreMetadata) != null); } - + public boolean hasValue(PrismValue value) { return hasValue(value, false); } - + public boolean hasRealValue(PrismValue value) { return hasValue(value, true); } - + public boolean isSingleValue() { // TODO what about dynamic definitions? See MID-3922 if (getDefinition() != null) { @@ -297,7 +297,7 @@ public boolean isSingleValue() { } return values.size() <= 1; } - + /** * Returns value that is equal or equivalent to the provided value. * The returned value is an instance stored in this item, while the @@ -311,7 +311,7 @@ public PrismValue findValue(PrismValue value, boolean ignoreMetadata) { } return null; } - + /** * Returns value that is previous to the specified value. * Note that the order is semantically insignificant and this is used only @@ -355,15 +355,15 @@ public Collection getClonedValues() { } return clonedValues; } - + public boolean contains(V value) { return contains(value, false); } - + public boolean containsEquivalentValue(V value) { return contains(value, true); } - + public boolean contains(V value, boolean ignoreMetadata, Comparator comparator) { if (comparator == null){ return contains(value, ignoreMetadata); @@ -375,10 +375,10 @@ public boolean contains(V value, boolean ignoreMetadata, Comparator comparato } } - + return false; } - + public boolean contains(V value, boolean ignoreMetadata) { for (V myValue: getValues()) { if (myValue.equals(value, ignoreMetadata)) { @@ -387,7 +387,7 @@ public boolean contains(V value, boolean ignoreMetadata) { } return false; } - + public boolean containsRealValue(V value) { for (V myValue: getValues()) { if (myValue.equalsRealValue(value)) { @@ -396,15 +396,15 @@ public boolean containsRealValue(V value) { } return false; } - + public boolean valuesExactMatch(Collection matchValues, Comparator comparator) { return MiscUtil.unorderedCollectionCompare(values, matchValues, comparator ); } - + public int size() { return values.size(); } - + public boolean addAll(Collection newValues) throws SchemaException { checkMutability(); // TODO consider weaker condition, like testing if there's a real change boolean changed = false; @@ -415,11 +415,11 @@ public boolean addAll(Collection newValues) throws SchemaException { } return changed; } - + public boolean add(@NotNull V newValue) throws SchemaException { return add(newValue, true); } - + public boolean add(@NotNull V newValue, boolean checkUniqueness) throws SchemaException { checkMutability(); if (newValue.getPrismContext() == null) { @@ -434,7 +434,7 @@ public boolean add(@NotNull V newValue, boolean checkUniqueness) throws SchemaEx } return values.add(newValue); } - + public boolean removeAll(Collection newValues) { checkMutability(); // TODO consider if there is real change boolean changed = false; @@ -462,7 +462,7 @@ public boolean remove(V newValue) { } return changed; } - + public V remove(int index) { checkMutability(); // TODO consider if there is real change return values.remove(index); @@ -480,19 +480,19 @@ public void replace(V newValue) { newValue.setParent(this); values.add(newValue); } - + public void clear() { checkMutability(); // TODO consider if there is real change values.clear(); } - + public void normalize() { checkMutability(); // TODO consider if there is real change for (V value : values) { value.normalize(); } } - + /** * Merge all the values of other item to this item. */ @@ -505,14 +505,14 @@ public void merge(Item otherItem) throws SchemaException { } public abstract Object find(ItemPath path); - + public abstract PartiallyResolvedItem findPartial(ItemPath path); - + // We want this method to be consistent with property diff public ItemDelta diff(Item other) { return diff(other, true, false); } - + // We want this method to be consistent with property diff public ItemDelta diff(Item other, boolean ignoreMetadata, boolean isLiteral) { List itemDeltas = new ArrayList<>(); @@ -525,8 +525,8 @@ public ItemDelta diff(Item other, boolean ignoreMetadata, boolean isLi } return itemDeltas.get(0); } - - protected void diffInternal(Item other, Collection deltas, + + protected void diffInternal(Item other, Collection deltas, boolean ignoreMetadata, boolean isLiteral) { ItemDelta delta = createDelta(); if (other == null) { @@ -547,7 +547,7 @@ protected void diffInternal(Item other, Collection del if (thisValue.representsSameValue(otherValue, true) || delta == null) { found = true; // Matching IDs, look inside to figure out internal deltas - thisValue.diffMatchingRepresentation(otherValue, deltas, + thisValue.diffMatchingRepresentation(otherValue, deltas, ignoreMetadata, isLiteral); // No need to process this value again iterator.remove(); @@ -580,7 +580,7 @@ protected void diffInternal(Item other, Collection del ((Collection)deltas).add(delta); } } - + protected ItemDelta fixupDelta(ItemDelta delta, Item other, boolean ignoreMetadata) { return delta; @@ -591,7 +591,7 @@ protected ItemDelta fixupDelta(ItemDelta delta, Item other, * represents (e.g. PropertyDelta, ContainerDelta, ...) */ public abstract ItemDelta createDelta(); - + public abstract ItemDelta createDelta(ItemPath path); @Override @@ -601,7 +601,7 @@ public void accept(Visitor visitor) { value.accept(visitor); } } - + @Override public void accept(Visitor visitor, ItemPath path, boolean recursive) { // This implementation is supposed to only work for non-hierarchical items, such as properties and references. @@ -612,7 +612,7 @@ public void accept(Visitor visitor, ItemPath path, boolean recursive) { visitor.visit(this); } } - + public void filterValues(Function function) { Iterator iterator = values.iterator(); while (iterator.hasNext()) { @@ -626,7 +626,7 @@ public void filterValues(Function function) { public void applyDefinition(D definition) throws SchemaException { applyDefinition(definition, true); } - + public void applyDefinition(D definition, boolean force) throws SchemaException { checkMutability(); // TODO consider if there is real change if (definition != null) { @@ -640,7 +640,7 @@ public void applyDefinition(D definition, boolean force) throws SchemaException pval.applyDefinition(definition, force); } } - + public void revive(PrismContext prismContext) throws SchemaException { // it is necessary to do e.g. PolyString recomputation even if PrismContext is set if (this.prismContext == null) { @@ -667,11 +667,11 @@ protected void copyValues(Item clone) { clone.incomplete = this.incomplete; // Also do not copy 'immutable' flag so the clone is free to be modified } - + protected void propagateDeepCloneDefinition(boolean ultraDeep, D clonedDefinition) { // nothing to do by default } - + public static Collection cloneCollection(Collection items) { Collection clones = new ArrayList(items.size()); for (T item: items) { @@ -679,7 +679,7 @@ public static Collection cloneCollection(Collection items } return clones; } - + /** * Sets all parents to null. This is good if the items are to be "transplanted" into a * different Containerable. @@ -690,7 +690,7 @@ public static Collection resetParentCollection(Collection } return items; } - + public static T createNewDefinitionlessItem(QName name, Class type, PrismContext prismContext) { T item = null; try { @@ -704,7 +704,7 @@ public static T createNewDefinitionlessItem(QName name, Class thisValue, List otherValues) { - return MiscUtil.unorderedCollectionEquals(thisValue, otherValues, + return MiscUtil.unorderedCollectionEquals(thisValue, otherValues, (o1, o2) -> { if (o1 instanceof PrismValue && o2 instanceof PrismValue) { PrismValue v1 = (PrismValue)o1; @@ -854,9 +854,9 @@ private boolean equalsRealValues(List thisValue, List otherValues) { } }); } - + private boolean match(List thisValue, List otherValues) { - return MiscUtil.unorderedCollectionEquals(thisValue, otherValues, + return MiscUtil.unorderedCollectionEquals(thisValue, otherValues, (o1, o2) -> { if (o1 instanceof PrismValue && o2 instanceof PrismValue) { PrismValue v1 = (PrismValue)o1; @@ -898,7 +898,7 @@ public boolean equals(Object obj) { return false; return true; } - + public boolean match(Object obj) { if (this == obj) return true; @@ -928,7 +928,7 @@ public boolean match(Object obj) { return false; return true; } - + /** * Returns true if this item is metadata item that should be ignored * for metadata-insensitive comparisons and hashCode functions. @@ -936,7 +936,7 @@ public boolean match(Object obj) { public boolean isMetadata() { D def = getDefinition(); if (def != null) { - return def.isOperational(); + return def.isOperational(); } else { return false; } @@ -969,7 +969,7 @@ protected void appendDebugDumpSuffix(StringBuilder sb) { sb.append(" (incomplete)"); } } - + public boolean isImmutable() { return immutable; } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/ItemDefinition.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/ItemDefinition.java index 8e597ca79a6..1689dbe61dc 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/ItemDefinition.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/ItemDefinition.java @@ -67,10 +67,10 @@ public interface ItemDefinition extends Definition { * Returns true if this item can be read (displayed). * In case of containers this means that the container itself can be read, e.g. that the container * label or block should be displayed. This usually happens if the container contains at least one - * readable item. + * readable item. * This does NOT mean that also all the container items can be displayed. The sub-item permissions * are controlled by similar properties on the items. This property only applies to the container - * itself: the "shell" of the container. + * itself: the "shell" of the container. */ boolean canRead(); @@ -78,7 +78,7 @@ public interface ItemDefinition extends Definition { * Returns true if this item can be modified (updated). * In case of containers this means that the container itself should be displayed in modification forms * E.g. that the container label or block should be displayed. This usually happens if the container - * contains at least one modifiable item. + * contains at least one modifiable item. * This does NOT mean that also all the container items can be modified. The sub-item permissions * are controlled by similar properties on the items. This property only applies to the container * itself: the "shell" of the container. @@ -89,7 +89,7 @@ public interface ItemDefinition extends Definition { * Returns true if this item can be added: it can be part of an object that is created. * In case of containers this means that the container itself should be displayed in creation forms * E.g. that the container label or block should be displayed. This usually happens if the container - * contains at least one createable item. + * contains at least one createable item. * This does NOT mean that also all the container items can be created. The sub-item permissions * are controlled by similar properties on the items. This property only applies to the container * itself: the "shell" of the container. @@ -97,8 +97,8 @@ public interface ItemDefinition extends Definition { boolean canAdd(); /** - * Returns the name of an element this one can be substituted for (e.g. c:user -> c:object, - * s:pipeline -> s:expression, etc). EXPERIMENTAL + * Returns the name of an element this one can be substituted for (e.g. c:user -> c:object, + * s:pipeline -> s:expression, etc). EXPERIMENTAL */ QName getSubstitutionHead(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/ItemDefinitionImpl.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/ItemDefinitionImpl.java index 1c904606cb1..ea2525074ec 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/ItemDefinitionImpl.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/ItemDefinitionImpl.java @@ -30,27 +30,27 @@ /** * Abstract item definition in the schema. - * + * * This is supposed to be a superclass for all item definitions. Items are things * that can appear in property containers, which generally means only a property * and property container itself. Therefore this is in fact superclass for those * two definitions. - * + * * The definitions represent data structures of the schema. Therefore instances * of Java objects from this class represent specific definitions from * the schema, not specific properties or objects. E.g the definitions does not * have any value. - * + * * To transform definition to a real property or object use the explicit * instantiate() methods provided in the definition classes. E.g. the * instantiate() method will create instance of Property using appropriate * PropertyDefinition. - * + * * The convenience methods in Schema are using this abstract class to find * appropriate definitions easily. - * + * * @author Radovan Semancik - * + * */ public abstract class ItemDefinitionImpl extends DefinitionImpl implements ItemDefinition { @@ -73,7 +73,7 @@ public abstract class ItemDefinitionImpl extends DefinitionImpl /** * The constructors should be used only occasionally (if used at all). * Use the factory methods in the ResourceObjectDefintion instead. - * + * * @param name definition name (element Name) * @param typeName type name (XSD complex or simple type) */ @@ -84,17 +84,17 @@ public abstract class ItemDefinitionImpl extends DefinitionImpl /** * Returns name of the defined entity. - * + * * The name is a name of the entity instance if it is fixed by the schema. * E.g. it may be a name of the property in the container that cannot be * changed. - * + * * The name corresponds to the XML element name in the XML representation of * the schema. It does NOT correspond to a XSD type name. - * + * * Name is optional. If name is not set the null value is returned. If name is * not set the type is "abstract", does not correspond to the element. - * + * * @return the name name of the entity or null. */ @Override @@ -106,12 +106,12 @@ public QName getName() { public void setName(@NotNull QName name) { this.name = name; } - + @Override public String getNamespace() { return getName().getNamespaceURI(); } - + /** * Return the number of minimal value occurrences. * @@ -125,10 +125,10 @@ public int getMinOccurs() { public void setMinOccurs(int minOccurs) { this.minOccurs = minOccurs; } - + /** * Return the number of maximal value occurrences. - *

+ *

* Any negative number means "unbounded". * * @return the maxOccurs @@ -141,7 +141,7 @@ public int getMaxOccurs() { public void setMaxOccurs(int maxOccurs) { this.maxOccurs = maxOccurs; } - + /** * Returns true if property is single-valued. * @@ -197,11 +197,11 @@ public void setOperational(boolean operational) { public boolean isDynamic() { return dynamic; } - + public void setDynamic(boolean dynamic) { this.dynamic = dynamic; } - + /** * Returns true if the property can be read. I.e. if it is returned in objects * retrieved from "get", "search" and similar operations. @@ -271,7 +271,7 @@ public void setHeterogeneousListItem(boolean heterogeneousListItem) { /** * Reference to an object that directly or indirectly represents possible values for * this item. We do not define here what exactly the object has to be. It can be a lookup - * table, script that dynamically produces the values or anything similar. + * table, script that dynamically produces the values or anything similar. * The object must produce the values of the correct type for this item otherwise an * error occurs. */ @@ -295,7 +295,7 @@ public boolean isValidFor(@NotNull QName elementQName, @NotNull Class clone) { /** * Make a deep clone, cloning all the sub-items and definitions. - * - * @param ultraDeep if set to true then even the objects that were same instance in the original will be + * + * @param ultraDeep if set to true then even the objects that were same instance in the original will be * cloned as separate instances in the clone. - * + * */ @Override public ItemDefinition deepClone(boolean ultraDeep) { @@ -361,12 +361,12 @@ public ItemDefinition deepClone(boolean ultraDeep) { return deepClone(new HashMap<>()); } } - + @Override public ItemDefinition deepClone(Map ctdMap) { return clone(); } - + @Override public void revive(PrismContext prismContext) { if (this.prismContext != null) { @@ -374,7 +374,7 @@ public void revive(PrismContext prismContext) { } this.prismContext = prismContext; } - + @Override public int hashCode() { final int prime = 31; @@ -425,7 +425,7 @@ public String toString() { debugDumpShortToString(sb); return sb.toString(); } - + /** * Used in debugDumping items. Does not need to have name in it as item already has it. Does not need * to have class as that is just too much info that is almost anytime pretty obvious anyway. @@ -470,7 +470,7 @@ public String debugFlags() { } return sb.toString(); } - + protected void extendToString(StringBuilder sb) { sb.append(","); if (canRead()) { diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/Itemable.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/Itemable.java index e48e00474a3..26e1b16e94e 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/Itemable.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/Itemable.java @@ -21,23 +21,23 @@ /** * Interface for objects that behave like an item: they have a name and may have a definition. - * + * * Currently provides common abstraction on top of Item and ItemDelta, as both can hold values and * construct them in a similar way. * * Also used for ValueFilter, although semantics of e.g. getPath() is quite different in this case. - * + * * @author Radovan Semancik * */ public interface Itemable { - + QName getElementName(); - + ItemDefinition getDefinition(); - + PrismContext getPrismContext(); - + ItemPath getPath(); } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/LiteralEqualsStrategy.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/LiteralEqualsStrategy.java index 34665615c33..fc24bb69ca4 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/LiteralEqualsStrategy.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/LiteralEqualsStrategy.java @@ -37,7 +37,7 @@ * */ public class LiteralEqualsStrategy extends JAXBEqualsStrategy { - + public static EqualsStrategy INSTANCE = new LiteralEqualsStrategy(); @Override @@ -68,5 +68,5 @@ protected boolean equalsInternal(ObjectLocator leftLocator, return super.equalsInternal(leftLocator, rightLocator, lhs, rhs); } } - + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/Objectable.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/Objectable.java index e6bad33f520..e17825f48a8 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/Objectable.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/Objectable.java @@ -22,23 +22,23 @@ * */ public interface Objectable extends Containerable { - + String getOid(); - + void setOid(String oid); - + String getVersion(); - + void setVersion(String version); - + PolyStringType getName(); - + void setName(PolyStringType name); - + String getDescription(); - + void setDescription(String description); - + /** * Returns short string representing identity of this object. * It should container object type, OID and name. It should be presented @@ -46,7 +46,7 @@ public interface Objectable extends Containerable { * system administrator). */ String toDebugName(); - + /** * Returns short string identification of object type. It should be in a form * suitable for log messages. There is no requirement for the type name to be unique, @@ -57,10 +57,10 @@ public interface Objectable extends Containerable { String toDebugType(); PrismObject asPrismObject(); - + void setupContainer(PrismObject object); // public PrismObject asPrismObject(); -// +// // public void setupContainer(PrismObject object); } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PartiallyResolvedItem.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PartiallyResolvedItem.java index ad1388658c8..de1336ebef4 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PartiallyResolvedItem.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PartiallyResolvedItem.java @@ -22,10 +22,10 @@ * */ public class PartiallyResolvedItem { - + private Item item; private ItemPath residualPath; - + public PartiallyResolvedItem(Item item, ItemPath residualPath) { super(); this.item = item; diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PathVisitable.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PathVisitable.java index 86a3b2cd081..4b9993e55d1 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PathVisitable.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PathVisitable.java @@ -19,13 +19,13 @@ /** * Visits only objects that are on the specified path or below. - * + * * @author Radovan Semancik * */ @FunctionalInterface public interface PathVisitable { - + void accept(Visitor visitor, ItemPath path, boolean recursive); } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismConstants.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismConstants.java index 39e5276b22c..705a1c3619c 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismConstants.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismConstants.java @@ -34,10 +34,10 @@ public class PrismConstants { public static final String ATTRIBUTE_VERSION_LOCAL_NAME = "version"; public static final String ATTRIBUTE_REF_TYPE_LOCAL_NAME = "type"; public static final String ATTRIBUTE_RELATION_LOCAL_NAME = "relation"; - + public static final String ELEMENT_DESCRIPTION_LOCAL_NAME = "description"; public static final String ELEMENT_FILTER_LOCAL_NAME = "filter"; - + public static final String NS_PREFIX = "http://prism.evolveum.com/xml/ns/public/"; public static final String NS_ANNOTATION = NS_PREFIX + "annotation-3"; public static final String PREFIX_NS_ANNOTATION = "a"; @@ -45,10 +45,10 @@ public class PrismConstants { public static final String PREFIX_NS_TYPES = "t"; public static final String NS_QUERY = NS_PREFIX + "query-3"; public static final String PREFIX_NS_QUERY = "q"; - + public static final String NS_MATCHING_RULE = NS_PREFIX + "matching-rule-3"; public static final String PREFIX_NS_MATCHING = "mr"; - + public static final String NS_PREFIX_CRYPTO = NS_PREFIX + "crypto/"; public static final String NS_PREFIX_CRYPTO_ALGORITHM = NS_PREFIX_CRYPTO + "algorithm/"; public static final String NS_CRYPTO_ALGORITHM_PBKD = NS_PREFIX_CRYPTO_ALGORITHM + "pbkd-3"; @@ -64,7 +64,7 @@ public class PrismConstants { public static final QName A_TYPE = new QName(NS_ANNOTATION, "type"); public static final QName A_DISPLAY_NAME = new QName(NS_ANNOTATION, "displayName"); public static final QName A_DISPLAY_ORDER = new QName(NS_ANNOTATION, "displayOrder"); - public static final QName A_HELP = new QName(NS_ANNOTATION, "help"); + public static final QName A_HELP = new QName(NS_ANNOTATION, "help"); public static final QName A_ACCESS = new QName(NS_ANNOTATION, "access"); public static final String A_ACCESS_CREATE = "create"; public static final String A_ACCESS_UPDATE = "update"; @@ -86,14 +86,14 @@ public class PrismConstants { public static final QName SCHEMA_DOCUMENTATION = new QName(W3C_XML_SCHEMA_NS_URI, "documentation"); public static final QName SCHEMA_APP_INFO = new QName(W3C_XML_SCHEMA_NS_URI, "appinfo"); - + public static final QName A_MAX_OCCURS = new QName(NS_ANNOTATION, "maxOccurs"); public static final String MULTIPLICITY_UNBONUNDED = "unbounded"; - + public static final QName A_NAMESPACE = new QName(NS_ANNOTATION, "namespace"); public static final String A_NAMESPACE_PREFIX = "prefix"; public static final String A_NAMESPACE_URL = "url"; - + //Query constants public static final QName Q_OID = new QName(NS_QUERY, "oid"); public static final QName Q_TYPE = new QName(NS_QUERY, "type"); @@ -110,18 +110,18 @@ public class PrismConstants { public static final QName T_ID = new QName(NS_TYPES, T_ID_LOCAL_PART); // Misc - + public static final Class DEFAULT_VALUE_CLASS = String.class; - + public static final QName POLYSTRING_TYPE_QNAME = new QName(NS_TYPES, "PolyStringType"); public static final QName POLYSTRING_ELEMENT_ORIG_QNAME = new QName(NS_TYPES, "orig"); public static final QName POLYSTRING_ELEMENT_NORM_QNAME = new QName(NS_TYPES, "norm"); // a bit of hack: by this local name we know if a object is a reference (c:ObjectReferenceType) public static final String REFERENCE_TYPE_NAME = "ObjectReferenceType"; - + public static final boolean EQUALS_DEFAULT_IGNORE_METADATA = true; public static final boolean EQUALS_DEFAULT_IS_LITERAL = false; - + public static final String EXPRESSION_LOCAL_PART = "expression"; } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContainer.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContainer.java index 8f42ea5b00c..b566ef7c324 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContainer.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContainer.java @@ -94,7 +94,7 @@ public PrismContainer(QName name, Class compileTimeClass, PrismContext prismC protected PrismContainer(QName name, PrismContainerDefinition definition, PrismContext prismContext) { super(name, definition, prismContext); } - + public Class getCompileTimeClass() { if (this.compileTimeClass != null) { return compileTimeClass; @@ -104,7 +104,7 @@ public Class getCompileTimeClass() { } return null; } - + /** * Returns true if this object can represent specified compile-time class. * I.e. this object can be presented in the compile-time form that is an @@ -123,11 +123,11 @@ public Collection getRealValues() { for (PrismContainerValue value : getValues()) { realValues.add(value.asContainerable()); } - + return realValues; - + } - + @Override public C getRealValue() { if (getValue() == null) { @@ -135,7 +135,7 @@ public C getRealValue() { } return getValue().asContainerable(); } - + public PrismContainerValue getValue() { if (getValues().size() == 1) { return getValues().get(0); @@ -173,7 +173,7 @@ public PrismContainerValue getValue() { return pValue; } } - + public void setValue(@NotNull PrismContainerValue value) throws SchemaException { checkMutability(); if (getDefinition() != null) { @@ -205,7 +205,7 @@ public boolean add(@NotNull PrismContainerValue newValue, boolean checkUniquenes } return super.add(newValue, checkUniqueness); } - + @Override public PrismContainerValue getPreviousValue(PrismValue value) { return (PrismContainerValue) super.getPreviousValue(value); @@ -227,7 +227,7 @@ private boolean canAssumeSingleValue() { } } } - + public PrismContainerValue getValue(Long id) { for (PrismContainerValue pval: getValues()) { if ((id == null && pval.getId() == null) || @@ -237,13 +237,13 @@ public PrismContainerValue getValue(Long id) { } return null; } - + public void setPropertyRealValue(QName propertyName, Object realValue) throws SchemaException { checkMutability(); PrismProperty property = findOrCreateProperty(propertyName); property.setRealValue(realValue); } - + public T getPropertyRealValue(QName propertyName, Class type) { return getPropertyRealValue(new ItemPath(propertyName), type); } @@ -255,7 +255,7 @@ public T getPropertyRealValue(ItemPath propertyPath, Class type) { } return property.getRealValue(type); } - + /** * Convenience method. Works only on single-valued containers. */ @@ -263,7 +263,7 @@ public void add(Item item) throws SchemaException { checkMutability(); getValue().add(item); } - + public PrismContainerValue createNewValue() { checkMutability(); PrismContainerValue pValue = new PrismContainerValue<>(prismContext); @@ -279,17 +279,17 @@ public PrismContainerValue createNewValue() { } return pValue; } - + public void mergeValues(PrismContainer other) throws SchemaException { mergeValues(other.getValues()); } - + public void mergeValues(Collection> otherValues) throws SchemaException { for (PrismContainerValue otherValue : otherValues) { mergeValue(otherValue); } } - + public void mergeValue(PrismContainerValue otherValue) throws SchemaException { checkMutability(); Iterator> iterator = getValues().iterator(); @@ -324,10 +324,10 @@ public void trim() { } } } - + /** * Returns applicable property container definition. - *

+ *

* May return null if no definition is applicable or the definition is not * know. * @@ -359,7 +359,7 @@ public void setDefinition(PrismContainerDefinition definition) { } this.definition = definition; } - + @Override public void applyDefinition(PrismContainerDefinition definition) throws SchemaException { checkMutability(); @@ -378,7 +378,7 @@ public > I throw new SystemException("Internal Error: "+e.getMessage(),e); } } - + /** * Returns true if the object and all contained prisms have proper definition. */ @@ -394,13 +394,13 @@ public boolean hasCompleteDefinition() { } return true; } - + @Override public Object find(ItemPath path) { if (path == null || path.isEmpty()) { return this; } - + IdItemPathSegment idSegment = ItemPath.getFirstIdSegment(path); PrismContainerValue cval = findValue(idSegment); if (cval == null) { @@ -416,7 +416,7 @@ public PartiallyResolvedItem((Item) this, null); } - + IdItemPathSegment idSegment = ItemPath.getFirstIdSegment(path); PrismContainerValue cval = findValue(idSegment); if (cval == null) { @@ -435,11 +435,11 @@ public Item findItem(QN throw new SystemException("Internal Error: "+e.getMessage(),e); } } - + > I findCreateItem(QName itemQName, Class type, boolean create) throws SchemaException { return getValue().findCreateItem(itemQName, type, null, create); } - + public > I findItem(ItemPath path, Class type) { try { return findCreateItem(path, type, null, false); @@ -448,7 +448,7 @@ public > I throw new SystemException("Internal Error:(path="+path+",type="+type+"): "+e.getMessage(),e); } } - + public Item findItem(ItemPath path) { try { return findCreateItem(path, Item.class, null, false); @@ -457,7 +457,7 @@ public Item findItem(It throw new SystemException("Internal Error:(path="+path+"): "+e.getMessage(),e); } } - + public boolean containsItem(ItemPath itemPath, boolean acceptEmptyItem) throws SchemaException { if (itemPath == null || itemPath.isEmpty()) { throw new IllegalArgumentException("Empty path specified"); @@ -469,15 +469,15 @@ public boolean containsItem(ItemPath itemPath, boolean acceptEmptyItem) throws S return true; } } - + return false; } - + > I findCreateItem(ItemPath itemPath, Class type, ID itemDefinition, boolean create) throws SchemaException { if (itemPath == null || itemPath.isEmpty()) { throw new IllegalArgumentException("Empty path specified"); } - + IdItemPathSegment idSegment = ItemPath.getFirstIdSegment(itemPath); PrismContainerValue cval = findValue(idSegment); if (cval == null) { @@ -487,7 +487,7 @@ > I findCr ItemPath rest = ItemPath.pathRestStartingWithName(itemPath); return cval.findCreateItem(rest, type, itemDefinition, create); } - + public PrismContainerValue findValue(long id) { for (PrismContainerValue pval : getValues()) { if (id == pval.getId()) { @@ -522,7 +522,7 @@ private PrismContainerValue findValue(IdItemPathSegment idSegment) { public PrismContainer findContainer(ItemPath path) { return findItem(path, PrismContainer.class); } - + public PrismContainer findContainer(QName containerName) { return findItem(containerName, PrismContainer.class); } @@ -530,7 +530,7 @@ public PrismContainer findContainer(QName container public PrismProperty findProperty(ItemPath path) { return findItem(path, PrismProperty.class); } - + public PrismProperty findProperty(QName propertyQName) { return findItem(propertyQName, PrismProperty.class); } @@ -538,19 +538,19 @@ public PrismProperty findProperty(QName propertyQName) { public PrismReference findReference(ItemPath path) { return findItem(path, PrismReference.class); } - + public PrismReference findReference(QName referenceQName) { return findItem(referenceQName, PrismReference.class); } - + public PrismReference findReferenceByCompositeObjectElementName(QName elementName) { return getValue().findReferenceByCompositeObjectElementName(elementName); } - + public > I findOrCreateItem(ItemPath containerPath, Class type) throws SchemaException { return findCreateItem(containerPath, type, null, true); } - + // The "definition" parameter provides definition of item to create, in case that the container does not have // the definition (e.g. in case of "extension" containers) public > I findOrCreateItem(ItemPath containerPath, Class type, ID definition) throws SchemaException { @@ -562,19 +562,19 @@ public > I } return findCreateItem(containerPath, type, definition, true); } - + public PrismContainer findOrCreateContainer(ItemPath containerPath) throws SchemaException { return findCreateItem(containerPath, PrismContainer.class, null, true); } - + public PrismContainer findOrCreateContainer(QName containerName) throws SchemaException { return findCreateItem(containerName, PrismContainer.class, true); } - + public PrismProperty findOrCreateProperty(ItemPath propertyPath) throws SchemaException { return findCreateItem(propertyPath, PrismProperty.class, null, true); } - + public PrismProperty findOrCreateProperty(QName propertyName) throws SchemaException { return findCreateItem(propertyName, PrismProperty.class, true); } @@ -582,38 +582,38 @@ public PrismProperty findOrCreateProperty(QName propertyName) throws Sche public PrismReference findOrCreateReference(ItemPath propertyPath) throws SchemaException { return findCreateItem(propertyPath, PrismReference.class, null, true); } - + public PrismReference findOrCreateReference(QName propertyName) throws SchemaException { return findCreateItem(propertyName, PrismReference.class, true); } - + /** * Convenience method. Works only on single-valued containers. */ public void remove(Item item) { getValue().remove(item); } - + public void removeProperty(QName propertyQName) { removeItem(new ItemPath(propertyQName), PrismProperty.class); } - + public void removeProperty(ItemPath path) { removeItem(path, PrismProperty.class); } - + public void removeContainer(QName containerQName) { removeItem(new ItemPath(containerQName), PrismContainer.class); } - + public void removeContainer(ItemPath path) { removeItem(path, PrismContainer.class); } - + public void removeReference(QName referenceQName) { removeItem(new ItemPath(referenceQName), PrismReference.class); } - + public void removeReference(ItemPath path) { removeItem(path, PrismReference.class); } @@ -647,12 +647,12 @@ public > v // pval.addItemPathsToList(subpath, list); // } // } - + @Override public ContainerDelta createDelta() { return new ContainerDelta(getPath(), getDefinition(), getPrismContext()); } - + @Override public ContainerDelta createDelta(ItemPath path) { return new ContainerDelta(path, getDefinition(), getPrismContext()); @@ -666,14 +666,14 @@ public boolean isEmpty() { } return true; } - + @Override protected void checkDefinition(PrismContainerDefinition def) { if (def == null) { throw new IllegalArgumentException("Null definition cannot be applied to container "+this); } } - + @Override public void checkConsistenceInternal(Itemable rootItem, boolean requireDefinitions, boolean prohibitRaw, ConsistencyCheckScope scope) { @@ -710,19 +710,19 @@ public void assertDefinitions(boolean tolarateRaw, String sourceDescription) thr val.assertDefinitions(tolarateRaw, this.toString()+" in "+sourceDescription); } } - + public ContainerDelta diff(PrismContainer other) { return (ContainerDelta) super.diff(other); } - + public ContainerDelta diff(PrismContainer other, boolean ignoreMetadata, boolean isLiteral) { return (ContainerDelta) super.diff(other, true, false); } - + public List diffModifications(PrismContainer other) { return diffModifications(other, true, false); } - + public List diffModifications(PrismContainer other, boolean ignoreMetadata, boolean isLiteral) { List itemDeltas = new ArrayList<>(); diffInternal(other, itemDeltas, ignoreMetadata, isLiteral); @@ -748,14 +748,14 @@ protected void copyValues(PrismContainer clone) { } } } - + public PrismContainerDefinition deepCloneDefinition(boolean ultraDeep) { PrismContainerDefinition clonedDef = (PrismContainerDefinition) getDefinition().deepClone(ultraDeep); propagateDeepCloneDefinition(ultraDeep, clonedDef); setDefinition(clonedDef); return clonedDef; } - + @Override protected void propagateDeepCloneDefinition(boolean ultraDeep, PrismContainerDefinition clonedDef) { for(PrismContainerValue cval: getValues()) { @@ -771,7 +771,7 @@ public boolean containsEquivalentValue(PrismContainerValue value) { return super.contains(value, false); } } - + @Override public void accept(Visitor visitor, ItemPath path, boolean recursive) { if (path == null || path.isEmpty()) { diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContainerDefinition.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContainerDefinition.java index 7144999cfe7..5e8fd9f2f6d 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContainerDefinition.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContainerDefinition.java @@ -52,7 +52,7 @@ public interface PrismContainerDefinition extends ItemD PrismContainerDefinition clone(); PrismContainerDefinition cloneWithReplacedDefinition(QName itemName, ItemDefinition newDefinition); - + void replaceDefinition(QName itemName, ItemDefinition newDefinition); PrismContainerValue createValue(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContainerDefinitionImpl.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContainerDefinitionImpl.java index b1f019ee630..ef007b30fed 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContainerDefinitionImpl.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContainerDefinitionImpl.java @@ -40,7 +40,7 @@ /** * Definition of a property container. - *

+ *

* Property container groups properties into logical blocks. The reason for * grouping may be as simple as better understandability of data structure. But * the group usually means different meaning, source or structure of the data. @@ -48,13 +48,13 @@ * that are dynamic, not fixed by a static schema. Such grouping also naturally * translates to XML and helps to "quarantine" such properties to avoid Unique * Particle Attribute problems. - *

+ *

* Property Container contains a set of (potentially multi-valued) properties. * The order of properties is not significant, regardless of the fact that it * may be fixed in the XML representation. In the XML representation, each * element inside Property Container must be either Property or a Property * Container. - *

+ *

* This class represents schema definition for property container. See * {@link Definition} for more details. * @@ -109,13 +109,13 @@ public Class getCompileTimeClass() { if (complexTypeDefinition == null) { return null; } - return (Class) complexTypeDefinition.getCompileTimeClass(); + return (Class) complexTypeDefinition.getCompileTimeClass(); } public void setCompileTimeClass(Class compileTimeClass) { this.compileTimeClass = compileTimeClass; } - + protected String getSchemaNamespace() { return getName().getNamespaceURI(); } @@ -136,7 +136,7 @@ public boolean isAbstract() { } return complexTypeDefinition != null && complexTypeDefinition.isAbstract(); } - + @Override public void revive(PrismContext prismContext) { if (this.prismContext != null) { @@ -212,7 +212,7 @@ public ID findNamedItemDefinition(@NotNull QName fir } } } - + for (ItemDefinition def : getDefinitions()) { if (firstName.equals(def.getName())) { return (ID) def.findItemDefinition(rest, clazz); @@ -247,10 +247,10 @@ public ID findNamedItemDefinition(@NotNull QName fir /** * Returns set of property definitions. - *

+ *

* WARNING: This may return definitions from the associated complex type. * Therefore changing the returned set may influence also the complex type definition. - *

+ *

* The set contains all property definitions of all types that were parsed. * Order of definitions is insignificant. * @@ -268,10 +268,10 @@ public List getDefinitions() { /** * Returns set of property definitions. - *

+ *

* The set contains all property definitions of all types that were parsed. * Order of definitions is insignificant. - *

+ *

* The returned set is immutable! All changes may be lost. * * @return set of definitions @@ -324,7 +324,7 @@ protected void copyDefinitionData(PrismContainerDefinitionImpl clone) { clone.complexTypeDefinition = this.complexTypeDefinition; clone.compileTimeClass = this.compileTimeClass; } - + @Override public ItemDefinition deepClone(Map ctdMap) { PrismContainerDefinitionImpl clone = clone(); @@ -353,7 +353,7 @@ public void replaceDefinition(QName itemName, ItemDefinition newDefinition) { /** * Creates new instance of property definition and adds it to the container. - *

+ *

* This is the preferred method of creating a new definition. * * @param name name of the property (element name) @@ -365,7 +365,7 @@ public PrismPropertyDefinitionImpl createPropertyDefinition(QName name, QName ty addDefinition(propDef); return propDef; } - + private void addDefinition(ItemDefinition itemDef) { if (complexTypeDefinition == null) { throw new UnsupportedOperationException("Cannot add an item definition because there's no complex type definition"); @@ -378,7 +378,7 @@ private void addDefinition(ItemDefinition itemDef) { /** * Creates new instance of property definition and adds it to the container. - *

+ *

* This is the preferred method of creating a new definition. * * @param name name of the property (element name) @@ -407,7 +407,7 @@ public PrismPropertyDefinition createPropertyDefinition(QName name) { /** * Creates new instance of property definition and adds it to the container. - *

+ *

* This is the preferred method of creating a new definition. * * @param localName name of the property (element name) relative to the schema namespace @@ -421,7 +421,7 @@ public PrismPropertyDefinition createPropertyDefinition(String localName, QName /** * Creates new instance of property definition and adds it to the container. - *

+ *

* This is the preferred method of creating a new definition. * * @param localName name of the property (element name) relative to the schema namespace @@ -436,7 +436,7 @@ public PrismPropertyDefinition createPropertyDefinition(String localName, String /** * Creates new instance of property definition and adds it to the container. - *

+ *

* This is the preferred method of creating a new definition. * * @param localName name of the property (element name) relative to the schema namespace @@ -454,11 +454,11 @@ public PrismPropertyDefinition createPropertyDefinition(String localName, String propertyDefinition.setMaxOccurs(maxOccurs); return propertyDefinition; } - + public PrismContainerDefinition createContainerDefinition(QName name, QName typeName) { return createContainerDefinition(name, typeName, 1, 1); } - + public PrismContainerDefinition createContainerDefinition(QName name, QName typeName, int minOccurs, int maxOccurs) { PrismSchema typeSchema = prismContext.getSchemaRegistry().findSchemaByNamespace(typeName.getNamespaceURI()); @@ -471,7 +471,7 @@ public PrismContainerDefinition createContainerDefinition(QName name, QName type } return createContainerDefinition(name, typeDefinition, minOccurs, maxOccurs); } - + public PrismContainerDefinition createContainerDefinition(QName name, ComplexTypeDefinition complexTypeDefinition, int minOccurs, int maxOccurs) { PrismContainerDefinitionImpl def = new PrismContainerDefinitionImpl(name, complexTypeDefinition, prismContext); @@ -480,7 +480,7 @@ public PrismContainerDefinition createContainerDefinition(QName name, Complex addDefinition(def); return def; } - + @Override public PrismContainerValue createValue() { return new PrismContainerValue<>(prismContext); @@ -512,7 +512,7 @@ public String debugDump(int indent) { public boolean isEmpty() { return complexTypeDefinition.isEmpty(); } - + /** * Return a human readable name of this class suitable for logs. */ diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContainerValue.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContainerValue.java index 143f4fe78e8..cc128e14ada 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContainerValue.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContainerValue.java @@ -52,7 +52,7 @@ public class PrismContainerValue extends PrismValue imp // output in DOM and other ordering-sensitive representations protected List> items = null; private Long id; - + private C containerable = null; // Definition of this value. Usually it is the same as CTD declared in the parent container. @@ -110,15 +110,15 @@ public PrismContext getPrismContextLocal() { /** * Returns a set of items that the property container contains. The items may be properties or inner property containers. - *

+ *

* The set may be null. In case there are no properties an empty set is * returned. - *

+ *

* Returned set is mutable. Live object is returned. * * @return set of items that the property container contains. */ - + public List> getItems() { if (items == null) { return null; @@ -129,7 +129,7 @@ public List> getItems() { return items; } } - + public Item getNextItem(Item referenceItem) { if (items == null) { return null; @@ -165,13 +165,13 @@ public Item getPreviousItem(Item referenceItem) { throw new IllegalArgumentException("Item "+referenceItem+" is not part of "+this); } - + /** * Returns a set of properties that the property container contains. - *

+ *

* The set must not be null. In case there are no properties an empty set is * returned. - *

+ *

* Returned set is immutable! Any change to it will be ignored. * * @return set of properties that the property container contains. @@ -187,7 +187,7 @@ public Set> getProperties() { } return properties; } - + public Long getId() { return id; } @@ -196,7 +196,7 @@ public void setId(Long id) { checkMutability(); this.id = id; } - + @SuppressWarnings("unchecked") public PrismContainerable getParent() { Itemable parent = super.getParent(); @@ -209,7 +209,7 @@ public PrismContainerable getParent() { } return (PrismContainerable)parent; } - + @SuppressWarnings("unchecked") public PrismContainer getContainer() { Itemable parent = super.getParent(); @@ -222,7 +222,7 @@ public PrismContainer getContainer() { } return (PrismContainer)super.getParent(); } - + @NotNull public ItemPath getPath() { Itemable parent = getParent(); @@ -236,7 +236,7 @@ public ItemPath getPath() { return parentPath; } } - + // For compatibility with other PrismValue types public C getValue() { return asContainerable(); @@ -318,16 +318,16 @@ public Collection getPropertyNames() { } return names; } - + public boolean add(Item item) throws SchemaException { return add(item, true); } - + /** * Adds an item to a property container. * * @param item item to add. - * @throws SchemaException + * @throws SchemaException * @throws IllegalArgumentException an attempt to add value that already exists */ public boolean add(Item item, boolean checkUniqueness) throws SchemaException { @@ -371,7 +371,7 @@ public boolean merge(Item void addReplaceExisting } add(item); } - + public void remove(Item item) { Validate.notNull(item, "Item must not be null."); checkMutability(); @@ -421,7 +421,7 @@ public void remove(Item existingItem.setParent(null); } } - + public void removeAll() { checkMutability(); if (items == null){ @@ -463,7 +463,7 @@ public void addAllReplaceExisting(Collection> itemsToAdd) th } addAll(itemsToAdd); } - + public void replace(Item oldItem, Item newItem) throws SchemaException { remove(oldItem); add(newItem); @@ -475,7 +475,7 @@ public void clear() { items.clear(); } } - + public boolean contains(Item item) { return items != null && items.contains(item); } @@ -483,7 +483,7 @@ public boolean contains(Item item) { public boolean contains(QName itemName) { return findItem(itemName) != null; } - + public static boolean containsRealValue(Collection> cvalCollection, PrismContainerValue cval) { for (PrismContainerValue colVal: cvalCollection) { @@ -493,7 +493,7 @@ public static boolean containsRealValue(Collection PartiallyResolvedItem findPartial(ItemPath path) { if (path == null || path.isEmpty()) { @@ -535,14 +535,14 @@ public PartiallyResolvedItem PrismProperty findProperty(QName propertyQName) { return findItem(propertyQName, PrismProperty.class); } - + public PrismProperty findProperty(ItemPath propertyPath) { return (PrismProperty) findItem(propertyPath); } /** * Finds a specific property in the container by definition. - *

+ *

* Returns null if nothing is found. * * @param propertyDefinition property definition to find. @@ -554,15 +554,15 @@ public PrismProperty findProperty(PrismPropertyDefinition propertyDefi } return findProperty(propertyDefinition.getName()); } - + public PrismContainer findContainer(QName containerName) { return findItem(containerName, PrismContainer.class); } - + public PrismReference findReference(QName elementName) { return findItem(elementName, PrismReference.class); } - + public PrismReference findReferenceByCompositeObjectElementName(QName elementName) { if (items == null){ return null; @@ -580,7 +580,7 @@ public PrismReference findReferenceByCompositeObjectElementName(QName elementNam } return null; } - + public > I findItem(QName itemName, Class type) { try { return findCreateItem(itemName, type, null, false); @@ -589,7 +589,7 @@ public > throw new SystemException("Internal Error: "+e.getMessage(),e); } } - + public Item findItem(QName itemName) { try { return findCreateItem(itemName, Item.class, null, false); @@ -598,7 +598,7 @@ public Item findItem(QN throw new SystemException("Internal Error: "+e.getMessage(),e); } } - + public Item findItem(ItemPath itemPath) { try { return findCreateItem(itemPath, Item.class, null, false); @@ -607,7 +607,7 @@ public Item findItem(It throw new SystemException("Internal Error: "+e.getMessage(),e); } } - + @SuppressWarnings("unchecked") > I findCreateItem(QName itemName, Class type, ID itemDefinition, boolean create) throws SchemaException { Item item = findItemByQName(itemName); @@ -629,7 +629,7 @@ > I findC return null; } } - + public > I findItem(ItemDefinition itemDefinition, Class type) { if (itemDefinition == null) { throw new IllegalArgumentException("No item definition"); @@ -790,19 +790,19 @@ private > public PrismContainer findOrCreateContainer(QName containerName) throws SchemaException { return findCreateItem(containerName, PrismContainer.class, null, true); } - + public PrismReference findOrCreateReference(QName referenceName) throws SchemaException { return findCreateItem(referenceName, PrismReference.class, null, true); } - + public Item findOrCreateItem(QName containerName) throws SchemaException { return findCreateItem(containerName, Item.class, null, true); } - + public > I findOrCreateItem(QName containerName, Class type) throws SchemaException { return findCreateItem(containerName, type, null, true); } - + public > I findOrCreateItem(ItemPath path, Class type, ID definition) throws SchemaException { return findCreateItem(path, type, definition, true); } @@ -814,11 +814,11 @@ public PrismProperty findOrCreateProperty(QName propertyQName) throws Sch } return createProperty(propertyQName); } - + public PrismProperty findOrCreateProperty(ItemPath propertyPath) throws SchemaException { return findOrCreateItem(propertyPath, PrismProperty.class, null); } - + public PrismProperty findOrCreateProperty(PrismPropertyDefinition propertyDef) throws SchemaException { PrismProperty property = findItem(propertyDef.getName(), PrismProperty.class); if (property != null) { @@ -846,25 +846,25 @@ public PrismProperty createProperty(QName propertyName) throws SchemaExce add(property, false); return property; } - + public PrismProperty createProperty(PrismPropertyDefinition propertyDefinition) throws SchemaException { PrismProperty property = propertyDefinition.instantiate(); add(property); return property; } - + public void removeProperty(QName propertyName) { removeProperty(new ItemPath(propertyName)); } - + public void removeProperty(ItemPath propertyPath) { removeItem(propertyPath, PrismProperty.class); } - + public void removeContainer(QName containerName) { removeContainer(new ItemPath(containerName)); } - + public void removeContainer(ItemPath itemPath) { removeItem(itemPath, PrismContainer.class); } @@ -903,11 +903,11 @@ > void rem throw new IllegalArgumentException("Attempt to remove item "+subName+" from "+this+ " of type "+itemType+" while the existing item is of incompatible type "+item.getClass()); } - } + } } } } - + public void setPropertyRealValue(QName propertyName, Object realValue, PrismContext prismContext) throws SchemaException { checkMutability(); PrismProperty property = findOrCreateProperty(propertyName); @@ -916,7 +916,7 @@ public void setPropertyRealValue(QName propertyName, Object realValue, PrismCont property.setPrismContext(prismContext); } } - + public T getPropertyRealValue(QName propertyName, Class type) { PrismProperty property = findProperty(propertyName); if (property == null) { // when using sql repo, even non-existing properties do not have 'null' here @@ -924,12 +924,12 @@ public T getPropertyRealValue(QName propertyName, Class type) { } return property.getRealValue(type); } - + @Override public void recompute(PrismContext prismContext) { // Nothing to do. The subitems should be already recomputed as they are added to this container. } - + @Override public void accept(Visitor visitor) { super.accept(visitor); @@ -939,7 +939,7 @@ public void accept(Visitor visitor) { } } } - + @Override public void accept(Visitor visitor, ItemPath path, boolean recursive) { if (path == null || path.isEmpty()) { @@ -965,7 +965,7 @@ public void accept(Visitor visitor, ItemPath path, boolean recursive) { } } } - + public boolean hasCompleteDefinition() { if (items != null) { for (Item item : getItems()) { @@ -985,7 +985,7 @@ public boolean representsSameValue(PrismValue other, boolean lax) { return false; } } - + @SuppressWarnings("Duplicates") private boolean representsSameValue(PrismContainerValue other, boolean lax) { if (lax && getParent() != null) { @@ -1020,19 +1020,19 @@ void diffMatchingRepresentation(PrismValue otherValue, diffRepresentation((PrismContainerValue)otherValue, deltas, ignoreMetadata, isLiteral); } else { throw new IllegalStateException("Comparing incompatible values "+this+" - "+otherValue); - } + } } - + void diffRepresentation(PrismContainerValue otherValue, Collection deltas, boolean ignoreMetadata, boolean isLiteral) { diffItems(this, otherValue, deltas, ignoreMetadata, isLiteral); } - + @Override public boolean isRaw() { return false; } - + public boolean addRawElement(Object element) throws SchemaException { checkMutability(); PrismContainerDefinition definition = getDefinition(); @@ -1044,7 +1044,7 @@ public boolean addRawElement(Object element) throws SchemaException { return merge(subitem); } } - + public boolean deleteRawElement(Object element) throws SchemaException { checkMutability(); PrismContainerDefinition definition = getDefinition(); @@ -1057,7 +1057,7 @@ public boolean deleteRawElement(Object element) throws SchemaException { } } - + public boolean removeRawElement(Object element) { checkMutability(); throw new UnsupportedOperationException("Definition-less containers are not supported any more."); @@ -1067,15 +1067,15 @@ private Item parseRawEl JaxbDomHack jaxbDomHack = definition.getPrismContext().getJaxbDomHack(); return jaxbDomHack.parseRawElement(element, definition); } - + private PrismContainerValue parseRawElementsToNewValue(PrismContainerValue origCVal, PrismContainerValue definitionSource) throws SchemaException { throw new UnsupportedOperationException("Definition-less containers are not supported any more."); } - + @SuppressWarnings({ "rawtypes", "unchecked" }) void diffItems(PrismContainerValue thisValue, PrismContainerValue other, Collection deltas, boolean ignoreMetadata, boolean isLiteral) { - + if (thisValue.getItems() != null) { for (Item thisItem: thisValue.getItems()) { Item otherItem = other.findItem(thisItem.getElementName()); @@ -1093,7 +1093,7 @@ void diffItems(PrismContainerValue thisValue, PrismContainerValue other, thisItem.diffInternal(otherItem, deltas, ignoreMetadata, isLiteral); } } - + if (other.getItems() != null) { for (Item otherItem: other.getItems()) { Item thisItem = thisValue.findItem(otherItem.getElementName()); @@ -1119,8 +1119,8 @@ void diffItems(PrismContainerValue thisValue, PrismContainerValue other, } } } - } - + } + private boolean isOperationalOnly(Item item, ItemDefinition itemDef) { if (itemDef != null && itemDef.isOperational()) { return true; @@ -1227,7 +1227,7 @@ public void revive(PrismContext prismContext) throws SchemaException { } } } - + @Override public boolean isEmpty() { if (id != null) { @@ -1238,7 +1238,7 @@ public boolean isEmpty() { } return items.isEmpty(); } - + @Override public void normalize() { checkMutability(); @@ -1273,11 +1273,11 @@ public void checkConsistenceInternal(Itemable rootItem, boolean requireDefinitio } } } - + public void assertDefinitions(String sourceDescription) throws SchemaException { assertDefinitions(false, sourceDescription); } - + public void assertDefinitions(boolean tolerateRaw, String sourceDescription) throws SchemaException { if (getItems() == null){ return; @@ -1293,7 +1293,7 @@ public PrismContainerValue clone() { // TODO resolve also the definition? copyValues(clone); return clone; } - + protected void copyValues(PrismContainerValue clone) { super.copyValues(clone); clone.id = this.id; @@ -1325,7 +1325,7 @@ protected void deepCloneDefinition(boolean ultraDeep, PrismContainerDefinition> void deepCloneDefinitionItem(I item, boolean ultraDeep, PrismContainerDefinition clonedContainerDef) { PrismContainerDefinition oldContainerDef = getDefinition(); QName itemName = item.getElementName(); @@ -1340,7 +1340,7 @@ private > item.propagateDeepCloneDefinition(ultraDeep, clonedItemDef); // propagate to items in values item.setDefinition(clonedItemDef); // sets CTD in values only if null! } - + @Override public boolean equalsComplex(PrismValue other, boolean ignoreMetadata, boolean isLiteral) { if (other == null || !(other instanceof PrismContainerValue)) { @@ -1348,7 +1348,7 @@ public boolean equalsComplex(PrismValue other, boolean ignoreMetadata, boolean i } return equalsComplex((PrismContainerValue)other, ignoreMetadata, isLiteral); } - + public boolean equalsComplex(PrismContainerValue other, boolean ignoreMetadata, boolean isLiteral) { if (!super.equalsComplex(other, ignoreMetadata, isLiteral)) { return false; @@ -1368,12 +1368,12 @@ public boolean equalsComplex(PrismContainerValue other, boolean ignoreMetadat } return true; } - + boolean equalsItems(PrismContainerValue other, boolean ignoreMetadata, boolean isLiteral) { return equalsItems(this, other, ignoreMetadata, isLiteral); } - - boolean equalsItems(PrismContainerValue thisValue, PrismContainerValue other, + + boolean equalsItems(PrismContainerValue thisValue, PrismContainerValue other, boolean ignoreMetadata, boolean isLiteral) { Collection> deltas = new ArrayList>(); // The EMPTY_PATH is a lie. We don't really care if the returned deltas have correct path or not @@ -1385,7 +1385,7 @@ boolean equalsItems(PrismContainerValue thisValue, PrismContainerValue oth public boolean equivalent(PrismContainerValue other) { return equalsRealValue(other); } - + @Override public boolean equals(Object obj) { if (this == obj) @@ -1397,7 +1397,7 @@ public boolean equals(Object obj) { PrismContainerValue other = (PrismContainerValue) obj; return equalsComplex(other, false, false); } - + @Override public int hashCode() { final int prime = 31; @@ -1414,7 +1414,7 @@ public int hashCode() { } return result; } - + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContainerable.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContainerable.java index 00da6e2079b..fafe1671bb3 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContainerable.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContainerable.java @@ -20,7 +20,7 @@ * */ public interface PrismContainerable extends Itemable { - + @Override public PrismContainerDefinition getDefinition(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContext.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContext.java index 0da44d8d060..b104bce6fd4 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContext.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContext.java @@ -232,7 +232,6 @@ void adopt(PrismContainerValue O createKnownObjectable(@NotNull Class clazz); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContextImpl.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContextImpl.java index 0d752830fef..4dcd2774552 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContextImpl.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismContextImpl.java @@ -51,10 +51,10 @@ public class PrismContextImpl implements PrismContext { private static final Trace LOGGER = TraceManager.getTrace(PrismContextImpl.class); - + private static boolean allowSchemalessSerialization = true; private static boolean extraValidation = false; // TODO replace by something serious - + @NotNull private final SchemaRegistryImpl schemaRegistry; @NotNull private final LexicalProcessorRegistry lexicalProcessorRegistry; @NotNull private final PolyStringNormalizer defaultPolyStringNormalizer; // TODO make non-final when needed @@ -68,7 +68,7 @@ public class PrismContextImpl implements PrismContext { @Autowired // TODO is this really applied? private Protector defaultProtector; - + // We need to keep this because of deprecated methods and various hacks @NotNull private final JaxbDomHack jaxbDomHack; @@ -98,7 +98,7 @@ private PrismContextImpl(@NotNull SchemaRegistryImpl schemaRegistry) { public static PrismContextImpl create(@NotNull SchemaRegistryImpl schemaRegistry) { return new PrismContextImpl(schemaRegistry); } - + public static PrismContextImpl createEmptyContext(@NotNull SchemaRegistryImpl schemaRegistry) { return new PrismContextImpl(schemaRegistry); } @@ -207,7 +207,7 @@ private LexicalProcessor getParserNotNull(String language) { public Protector getDefaultProtector() { return defaultProtector; } - + public void setDefaultProtector(Protector defaultProtector) { this.defaultProtector = defaultProtector; } @@ -291,7 +291,7 @@ public void adopt(PrismContainer container, Class void adopt(PrismContainer container) throws SchemaException { adopt(container, container.getCompileTimeClass()); @@ -317,7 +317,7 @@ public void adopt(ObjectDelta delta) throws SchemaExce delta.revive(this); getSchemaRegistry().applyDefinition(delta, delta.getObjectTypeClass(), false); } - + @Override public void adopt(C containerable, Class type, ItemPath path) throws SchemaException { PrismContainerValue prismContainerValue = containerable.asPrismContainerValue(); @@ -330,7 +330,7 @@ public void adopt(PrismContainer prismContainerValue.revive(this); getSchemaRegistry().applyDefinition(prismContainerValue, type, path, false); } - + @Override public void adopt(PrismContainerValue prismContainerValue, QName typeName, ItemPath path) throws SchemaException { diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismObject.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismObject.java index 5de3f6c1fca..1f49d8ad312 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismObject.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismObject.java @@ -56,7 +56,7 @@ public class PrismObject extends PrismContainer { private static final long serialVersionUID = 7321429132391159949L; - + private static final String PROPERTY_NAME_LOCALPART = "name"; public PrismObject(QName name, Class compileTimeClass) { @@ -153,7 +153,7 @@ public PrismObjectDefinition getDefinition() { public O asObjectable() { return getValue().asObjectable(); } - + public PolyString getName() { PrismProperty nameProperty = getValue().findProperty(getNamePropertyElementName()); if (nameProperty == null) { @@ -165,11 +165,11 @@ public PolyString getName() { private QName getNamePropertyElementName() { return new QName(getElementName().getNamespaceURI(), PrismConstants.NAME_LOCAL_NAME); } - + public PrismContainer getExtension() { return (PrismContainer) getValue().findItem(getExtensionContainerElementName(), PrismContainer.class); } - + public I findExtensionItem(QName elementName) { PrismContainer extension = getExtension(); if (extension == null) { @@ -177,7 +177,7 @@ public I findExtensionItem(QName elementName) { } return (I) extension.findItem(elementName); } - + public void addExtensionItem(I item) throws SchemaException { PrismContainer extension = getExtension(); if (extension == null) { @@ -222,21 +222,21 @@ public PrismObject clone() { if (prismContext != null && prismContext.getMonitor() != null) { prismContext.getMonitor().beforeObjectClone(this); } - + PrismObject clone = new PrismObject(getElementName(), getDefinition(), prismContext); copyValues(clone); - + if (prismContext != null && prismContext.getMonitor() != null) { prismContext.getMonitor().afterObjectClone(this, clone); } - + return clone; } protected void copyValues(PrismObject clone) { super.copyValues(clone); } - + public PrismObjectDefinition deepCloneDefinition(boolean ultraDeep) { return (PrismObjectDefinition) super.deepCloneDefinition(ultraDeep); } @@ -269,14 +269,14 @@ public ObjectDelta createDelta(ChangeType changeType) { delta.setOid(getOid()); return delta; } - + public ObjectDelta createAddDelta() { ObjectDelta delta = createDelta(ChangeType.ADD); // TODO: clone? delta.setObjectToAdd(this); return delta; } - + public ObjectDelta createModifyDelta() { ObjectDelta delta = createDelta(ChangeType.MODIFY); delta.setOid(this.getOid()); @@ -303,7 +303,7 @@ public PrismValue getParent() { public ItemPath getPath() { return ItemPath.EMPTY_PATH; } - + @Override public boolean equals(Object obj) { if (prismContext != null && prismContext.getMonitor() != null) { @@ -311,7 +311,7 @@ public boolean equals(Object obj) { } return super.equals(obj); } - + /** * this method ignores some part of the object during comparison (e.g. source demarcation in values) * These methods compare the "meaningful" parts of the objects. @@ -328,12 +328,12 @@ public boolean equivalent(Object obj) { ObjectDelta delta = diff(other, true, false); return delta.isEmpty(); } - + @Override public String toString() { return toDebugName(); } - + /** * Returns short string representing identity of this object. * It should container object type, OID and name. It should be presented @@ -343,13 +343,13 @@ public String toString() { public String toDebugName() { return toDebugType()+":"+getOid()+"("+getNamePropertyStringValue()+")"; } - + private PrismProperty getNameProperty() { QName elementName = getElementName(); String myNamespace = elementName.getNamespaceURI(); return findProperty(new QName(myNamespace, PrismConstants.NAME_LOCAL_NAME)); } - + private String getNamePropertyStringValue() { PrismProperty nameProperty = getNameProperty(); if (nameProperty == null) { @@ -361,7 +361,7 @@ private String getNamePropertyStringValue() { } return realValue.getOrig(); } - + /** * Returns short string identification of object type. It should be in a form * suitable for log messages. There is no requirement for the type name to be unique, @@ -397,10 +397,10 @@ protected void appendDebugDumpSuffix(StringBuilder sb) { } sb.append(")"); } - + /** * Return display name intended for business users of midPoint - */ + */ public String getBusinessDisplayName() { return getNamePropertyStringValue(); } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismObjectDefinitionImpl.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismObjectDefinitionImpl.java index 3d30625a994..9270c9097a2 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismObjectDefinitionImpl.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismObjectDefinitionImpl.java @@ -23,19 +23,19 @@ /** * MidPoint Object Definition. - * + * * Objects are storable entities in midPoint. - * + * * This is mostly just a marker class to identify object boundaries in schema. - * + * * This class represents schema definition for objects. See {@link Definition} * for more details. - * + * * "Instance" class of this class is MidPointObject, not Object - to avoid * confusion with java.lang.Object. - * + * * @author Radovan Semancik - * + * */ public class PrismObjectDefinitionImpl extends PrismContainerDefinitionImpl implements PrismObjectDefinition { @@ -46,7 +46,7 @@ public PrismObjectDefinitionImpl(QName elementName, ComplexTypeDefinition comple // Object definition can only be top-level, hence null parent super(elementName, complexTypeDefinition, prismContext, compileTimeClass); } - + @Override @NotNull public PrismObject instantiate() throws SchemaException { @@ -55,7 +55,7 @@ public PrismObject instantiate() throws SchemaException { } return new PrismObject(getName(), this, prismContext); } - + @NotNull @Override public PrismObject instantiate(QName name) throws SchemaException { @@ -65,7 +65,7 @@ public PrismObject instantiate(QName name) throws SchemaException { name = addNamespaceIfApplicable(name); return new PrismObject<>(name, this, prismContext); } - + @NotNull @Override public PrismObjectDefinitionImpl clone() { @@ -73,7 +73,7 @@ public PrismObjectDefinitionImpl clone() { copyDefinitionData(clone); return clone; } - + @Override public PrismObjectDefinition deepClone(boolean ultraDeep) { return (PrismObjectDefinition) super.deepClone(ultraDeep); @@ -83,7 +83,7 @@ public PrismObjectDefinition deepClone(boolean ultraDeep) { public PrismObjectDefinition cloneWithReplacedDefinition(QName itemName, ItemDefinition newDefinition) { return (PrismObjectDefinition) super.cloneWithReplacedDefinition(itemName, newDefinition); } - + @Override public PrismContainerDefinition getExtensionDefinition() { return findContainerDefinition(getExtensionQName()); @@ -91,9 +91,9 @@ public PrismContainerDefinition getExtensionDefinition() { public void setExtensionDefinition(ComplexTypeDefinition extensionComplexTypeDefinition) { QName extensionQName = getExtensionQName(); - + PrismContainerDefinition oldExtensionDef = findContainerDefinition(extensionQName); - + PrismContainerDefinitionImpl newExtensionDef = new PrismContainerDefinitionImpl<>(extensionQName, extensionComplexTypeDefinition, prismContext); newExtensionDef.setRuntimeSchema(true); @@ -108,7 +108,7 @@ public void setExtensionDefinition(ComplexTypeDefinition extensionComplexTypeDef newExtensionDef.setHelp(oldExtensionDef.getHelp()); } } - + ComplexTypeDefinitionImpl newCtd = (ComplexTypeDefinitionImpl) this.complexTypeDefinition.clone(); newCtd.replaceDefinition(extensionQName, newExtensionDef); if (newCtd.getDisplayName() == null) { @@ -134,7 +134,7 @@ private QName getExtensionQName() { String namespace = getName().getNamespaceURI(); return new QName(namespace, PrismConstants.EXTENSION_LOCAL_NAME); } - + public I getExtensionItemDefinition(QName elementName) { PrismContainerDefinition extensionDefinition = getExtensionDefinition(); if (extensionDefinition == null) { @@ -152,5 +152,5 @@ protected String getDebugDumpClassName() { public String getDocClassName() { return "object"; } - + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismParser.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismParser.java index 5e6ff4f623b..e0d2a4222f9 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismParser.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismParser.java @@ -238,7 +238,7 @@ interface ObjectHandler { /** * Currently implemented for JSON/YAML only. For XML, use old Validator code. - * + * * @param handler * @throws SchemaException * @throws IOException diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismProperty.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismProperty.java index c9bd11779fc..a517f681389 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismProperty.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismProperty.java @@ -43,21 +43,21 @@ * Property is a specific characteristic of an object. It may be considered * object "attribute" or "field". For example User has fullName property that * contains string value of user's full name. - *

+ *

* Properties may be single-valued or multi-valued - *

+ *

* Properties may contain primitive types or complex types (defined by XSD * schema) - *

+ *

* Property values are unordered, implementation may change the order of values - *

+ *

* Duplicate values of properties should be silently removed by implementations, * but clients must be able tolerate presence of duplicate values. - *

+ *

* Operations that modify the objects work with the granularity of properties. * They add/remove/replace the values of properties, but do not "see" inside the * property. - *

+ *

* Property is mutable. * * @author Radovan Semancik @@ -84,7 +84,7 @@ protected PrismProperty(QName name, PrismPropertyDefinition definition, Prism /** * Returns applicable property definition. - *

+ *

* May return null if no definition is applicable or the definition is not * know. * @@ -137,11 +137,11 @@ public Collection getRealValues() { } return realValues; } - + /** * Type override, also for compatibility. */ - + public Collection getRealValues(Class type) { Collection realValues = new ArrayList(getValues().size()); for (PrismPropertyValue pValue: getValues()) { @@ -149,7 +149,7 @@ public Collection getRealValues(Class type) { } return realValues; } - + public T getAnyRealValue() { Collection values = getRealValues(); if (values.isEmpty()) { @@ -173,7 +173,7 @@ public T getRealValue() { } return getValue().getValue(); } - + /** * Type override, also for compatibility. */ @@ -267,12 +267,12 @@ public void addValue(PrismPropertyValue pValueToAdd) { pValueToAdd.recompute(); getValues().add(pValueToAdd); } - + public void addRealValue(T valueToAdd) { PrismPropertyValue pval = new PrismPropertyValue(valueToAdd); addValue(pval); } - + public boolean deleteValues(Collection> pValuesToDelete) { checkMutability(); boolean changed = false; @@ -323,7 +323,7 @@ public boolean hasRealValue(PrismPropertyValue value) { return false; } - + @Override public PrismPropertyValue getPreviousValue(PrismValue value) { return (PrismPropertyValue) super.getPreviousValue(value); @@ -350,17 +350,17 @@ public Class getValueClass() { // TODO: How to determine value class????? return PrismConstants.DEFAULT_VALUE_CLASS; } - + @Override public PropertyDelta createDelta() { return new PropertyDelta(getPath(), getDefinition(), prismContext); } - + @Override public PropertyDelta createDelta(ItemPath path) { return new PropertyDelta(path, getDefinition(), prismContext); } - + @Override public Object find(ItemPath path) { if (path == null || path.isEmpty()) { @@ -390,11 +390,11 @@ public PartiallyResolvedItem diff(PrismProperty other) { return (PropertyDelta) super.diff(other); } - + public PropertyDelta diff(PrismProperty other, boolean ignoreMetadata, boolean isLiteral) { return (PropertyDelta) super.diff(other, true, false); } - + public static PropertyDelta diff(PrismProperty a, PrismProperty b) { if (a == null) { if (b == null) { @@ -445,7 +445,7 @@ public boolean equals(Object obj) { return false; return true; } - + @Override protected ItemDelta fixupDelta(ItemDelta delta, Item otherItem, boolean ignoreMetadata) { @@ -466,9 +466,9 @@ protected ItemDelta fixupDelta(ItemDelta delta, Item otherItem, return super.fixupDelta(delta, otherItem, ignoreMetadata); } } - + public static boolean compareCollectionRealValues(Collection col1, Collection col2) { - return MiscUtil.unorderedCollectionEquals(col1, col2, + return MiscUtil.unorderedCollectionEquals(col1, col2, (p1, p2) -> { if (!p1.getElementName().equals(p2.getElementName())) { return false; @@ -494,13 +494,13 @@ public String debugDump(int indent) { sb.append(getDebugDumpClassName()).append(": "); } sb.append(DebugUtil.formatElementName(getElementName())).append(": "); - + boolean isMultivalue = true; PrismPropertyDefinition def = getDefinition(); if (def != null) { isMultivalue = def.isMultiValue(); } - + List> values = getValues(); if (values.isEmpty()) { sb.append("[]"); @@ -517,7 +517,7 @@ public String debugDump(int indent) { } } if (multiline) { - + for (PrismPropertyValue value: getValues()) { sb.append("\n"); if (value.isRaw()) { @@ -567,9 +567,9 @@ public String debugDump(int indent) { } } } - + appendDebugDumpSuffix(sb); - + if (def != null && DebugUtil.isDetailedDebugDump()) { sb.append(" def("); def.debugDumpShortToString(sb); @@ -580,7 +580,7 @@ public String debugDump(int indent) { } return sb.toString(); } - + private String formatRawValueForDump(Object rawElement) { if (rawElement == null) { return null; diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismPropertyDefinition.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismPropertyDefinition.java index 8672deb1bca..b69d8ced795 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismPropertyDefinition.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismPropertyDefinition.java @@ -35,7 +35,7 @@ public interface PrismPropertyDefinition extends ItemDefinition + *

* The returned type is either XSD simple type or complex type. It may not * be defined in the same schema (especially if it is standard XSD simple * type). @@ -70,7 +70,7 @@ default boolean isAnyType() { @NotNull @Override PrismPropertyDefinition clone(); - + @Override Class getTypeClass(); } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismPropertyDefinitionImpl.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismPropertyDefinitionImpl.java index 8f51e8eb472..8b0831cfaec 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismPropertyDefinitionImpl.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismPropertyDefinitionImpl.java @@ -27,28 +27,28 @@ /** * Property Definition. - *

+ *

* Property is a basic unit of information in midPoint. This class provides * definition of property type, multiplicity and so on. - *

+ *

* Property is a specific characteristic of an object. It may be considered * object "attribute" or "field". For example User has fullName property that * contains string value of user's full name. - *

+ *

* Properties may be single-valued or multi-valued - *

+ *

* Properties may contain primitive types or complex types (defined by XSD * schema) - *

+ *

* Property values are unordered, implementation may change the order of values - *

+ *

* Duplicate values of properties should be silently removed by implementations, * but clients must be able tolerate presence of duplicate values. - *

+ *

* Operations that modify the objects work with the granularity of properties. * They add/remove/replace the values of properties, but do not "see" inside the * property. - *

+ *

* This class represents schema definition for property. See {@link Definition} * for more details. * @@ -66,7 +66,7 @@ public class PrismPropertyDefinitionImpl extends ItemDefinitionImpl> allowedValues, T defaultValue) { super(elementName, typeName, prismContext); this.allowedValues = allowedValues; @@ -94,15 +94,15 @@ public QName getValueType() { } /** - * This is XSD annotation that specifies whether a property should + * This is XSD annotation that specifies whether a property should * be indexed in the storage. It can only apply to properties. It * has following meaning: - * + * * true: the property must be indexed. If the storage is not able to * index the value, it should indicate an error. - * + * * false: the property should not be indexed. - * + * * null: data store decides whether to index the property or * not. */ @@ -119,7 +119,7 @@ public void setIndexed(Boolean indexed) { * Returns matching rule name. Matching rules are algorithms that specify * how to compare, normalize and/or order the values. E.g. there are matching * rules for case insensitive string comparison, for LDAP DNs, etc. - * + * * @return matching rule name */ @Override @@ -175,7 +175,7 @@ protected void extendToString(StringBuilder sb) { sb.append(",AVals:").append(allowedValues.size()); } } - + @Override public int hashCode() { final int prime = 31; diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismPropertyValue.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismPropertyValue.java index d5790772973..717443a2030 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismPropertyValue.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismPropertyValue.java @@ -60,7 +60,7 @@ public class PrismPropertyValue extends PrismValue implements DebugDumpable, // We can't do anything smarter, as we don't have definition nor prism context. So we store the raw // elements here and process them later (e.g. during applyDefinition or getting a value with explicit type). private XNode rawElement; - + @Nullable private ExpressionWrapper expression; public PrismPropertyValue(T value) { @@ -181,7 +181,7 @@ public ExpressionWrapper getExpression() { public void setExpression(@Nullable ExpressionWrapper expression) { this.expression = expression; } - + @Override public void applyDefinition(ItemDefinition definition) throws SchemaException { PrismPropertyDefinition propertyDefinition = (PrismPropertyDefinition) definition; @@ -280,7 +280,7 @@ void checkValue() { if (value instanceof RawType) { return; } - + throw new IllegalArgumentException("Unsupported value "+value+" ("+valueClass+") in "+this); } @@ -402,8 +402,8 @@ private PrismPropertyValue parseRawElementToNewValue(PrismPropertyValue or " values in a raw parsing state (raw elements) with parsed value that has no definition"); } } - - private T parseRawElementToNewRealValue(PrismPropertyValue prismPropertyValue, PrismPropertyDefinition definition) + + private T parseRawElementToNewRealValue(PrismPropertyValue prismPropertyValue, PrismPropertyDefinition definition) throws SchemaException { PrismContext prismContext = definition.getPrismContext(); //noinspection UnnecessaryLocalVariable @@ -464,19 +464,19 @@ public boolean equalsComplex(PrismPropertyValue other, boolean ignoreMetadata return thisRealValue.equals(otherRealValue); } } else { - + if (thisRealValue instanceof Element && otherRealValue instanceof Element) { return DOMUtil.compareElement((Element)thisRealValue, (Element)otherRealValue, isLiteral); } - + if (thisRealValue instanceof SchemaDefinitionType && otherRealValue instanceof SchemaDefinitionType) { SchemaDefinitionType thisSchema = (SchemaDefinitionType) thisRealValue; return thisSchema.equals(otherRealValue, isLiteral); // return DOMUtil.compareElement((Element)thisRealValue, (Element)otherRealValue, isLiteral); } - + if (thisRealValue instanceof byte[] && otherRealValue instanceof byte[]) { return Arrays.equals((byte[]) thisRealValue, (byte[]) otherRealValue); } @@ -589,12 +589,12 @@ public String debugDump() { return toString(); } - + @Override public String debugDump(int indent) { return debugDump(indent, false); } - + public String debugDump(int indent, boolean detailedDump) { detailedDump = detailedDump || DebugUtil.isDetailedDebugDump(); StringBuilder sb = new StringBuilder(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismReference.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismReference.java index 1e6a89277f2..6d890ce24bf 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismReference.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismReference.java @@ -35,20 +35,20 @@ * used to represent association between objects. For example reference from * User object to Account objects that belong to the user. The reference is a * simple uni-directional link using an OID as an identifier. - * + * * This type should be used for all object references so the implementations can * detect them and automatically resolve them. - * + * * @author semancik - * + * */ public class PrismReference extends Item { private static final long serialVersionUID = 1872343401395762657L; - + public PrismReference(QName name) { super(name); } - + PrismReference(QName name, PrismReferenceDefinition definition, PrismContext prismContext) { super(name, definition, prismContext); } @@ -82,7 +82,7 @@ public PrismReferenceValue getValue() { } return getValues().iterator().next(); } - + private PrismReferenceValue getValue(String oid) { // We need to tolerate null OIDs here. Because of JAXB. for (PrismReferenceValue val: getValues()) { @@ -92,7 +92,7 @@ private PrismReferenceValue getValue(String oid) { } return null; } - + @Override public Referencable getRealValue() { if (getValue() == null) { @@ -100,7 +100,7 @@ public Referencable getRealValue() { } return getValue().asReferencable(); } - + @Override public Collection getRealValues() { if (getValues() == null) { @@ -113,12 +113,12 @@ public Collection getRealValues() { return realValues; } - + public boolean add(@NotNull PrismReferenceValue value) { value.setParent(this); return getValues().add(value); } - + public boolean merge(PrismReferenceValue value) { String newOid = value.getOid(); // We need to tolerate null OIDs here. Because of JAXB. @@ -126,7 +126,7 @@ public boolean merge(PrismReferenceValue value) { if (existingValue == null) { return add(value); } - + // if there is newValue containing object (instead of oid only) and also // old value containing object (instead of oid only) we need to compare // these two object if they are equals..this can avoid of bad resolving @@ -140,8 +140,8 @@ public boolean merge(PrismReferenceValue value) { if (value.getObject() != null) { existingValue.setObject(value.getObject()); return true; - } - + } + // in the case, if the existing value and new value are not equal, add // also another reference alhtrough one with the same oid exist. It is // needed for parent org refs, becasue there can exist more than one @@ -150,15 +150,15 @@ public boolean merge(PrismReferenceValue value) { if (!value.equalsComplex(existingValue, false, false)) { return add(value); } - + if (value.getTargetType() != null) { existingValue.setTargetType(value.getTargetType()); // return true; - } + } // No need to copy OID as OIDs match return true; } - + public String getOid() { return getValue().getOid(); @@ -167,7 +167,7 @@ public String getOid() { public PolyString getTargetName() { return getValue().getTargetName(); } - + public PrismReferenceValue findValueByOid(String oid) { for (PrismReferenceValue pval: getValues()) { if (oid.equals(pval.getOid())) { @@ -176,7 +176,7 @@ public PrismReferenceValue findValueByOid(String oid) { } return null; } - + @Override public Object find(ItemPath path) { if (path == null || path.isEmpty()) { @@ -189,8 +189,8 @@ public Object find(ItemPath path) { return value.find(path); } - - + + @Override public PartiallyResolvedItem findPartial(ItemPath path) { if (path == null || path.isEmpty()) { @@ -207,7 +207,7 @@ public PartiallyResolvedItem implements PrismReferenceDefinition { @@ -55,11 +55,11 @@ public PrismReferenceDefinitionImpl(QName elementName, QName typeName, PrismCont /** * Returns valid XSD object types whose may be the targets of the reference. - * + * * Corresponds to "targetType" XSD annotation. - * + * * Returns empty set if not specified. Must not return null. - * + * * @return set of target type names */ @Override @@ -79,7 +79,7 @@ public QName getCompositeObjectElementName() { public void setCompositeObjectElementName(QName compositeObjectElementName) { this.compositeObjectElementName = compositeObjectElementName; } - + @Override public boolean isComposite() { return isComposite; @@ -131,7 +131,7 @@ public PrismReference instantiate(QName name) { name = addNamespaceIfApplicable(name); return new PrismReference(name, this, prismContext); } - + @Override public ItemDelta createEmptyDelta(ItemPath path) { return new ReferenceDelta(path, this, prismContext); @@ -144,7 +144,7 @@ public PrismReferenceDefinition clone() { copyDefinitionData(clone); return clone; } - + protected void copyDefinitionData(PrismReferenceDefinitionImpl clone) { super.copyDefinitionData(clone); clone.targetTypeName = this.targetTypeName; diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismReferenceValue.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismReferenceValue.java index 02dee46b197..f4dd64d528b 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismReferenceValue.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismReferenceValue.java @@ -60,9 +60,9 @@ public class PrismReferenceValue extends PrismValue implements DebugDumpable, Se private SearchFilterType filter = null; private EvaluationTimeType resolutionTime; private PolyString targetName = null; - + private Referencable referencable; - + public PrismReferenceValue() { this(null,null,null); } @@ -70,7 +70,7 @@ public PrismReferenceValue() { public PrismReferenceValue(String oid) { this(oid, null, null); } - + public PrismReferenceValue(String oid, QName targetType) { this(oid, null, null); this.targetType = targetType; @@ -83,10 +83,10 @@ public PrismReferenceValue(String oid, OriginType type, Objectable source) { /** * OID of the object that this reference refers to (reference target). - * + * * May return null, but the reference is in that case incomplete and * unusable. - * + * * @return the target oid */ public String getOid() { @@ -103,15 +103,15 @@ public void setOid(String oid) { checkMutability(); this.oid = oid; } - + /** * Returns object that this reference points to. The object is supposed to be used * for caching and optimizations. Only oid and type of the object really matters for * the reference. - * + * * The object is transient. It will NOT be serialized. Therefore the client must * expect that the object can disappear when serialization boundary is crossed. - * The client must expect that the object is null. + * The client must expect that the object is null. */ public PrismObject getObject() { return object; @@ -125,9 +125,9 @@ public void setObject(PrismObject object) { /** * Returns XSD type of the object that this reference refers to. It may be * used in XPath expressions and similar filters. - * + * * May return null if the type name is not set. - * + * * @return the target type name */ public QName getTargetType() { @@ -177,7 +177,7 @@ public PolyString getTargetName() { } return null; } - + public void setTargetName(PolyString name) { checkMutability(); this.targetName = name; @@ -207,7 +207,7 @@ public Class getTargetTypeCompileTimeClass(PrismContext prismContext return objDef != null ? objDef.getCompileTimeClass() : null; } } - + public QName getRelation() { return relation; } @@ -253,7 +253,7 @@ public void setResolutionTime(EvaluationTimeType resolutionTime) { public PrismReferenceDefinition getDefinition() { return (PrismReferenceDefinition) super.getDefinition(); } - + @Override public boolean isRaw() { // Reference value cannot be raw @@ -376,7 +376,7 @@ public void checkConsistenceInternal(Itemable rootItem, boolean requireDefinitio public boolean isEmpty() { return oid == null && object == null && filter == null && relation == null && targetType == null; } - + /** * Returns a version of this value that is canonical, that means it has the minimal form. * E.g. it will have only OID and no object. @@ -467,7 +467,7 @@ public boolean equals(Object obj) { PrismReferenceValue other = (PrismReferenceValue) obj; return equalsComplex(other, false, false); } - + @Override public int hashCode() { final int prime = 31; @@ -483,7 +483,7 @@ public int hashCode() { } return result; } - + @Override public boolean representsSameValue(PrismValue other, boolean lax) { if (other instanceof PrismReferenceValue) { @@ -492,14 +492,14 @@ public boolean representsSameValue(PrismValue other, boolean lax) { return false; } } - + public boolean representsSameValue(PrismReferenceValue other) { if (this.getOid() != null && other.getOid() != null) { return this.getOid().equals(other.getOid()) && relationsEquivalent(this.getRelation(), other.getRelation(), false); } return false; } - + public static PrismReferenceValue createFromTarget(PrismObject refTarget) { PrismReferenceValue refVal = new PrismReferenceValue(refTarget.getOid()); refVal.setObject(refTarget); @@ -508,7 +508,7 @@ public static PrismReferenceValue createFromTarget(PrismObject refTarget) { } return refVal; } - + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -614,7 +614,7 @@ public static List asReferencables(@NotNull Collection asReferenceValues(@NotNull Collection referencables) { return referencables.stream().map(ref -> ref.asReferenceValue()).collect(Collectors.toList()); } - + @Override public String debugDump() { return toString(); @@ -624,7 +624,7 @@ public String debugDump() { public String debugDump(int indent) { return debugDump(indent, false); } - + public String debugDump(int indent, boolean expandObject) { StringBuilder sb = new StringBuilder(); DebugUtil.indentDebugDump(sb, indent); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismValue.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismValue.java index 2e0e3996391..1b911c9d58f 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismValue.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/PrismValue.java @@ -41,7 +41,7 @@ * */ public abstract class PrismValue implements IPrismValue { - + private OriginType originType; private Objectable originObject; private Itemable parent; @@ -56,7 +56,7 @@ public abstract class PrismValue implements IPrismValue { PrismValue(PrismContext prismContext) { this.prismContext = prismContext; } - + PrismValue(OriginType type, Objectable source) { this(null, type, source); } @@ -66,7 +66,7 @@ public abstract class PrismValue implements IPrismValue { this.originType = type; this.originObject = source; } - + PrismValue(PrismContext prismContext, OriginType type, Objectable source, Itemable parent) { this.prismContext = prismContext; this.originType = type; @@ -85,7 +85,7 @@ public void setOriginObject(Objectable source) { public void setOriginType(OriginType type) { this.originType = type; } - + @Override public OriginType getOriginType() { return originType; @@ -122,17 +122,17 @@ public void setParent(Itemable parent) { } this.parent = parent; } - + @NotNull @Override public ItemPath getPath() { Itemable parent = getParent(); if (parent == null) { - throw new IllegalStateException("No parent, cannot create value path for "+this); + throw new IllegalStateException("No parent, cannot create value path for "+this); } return parent.getPath(); } - + /** * Used when we are removing the value from the previous parent. * Or when we know that the previous parent will be discarded and we @@ -142,7 +142,7 @@ public ItemPath getPath() { public void clearParent() { parent = null; } - + public static void clearParent(List> values) { if (values == null) { return; @@ -151,7 +151,7 @@ public static void clearParent(List> values) { val.clearParent(); } } - + @Override public PrismContext getPrismContext() { if (prismContext != null) { @@ -163,7 +163,7 @@ public PrismContext getPrismContext() { } return null; } - + protected ItemDefinition getDefinition() { Itemable parent = getParent(); if (parent == null) { @@ -171,19 +171,19 @@ protected ItemDefinition getDefinition() { } return parent.getDefinition(); } - + @Override public void applyDefinition(ItemDefinition definition) throws SchemaException { checkMutability(); // TODO reconsider applyDefinition(definition, true); } - + @Override public void applyDefinition(ItemDefinition definition, boolean force) throws SchemaException { checkMutability(); // TODO reconsider // Do nothing by default } - + public void revive(PrismContext prismContext) throws SchemaException { if (this.prismContext == null) { this.prismContext = prismContext; @@ -192,7 +192,7 @@ public void revive(PrismContext prismContext) throws SchemaException { recompute(prismContext); } } - + /** * Recompute the value or otherwise "initialize" it before adding it to a prism tree. * This may as well do nothing if no recomputing or initialization is needed. @@ -206,7 +206,7 @@ public void recompute() { public void accept(Visitor visitor) { visitor.visit(this); } - + @Override public void accept(Visitor visitor, ItemPath path, boolean recursive) { // This implementation is supposed to only work for non-hierarchical values, such as properties and references. @@ -217,9 +217,9 @@ public void accept(Visitor visitor, ItemPath path, boolean recursive) { visitor.visit(this); } } - + public abstract void checkConsistenceInternal(Itemable rootItem, boolean requireDefinitions, boolean prohibitRaw, ConsistencyCheckScope scope); - + /** * Returns true if this and other value represent the same value. * E.g. if they have the same IDs, OIDs or it is otherwise know @@ -234,7 +234,7 @@ public void accept(Visitor visitor, ItemPath path, boolean recursive) { public boolean representsSameValue(PrismValue other, boolean lax) { return false; } - + public static boolean containsRealValue(Collection collection, V value) { if (collection == null) { return false; @@ -246,11 +246,11 @@ public static boolean containsRealValue(Collection col } return false; } - + public static boolean equalsRealValues(Collection collection1, Collection collection2) { return MiscUtil.unorderedCollectionEquals(collection1, collection2, (v1, v2) -> v1.equalsRealValue(v2)); } - + public static boolean containsAll(Collection thisSet, Collection otherSet, boolean ignoreMetadata, boolean isLiteral) { if (thisSet == null && otherSet == null) { return true; @@ -268,7 +268,7 @@ public static boolean containsAll(Collection thisSet, } return true; } - + public static boolean contains(Collection thisSet, V otherValue, boolean ignoreMetadata, boolean isLiteral) { for (V thisValue: thisSet) { if (thisValue.equalsComplex(otherValue, ignoreMetadata, isLiteral)) { @@ -292,7 +292,7 @@ public static Collection cloneValues(Collection val } public abstract PrismValue clone(); - + protected void copyValues(PrismValue clone) { clone.originType = this.originType; clone.originObject = this.originObject; @@ -315,7 +315,7 @@ public static Collection cloneCollection(Collection } return clones; } - + /** * Sets all parents to null. This is good if the items are to be "transplanted" into a * different Containerable. @@ -332,7 +332,7 @@ public int hashCode() { int result = 0; return result; } - + public boolean equalsComplex(PrismValue other, boolean ignoreMetadata, boolean isLiteral) { // parent is not considered at all. it is not relevant. // neither the immutable flag @@ -347,12 +347,12 @@ public boolean equalsComplex(PrismValue other, boolean ignoreMetadata, boolean i } return true; } - + @Override public boolean equals(PrismValue otherValue, boolean ignoreMetadata) { return equalsComplex(otherValue, ignoreMetadata, false); } - + public boolean equals(PrismValue thisValue, PrismValue otherValue) { if (thisValue == null && otherValue == null) { return true; @@ -362,11 +362,11 @@ public boolean equals(PrismValue thisValue, PrismValue otherValue) { } return thisValue.equalsComplex(otherValue, false, false); } - + public boolean equalsRealValue(PrismValue otherValue) { return equalsComplex(otherValue, true, false); } - + public boolean equalsRealValue(PrismValue thisValue, PrismValue otherValue) { if (thisValue == null && otherValue == null) { return true; @@ -376,7 +376,7 @@ public boolean equalsRealValue(PrismValue thisValue, PrismValue otherValue) { } return thisValue.equalsComplex(otherValue, true, false); } - + @Override public boolean equals(Object obj) { if (this == obj) @@ -388,19 +388,19 @@ public boolean equals(Object obj) { PrismValue other = (PrismValue) obj; return equalsComplex(other, false, false); } - + /** * Assumes matching representations. I.e. it assumes that both this and otherValue represent the same instance of item. - * E.g. the container with the same ID. + * E.g. the container with the same ID. */ @Override public Collection diff(PrismValue otherValue) { return diff(otherValue, true, false); } - + /** * Assumes matching representations. I.e. it assumes that both this and otherValue represent the same instance of item. - * E.g. the container with the same ID. + * E.g. the container with the same ID. */ @Override public Collection diff(PrismValue otherValue, boolean ignoreMetadata, boolean isLiteral) { @@ -408,7 +408,7 @@ public Collection diff(PrismValue otherValue, boolean ignor diffMatchingRepresentation(otherValue, itemDeltas, ignoreMetadata, isLiteral); return itemDeltas; } - + void diffMatchingRepresentation(PrismValue otherValue, Collection deltas, boolean ignoreMetadata, boolean isLiteral) { // Nothing to do by default diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/Recomputable.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/Recomputable.java index 08f28f6efd5..f2231cc442a 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/Recomputable.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/Recomputable.java @@ -20,11 +20,11 @@ * */ public interface Recomputable { - + // TODO recompute method - + boolean equalsOriginalValue(Recomputable other); - + /** * @throws IllegalStateException */ diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/Referencable.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/Referencable.java index 0f584307ca2..b58b6ed3d2b 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/Referencable.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/Referencable.java @@ -30,7 +30,7 @@ public interface Referencable { PrismReferenceValue asReferenceValue(); - + void setupReferenceValue(PrismReferenceValue value); String getOid(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/Revivable.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/Revivable.java index 82c82d3f49a..d05cebe7bef 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/Revivable.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/Revivable.java @@ -25,5 +25,5 @@ public interface Revivable { void revive(PrismContext prismContext) throws SchemaException; - + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/SerializationOptions.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/SerializationOptions.java index 7c694177fc6..c4f7b66aa73 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/SerializationOptions.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/SerializationOptions.java @@ -35,7 +35,7 @@ public boolean isSerializeReferenceNames() { public void setSerializeReferenceNames(boolean serializeReferenceNames) { this.serializeReferenceNames = serializeReferenceNames; } - + public static SerializationOptions createSerializeReferenceNames(){ SerializationOptions serializationOptions = new SerializationOptions(); serializationOptions.setSerializeReferenceNames(true); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/SimpleVisitor.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/SimpleVisitor.java index 5fc91743d74..88c9877324f 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/SimpleVisitor.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/SimpleVisitor.java @@ -21,7 +21,7 @@ */ @FunctionalInterface public interface SimpleVisitor { - + void visit(T element); } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/Structured.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/Structured.java index 32a709649d3..ab7fbbdc738 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/Structured.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/Structured.java @@ -23,7 +23,7 @@ */ @FunctionalInterface public interface Structured { - + Object resolve(ItemPath subpath); } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/Visitable.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/Visitable.java index 95d5bec438a..7ecbb994afb 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/Visitable.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/Visitable.java @@ -21,7 +21,7 @@ */ @FunctionalInterface public interface Visitable { - + void accept(Visitor visitor); } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/Visitor.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/Visitor.java index b215788ae96..6950106bcc2 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/Visitor.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/Visitor.java @@ -21,7 +21,7 @@ */ @FunctionalInterface public interface Visitor { - + void visit(Visitable visitable); } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/crypto/BaseProtector.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/crypto/BaseProtector.java index eda7b5f1f11..a894910263a 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/crypto/BaseProtector.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/crypto/BaseProtector.java @@ -68,5 +68,5 @@ public boolean isEncrypted(ProtectedStringType ps) { Validate.notNull(ps, "Protected string must not be null."); return ps.isEncrypted(); } - + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/crypto/ProtectedData.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/crypto/ProtectedData.java index c2de3b4e22e..87505985dea 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/crypto/ProtectedData.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/crypto/ProtectedData.java @@ -23,30 +23,30 @@ * */ public interface ProtectedData { - + byte[] getClearBytes(); - + void setClearBytes(byte[] bytes); - + T getClearValue(); - + void setClearValue(T data); - + void destroyCleartext(); - + boolean canGetCleartext(); EncryptedDataType getEncryptedDataType(); void setEncryptedData(EncryptedDataType encryptedDataType); - + boolean isEncrypted(); - + HashedDataType getHashedDataType(); - + void setHashedData(HashedDataType hashedDataType); - + boolean isHashed(); - + boolean canSupportType(Class type); } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/crypto/ProtectorImpl.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/crypto/ProtectorImpl.java index 03ec844fb6c..4712e99bf45 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/crypto/ProtectorImpl.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/crypto/ProtectorImpl.java @@ -77,33 +77,33 @@ * @author lazyman */ public class ProtectorImpl extends BaseProtector { - + private static final String ALGORITHM_PKKDF2_NAME = "PBKDF2WithHmacSHA512"; private static final QName ALGORITH_PBKDF2_WITH_HMAC_SHA512_QNAME = new QName(PrismConstants.NS_CRYPTO_ALGORITHM_PBKD, ALGORITHM_PKKDF2_NAME); private static final String ALGORITH_PBKDF2_WITH_HMAC_SHA512_URI = QNameUtil.qNameToUri(ALGORITH_PBKDF2_WITH_HMAC_SHA512_QNAME); - + private static final String KEY_DIGEST_TYPE = "SHA1"; private static final String DEFAULT_ENCRYPTION_ALGORITHM = XMLCipher.AES_128; private static final char[] KEY_PASSWORD = "midpoint".toCharArray(); - + private static final String DEFAULT_DIGEST_ALGORITHM = ALGORITH_PBKDF2_WITH_HMAC_SHA512_URI; // "http://www.w3.org/2009/xmlenc11#pbkdf2" - + private Random randomNumberGenerator; - + private static final Trace LOGGER = TraceManager.getTrace(ProtectorImpl.class); private String keyStorePath; private String keyStorePassword; private String encryptionKeyAlias = "default"; - + private String requestedJceProviderName = null; private String encryptionAlgorithm; private String digestAlgorithm; - + private List trustManagers; private static final KeyStore keyStore; - + static { try { keyStore = KeyStore.getInstance("jceks"); @@ -111,7 +111,7 @@ public class ProtectorImpl extends BaseProtector { throw new SystemException(ex.getMessage(), ex); } } - + /** * @throws SystemException if jceks keystore is not available on {@link ProtectorImpl#getKeyStorePath} */ @@ -159,16 +159,16 @@ public void init() { for (TrustManager trustManager : tmFactory.getTrustManagers()) { trustManagers.add(trustManager); } - + //init apache crypto library Init.init(); - + } catch (Exception ex) { LOGGER.error("Unable to work with keystore {}, reason {}.", new Object[]{getKeyStorePath(), ex.getMessage()}, ex); throw new SystemException(ex.getMessage(), ex); } - + randomNumberGenerator = new SecureRandom(); } @@ -187,7 +187,7 @@ public String getEncryptionAlgorithm() { public void setEncryptionAlgorithm(String encryptionAlgorithm) { this.encryptionAlgorithm = encryptionAlgorithm; } - + private String getCipherAlgorithm() { if (encryptionAlgorithm != null) { return encryptionAlgorithm; @@ -195,7 +195,7 @@ private String getCipherAlgorithm() { return DEFAULT_ENCRYPTION_ALGORITHM; } } - + private String getDigestAlgorithm() { if (digestAlgorithm != null) { return digestAlgorithm; @@ -203,9 +203,9 @@ private String getDigestAlgorithm() { return DEFAULT_DIGEST_ALGORITHM; } } - + // TODO: make it configurable - + private int getPbkdKeyLength() { return 256; } @@ -217,7 +217,7 @@ private int getPbkdIterations() { private int getPbkdSaltLength() { return 32; } - + /** * @return the encryptionKeyAlias * @throws IllegalStateException if encryption key digest is null or empty string @@ -228,7 +228,7 @@ private String getEncryptionKeyAlias() { } return encryptionKeyAlias; } - + @Override protected byte[] decryptBytes(ProtectedData protectedData) throws SchemaException, EncryptionException { EncryptedDataType encryptedDataType = protectedData.getEncryptedDataType(); @@ -279,9 +279,9 @@ public void encrypt(ProtectedData protectedData) throws EncryptionExcepti } SecretKey key = getSecretKeyByAlias(getEncryptionKeyAlias()); String algorithm = getCipherAlgorithm(); - + byte[] clearBytes = protectedData.getClearBytes(); - + byte[] encryptedBytes; try { encryptedBytes = encryptBytes(clearBytes, algorithm, key); @@ -289,22 +289,22 @@ public void encrypt(ProtectedData protectedData) throws EncryptionExcepti | NoSuchProviderException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException e) { throw new EncryptionException(e.getMessage(), e); } - + // Construct encryption types EncryptedDataType encryptedDataType = new EncryptedDataType(); - + EncryptionMethodType encryptionMethodType = new EncryptionMethodType(); encryptionMethodType.setAlgorithm(algorithm); encryptedDataType.setEncryptionMethod(encryptionMethodType); - + KeyInfoType keyInfoType = new KeyInfoType(); keyInfoType.setKeyName(getSecretKeyDigest(key)); encryptedDataType.setKeyInfo(keyInfoType); - + CipherDataType cipherDataType = new CipherDataType(); cipherDataType.setCipherValue(encryptedBytes); encryptedDataType.setCipherData(cipherDataType); - + protectedData.setEncryptedData(encryptedDataType); protectedData.destroyCleartext(); } @@ -312,34 +312,34 @@ public void encrypt(ProtectedData protectedData) throws EncryptionExcepti private byte[] encryptBytes(byte[] clearData, String algorithmUri, Key key) throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { Cipher cipher = getCipher(Cipher.ENCRYPT_MODE, algorithmUri); cipher.init(Cipher.ENCRYPT_MODE, key); - + byte[] encryptedData = cipher.doFinal(clearData); - + // Place IV at the beginning of the encrypted bytes so it can be reused on decryption byte[] iv = cipher.getIV(); byte[] encryptedBytes = new byte[iv.length + encryptedData.length]; System.arraycopy(iv, 0, encryptedBytes, 0, iv.length); System.arraycopy(encryptedData, 0, encryptedBytes, iv.length, encryptedData.length); - + return encryptedBytes; } - + private byte[] decryptBytes(byte[] encryptedBytes, String algorithmUri, Key key) throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { Cipher cipher = getCipher(Cipher.DECRYPT_MODE, algorithmUri); - + // Extract IV from the beginning of the encrypted bytes int ivLen = cipher.getBlockSize(); byte[] ivBytes = new byte[ivLen]; System.arraycopy(encryptedBytes, 0, ivBytes, 0, ivLen); IvParameterSpec iv = new IvParameterSpec(ivBytes); - + cipher.init(Cipher.DECRYPT_MODE, key, iv); - + byte[] decryptedData = cipher.doFinal(encryptedBytes, ivLen, encryptedBytes.length - ivLen); - + return decryptedData; } - + private Cipher getCipher(int cipherMode, String algorithmUri) throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException, InvalidKeyException, InvalidAlgorithmParameterException { String jceAlgorithm = JCEMapper.translateURItoJCEID(algorithmUri);//JCEMapper.getJCEKeyAlgorithmFromURI(algorithmUri); Cipher cipher; @@ -362,7 +362,7 @@ private Cipher getCipher(int cipherMode, String algorithmUri) throws NoSuchAlgor } return cipher; } - + public String getSecretKeyDigest(SecretKey key) throws EncryptionException { MessageDigest sha1; try { @@ -373,7 +373,7 @@ public String getSecretKeyDigest(SecretKey key) throws EncryptionException { return Base64.encode(sha1.digest(key.getEncoded())); } - + @Override public List getTrustManagers() { return trustManagers; @@ -425,7 +425,7 @@ public String getKeyStorePath() { } return keyStorePath; } - + private SecretKey getSecretKeyByAlias(String alias) throws EncryptionException { Key key; try { @@ -473,7 +473,7 @@ private SecretKey getSecretKeyByDigest(String digest) throws EncryptionException throw new EncryptionException("Key '" + digest + "' is not in keystore."); } - + @Override public void hash(ProtectedData protectedData) throws EncryptionException, SchemaException { if (protectedData.isHashed()) { @@ -485,7 +485,7 @@ public void hash(ProtectedData protectedData) throws EncryptionException, if (algorithmNamespace == null) { throw new SchemaException("No algorithm namespace"); } - + HashedDataType hashedDataType; switch (algorithmNamespace) { case PrismConstants.NS_CRYPTO_ALGORITHM_PBKD: @@ -497,18 +497,18 @@ public void hash(ProtectedData protectedData) throws EncryptionException, default: throw new SchemaException("Unkown namespace "+algorithmNamespace); } - + protectedData.setHashedData(hashedDataType); protectedData.destroyCleartext(); protectedData.setEncryptedData(null); } - - private HashedDataType hashPbkd(ProtectedData protectedData, String algorithmUri, String algorithmName) throws EncryptionException { - + + private HashedDataType hashPbkd(ProtectedData protectedData, String algorithmUri, String algorithmName) throws EncryptionException { + char[] clearChars = getClearChars(protectedData); byte[] salt = generatePbkdSalt(); int iterations = getPbkdIterations(); - + SecretKeyFactory secretKeyFactory; try { secretKeyFactory = SecretKeyFactory.getInstance( algorithmName ); @@ -525,15 +525,15 @@ private HashedDataType hashPbkd(ProtectedData protectedData, String algo byte[] hashBytes = key.getEncoded( ); HashedDataType hashedDataType = new HashedDataType(); - + DigestMethodType digestMethod = new DigestMethodType(); digestMethod.setAlgorithm(algorithmUri); digestMethod.setSalt(salt); digestMethod.setWorkFactor(iterations); hashedDataType.setDigestMethod(digestMethod); - + hashedDataType.setDigestValue(hashBytes); - + return hashedDataType; } @@ -565,7 +565,7 @@ public boolean compare(ProtectedStringType a, ProtectedStringType b) throws Encr if (a.isHashed() && b.isHashed()) { throw new SchemaException("Cannot compare two hased protected strings"); } - + if (a.isHashed() || b.isHashed()) { String clear; ProtectedStringType hashedPs; @@ -580,7 +580,7 @@ public boolean compare(ProtectedStringType a, ProtectedStringType b) throws Encr return false; } return compareHashed(hashedPs, clear.toCharArray()); - + } else { String aClear = decryptString(a); String bClear = decryptString(b); @@ -606,7 +606,7 @@ private boolean compareHashed(ProtectedStringType hashedPs, char[] clearChars) t if (algorithmNamespace == null) { throw new SchemaException("No algorithm namespace"); } - + switch (algorithmNamespace) { case PrismConstants.NS_CRYPTO_ALGORITHM_PBKD: return compareHashedPbkd(hashedDataType, algorithmQName.getLocalPart(), clearChars); @@ -621,7 +621,7 @@ private boolean compareHashedPbkd(HashedDataType hashedDataType, String algorith Integer workFactor = digestMethodType.getWorkFactor(); byte[] digestValue = hashedDataType.getDigestValue(); int keyLen = digestValue.length * 8; - + SecretKeyFactory secretKeyFactory; try { secretKeyFactory = SecretKeyFactory.getInstance( algorithmName ); @@ -636,10 +636,10 @@ private boolean compareHashedPbkd(HashedDataType hashedDataType, String algorith throw new EncryptionException(e.getMessage(), e); } byte[] hashBytes = key.getEncoded( ); - + return Arrays.equals(digestValue, hashBytes); } - - + + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ChangeType.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ChangeType.java index 9e0c2dff650..6c56bf731f4 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ChangeType.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ChangeType.java @@ -23,13 +23,13 @@ */ public enum ChangeType { ADD, MODIFY, DELETE; - + public static ChangeType toChangeType(ChangeTypeType changeType){ - + if (changeType == null){ return null; } - + switch (changeType){ case ADD : return ChangeType.ADD; case DELETE : return ChangeType.DELETE; diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ContainerDelta.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ContainerDelta.java index 2f6a488a7f5..0f91ab239cb 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ContainerDelta.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ContainerDelta.java @@ -70,12 +70,12 @@ public Collection> getValues(Cl } return (Collection) MiscUtil.union(valuesToAdd, valuesToDelete); } - + @Override public PrismContainerDefinition getDefinition() { return (PrismContainerDefinition) super.getDefinition(); } - + @Override public void setDefinition(PrismContainerDefinition definition) { if (!(definition instanceof PrismContainerDefinition)) { @@ -95,7 +95,7 @@ public void applyDefinition(PrismContainerDefinition definition) throws Schem } super.applyDefinition(definition); } - + @Override public boolean hasCompleteDefinition() { if (!super.hasCompleteDefinition()) { @@ -132,7 +132,7 @@ public Class getCompileTimeClass() { } return null; } - + @Override protected boolean isApplicableToType(Item item) { return item instanceof PrismContainer; @@ -162,7 +162,7 @@ public ItemDelta getSubDelta(ItemPath path) { } return itemDelta; } - + private Collection findItemValues(Long id, ItemPath path, Collection> cvalues) { if (cvalues == null) { return null; @@ -178,7 +178,7 @@ private Collection findItemValues(Long id, ItemPath path, Collection void expand(PrismObject object) throws SchemaEx } } } - + @Override protected boolean isValueEquivalent(PrismContainerValue a, PrismContainerValue b) { if (!super.isValueEquivalent(a, b)) { @@ -257,7 +257,7 @@ public ContainerDelta clone() { copyValues(clone); return clone; } - + protected void copyValues(ContainerDelta clone) { super.copyValues(clone); } @@ -266,18 +266,18 @@ public static ContainerDelta c Class type, PrismContext prismContext) { return createDelta(new ItemPath(containerName), type, prismContext); } - + public static ContainerDelta createDelta(ItemPath containerPath, Class type, PrismContext prismContext) { PrismObjectDefinition objectDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(type); return createDelta(containerPath, objectDefinition); } - + public static ContainerDelta createDelta(QName containerName, PrismObjectDefinition objectDefinition) { return createDelta(new ItemPath(containerName), objectDefinition); } - + public static ContainerDelta createDelta(ItemPath containerPath, PrismObjectDefinition objectDefinition) { PrismContainerDefinition containerDefinition = objectDefinition.findContainerDefinition(containerPath); @@ -298,18 +298,18 @@ public static ContainerDelta c Class type, PrismContext prismContext, T containerable) throws SchemaException { return createModificationAdd(new ItemPath(containerName), type, prismContext, containerable); } - - public static ContainerDelta createModificationAdd(ItemPath containerPath, + + public static ContainerDelta createModificationAdd(ItemPath containerPath, Class type, PrismContext prismContext, T containerable) throws SchemaException { return createModificationAdd(containerPath, type, prismContext, containerable.asPrismContainerValue()); } - - public static ContainerDelta createModificationAdd(QName containerName, + + public static ContainerDelta createModificationAdd(QName containerName, Class type, PrismContext prismContext, PrismContainerValue cValue) throws SchemaException { return createModificationAdd(new ItemPath(containerName), type, prismContext, cValue); } - - public static ContainerDelta createModificationAdd(ItemPath containerPath, + + public static ContainerDelta createModificationAdd(ItemPath containerPath, Class type, PrismContext prismContext, PrismContainerValue cValue) throws SchemaException { ContainerDelta delta = createDelta(containerPath, type, prismContext); prismContext.adopt(cValue, type, containerPath); @@ -317,22 +317,22 @@ public static ContainerDelta c return delta; } - public static ContainerDelta createModificationDelete(QName containerName, + public static ContainerDelta createModificationDelete(QName containerName, Class type, PrismContext prismContext, T containerable) throws SchemaException { return createModificationDelete(new ItemPath(containerName), type, prismContext, containerable); } - - public static ContainerDelta createModificationDelete(ItemPath containerPath, + + public static ContainerDelta createModificationDelete(ItemPath containerPath, Class type, PrismContext prismContext, T containerable) throws SchemaException { return createModificationDelete(containerPath, type, prismContext, containerable.asPrismContainerValue()); } - - public static ContainerDelta createModificationDelete(QName containerName, + + public static ContainerDelta createModificationDelete(QName containerName, Class type, PrismContext prismContext, PrismContainerValue cValue) throws SchemaException { return createModificationDelete(new ItemPath(containerName), type, prismContext, cValue); } - - public static ContainerDelta createModificationDelete(ItemPath containerPath, + + public static ContainerDelta createModificationDelete(ItemPath containerPath, Class type, PrismContext prismContext, PrismContainerValue cValue) throws SchemaException { ContainerDelta delta = createDelta(containerPath, type, prismContext); prismContext.adopt(cValue, type, containerPath); @@ -340,7 +340,7 @@ public static ContainerDelta c return delta; } - public static ContainerDelta createModificationReplace(QName containerName, + public static ContainerDelta createModificationReplace(QName containerName, Class type, PrismContext prismContext, T containerable) throws SchemaException { return createModificationReplace(new ItemPath(containerName), type, prismContext, containerable); } @@ -349,8 +349,8 @@ public static ContainerDelta c Class type, PrismContext prismContext, Collection containerables) throws SchemaException { return createModificationReplace(new ItemPath(containerName), type, prismContext, containerables); } - - public static ContainerDelta createModificationReplace(ItemPath containerPath, + + public static ContainerDelta createModificationReplace(ItemPath containerPath, Class type, PrismContext prismContext, T containerable) throws SchemaException { return createModificationReplace(containerPath, type, prismContext, containerable.asPrismContainerValue()); } @@ -365,13 +365,13 @@ public static ContainerDelta c delta.setValuesToReplace(pcvs); return delta; } - - public static ContainerDelta createModificationReplace(QName containerName, + + public static ContainerDelta createModificationReplace(QName containerName, Class type, PrismContext prismContext, PrismContainerValue cValue) throws SchemaException { return createModificationReplace(new ItemPath(containerName), type, prismContext, cValue); } - - public static ContainerDelta createModificationReplace(ItemPath containerPath, + + public static ContainerDelta createModificationReplace(ItemPath containerPath, Class type, PrismContext prismContext, PrismContainerValue cValue) throws SchemaException { ContainerDelta delta = createDelta(containerPath, type, prismContext); prismContext.adopt(cValue, type, containerPath); @@ -417,5 +417,5 @@ protected void dumpValues(StringBuilder sb, String label, Collection getPlusMap() { public Map getMinusMap() { return minusMap; } - + public Map getMap(PlusMinusZero plusMinusZero) { if (plusMinusZero == null) { return null; @@ -89,7 +89,7 @@ public Map getMap(PlusMinusZero plusMinusZero) { // notreached throw new IllegalStateException(); } - + public boolean hasPlusMap() { return (plusMap != null && !plusMap.isEmpty()); } @@ -101,7 +101,7 @@ public boolean hasZeroMap() { public boolean hasMinusMap() { return (minusMap != null && !minusMap.isEmpty()); } - + public boolean isZeroOnly() { return hasZeroMap() && !hasPlusMap() && !hasMinusMap(); } @@ -142,7 +142,7 @@ public void addAllToMap(PlusMinusZero destination, Map map) { addAllToMap(zeroMap, map); } } - + private void addAllToMap(Map set, Map items) { if (items == null) { return; @@ -158,15 +158,15 @@ private void addToMap(Map set, K key, V value) { } set.put(key, value); } - + public void clearPlusMap() { clearMap(plusMap); } - + public void clearMinusMap() { clearMap(minusMap); } - + public void clearZeroMap() { clearMap(zeroMap); } @@ -176,7 +176,7 @@ private void clearMap(Map set) { set.clear(); } } - + public int size() { return sizeMap(zeroMap) + sizeMap(plusMap) + sizeMap(minusMap); } @@ -187,20 +187,20 @@ private int sizeMap(Map set) { } return set.size(); } - + public void merge(DeltaMapTriple triple) { addAllToZeroMap(triple.zeroMap); addAllToPlusMap(triple.plusMap); addAllToMinusMap(triple.minusMap); } - + /** * Returns all values, regardless of the internal sets. */ public Collection unionKeySets() { return MiscUtil.union(zeroMap.keySet(), plusMap.keySet(), minusMap.keySet()); } - + public DeltaMapTriple clone(Cloner> cloner) { DeltaMapTriple clone = new DeltaMapTriple(); copyValues(clone, cloner); @@ -210,7 +210,7 @@ public DeltaMapTriple clone(Cloner> cloner) { protected void copyValues(DeltaMapTriple clone, Cloner> cloner) { clone.zeroMap = cloneSet(this.zeroMap, cloner); clone.plusMap = cloneSet(this.plusMap, cloner); - clone.minusMap = cloneSet(this.minusMap, cloner); + clone.minusMap = cloneSet(this.minusMap, cloner); } private Map cloneSet(Map origSet, Cloner> cloner) { @@ -224,18 +224,18 @@ private Map cloneSet(Map origSet, Cloner> cloner) { } return clonedSet; } - + public boolean isEmpty() { return isEmpty(minusMap) && isEmpty(plusMap) && isEmpty(zeroMap); } - + private boolean isEmpty(Map set) { if (set == null) { return true; } return set.isEmpty(); } - + @Override public void simpleAccept(SimpleVisitor> visitor) { acceptMap(visitor, zeroMap); @@ -262,7 +262,7 @@ public String toString() { sb.append(")"); return sb.toString(); } - + protected String debugName() { return "DeltaMapTriple"; } @@ -300,5 +300,5 @@ private void debugDumpMap(StringBuilder sb, String label, Map set, int inde sb.append("\n"); DebugUtil.debugDumpMapMultiLine(sb, set, indent + 1); } - + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/DeltaSetTriple.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/DeltaSetTriple.java index c29ed0770bf..8de793b5a0e 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/DeltaSetTriple.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/DeltaSetTriple.java @@ -36,10 +36,10 @@ /** * The triple of values (added, unchanged, deleted) that represents difference between two collections of values. - *

+ *

* The DeltaSetTriple is used as a result of a "diff" operation or it is constructed to determine a ObjectDelta or * PropertyDelta. It is a very useful structure in numerous situations when dealing with relative changes. - *

+ *

* DeltaSetTriple (similarly to other parts of this system) deal only with unordered values. * * @author Radovan Semancik @@ -84,7 +84,7 @@ public static DeltaSetTriple diff(Collection valuesOld, Collection diff(valuesOld, valuesNew, triple); return triple; } - + protected static void diff(Collection valuesOld, Collection valuesNew, DeltaSetTriple triple) { if (valuesOld == null && valuesNew == null) { // No values, no change -> empty triple @@ -130,7 +130,7 @@ public Collection getPlusSet() { public Collection getMinusSet() { return minusSet; } - + public boolean hasPlusSet() { return !plusSet.isEmpty(); } @@ -142,7 +142,7 @@ public boolean hasZeroSet() { public boolean hasMinusSet() { return !minusSet.isEmpty(); } - + public boolean isZeroOnly() { return hasZeroSet() && !hasPlusSet() && !hasMinusSet(); } @@ -192,7 +192,7 @@ public void addAllToSet(PlusMinusZero destination, Collection items) { addAllToSet(zeroSet, items); } } - + public void addToSet(PlusMinusZero destination, T item) { if (destination == null) { // no op @@ -204,7 +204,7 @@ public void addToSet(PlusMinusZero destination, T item) { addToSet(zeroSet, item); } } - + private void addAllToSet(Collection set, Collection items) { if (items == null) { return; @@ -238,15 +238,15 @@ public boolean presentInZeroSet(T item) { private boolean presentInSet(Collection set, T item) { return set != null && set.contains(item); } - + public void clearPlusSet() { clearSet(plusSet); } - + public void clearMinusSet() { clearSet(minusSet); } - + public void clearZeroSet() { clearSet(zeroSet); } @@ -256,7 +256,7 @@ private void clearSet(Collection set) { set.clear(); } } - + public int size() { return sizeSet(zeroSet) + sizeSet(plusSet) + sizeSet(minusSet); } @@ -275,7 +275,7 @@ private int sizeSet(Collection set) { public Collection union() { return MiscUtil.union(zeroSet, plusSet, minusSet); } - + public T getAnyValue() { if (!zeroSet.isEmpty()) { return zeroSet.iterator().next(); @@ -288,7 +288,7 @@ public T getAnyValue() { } return null; } - + public Collection getAllValues() { Collection allValues = new ArrayList<>(size()); addAllValuesSet(allValues, zeroSet); @@ -320,13 +320,13 @@ public Collection getNonNegativeValues() { public Collection getNonPositiveValues() { return MiscUtil.union(zeroSet, minusSet); } - + public void merge(DeltaSetTriple triple) { zeroSet.addAll(triple.zeroSet); plusSet.addAll(triple.plusSet); minusSet.addAll(triple.minusSet); } - + public DeltaSetTriple clone(Cloner cloner) { DeltaSetTriple clone = new DeltaSetTriple<>(); copyValues(clone, cloner); @@ -350,15 +350,15 @@ private Collection cloneSet(@NotNull Collection origSet, Cloner cloner) } return clonedSet; } - + public boolean isEmpty() { return isEmpty(minusSet) && isEmpty(plusSet) && isEmpty(zeroSet); } - + private boolean isEmpty(Collection set) { return set == null || set.isEmpty(); } - + /** * Process each element of every set. * This is different from the visitor. Visitor will go @@ -370,7 +370,7 @@ public void foreach(Processor processor) { foreachSet(processor, plusSet); foreachSet(processor, minusSet); } - + private void foreachSet(Processor processor, Collection set) { if (set == null) { return; @@ -395,7 +395,7 @@ private void acceptSet(SimpleVisitor visitor, Collection set) { visitor.visit(element); } } - + public void transform(DeltaSetTriple transformTarget, Transformer transformer) { for (T orig: getZeroSet()) { X transformed = transformer.transform(orig); @@ -421,7 +421,7 @@ public String toString() { sb.append(")"); return sb.toString(); } - + protected String debugName() { return "DeltaSetTriple"; } @@ -445,8 +445,8 @@ public String debugDump() { public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); DebugUtil.debugDumpLabelLn(sb, "DeltaSetTriple", indent); - - debugDumpSets(sb, + + debugDumpSets(sb, val -> sb.append(DebugUtil.debugDump(val, indent + 3)), indent + 1); @@ -458,9 +458,9 @@ public void debugDumpSets(StringBuilder sb, Consumer dumper, int indent) { sb.append("\n"); debugDumpSet(sb, "plus", dumper, plusSet, indent + 1); sb.append("\n"); - debugDumpSet(sb, "minus", dumper, minusSet, indent + 1); + debugDumpSet(sb, "minus", dumper, minusSet, indent + 1); } - + private void debugDumpSet(StringBuilder sb, String label, Consumer dumper, Collection set, int indent) { DebugUtil.debugDumpLabel(sb, label, indent); if (set == null) { @@ -472,7 +472,7 @@ private void debugDumpSet(StringBuilder sb, String label, Consumer dumper, Co } } } - + public String toHumanReadableString() { StringBuilder sb = new StringBuilder(); boolean first = toHumanReadableString(sb, "added", plusSet, true); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/DeltaTriple.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/DeltaTriple.java index cc831dfa64c..a5ec8c9ff52 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/DeltaTriple.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/DeltaTriple.java @@ -24,7 +24,7 @@ /** * Utility class for keeping things in three: plus, zero and minus. - * + * * @author semancik */ public class DeltaTriple implements DebugDumpable, Foreachable { @@ -32,13 +32,13 @@ public class DeltaTriple implements DebugDumpable, Foreachable { private T plus; private T zero; private T minus; - + public DeltaTriple() { plus = null; zero = null; minus = null; } - + public DeltaTriple(Supplier initializer) { plus = initializer.get(); zero = initializer.get(); @@ -68,7 +68,7 @@ public T getMinus() { public void setMinus(T minus) { this.minus = minus; } - + public T get(PlusMinusZero mode) { switch (mode) { case PLUS: return plus; @@ -83,8 +83,8 @@ public void foreach(Processor processor) { processor.process(plus); processor.process(zero); processor.process(minus); - } - + } + @Override public String debugDump(int indent) { StringBuilder sb = DebugUtil.createTitleStringBuilder(DeltaTriple.class, indent); @@ -92,7 +92,7 @@ public String debugDump(int indent) { debugDumpNoTitle(sb, indent); return sb.toString(); } - + public String debugDumpNoTitle(StringBuilder sb, int indent) { debugDumpVal(sb, plus, "plus", indent); sb.append("\n"); @@ -160,5 +160,5 @@ public boolean equals(Object obj) { public String toString() { return "DeltaTriple(plus=" + plus + ", zero=" + zero + ", minus=" + minus + ")"; } - + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/DiffUtil.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/DiffUtil.java index cd7e64750f5..5d1109c8d2e 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/DiffUtil.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/DiffUtil.java @@ -42,7 +42,7 @@ public static ObjectDelta diff(PrismObject oldObjec return oldObject.diff(newObject); } } - + private static PrismContext getPrismContext(PrismObject... objects) { for (PrismObject object: objects) { if (object != null) { @@ -64,7 +64,7 @@ public static ObjectDelta diff(T oldObjectType, T newO return diff(oldObject, newObject); } - + public static ObjectDelta diff(String oldXml, String newXml, Class type, PrismContext prismContext) throws SchemaException { PrismObject oldObject = null; if (oldXml != null) { diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ItemDelta.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ItemDelta.java index fb425b1f323..2d74a08b5b2 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ItemDelta.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ItemDelta.java @@ -49,12 +49,12 @@ /** * @author Radovan Semancik - * + * */ public abstract class ItemDelta implements Itemable, DebugDumpable, Visitable, PathVisitable, Foreachable, Serializable { private static final Trace LOGGER = TraceManager.getTrace(ItemDelta.class); - + /** * Name of the property */ @@ -164,7 +164,7 @@ public void setDefinition(D definition) { public void accept(Visitor visitor) { accept(visitor, true); } - + public void accept(Visitor visitor, boolean includeOldValues) { visitor.visit(this); if (getValuesToAdd() != null) { @@ -192,7 +192,7 @@ public void accept(Visitor visitor, boolean includeOldValues) { public int size() { return sizeSet(valuesToReplace) + sizeSet(valuesToAdd) + sizeSet(valuesToDelete); } - + private int sizeSet(Collection set) { if (set == null) { return 0; @@ -252,7 +252,7 @@ private void acceptSet(Collection set, Long id, Visitor visitor, ItemPath res } else { throw new IllegalArgumentException("Attempt to fit container id to "+pval.getClass()); } - } + } } public void applyDefinition(D definition) throws SchemaException { @@ -286,7 +286,7 @@ public static void applyDefinitionIfPresent(Collection delt } } } - + public boolean hasCompleteDefinition() { return getDefinition() != null; } @@ -301,7 +301,7 @@ public PrismContext getPrismContext() { public Collection getValuesToAdd() { return valuesToAdd; } - + public void clearValuesToAdd() { valuesToAdd = null; } @@ -309,7 +309,7 @@ public void clearValuesToAdd() { public Collection getValuesToDelete() { return valuesToDelete; } - + public void clearValuesToDelete() { valuesToDelete = null; } @@ -317,7 +317,7 @@ public void clearValuesToDelete() { public Collection getValuesToReplace() { return valuesToReplace; } - + public void clearValuesToReplace() { valuesToReplace = null; } @@ -330,7 +330,7 @@ public void addValuesToAdd(Collection newValues) { addValueToAdd(val); } } - + public void addValuesToAdd(V... newValues) { for (V val : newValues) { addValueToAdd(val); @@ -352,19 +352,19 @@ public void addValueToAdd(V newValue) { newValue.setParent(this); newValue.recompute(); } - + public boolean removeValueToAdd(PrismValue valueToRemove) { return removeValue(valueToRemove, valuesToAdd, false); } - + public boolean removeValueToDelete(PrismValue valueToRemove) { return removeValue(valueToRemove, valuesToDelete, true); } - + public boolean removeValueToReplace(PrismValue valueToRemove) { return removeValue(valueToRemove, valuesToReplace, false); } - + private boolean removeValue(PrismValue valueToRemove, Collection set, boolean toDelete) { boolean removed = false; if (set == null) { @@ -392,7 +392,7 @@ public void mergeValuesToAdd(Collection newValues) { mergeValueToAdd(val); } } - + public void mergeValuesToAdd(V[] newValues) { if (newValues == null) { return; @@ -401,7 +401,7 @@ public void mergeValuesToAdd(V[] newValues) { mergeValueToAdd(val); } } - + public void mergeValueToAdd(V newValue) { if (valuesToReplace != null) { if (!PrismValue.containsRealValue(valuesToReplace, newValue)) { @@ -429,7 +429,7 @@ public void addValuesToDelete(V... newValues) { addValueToDelete(val); } } - + public void addValueToDelete(V newValue) { if (valuesToReplace != null) { throw new IllegalStateException("Delta " + this @@ -445,7 +445,7 @@ public void addValueToDelete(V newValue) { newValue.setParent(this); newValue.recompute(); } - + protected boolean containsEquivalentValue(Collection collection, V value) { if (collection == null) { return false; @@ -457,11 +457,11 @@ protected boolean containsEquivalentValue(Collection collection, V value) { } return false; } - + protected boolean isValueEquivalent(V a, V b) { return a.equalsRealValue(b); } - + public void mergeValuesToDelete(Collection newValues) { for (V val : newValues) { mergeValueToDelete(val); @@ -473,7 +473,7 @@ public void mergeValuesToDelete(V[] newValues) { mergeValueToDelete(val); } } - + public void mergeValueToDelete(V newValue) { if (valuesToReplace != null) { removeValueToReplace(newValue); @@ -491,7 +491,7 @@ public void resetValuesToAdd() { public void resetValuesToDelete() { valuesToDelete = null; } - + public void resetValuesToReplace() { valuesToReplace = null; } @@ -540,7 +540,7 @@ public void setValuesToReplace(V... newValues) { val.recompute(); } } - + /** * Sets empty value to replace. This efficiently means removing all values. */ @@ -551,7 +551,7 @@ public void setValueToReplace() { valuesToReplace.clear(); } } - + public void setValueToReplace(V newValue) { if (valuesToAdd != null) { throw new IllegalStateException("Delta " + this @@ -572,7 +572,7 @@ public void setValueToReplace(V newValue) { newValue.recompute(); } } - + public void addValueToReplace(V newValue) { if (valuesToAdd != null) { throw new IllegalStateException("Delta " + this @@ -591,7 +591,7 @@ public void addValueToReplace(V newValue) { newValue.recompute(); } } - + public void mergeValuesToReplace(Collection newValues) { // No matter what type the delta was before. We are just discarding all the previous // state as the replace that we are applying will overwrite that anyway. @@ -607,7 +607,7 @@ public void mergeValuesToReplace(V[] newValues) { valuesToDelete = null; setValuesToReplace(newValues); } - + public void mergeValueToReplace(V newValue) { // No matter what type the delta was before. We are just discarding all the previous // state as the replace that we are applying will overwrite that anyway. @@ -655,7 +655,7 @@ private boolean isValueSet(V value, boolean ignoreMetadata, Collection set) { } return false; } - + public V getAnyValue() { V anyValue = getAnyValue(valuesToAdd); if (anyValue != null) { @@ -697,21 +697,21 @@ public static boolean isEmpty(ItemDeltaType itemDeltaType) { } return !itemDeltaType.getValue().isEmpty(); } - + public boolean addsAnyValue() { - return hasAnyValue(valuesToAdd) || hasAnyValue(valuesToReplace); + return hasAnyValue(valuesToAdd) || hasAnyValue(valuesToReplace); } - + private boolean hasAnyValue(Collection set) { return (set != null && !set.isEmpty()); } - + public void foreach(Processor processor) { foreachSet(processor, valuesToAdd); foreachSet(processor, valuesToDelete); foreachSet(processor, valuesToReplace); } - + private void foreachSet(Processor processor, Collection set) { if (set == null) { return; @@ -720,19 +720,19 @@ private void foreachSet(Processor processor, Collection set) { processor.process(val); } } - + /** * Returns estimated state of the old value before the delta is applied. * This information is not entirely reliable. The state might change * between the value is read and the delta is applied. This is property * is optional and even if provided it is only for for informational * purposes. - * + * * If this method returns null then it should be interpreted as "I do not know". * In that case the delta has no information about the old values. * If this method returns empty collection then it should be interpreted that * we know that there were no values in this item before the delta was applied. - * + * * @return estimated state of the old value before the delta is applied (may be null). */ public Collection getEstimatedOldValues() { @@ -742,13 +742,13 @@ public Collection getEstimatedOldValues() { public void setEstimatedOldValues(Collection estimatedOldValues) { this.estimatedOldValues = estimatedOldValues; } - + public void addEstimatedOldValues(Collection newValues) { for (V val : newValues) { addEstimatedOldValue(val); } } - + public void addEstimatedOldValues(V... newValues) { for (V val : newValues) { addEstimatedOldValue(val); @@ -799,7 +799,7 @@ public void clear() { valuesToAdd = null; valuesToDelete = null; } - + public static PropertyDelta findPropertyDelta(Collection deltas, QName propertyName) { return findPropertyDelta(deltas, new ItemPath(propertyName)); } @@ -807,11 +807,11 @@ public static PropertyDelta findPropertyDelta(Collection PropertyDelta findPropertyDelta(Collection deltas, ItemPath parentPath, QName propertyName) { return findPropertyDelta(deltas, new ItemPath(parentPath, propertyName)); } - + public static PropertyDelta findPropertyDelta(Collection deltas, ItemPath propertyPath) { return findItemDelta(deltas, propertyPath, PropertyDelta.class); } - + public static ContainerDelta findContainerDelta(Collection deltas, ItemPath propertyPath) { return findItemDelta(deltas, propertyPath, ContainerDelta.class); } @@ -834,7 +834,7 @@ public static

DD findItemDelta(Collection> findItemDeltasSubPath(Collection> deltas, ItemPath itemPath) { Collection> foundDeltas = new ArrayList>(); if (deltas == null) { @@ -847,15 +847,15 @@ public static Collection> findItemDeltasSubPath(Collect } return foundDeltas; } - + public static D findItemDelta(Collection deltas, QName itemName, Class deltaType) { return findItemDelta(deltas, new ItemPath(itemName), deltaType); } - + public static ReferenceDelta findReferenceModification(Collection deltas, QName itemName) { return findItemDelta(deltas, itemName, ReferenceDelta.class); } - + public static void removeItemDelta(Collection deltas, ItemPath propertyPath, Class deltaType) { if (deltas == null) { return; @@ -868,7 +868,7 @@ public static void removeItemDelta(Collection void removeItemDelta(Collection deltas, ItemDelta deltaToRemove) { if (deltas == null) { return; @@ -881,11 +881,11 @@ public static void removeItemDelta(Collection narrow(PrismObject object) { return narrow(object, null); @@ -984,7 +984,7 @@ public boolean isRedundant(PrismObject object, Comparator< public void validate() throws SchemaException { validate(null); } - + public void validate(String contextDescription) throws SchemaException { if (definition == null) { throw new IllegalStateException("Attempt to validate delta without a definition: "+this); @@ -1006,12 +1006,12 @@ public void validate(String contextDescription) throws SchemaException { } } } - - + + public void validateValues(ItemDeltaValidator validator) throws SchemaException { validateValues(validator, getEstimatedOldValues()); } - + public void validateValues(ItemDeltaValidator validator, Collection oldValues) throws SchemaException { validateSet(valuesToAdd, PlusMinusZero.PLUS, validator); validateSet(valuesToDelete, PlusMinusZero.MINUS, validator); @@ -1049,9 +1049,9 @@ public static void checkConsistence(Collection deltas) { public static void checkConsistence(Collection deltas, ConsistencyCheckScope scope) { checkConsistence(deltas, false, false, scope); } - + public static void checkConsistence(Collection deltas, boolean requireDefinition, boolean prohibitRaw, ConsistencyCheckScope scope) { - Map> pathMap = new HashMap<>(); + Map> pathMap = new HashMap<>(); for (ItemDelta delta : deltas) { delta.checkConsistence(requireDefinition, prohibitRaw, scope); int matches = 0; @@ -1164,15 +1164,15 @@ public void merge(ItemDelta deltaToMerge) { } if (deltaToMerge.valuesToDelete != null) { mergeValuesToDelete(PrismValue.cloneValues(deltaToMerge.valuesToDelete)); - } + } } // We do not want to clean up the sets during merging (e.g. in removeValue methods) because the set // may become empty and the a values may be added later. So just clean it up when all is done. removeEmptySets(); } - + private void removeEmptySets() { - // Do not remove replace set, even if it is empty. + // Do not remove replace set, even if it is empty. // Empty replace set is not the same as no replace set if (valuesToAdd != null && valuesToAdd.isEmpty()) { valuesToAdd = null; @@ -1181,10 +1181,10 @@ private void removeEmptySets() { valuesToDelete = null; } } - + public Collection getValueChanges(PlusMinusZero mode) { Collection out = new ArrayList<>(); - + if (isReplace()) { switch (mode) { case PLUS: @@ -1209,7 +1209,7 @@ public Collection getValueChanges(PlusMinusZero mode) { break; } } - + return out; } @@ -1238,16 +1238,16 @@ private void setIntersection(Collection out, Collection a, Collection b } } } - + private void setAddAll(Collection out, Collection in) { if (in != null) { out.addAll(in); } } - + /** * Transforms the delta to the simplest (and safest) form. E.g. it will transform add delta for - * single-value properties to replace delta. + * single-value properties to replace delta. */ public void simplify() { ItemDefinition itemDefinition = getDefinition(); @@ -1260,7 +1260,7 @@ public void simplify() { valuesToDelete = null; } } - + private void cleanupAllTheWayUp(Item item) { if (item.isEmpty()) { PrismValue itemParent = item.getParent(); @@ -1286,14 +1286,14 @@ public static void applyTo(Collection deltas, PrismContaine delta.applyTo(propertyContainer); } } - + public static void applyTo(Collection deltas, PrismContainerValue propertyContainerValue) throws SchemaException { for (ItemDelta delta : deltas) { delta.applyTo(propertyContainerValue); } } - + public static void applyToMatchingPath(Collection deltas, PrismContainer propertyContainer) throws SchemaException { for (ItemDelta delta : deltas) { @@ -1309,7 +1309,7 @@ public void applyTo(PrismContainerValue containerValue) throws SchemaException { Item subItem = containerValue.findOrCreateItem(deltaPath, getItemClass(), getDefinition()); applyToMatchingPath(subItem); } - + public void applyTo(Item item) throws SchemaException { ItemPath itemPath = item.getPath(); ItemPath deltaPath = getPath(); @@ -1332,7 +1332,7 @@ public void applyTo(Item item) throws SchemaException { throw new SchemaException("Cannot apply delta "+this+" to "+item+" as paths do not match"); } } - + /** * Applies delta to item were path of the delta and path of the item matches (skips path checks). */ @@ -1371,11 +1371,11 @@ public void applyToMatchingPath(Item item) throws SchemaException { // Those needs to be cleaned-up (removed) as empty item is not a legal state. cleanupAllTheWayUp(item); } - + public ItemDelta getSubDelta(ItemPath path) { return this; } - + public boolean isApplicableTo(Item item) { if (item == null) { return false; @@ -1386,9 +1386,9 @@ public boolean isApplicableTo(Item item) { // TODO: maybe check path? return true; } - + protected abstract boolean isApplicableToType(Item item); - + public static void accept(Collection modifications, Visitor visitor, ItemPath path, boolean recursive) { for (ItemDelta modification: modifications) { @@ -1409,7 +1409,7 @@ public static void accept(Collection modifications, Visitor public Item getItemNew() throws SchemaException { return getItemNew(null); } - + /** * Returns the "new" state of the property - the state that would be after * the delta is applied. @@ -1430,7 +1430,7 @@ public Item getItemNew(Item itemOld) throws SchemaException { applyTo(itemNew); return itemNew; } - + public Item getItemNewMatchingPath(Item itemOld) throws SchemaException { if (definition == null) { throw new IllegalStateException("No definition in "+this); @@ -1447,21 +1447,21 @@ public Item getItemNewMatchingPath(Item itemOld) throws SchemaExceptio applyToMatchingPath(itemNew); return itemNew; } - + /** * Returns true if the other delta is a complete subset of this delta. * I.e. if all the statements of the other delta are already contained * in this delta. As a consequence it also returns true if the two - * deltas are equal. + * deltas are equal. */ public boolean contains(ItemDelta other) { return contains(other, PrismConstants.EQUALS_DEFAULT_IGNORE_METADATA, PrismConstants.EQUALS_DEFAULT_IS_LITERAL); - } + } /** * Returns true if the other delta is a complete subset of this delta. * I.e. if all the statements of the other delta are already contained * in this delta. As a consequence it also returns true if the two - * deltas are equal. + * deltas are equal. */ public boolean contains(ItemDelta other, boolean ignoreMetadata, boolean isLiteral) { if (!this.getPath().equivalent(other.getPath())) { @@ -1478,7 +1478,7 @@ public boolean contains(ItemDelta other, boolean ignoreMetadata, boolean is } return true; } - + public void filterValues(Function function) { filterValuesSet(this.valuesToAdd, function); filterValuesSet(this.valuesToDelete, function); @@ -1522,7 +1522,7 @@ private Collection cloneSet(ItemDelta clone, Collection thisSet) { } return clonedSet; } - + public static > Collection cloneCollection(Collection orig) { if (orig == null) { return null; @@ -1536,7 +1536,7 @@ public static > Collection cloneCollection(Collectio @Deprecated - public static PrismValueDeltaSetTriple toDeltaSetTriple(Item item, ItemDelta delta, + public static PrismValueDeltaSetTriple toDeltaSetTriple(Item item, ItemDelta delta, boolean oldValuesValid, boolean newValuesValid) { if (item == null && delta == null) { return null; @@ -1564,7 +1564,7 @@ public static PrismValueDeltaS } return delta.toDeltaSetTriple(item); } - + public static PrismValueDeltaSetTriple toDeltaSetTriple(Item item, ItemDelta delta) { if (item == null && delta == null) { return null; @@ -1576,11 +1576,11 @@ public static PrismValueDeltaS } return delta.toDeltaSetTriple(item); } - + public PrismValueDeltaSetTriple toDeltaSetTriple() { return toDeltaSetTriple(null); } - + public PrismValueDeltaSetTriple toDeltaSetTriple(Item itemOld) { PrismValueDeltaSetTriple triple = new PrismValueDeltaSetTriple(); if (isReplace()) { @@ -1605,11 +1605,11 @@ public PrismValueDeltaSetTriple toDeltaSetTriple(Item itemOld) { } return triple; } - + public void assertDefinitions(String sourceDescription) throws SchemaException { assertDefinitions(false, sourceDescription); } - + public void assertDefinitions(boolean tolarateRawValues, String sourceDescription) throws SchemaException { if (tolarateRawValues && isRaw()) { return; @@ -1638,7 +1638,7 @@ private void assertDefinitions(boolean tolarateRawValues, Collection values, } } } - + public boolean isRaw() { Boolean isRaw = MiscUtil.and(isRawSet(valuesToAdd), isRawSet(valuesToReplace), isRawSet(valuesToDelete)); if (isRaw == null) { @@ -1658,7 +1658,7 @@ private Boolean isRawSet(Collection set) { } return true; } - + public void revive(PrismContext prismContext) throws SchemaException { this.prismContext = prismContext; reviveSet(valuesToAdd, prismContext); @@ -1674,7 +1674,7 @@ private void reviveSet(Collection set, PrismContext prismContext) throws Sche val.revive(prismContext); } } - + public void applyDefinition(D itemDefinition, boolean force) throws SchemaException { if (this.definition != null && !force) { return; @@ -1693,7 +1693,7 @@ private void applyDefinitionSet(Collection set, ItemDefinition itemDefinition val.applyDefinition(itemDefinition, force); } } - + @Override public int hashCode() { final int prime = 31; @@ -1729,7 +1729,7 @@ public boolean equivalent(ItemDelta other) { return false; return true; } - + public static boolean hasEquivalent(Collection col, ItemDelta delta) { for (ItemDelta colItem: col) { if (colItem.equivalent(delta)) { @@ -1738,7 +1738,7 @@ public static boolean hasEquivalent(Collection col, ItemDel } return false; } - + @Override public boolean equals(Object obj) { if (this == obj) @@ -1775,7 +1775,7 @@ public boolean equals(Object obj) { } private boolean equivalentSetRealValue(Collection thisValue, Collection otherValues, boolean isDelete) { - return MiscUtil.unorderedCollectionEquals(thisValue, otherValues, + return MiscUtil.unorderedCollectionEquals(thisValue, otherValues, (v1, v2) -> { if (v1 != null && v2 != null) { if (!isDelete || !(v1 instanceof PrismContainerValue) || !(v2 instanceof PrismContainerValue)) { @@ -1838,7 +1838,7 @@ public String debugDump(int indent) { } ItemPath path = getPath(); sb.append(path); - + if (definition != null && DebugUtil.isDetailedDebugDump()) { sb.append(" def"); } @@ -1857,7 +1857,7 @@ public String debugDump(int indent) { sb.append("\n"); dumpValues(sb, "DELETE", valuesToDelete, indent + 1); } - + if (estimatedOldValues != null) { sb.append("\n"); dumpValues(sb, "OLD", estimatedOldValues, indent + 1); @@ -1901,7 +1901,7 @@ public static void addAll(Collection modifications, Collect } } } - + public static void merge(Collection modifications, ItemDelta delta) { for (ItemDelta modification: modifications) { if (modification.getPath().equals(delta.getPath())) { @@ -1911,7 +1911,7 @@ public static void merge(Collection modifications, ItemDelt } ((Collection)modifications).add(delta); } - + public static void mergeAll(Collection modifications, Collection deltasToMerge) { if (deltasToMerge == null) { return; @@ -1938,7 +1938,7 @@ public ItemDelta createReverseDelta() { Collection cloneValuesToDelete = reverseDelta.valuesToDelete; Collection cloneValuesToReplace = reverseDelta.valuesToReplace; Collection cloneEstimatedOldValues = reverseDelta.estimatedOldValues; - + reverseDelta.valuesToAdd = cloneValuesToDelete; reverseDelta.valuesToDelete = cloneValuesToAdd; if (cloneValuesToReplace != null) { @@ -1954,7 +1954,7 @@ public ItemDelta createReverseDelta() { } else { // TODO: what about estimatedOldValues here? } - + return reverseDelta; } @@ -1974,7 +1974,7 @@ private V findValue(Collection values, V value) { .filter(v -> !differentIds(v, value) && v.equals(value, true)) .findFirst().orElse(null); } - + /** * Set origin type to all values and subvalues */ diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ItemDeltaValidator.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ItemDeltaValidator.java index 3d95f8ed2a3..ad68953e7f3 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ItemDeltaValidator.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ItemDeltaValidator.java @@ -23,7 +23,7 @@ */ @FunctionalInterface public interface ItemDeltaValidator { - + void validate(PlusMinusZero plusMinusZero, V itemValue); - + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ObjectDelta.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ObjectDelta.java index 3c750d14bcb..27101dac28e 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ObjectDelta.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ObjectDelta.java @@ -40,15 +40,15 @@ /** * Relative difference (delta) of the object. - *

+ *

* This class describes how the object changes. It can describe either object addition, modification of deletion. - *

+ *

* Addition described complete new (absolute) state of the object. - *

+ *

* Modification contains a set property deltas that describe relative changes to individual properties - *

+ *

* Deletion does not contain anything. It only marks object for deletion. - *

+ *

* The OID is mandatory for modification and deletion. * * @author Radovan Semancik @@ -79,26 +79,26 @@ public class ObjectDelta implements DebugDumpable, Visitab * Class of the object that we describe. */ private Class objectTypeClass; - + transient private PrismContext prismContext; public ObjectDelta(Class objectTypeClass, ChangeType changeType, PrismContext prismContext) { Validate.notNull(objectTypeClass,"No objectTypeClass"); Validate.notNull(changeType,"No changeType"); //Validate.notNull(prismContext, "No prismContext"); - + this.changeType = changeType; this.objectTypeClass = objectTypeClass; this.prismContext = prismContext; objectToAdd = null; modifications = createEmptyModifications(); } - + @Override public void accept(Visitor visitor) { accept(visitor, true); } - + public void accept(Visitor visitor, boolean includeOldValues) { visitor.visit(this); if (isAdd()) { @@ -131,7 +131,7 @@ public ChangeType getChangeType() { public void setChangeType(ChangeType changeType) { this.changeType = changeType; } - + public static boolean isAdd(ObjectDelta objectDelta) { if (objectDelta == null) { return false; @@ -206,7 +206,7 @@ public Collection> getModifications() { * Adds modification (itemDelta) and returns the modification that was added. * NOTE: the modification that was added may be different from the modification that was * passed into this method! E.g. in case if two modifications must be merged to keep the delta - * consistent. Therefore always use the returned modification after this method is invoked. + * consistent. Therefore always use the returned modification after this method is invoked. */ public D addModification(D itemDelta) { if (getChangeType() != ChangeType.MODIFY) { @@ -222,11 +222,11 @@ public D addModification(D itemDelta) { return itemDelta; } } - + public boolean containsModification(ItemDelta itemDelta) { return containsModification(itemDelta, PrismConstants.EQUALS_DEFAULT_IGNORE_METADATA, PrismConstants.EQUALS_DEFAULT_IS_LITERAL); } - + public boolean containsModification(ItemDelta itemDelta, boolean ignoreMetadata, boolean isLiteral) { for (ItemDelta modification: modifications) { if (modification.contains(itemDelta, ignoreMetadata, isLiteral)) { @@ -241,18 +241,18 @@ public void addModifications(Collection itemDeltas) { addModification(modDelta); } } - + public void addModifications(ItemDelta... itemDeltas) { for (ItemDelta modDelta: itemDeltas) { addModification(modDelta); } } - + public ItemDelta findItemDelta(ItemPath propertyPath) { return findItemDelta(propertyPath, ItemDelta.class, Item.class); } - - private ,DD extends ItemDelta> + + private ,DD extends ItemDelta> DD findItemDelta(ItemPath propertyPath, Class

deltaType, Class itemType) { if (changeType == ChangeType.ADD) { I item = objectToAdd.findItem(propertyPath, itemType); @@ -268,7 +268,7 @@ DD findItemDelta(ItemPath propertyPath, Class
deltaType, Class itemType) return null; } } - + public Collection> findPartial(ItemPath propertyPath) { if (changeType == ChangeType.ADD) { PartiallyResolvedItem partialValue = objectToAdd.findPartial(propertyPath); @@ -311,7 +311,7 @@ public boolean hasItemDelta(ItemPath propertyPath) { return false; } } - + public boolean hasCompleteDefinition() { if (isAdd()) { return getObjectToAdd().hasCompleteDefinition(); @@ -328,10 +328,10 @@ public boolean hasCompleteDefinition() { } throw new IllegalStateException("Strange things happen"); } - + private D createEmptyDelta(ItemPath propertyPath, ItemDefinition itemDef, Class deltaType, Class itemType) { - + if (PrismProperty.class.isAssignableFrom(itemType)) { return (D) new PropertyDelta(propertyPath, (PrismPropertyDefinition)itemDef, prismContext); } else if (PrismContainer.class.isAssignableFrom(itemType)) { @@ -361,12 +361,12 @@ public PropertyDelta findPropertyDelta(QName propertyName) { public PropertyDelta findPropertyDelta(ItemPath parentPath, QName propertyName) { return findPropertyDelta(new ItemPath(parentPath, propertyName)); } - + @SuppressWarnings("unchecked") public PropertyDelta findPropertyDelta(ItemPath propertyPath) { return findItemDelta(propertyPath, PropertyDelta.class, PrismProperty.class); } - + @SuppressWarnings("unchecked") public ContainerDelta findContainerDelta(ItemPath propertyPath) { return findItemDelta(propertyPath, ContainerDelta.class, PrismContainer.class); @@ -391,11 +391,11 @@ private D findModification(ItemPath propertyPath, Class return null; } } - + private D findModification(QName itemName, Class deltaType) { return findModification(new ItemPath(itemName), deltaType); } - + public ReferenceDelta findReferenceModification(QName itemName) { return findModification(itemName, ReferenceDelta.class); } @@ -411,23 +411,23 @@ public Collection> findItemDeltasSubPath(ItemPath itemP return ItemDelta.findItemDeltasSubPath(modifications, itemPath); } - + private void removeModification(ItemPath propertyPath, Class deltaType) { ItemDelta.removeItemDelta(modifications, propertyPath, deltaType); } - + public void removeModification(ItemDelta itemDelta) { ItemDelta.removeItemDelta(modifications, itemDelta); } - + private void removeModification(QName itemName, Class deltaType) { removeModification(new ItemPath(itemName), deltaType); } - + public void removeReferenceModification(QName itemName) { removeModification(itemName, ReferenceDelta.class); } - + public void removeReferenceModification(ItemPath itemPath) { removeModification(itemPath, ReferenceDelta.class); } @@ -439,11 +439,11 @@ public void removeContainerModification(QName itemName) { public void removePropertyModification(QName itemName) { removeModification(itemName, PropertyDelta.class); } - + public void removePropertyModification(ItemPath itemPath) { removeModification(itemPath, PropertyDelta.class); } - + public boolean isEmpty() { if (getChangeType() == ChangeType.DELETE) { // Delete delta is never empty @@ -480,7 +480,7 @@ public static boolean isEmpty(ObjectDeltaType deltaType) { return true; } } - + public void normalize() { if (objectToAdd != null) { objectToAdd.normalize(); @@ -560,21 +560,21 @@ public void merge(ObjectDelta deltaToMerge) throws SchemaException { } } } - + /** * Returns a delta that is a "sum" of all the deltas in the collection. * The deltas as processed as an ORDERED sequence. Therefore it correctly processes item overwrites and so on. - * It also means that if there is an ADD delta it has to be first. + * It also means that if there is an ADD delta it has to be first. */ @SafeVarargs public static ObjectDelta summarize(ObjectDelta... deltas) throws SchemaException { return summarize(Arrays.asList(deltas)); } - + /** * Returns a delta that is a "sum" of all the deltas in the collection. * The deltas as processed as an ORDERED sequence. Therefore it correctly processes item overwrites and so on. - * It also means that if there is an ADD delta it has to be first. + * It also means that if there is an ADD delta it has to be first. */ public static ObjectDelta summarize(List> deltas) throws SchemaException { if (deltas == null || deltas.isEmpty()) { @@ -592,7 +592,7 @@ public static ObjectDelta summarize(List ObjectDelta union(ObjectDelta... deltas) throws SchemaException { @@ -656,13 +656,13 @@ private static ObjectDelta mergeToDelta(ObjectDelta } return delta; } - + public void mergeModifications(Collection modificationsToMerge) throws SchemaException { for (ItemDelta propDelta : modificationsToMerge) { mergeModification(propDelta); } } - + public void mergeModification(ItemDelta modificationToMerge) throws SchemaException { if (changeType == ChangeType.ADD) { modificationToMerge.applyTo(objectToAdd); @@ -749,18 +749,18 @@ private Collection> createEmptyModifications() { // Lists are easier to debug return new ArrayList<>(); } - + public PropertyDelta createPropertyModification(QName name, PrismPropertyDefinition propertyDefinition) { PropertyDelta propertyDelta = new PropertyDelta(name, propertyDefinition, prismContext); return addModification(propertyDelta); } - + public PropertyDelta createPropertyModification(ItemPath path) { PrismObjectDefinition objDef = getPrismContext().getSchemaRegistry().findObjectDefinitionByCompileTimeClass(getObjectTypeClass()); PrismPropertyDefinition propDef = objDef.findPropertyDefinition(path); return createPropertyModification(path, propDef); } - + public PropertyDelta createPropertyModification(ItemPath path, PrismPropertyDefinition propertyDefinition) { PropertyDelta propertyDelta = new PropertyDelta(path, propertyDefinition, prismContext); // No point in adding the modification to this delta. It will get merged anyway and it may disappear @@ -777,70 +777,70 @@ public ReferenceDelta createReferenceModification(ItemPath path, PrismReferenceD ReferenceDelta referenceDelta = new ReferenceDelta(path, referenceDefinition, prismContext); return addModification(referenceDelta); } - + public ContainerDelta createContainerModification(QName qname) { return createContainerModification(new ItemPath(qname)); } - + public ContainerDelta createContainerModification(ItemPath path) { PrismObjectDefinition objDef = getPrismContext().getSchemaRegistry().findObjectDefinitionByCompileTimeClass(getObjectTypeClass()); PrismContainerDefinition propDef = objDef.findContainerDefinition(path); return createContainerModification(path, propDef); } - + public ContainerDelta createContainerModification(ItemPath path, PrismContainerDefinition containerDefinition) { ContainerDelta containerDelta = new ContainerDelta(path, containerDefinition, prismContext); return addModification(containerDelta); } - + /** * Convenience method for quick creation of object deltas that replace a single object property. This is used quite often - * to justify a separate method. + * to justify a separate method. */ public static ObjectDelta createModificationReplaceProperty(Class type, String oid, QName propertyName, PrismContext prismContext, X... propertyValues) { ItemPath propertyPath = new ItemPath(propertyName); return createModificationReplaceProperty(type, oid, propertyPath, prismContext, propertyValues); } - + /** * Convenience method for quick creation of object deltas that replace a single object property. This is used quite often - * to justify a separate method. + * to justify a separate method. */ - public static ObjectDelta createModificationReplaceProperty(Class type, String oid, + public static ObjectDelta createModificationReplaceProperty(Class type, String oid, ItemPath propertyPath, PrismContext prismContext, X... propertyValues) { ObjectDelta objectDelta = new ObjectDelta(type, ChangeType.MODIFY, prismContext); objectDelta.setOid(oid); fillInModificationReplaceProperty(objectDelta, propertyPath, propertyValues); return objectDelta; } - - public static ObjectDelta createModificationAddProperty(Class type, String oid, + + public static ObjectDelta createModificationAddProperty(Class type, String oid, QName propertyName, PrismContext prismContext, X... propertyValues) { return createModificationAddProperty(type, oid, new ItemPath(propertyName), prismContext, propertyValues); } - - public static ObjectDelta createModificationAddProperty(Class type, String oid, + + public static ObjectDelta createModificationAddProperty(Class type, String oid, ItemPath propertyPath, PrismContext prismContext, X... propertyValues) { ObjectDelta objectDelta = new ObjectDelta(type, ChangeType.MODIFY, prismContext); objectDelta.setOid(oid); fillInModificationAddProperty(objectDelta, propertyPath, propertyValues); return objectDelta; } - - public static ObjectDelta createModificationDeleteProperty(Class type, String oid, + + public static ObjectDelta createModificationDeleteProperty(Class type, String oid, QName propertyName, PrismContext prismContext, X... propertyValues) { return createModificationDeleteProperty(type, oid, new ItemPath(propertyName), prismContext, propertyValues); } - - public static ObjectDelta createModificationDeleteProperty(Class type, String oid, + + public static ObjectDelta createModificationDeleteProperty(Class type, String oid, ItemPath propertyPath, PrismContext prismContext, X... propertyValues) { ObjectDelta objectDelta = new ObjectDelta(type, ChangeType.MODIFY, prismContext); objectDelta.setOid(oid); fillInModificationDeleteProperty(objectDelta, propertyPath, propertyValues); return objectDelta; } - + /** * Convenience method for quick creation of object deltas that replace a single object reference. */ @@ -849,22 +849,22 @@ public static ObjectDelta createModificationReplace ItemPath propertyPath = new ItemPath(referenceName); return createModificationReplaceReference(type, oid, propertyPath, prismContext, refValues); } - + /** * Convenience method for quick creation of object deltas that replace a single object reference. */ - public static ObjectDelta createModificationReplaceReference(Class type, String oid, + public static ObjectDelta createModificationReplaceReference(Class type, String oid, ItemPath refPath, PrismContext prismContext, PrismReferenceValue... refValues) { ObjectDelta objectDelta = new ObjectDelta(type, ChangeType.MODIFY, prismContext); objectDelta.setOid(oid); fillInModificationReplaceReference(objectDelta, refPath, refValues); return objectDelta; } - + public void addModificationReplaceProperty(QName propertyQName, X... propertyValues) { addModificationReplaceProperty(new ItemPath(propertyQName), propertyValues); } - + public void addModificationReplaceProperty(ItemPath propertyPath, X... propertyValues) { fillInModificationReplaceProperty(this, propertyPath, propertyValues); } @@ -876,67 +876,67 @@ public void addModificationReplaceReference(ItemPath refPath, PrismReference public void addModificationAddProperty(QName propertyQName, X... propertyValues) { addModificationAddProperty(new ItemPath(propertyQName), propertyValues); } - + public void addModificationAddProperty(ItemPath propertyPath, X... propertyValues) { fillInModificationAddProperty(this, propertyPath, propertyValues); } - + public void addModificationDeleteProperty(QName propertyQName, X... propertyValues) { addModificationDeleteProperty(new ItemPath(propertyQName), propertyValues); } - + public void addModificationDeleteProperty(ItemPath propertyPath, X... propertyValues) { fillInModificationDeleteProperty(this, propertyPath, propertyValues); } - + public void addModificationAddContainer(QName propertyQName, C... containerables) throws SchemaException { addModificationAddContainer(new ItemPath(propertyQName), containerables); } - + public void addModificationAddContainer(ItemPath propertyPath, C... containerables) throws SchemaException { fillInModificationAddContainer(this, propertyPath, prismContext, containerables); } - + public void addModificationAddContainer(QName propertyQName, PrismContainerValue... containerValues) { addModificationAddContainer(new ItemPath(propertyQName), containerValues); } - + public void addModificationAddContainer(ItemPath propertyPath, PrismContainerValue... containerValues) { fillInModificationAddContainer(this, propertyPath, containerValues); } - + public void addModificationDeleteContainer(QName propertyQName, C... containerables) throws SchemaException { addModificationDeleteContainer(new ItemPath(propertyQName), containerables); } - + public void addModificationDeleteContainer(ItemPath propertyPath, C... containerables) throws SchemaException { fillInModificationDeleteContainer(this, propertyPath, prismContext, containerables); } - + public void addModificationDeleteContainer(QName propertyQName, PrismContainerValue... containerValues) { addModificationDeleteContainer(new ItemPath(propertyQName), containerValues); } - + public void addModificationDeleteContainer(ItemPath propertyPath, PrismContainerValue... containerValues) { fillInModificationDeleteContainer(this, propertyPath, containerValues); } - + public void addModificationReplaceContainer(QName propertyQName, PrismContainerValue... containerValues) { addModificationReplaceContainer(new ItemPath(propertyQName), containerValues); } - + public void addModificationReplaceContainer(ItemPath propertyPath, PrismContainerValue... containerValues) { fillInModificationReplaceContainer(this, propertyPath, containerValues); } - - public static ObjectDelta createModificationReplaceContainer(Class type, String oid, + + public static ObjectDelta createModificationReplaceContainer(Class type, String oid, ItemPath propertyPath, PrismContext prismContext, C... containerValues) throws SchemaException { ObjectDelta objectDelta = new ObjectDelta(type, ChangeType.MODIFY, prismContext); objectDelta.setOid(oid); fillInModificationReplaceContainer(objectDelta, propertyPath, containerValues); return objectDelta; } - + protected static void fillInModificationReplaceProperty(ObjectDelta objectDelta, ItemPath propertyPath, X... propertyValues) { PropertyDelta propertyDelta = objectDelta.createPropertyModification(propertyPath); @@ -956,7 +956,7 @@ protected static void fillInModificationAddProperty(Ob objectDelta.addModification(propertyDelta); } } - + protected static void fillInModificationDeleteProperty(ObjectDelta objectDelta, ItemPath propertyPath, X... propertyValues) { PropertyDelta propertyDelta = objectDelta.createPropertyModification(propertyPath); @@ -970,15 +970,15 @@ protected static void fillInModificationDeleteProperty public void addModificationAddReference(QName propertyQName, PrismReferenceValue... refValues) { fillInModificationAddReference(this, new ItemPath(propertyQName), refValues); } - + public void addModificationDeleteReference(QName propertyQName, PrismReferenceValue... refValues) { fillInModificationDeleteReference(this, new ItemPath(propertyQName), refValues); } - + public void addModificationReplaceReference(QName propertyQName, PrismReferenceValue... refValues) { fillInModificationReplaceReference(this, new ItemPath(propertyQName), refValues); } - + protected static void fillInModificationReplaceReference(ObjectDelta objectDelta, ItemPath refPath, PrismReferenceValue... refValues) { ReferenceDelta refDelta = objectDelta.createReferenceModification(refPath); @@ -987,7 +987,7 @@ protected static void fillInModificationReplaceReference( objectDelta.addModification(refDelta); } } - + protected static void fillInModificationAddReference(ObjectDelta objectDelta, ItemPath refPath, PrismReferenceValue... refValues) { ReferenceDelta refDelta = objectDelta.createReferenceModification(refPath); @@ -1013,25 +1013,25 @@ private ReferenceDelta createReferenceModification(ItemPath refPath) { } - public static ObjectDelta createModificationAddContainer(Class type, String oid, + public static ObjectDelta createModificationAddContainer(Class type, String oid, QName propertyName, PrismContext prismContext, PrismContainerValue... containerValues) { return createModificationAddContainer(type, oid, new ItemPath(propertyName), prismContext, containerValues); } - - public static ObjectDelta createModificationAddContainer(Class type, String oid, + + public static ObjectDelta createModificationAddContainer(Class type, String oid, ItemPath propertyPath, PrismContext prismContext, PrismContainerValue... containerValues) { ObjectDelta objectDelta = new ObjectDelta(type, ChangeType.MODIFY, prismContext); objectDelta.setOid(oid); fillInModificationAddContainer(objectDelta, propertyPath, containerValues); return objectDelta; } - - public static ObjectDelta createModificationAddContainer(Class type, String oid, + + public static ObjectDelta createModificationAddContainer(Class type, String oid, QName propertyName, PrismContext prismContext, C... containerValues) throws SchemaException { return createModificationAddContainer(type, oid, new ItemPath(propertyName), prismContext, containerValues); } - - public static ObjectDelta createModificationAddContainer(Class type, String oid, + + public static ObjectDelta createModificationAddContainer(Class type, String oid, ItemPath propertyPath, PrismContext prismContext, C... containerValues) throws SchemaException { ObjectDelta objectDelta = new ObjectDelta(type, ChangeType.MODIFY, prismContext); objectDelta.setOid(oid); @@ -1044,12 +1044,12 @@ public static ObjectDelta cre fillInModificationAddContainer(objectDelta, propertyPath, containerPValues); return objectDelta; } - - public static ObjectDelta createModificationDeleteContainer(Class type, + + public static ObjectDelta createModificationDeleteContainer(Class type, String oid, QName containerName, PrismContext prismContext, PrismContainerValue... containerValues) { return createModificationDeleteContainer(type, oid, new ItemPath(containerName), prismContext, containerValues); } - + public static ObjectDelta createModificationDeleteContainer(Class type, String oid, ItemPath containerPath, PrismContext prismContext, PrismContainerValue... containerValues) { ObjectDelta objectDelta = new ObjectDelta(type, ChangeType.MODIFY, prismContext); @@ -1057,13 +1057,13 @@ public static ObjectDelta cre fillInModificationDeleteContainer(objectDelta, containerPath, containerValues); return objectDelta; } - - public static ObjectDelta createModificationDeleteContainer(Class type, String oid, + + public static ObjectDelta createModificationDeleteContainer(Class type, String oid, QName containerName, PrismContext prismContext, C... containerValues) throws SchemaException { return createModificationDeleteContainer(type, oid, new ItemPath(containerName), prismContext, containerValues); } - - public static ObjectDelta createModificationDeleteContainer(Class type, String oid, + + public static ObjectDelta createModificationDeleteContainer(Class type, String oid, ItemPath propertyPath, PrismContext prismContext, C... containerValues) throws SchemaException { ObjectDelta objectDelta = new ObjectDelta(type, ChangeType.MODIFY, prismContext); objectDelta.setOid(oid); @@ -1076,7 +1076,7 @@ public static ObjectDelta cre fillInModificationDeleteContainer(objectDelta, propertyPath, containerPValues); return objectDelta; } - + protected static void fillInModificationDeleteContainer(ObjectDelta objectDelta, ItemPath propertyPath, PrismContainerValue... containerValues) { ContainerDelta containerDelta = objectDelta.createContainerModification(propertyPath); @@ -1084,12 +1084,12 @@ protected static void fillInModi containerDelta.addValuesToDelete(containerValues); } } - - public static ObjectDelta createModificationReplaceContainer(Class type, + + public static ObjectDelta createModificationReplaceContainer(Class type, String oid, QName containerName, PrismContext prismContext, PrismContainerValue... containerValues) { return createModificationReplaceContainer(type, oid, new ItemPath(containerName), prismContext, containerValues); } - + public static ObjectDelta createModificationReplaceContainer(Class type, String oid, ItemPath containerPath, PrismContext prismContext, PrismContainerValue... containerValues) { ObjectDelta objectDelta = new ObjectDelta(type, ChangeType.MODIFY, prismContext); @@ -1097,12 +1097,12 @@ public static ObjectDelta cre fillInModificationReplaceContainer(objectDelta, containerPath, containerValues); return objectDelta; } - - public static ObjectDelta createModificationReplaceContainer(Class type, String oid, + + public static ObjectDelta createModificationReplaceContainer(Class type, String oid, QName propertyName, PrismContext prismContext, C... containerValues) throws SchemaException { return createModificationReplaceContainer(type, oid, new ItemPath(propertyName), prismContext, containerValues); } - + protected static void fillInModificationAddContainer(ObjectDelta objectDelta, ItemPath propertyPath, PrismContainerValue... containerValues) { ContainerDelta containerDelta = objectDelta.createContainerModification(propertyPath); @@ -1110,7 +1110,7 @@ protected static void fillInModi containerDelta.addValuesToAdd(containerValues); } } - + protected static void fillInModificationAddContainer(ObjectDelta objectDelta, ItemPath propertyPath, PrismContext prismContext, C... containerables) throws SchemaException { ContainerDelta containerDelta = objectDelta.createContainerModification(propertyPath); @@ -1122,7 +1122,7 @@ protected static void fillInModi } } } - + protected static void fillInModificationDeleteContainer(ObjectDelta objectDelta, ItemPath propertyPath, PrismContext prismContext, C... containerables) throws SchemaException { ContainerDelta containerDelta = objectDelta.createContainerModification(propertyPath); @@ -1134,7 +1134,7 @@ protected static void fillInModi } } } - + protected static void fillInModificationReplaceContainer(ObjectDelta objectDelta, ItemPath propertyPath, PrismContainerValue... containerValues) { ContainerDelta containerDelta = objectDelta.createContainerModification(propertyPath); @@ -1145,7 +1145,7 @@ protected static void fillInModi containerDelta.setValuesToReplace(); } } - + protected static void fillInModificationReplaceContainer(ObjectDelta objectDelta, ItemPath propertyPath, C... containerValues) throws SchemaException { if (containerValues != null) { @@ -1155,7 +1155,7 @@ protected static void fillInModi objectDelta.addModification(containerDelta); } } - + protected static Collection> toPrismPropertyValues(PrismContext prismContext, X... propertyValues) { Collection> pvalues = new ArrayList>(propertyValues.length); for (X val: propertyValues) { @@ -1165,7 +1165,7 @@ protected static Collection> toPrismPropertyValues(Pri } return pvalues; } - + protected static Collection> toPrismContainerValues(Class type, ItemPath path, PrismContext prismContext, C... containerValues) throws SchemaException { Collection> pvalues = new ArrayList>(containerValues.length); for (C val: containerValues) { @@ -1176,10 +1176,10 @@ protected static Collection ObjectDelta createModificationAddReference(Class type, String oid, QName propertyName, PrismContext prismContext, PrismObject... referenceObjects) { @@ -1206,10 +1206,10 @@ public static ObjectDelta createModificationAddReferen } return createModificationAddReference(type, oid, propertyName, prismContext, referenceValues); } - + /** * Convenience method for quick creation of object deltas that replace a single object property. This is used quite often - * to justify a separate method. + * to justify a separate method. */ public static ObjectDelta createModificationAddReference(Class type, String oid, QName propertyName, PrismContext prismContext, PrismReferenceValue... referenceValues) { @@ -1225,8 +1225,8 @@ public static ObjectDelta createModificationAddReferen referenceDelta.addValuesToAdd(valuesToAdd); return objectDelta; } - - + + public static ObjectDelta createModificationDeleteReference(Class type, String oid, QName propertyName, PrismContext prismContext, String... targetOids) { PrismReferenceValue[] referenceValues = new PrismReferenceValue[targetOids.length]; @@ -1235,10 +1235,10 @@ public static ObjectDelta createModificationDeleteRefe } return createModificationDeleteReference(type, oid, propertyName, prismContext, referenceValues); } - + /** * Convenience method for quick creation of object deltas that replace a single object property. This is used quite often - * to justify a separate method. + * to justify a separate method. */ public static ObjectDelta createModificationDeleteReference(Class type, String oid, QName propertyName, PrismContext prismContext, PrismReferenceValue... referenceValues) { @@ -1254,14 +1254,14 @@ public static ObjectDelta createModificationDeleteRefe referenceDelta.addValuesToDelete(valuesToDelete); return objectDelta; } - + public static ObjectDelta createModifyDelta(String oid, ItemDelta modification, Class objectTypeClass, PrismContext prismContext) { Collection modifications = new ArrayList(1); modifications.add(modification); return createModifyDelta(oid, modifications, objectTypeClass, prismContext); } - + public static ObjectDelta createModifyDelta(String oid, Collection modifications, Class objectTypeClass, PrismContext prismContext) { ObjectDelta objectDelta = new ObjectDelta(objectTypeClass, ChangeType.MODIFY, prismContext); @@ -1269,7 +1269,7 @@ public static ObjectDelta createModifyDelta(String oid objectDelta.setOid(oid); return objectDelta; } - + public static ObjectDelta createEmptyAddDelta(Class type, String oid, PrismContext prismContext) throws SchemaException { ObjectDelta objectDelta = createEmptyDelta(type, oid, prismContext, ChangeType.ADD); PrismObjectDefinition objDef = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(type); @@ -1286,26 +1286,26 @@ public static ObjectDelta createEmptyDeleteDelta(Class return createEmptyDelta(type, oid, prismContext, ChangeType.DELETE); } - public static ObjectDelta createEmptyDelta(Class type, String oid, PrismContext prismContext, + public static ObjectDelta createEmptyDelta(Class type, String oid, PrismContext prismContext, ChangeType changeType) { ObjectDelta objectDelta = new ObjectDelta(type, changeType, prismContext); objectDelta.setOid(oid); return objectDelta; } - + public static ObjectDelta createAddDelta(PrismObject objectToAdd) { ObjectDelta objectDelta = new ObjectDelta(objectToAdd.getCompileTimeClass(), ChangeType.ADD, objectToAdd.getPrismContext()); objectDelta.setOid(objectToAdd.getOid()); objectDelta.setObjectToAdd(objectToAdd); return objectDelta; } - + public static ObjectDelta createDeleteDelta(Class type, String oid, PrismContext prismContext) { ObjectDelta objectDelta = new ObjectDelta(type, ChangeType.DELETE, prismContext); objectDelta.setOid(oid); return objectDelta; } - + public ObjectDelta createReverseDelta() throws SchemaException { if (isAdd()) { return createDeleteDelta(getObjectTypeClass(), getOid(), getPrismContext()); @@ -1319,7 +1319,7 @@ public ObjectDelta createReverseDelta() throws SchemaException { } return reverseDelta; } - + public void checkConsistence() { checkConsistence(ConsistencyCheckScope.THOROUGH); } @@ -1331,7 +1331,7 @@ public void checkConsistence(ConsistencyCheckScope scope) { public void checkConsistence(boolean requireOid, boolean requireDefinition, boolean prohibitRaw) { checkConsistence(requireOid, requireDefinition, prohibitRaw, ConsistencyCheckScope.THOROUGH); } - + public void checkConsistence(boolean requireOid, boolean requireDefinition, boolean prohibitRaw, ConsistencyCheckScope scope) { if (scope.isThorough() && prismContext == null) { throw new IllegalStateException("No prism context in "+this); @@ -1372,7 +1372,7 @@ public void checkConsistence(boolean requireOid, boolean requireDefinition, bool throw new IllegalStateException("Unknown change type "+getChangeType()+" in delta "+this); } } - + protected void checkIdentifierConsistence(boolean requireOid) { if (requireOid && getOid() == null) { throw new IllegalStateException("Null oid in delta "+this); @@ -1384,19 +1384,19 @@ public static void checkConsistence(Collection> deltas) delta.checkConsistence(); } } - + public void assertDefinitions() throws SchemaException { assertDefinitions(""); } - + public void assertDefinitions(String sourceDescription) throws SchemaException { assertDefinitions(false, sourceDescription); } - + public void assertDefinitions(boolean tolerateRawElements) throws SchemaException { assertDefinitions(tolerateRawElements, ""); } - + /** * Assert that all the items has appropriate definition. */ @@ -1410,7 +1410,7 @@ public void assertDefinitions(boolean tolerateRawElements, String sourceDescript } } } - + public void revive(PrismContext prismContext) throws SchemaException { if (objectToAdd != null) { objectToAdd.revive(prismContext); @@ -1425,7 +1425,7 @@ public void revive(PrismContext prismContext) throws SchemaException { this.prismContext = prismContext; } } - + public void applyDefinition(PrismObjectDefinition objectDefinition, boolean force) throws SchemaException { if (objectToAdd != null) { objectToAdd.applyDefinition(objectDefinition, force); @@ -1459,7 +1459,7 @@ public boolean equivalent(ObjectDelta other) { return false; } else if (!objectToAdd.equivalent(other.objectToAdd)) return false; - if (!MiscUtil.unorderedCollectionEquals(this.modifications, other.modifications, + if (!MiscUtil.unorderedCollectionEquals(this.modifications, other.modifications, (o1, o2) -> o1.equivalent((ItemDelta)o2))) { return false; } @@ -1526,15 +1526,15 @@ public String toString() { sb.append(")"); return sb.toString(); } - + protected String debugName() { return "ObjectDelta"; } - + protected String debugIdentifiers() { return toDebugType()+":" + getOid(); } - + /** * Returns short string identification of object type. It should be in a form * suitable for log messages. There is no requirement for the type name to be unique, diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/PartiallyResolvedDelta.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/PartiallyResolvedDelta.java index a2c2b0222b3..42a78b70030 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/PartiallyResolvedDelta.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/PartiallyResolvedDelta.java @@ -26,10 +26,10 @@ * */ public class PartiallyResolvedDelta implements DebugDumpable { - + private ItemDelta delta; private ItemPath residualPath; - + public PartiallyResolvedDelta(ItemDelta itemDelta, ItemPath residualPath) { super(); this.delta = itemDelta; @@ -82,7 +82,7 @@ public boolean equals(Object obj) { return false; return true; } - + @Override public String debugDump() { return debugDump(0); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/PlusMinusZero.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/PlusMinusZero.java index 51a0ef8883d..f996326ea20 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/PlusMinusZero.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/PlusMinusZero.java @@ -18,14 +18,14 @@ /** * Simple enumeration that refers to the plus, minus or zero concepts * used in delta set triples. - * + * * @author Radovan Semancik * */ public enum PlusMinusZero { PLUS, MINUS, ZERO; - + public static PlusMinusZero compute(PlusMinusZero mode1, PlusMinusZero mode2) { if (mode1 == null || mode2 == null) { return null; diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/PrismValueDeltaSetTriple.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/PrismValueDeltaSetTriple.java index 4d3bcbeed18..96da348dbb1 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/PrismValueDeltaSetTriple.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/PrismValueDeltaSetTriple.java @@ -33,11 +33,11 @@ /** * DeltaSetTriple that is limited to hold prism values. By limiting to the PrismValue descendants we gain advantage to be - * clonnable and ability to compare real values. + * clonnable and ability to compare real values. * * @author Radovan Semancik */ -public class PrismValueDeltaSetTriple extends DeltaSetTriple +public class PrismValueDeltaSetTriple extends DeltaSetTriple implements DebugDumpable, Visitable { public PrismValueDeltaSetTriple() { @@ -47,7 +47,7 @@ public PrismValueDeltaSetTriple() { public PrismValueDeltaSetTriple(Collection zeroSet, Collection plusSet, Collection minusSet) { super(zeroSet, plusSet, minusSet); } - + /** * Compares two (unordered) collections and creates a triple describing the differences. */ @@ -73,7 +73,7 @@ public void distributeAs(V myMember, PrismValueDeltaSetTr minusSet.add(myMember); } } - + public Class getValueClass() { V anyValue = getAnyValue(); if (anyValue == null) { @@ -81,7 +81,7 @@ public Class getValueClass() { } return (Class) anyValue.getClass(); } - + public Class getRealValueClass() { V anyValue = getAnyValue(); if (anyValue == null) { @@ -114,7 +114,7 @@ private boolean isRaw(Collection set) { } return false; } - + public void applyDefinition(ItemDefinition itemDefinition) throws SchemaException { applyDefinition(zeroSet, itemDefinition); applyDefinition(plusSet, itemDefinition); @@ -129,7 +129,7 @@ private void applyDefinition(Collection set, ItemDefinition itemDefinition) t item.applyDefinition(itemDefinition); } } - + /** * Sets specified source type for all values in all sets */ @@ -146,7 +146,7 @@ private void setOriginType(Collection set, OriginType sourceType) { } } } - + /** * Sets specified origin object for all values in all sets */ @@ -163,7 +163,7 @@ private void setOriginObject(Collection set, Objectable originObject) { } } } - + public void removeEmptyValues(boolean allowEmptyValues) { removeEmptyValues(plusSet, allowEmptyValues); removeEmptyValues(zeroSet, allowEmptyValues); @@ -210,7 +210,7 @@ public PrismValueDeltaSetTriple clone() { protected void copyValues(PrismValueDeltaSetTriple clone) { super.copyValues(clone, original -> (V) original.clone()); } - + public void checkConsistence() { Visitor visitor = visitable -> { if (visitable instanceof PrismValue) { @@ -220,7 +220,7 @@ public void checkConsistence() { } }; accept(visitor); - + Processor processor = pval -> { if (pval.getParent() != null) { throw new IllegalStateException("Value "+pval+" in triple "+PrismValueDeltaSetTriple.this+" has parent, looks like it was not cloned properly"); @@ -228,7 +228,7 @@ public void checkConsistence() { }; foreach(processor); } - + @Override public void accept(Visitor visitor) { acceptSet(zeroSet, visitor); @@ -244,13 +244,13 @@ private void acceptSet(Collection set, Visitor visitor) { val.accept(visitor); } } - + public void checkNoParent() { checkNoParent(zeroSet, "zero"); checkNoParent(plusSet, "plus"); checkNoParent(minusSet, "minus"); } - + private void checkNoParent(Collection set, String desc) { if (set == null) { return; @@ -261,7 +261,7 @@ private void checkNoParent(Collection set, String desc) { } } } - + protected String debugName() { return "PVDeltaSetTriple"; } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/PropertyDelta.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/PropertyDelta.java index fa37a8a1f67..958431b0d8d 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/PropertyDelta.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/PropertyDelta.java @@ -39,7 +39,7 @@ /** * Relative difference (delta) of a property values. - *

+ *

* This class describes what values are to be added, removed or replaced in the property. * The delta can be either add+delete or replace, but not both. It either describes what * values to add and delete from the property (add+delete) or what is the new set of values @@ -50,12 +50,12 @@ * @author Radovan Semancik * @see ObjectDelta */ -public class PropertyDelta extends ItemDelta,PrismPropertyDefinition> { +public class PropertyDelta extends ItemDelta, PrismPropertyDefinition> { public PropertyDelta(PrismPropertyDefinition propertyDefinition, PrismContext prismContext) { super(propertyDefinition, prismContext); } - + public PropertyDelta(QName name, PrismPropertyDefinition propertyDefinition, PrismContext prismContext) { super(name, propertyDefinition, prismContext); } @@ -67,7 +67,7 @@ public PropertyDelta(ItemPath parentPath, QName name, PrismPropertyDefinition public PropertyDelta(ItemPath propertyPath, PrismPropertyDefinition propertyDefinition, PrismContext prismContext) { super(propertyPath, propertyDefinition, prismContext); } - + public PrismPropertyDefinition getPropertyDefinition() { return super.getDefinition(); } @@ -75,7 +75,7 @@ public PrismPropertyDefinition getPropertyDefinition() { void setPropertyDefinition(PrismPropertyDefinition propertyDefinition) { super.setDefinition(propertyDefinition); } - + @Override public void setDefinition(PrismPropertyDefinition definition) { if (!(definition instanceof PrismPropertyDefinition)) { @@ -107,13 +107,13 @@ public Collection> getValues(Class type) { } return (Collection) MiscUtil.union(valuesToAdd, valuesToDelete); } - + public T getAnyRealValue() { PrismPropertyValue anyValue = getAnyValue(); return anyValue.getValue(); } - + public

P instantiateEmptyProperty() { PrismPropertyDefinition propertyDefinition = getPropertyDefinition(); if (propertyDefinition == null) { @@ -121,12 +121,12 @@ public

P instantiateEmptyProperty() { } return (P) propertyDefinition.instantiate(getElementName()); } - + @Override protected boolean isApplicableToType(Item item) { return item instanceof PrismProperty; } - + @Override public PropertyDelta clone() { PropertyDelta clone = new PropertyDelta(getElementName(), getPropertyDefinition(), getPrismContext()); @@ -156,7 +156,7 @@ public static PropertyDelta createReplaceDelta(Pris delta.setValuesToReplace(valuesToReplace); return delta; } - + public static PropertyDelta createReplaceDelta(PrismContainerDefinition containerDefinition, QName propertyName, PrismPropertyValue... pValues) { PrismPropertyDefinition propertyDefinition = containerDefinition.findPropertyDefinition(propertyName); @@ -222,10 +222,10 @@ public static PropertyDelta createReplaceEmptyDelta(Prism delta.setValuesToReplace(new ArrayList()); return delta; } - + public static PropertyDelta createReplaceDeltaOrEmptyDelta(PrismObjectDefinition objectDefinition, QName propertyName, T realValue) { - + if (realValue != null) return createReplaceDelta(objectDefinition, propertyName, realValue); else @@ -245,7 +245,7 @@ public boolean isRealValueToAdd(PrismPropertyValue value) { } return false; } - + public boolean isRealValueToDelete(PrismPropertyValue value) { if (valuesToDelete == null) { return false; @@ -267,7 +267,7 @@ public boolean isRealValueToDelete(PrismPropertyValue value) { public PrismProperty getPropertyNewMatchingPath() throws SchemaException { return (PrismProperty) super.getItemNewMatchingPath(null); } - + /** * Returns the "new" state of the property - the state that would be after the delta * is applied. @@ -275,12 +275,12 @@ public PrismProperty getPropertyNewMatchingPath() throws SchemaException { public PrismProperty getPropertyNewMatchingPath(PrismProperty propertyOld) throws SchemaException { return (PrismProperty) super.getItemNewMatchingPath(propertyOld); } - + @Override public PropertyDelta narrow(PrismObject object) { return (PropertyDelta) super.narrow(object); } - + public PropertyDelta narrow(PrismObject object, final MatchingRule matchingRule) { Comparator> comparator = (o1, o2) -> { if (o1.equalsComplex(o2, true, false, matchingRule)) { @@ -302,7 +302,7 @@ public boolean isRedundant(PrismObject object, final Match }; return super.isRedundant(object, comparator); } - + public static PropertyDelta createDelta(QName propertyName, PrismObjectDefinition objectDefinition) { return createDelta(new ItemPath(propertyName), objectDefinition); } @@ -311,27 +311,27 @@ public static PropertyDelta createDelta(ItemPath pro PrismPropertyDefinition propDef = objectDefinition.findPropertyDefinition(propertyPath); return new PropertyDelta(propertyPath, propDef, objectDefinition.getPrismContext()); // hoping the prismContext is there } - + public static PropertyDelta createDelta(QName propertyName, Class compileTimeClass, PrismContext prismContext) { return createDelta(new ItemPath(propertyName), compileTimeClass, prismContext); } - + public static PropertyDelta createDelta(ItemPath propertyPath, Class compileTimeClass, PrismContext prismContext) { PrismObjectDefinition objectDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(compileTimeClass); PrismPropertyDefinition propDef = objectDefinition.findPropertyDefinition(propertyPath); return new PropertyDelta(propertyPath, propDef, prismContext); } - - public static PropertyDelta createModificationReplaceProperty(QName propertyName, PrismObjectDefinition objectDefinition, + + public static PropertyDelta createModificationReplaceProperty(QName propertyName, PrismObjectDefinition objectDefinition, T... propertyValues) { return createModificationReplaceProperty(new ItemPath(propertyName), objectDefinition, propertyValues); } - + /** * Convenience method for quick creation of object deltas that replace a single object property. This is used quite often - * to justify a separate method. + * to justify a separate method. */ - public static PropertyDelta createModificationReplaceProperty(ItemPath propertyPath, PrismObjectDefinition objectDefinition, + public static PropertyDelta createModificationReplaceProperty(ItemPath propertyPath, PrismObjectDefinition objectDefinition, T... propertyValues) { PrismPropertyDefinition propDef = objectDefinition.findPropertyDefinition(propertyPath); PropertyDelta propertyDelta = new PropertyDelta(propertyPath, propDef, objectDefinition.getPrismContext()); // hoping the prismContext is there @@ -354,8 +354,8 @@ public static PropertyDelta createModificationReplaceProperty(ItemPath pr propertyDelta.setValuesToReplace(pValues); return propertyDelta; } - - public static PropertyDelta createModificationReplaceProperty(ItemPath propertyPath, PrismPropertyDefinition propertyDefinition, + + public static PropertyDelta createModificationReplaceProperty(ItemPath propertyPath, PrismPropertyDefinition propertyDefinition, T... propertyValues) { PropertyDelta propertyDelta = new PropertyDelta(propertyPath, propertyDefinition, propertyDefinition.getPrismContext()); // hoping the prismContext is there Collection> pValues = new ArrayList>(propertyValues.length); @@ -365,8 +365,8 @@ public static PropertyDelta createModificationReplaceProperty(ItemPath pr propertyDelta.setValuesToReplace(pValues); return propertyDelta; } - - public static PropertyDelta createModificationAddProperty(ItemPath propertyPath, PrismPropertyDefinition propertyDefinition, + + public static PropertyDelta createModificationAddProperty(ItemPath propertyPath, PrismPropertyDefinition propertyDefinition, T... propertyValues) { PropertyDelta propertyDelta = new PropertyDelta(propertyPath, propertyDefinition, propertyDefinition.getPrismContext()); // hoping the prismContext is there Collection> pValues = new ArrayList>(propertyValues.length); @@ -376,8 +376,8 @@ public static PropertyDelta createModificationAddProperty(ItemPath proper propertyDelta.addValuesToAdd(pValues); return propertyDelta; } - - public static PropertyDelta createModificationDeleteProperty(ItemPath propertyPath, PrismPropertyDefinition propertyDefinition, + + public static PropertyDelta createModificationDeleteProperty(ItemPath propertyPath, PrismPropertyDefinition propertyDefinition, T... propertyValues) { PropertyDelta propertyDelta = new PropertyDelta(propertyPath, propertyDefinition, propertyDefinition.getPrismContext()); // hoping the prismContext is there Collection> pValues = new ArrayList>(propertyValues.length); @@ -390,9 +390,9 @@ public static PropertyDelta createModificationDeleteProperty(ItemPath pro /** * Convenience method for quick creation of object deltas that replace a single object property. This is used quite often - * to justify a separate method. + * to justify a separate method. */ - public static Collection createModificationReplacePropertyCollection(QName propertyName, + public static Collection createModificationReplacePropertyCollection(QName propertyName, PrismObjectDefinition objectDefinition, Object... propertyValues) { Collection modifications = new ArrayList(1); PropertyDelta delta = createModificationReplaceProperty(propertyName, objectDefinition, propertyValues); @@ -408,7 +408,7 @@ public static PropertyDelta findPropertyDelta(Collection PropertyDelta findPropertyDelta(Collection modifications, QName propertyName) { for (ItemDelta delta: modifications) { if (delta instanceof PropertyDelta && delta.getParentPath().isEmpty() && diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ReferenceDelta.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ReferenceDelta.java index 6cfd69dc95b..35c87e30675 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ReferenceDelta.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/delta/ReferenceDelta.java @@ -52,7 +52,7 @@ public ReferenceDelta(ItemPath parentPath, QName name, PrismReferenceDefinition public ReferenceDelta(QName name, PrismReferenceDefinition itemDefinition, PrismContext prismContext) { super(name, itemDefinition, prismContext); } - + @Override public Class getItemClass() { return PrismReference.class; @@ -73,26 +73,26 @@ public void applyDefinition(PrismReferenceDefinition definition) throws SchemaEx } super.applyDefinition(definition); } - + @Override protected boolean isApplicableToType(Item item) { return item instanceof PrismReference; } - + @Override public ReferenceDelta clone() { ReferenceDelta clone = new ReferenceDelta(getPath(), (PrismReferenceDefinition)getDefinition(), getPrismContext()); copyValues(clone); return clone; } - + protected void copyValues(ReferenceDelta clone) { super.copyValues(clone); } /** * Convenience method for quick creation of object deltas that replace a single object property. This is used quite often - * to justify a separate method. + * to justify a separate method. */ public static Collection createModificationReplaceCollection(QName propertyName, PrismObjectDefinition objectDefinition, PrismReferenceValue refValue) { @@ -101,11 +101,11 @@ public static Collection createModificationReplaceCollectio ((Collection)modifications).add(delta); return modifications; } - + public static ReferenceDelta createModificationReplace(QName refName, PrismObjectDefinition objectDefinition, String oid) { return createModificationReplace(refName, objectDefinition, new PrismReferenceValue(oid)); } - + public static ReferenceDelta createModificationReplace(ItemPath path, PrismObjectDefinition objectDefinition, String oid) { return createModificationReplace(path, objectDefinition, new PrismReferenceValue(oid)); } @@ -114,7 +114,7 @@ public static ReferenceDelta createModificationReplace(QN PrismObjectDefinition objectDefinition = ctx.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(type); return createModificationReplace(refName, objectDefinition, oid==null?null:new PrismReferenceValue(oid)); } - + public static ReferenceDelta createModificationReplace(ItemPath path, Class type, PrismContext ctx, String oid) { PrismObjectDefinition objectDefinition = ctx.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(type); return createModificationReplace(path, objectDefinition, oid==null?null:new PrismReferenceValue(oid)); @@ -139,7 +139,7 @@ public static ReferenceDelta createModificationReplace(ItemPath path, PrismObjec referenceDelta.setValuesToReplace(refValues); return referenceDelta; } - + public static ReferenceDelta createModificationReplace(QName refName, PrismObjectDefinition objectDefinition, PrismReferenceValue refValue) { PrismReferenceDefinition referenceDefinition = objectDefinition.findItemDefinition(refName, PrismReferenceDefinition.class); @@ -159,7 +159,7 @@ public static Collection createModificationAddCollection(QN ((Collection)modifications).add(delta); return modifications; } - + private static Collection> createModificationsCollection(int initSize) { return new ArrayList>(initSize); } @@ -203,15 +203,15 @@ public static ReferenceDelta createModificationAdd(Class< PrismObjectDefinition objectDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(type); return createModificationAdd(refName, objectDefinition, refValue); } - + public static Collection createModificationAddCollection(Class type, QName refName, PrismContext prismContext, - String targetOid) { + String targetOid) { PrismReferenceValue refValue = new PrismReferenceValue(targetOid); return createModificationAddCollection(type, refName, prismContext, refValue ); } - + public static Collection createModificationAddCollection(Class type, QName refName, PrismContext prismContext, - PrismReferenceValue refValue) { + PrismReferenceValue refValue) { Collection> modifications = createModificationsCollection(1); ReferenceDelta delta = createModificationAdd(type, refName, prismContext, refValue); ((Collection)modifications).add(delta); @@ -225,13 +225,13 @@ public static ReferenceDelta createModificationAdd(Class< } public static Collection createModificationAddCollection(Class type, QName refName, PrismContext prismContext, - PrismObject refTarget) { + PrismObject refTarget) { Collection> modifications = createModificationsCollection(1); ReferenceDelta delta = createModificationAdd(type, refName, prismContext, refTarget); ((Collection)modifications).add(delta); return modifications; } - + public static Collection createModificationDeleteCollection(QName propertyName, PrismObjectDefinition objectDefinition, PrismReferenceValue refValue) { Collection modifications = new ArrayList(1); @@ -252,8 +252,8 @@ public static ReferenceDelta createModificationDelete(QName refName, PrismObject String oid) { return createModificationDelete(refName, objectDefinition, new PrismReferenceValue(oid)); } - - + + public static ReferenceDelta createModificationDelete(QName refName, PrismObjectDefinition objectDefinition, PrismObject refTarget) { PrismReferenceValue refValue = PrismReferenceValue.createFromTarget(refTarget); @@ -267,15 +267,15 @@ public static ReferenceDelta createModificationDelete(QName refName, PrismObject referenceDelta.addValueToDelete(refValue); return referenceDelta; } - + public static ReferenceDelta createModificationDelete(Class type, QName refName, PrismContext prismContext, PrismReferenceValue refValue) { PrismObjectDefinition objectDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(type); return createModificationDelete(refName, objectDefinition, refValue); } - + public static Collection createModificationDeleteCollection(Class type, QName refName, PrismContext prismContext, - PrismReferenceValue refValue) { + PrismReferenceValue refValue) { Collection> modifications = createModificationsCollection(1); ReferenceDelta delta = createModificationDelete(type, refName, prismContext, refValue); ((Collection)modifications).add(delta); @@ -292,9 +292,9 @@ public static ReferenceDelta createModificationDelete(Cla PrismReferenceValue refValue = PrismReferenceValue.createFromTarget(refTarget); return createModificationDelete(type, refName, refTarget.getPrismContext(), refValue); } - + public static Collection createModificationDeleteCollection(Class type, QName refName, PrismContext prismContext, - PrismObject refTarget) { + PrismObject refTarget) { Collection> modifications = createModificationsCollection(1); ReferenceDelta delta = createModificationDelete(type, refName, prismContext, refTarget); ((Collection)modifications).add(delta); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/dom/DomLexicalProcessor.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/dom/DomLexicalProcessor.java index 7761fe70a99..7381066c44a 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/dom/DomLexicalProcessor.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/dom/DomLexicalProcessor.java @@ -66,7 +66,7 @@ public class DomLexicalProcessor implements LexicalProcessor { public DomLexicalProcessor(@NotNull SchemaRegistry schemaRegistry) { this.schemaRegistry = schemaRegistry; } - + @Deprecated public XNode read(File file, ParsingContext parsingContext) throws SchemaException, IOException { return read(new ParserFileSource(file), parsingContext); @@ -184,7 +184,7 @@ public RootXNode read(Element rootElement) throws SchemaException { xroot.setSubnode(xnode); return xroot; } - + private void extractCommonMetadata(Element element, XNode xnode) throws SchemaException { QName xsiType = DOMUtil.resolveXsiType(element); if (xsiType != null) { @@ -200,7 +200,7 @@ private void extractCommonMetadata(Element element, XNode xnode) throws SchemaEx xnode.setMaxOccurs(maxOccurs); } } - + private int parseMultiplicity(String maxOccursString, Element element) throws SchemaException { if (PrismConstants.MULTIPLICITY_UNBONUNDED.equals(maxOccursString)) { return -1; @@ -423,11 +423,11 @@ public String toString() { return "ValueParser(DOMe, "+PrettyPrinter.prettyPrint(DOMUtil.getQName(element))+": "+element.getTextContent()+")"; } } - + private static class PrimitiveAttributeParser implements ValueParser, Serializable { - + private Attr attr; - + public PrimitiveAttributeParser(Attr attr) { this.attr = attr; } @@ -463,7 +463,7 @@ private PrimitiveXNode parsePrimitiveElement(final Element element) throw xnode.setValueParser(new PrimitiveValueParser<>(element)); return xnode; } - + private static T parsePrimitiveElementValue(Element element, QName typeName, XNodeProcessorEvaluationMode mode) throws SchemaException { try { if (ItemPathType.COMPLEX_TYPE.equals(typeName)) { @@ -622,7 +622,7 @@ private Element serializeToElement(XNode xnode, QName elementName) throws Schema throw new IllegalArgumentException("Cannot serialized "+xnode+" to element"); } } - + public Element serializeSingleElementMapToElement(MapXNode xmap) throws SchemaException { if (xmap == null || xmap.isEmpty()) { return null; @@ -632,5 +632,5 @@ public Element serializeSingleElementMapToElement(MapXNode xmap) throws SchemaEx return DOMUtil.getFirstChildElement(parent); } - + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/dom/DomLexicalWriter.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/dom/DomLexicalWriter.java index 2af2d755f23..b4b1d1a1ff8 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/dom/DomLexicalWriter.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/dom/DomLexicalWriter.java @@ -48,7 +48,7 @@ * */ public class DomLexicalWriter { - + private Document doc; private boolean serializeCompositeObjects = false; private SchemaRegistry schemaRegistry; @@ -109,7 +109,7 @@ public Element serialize(RootXNode rootxnode, Document document) throws SchemaEx initializeWithExistingDocument(document); return serializeInternal(rootxnode, null); } - + public Element serializeUnderElement(RootXNode rootxnode, Element parentElement) throws SchemaException { initializeWithExistingDocument(parentElement.getOwnerDocument()); return serializeInternal(rootxnode, parentElement); @@ -170,7 +170,7 @@ Element serializeToElement(MapXNode xmap, QName elementName) throws SchemaExcept serializeMap(xmap, element); return element; } - + private void serializeMap(MapXNode xmap, Element topElement) throws SchemaException { for (Entry entry: xmap.entrySet()) { QName elementQName = entry.getKey(); @@ -178,7 +178,7 @@ private void serializeMap(MapXNode xmap, Element topElement) throws SchemaExcept serializeSubnode(xsubnode, topElement, elementQName); } } - + private void serializeSubnode(XNode xsubnode, Element parentElement, QName elementName) throws SchemaException { if (xsubnode == null) { return; @@ -392,7 +392,7 @@ private QName setQNamePrefixExplicitIfNeeded(QName name) { return name; } } - + private QName setQNamePrefixExplicit(QName qname) { DynamicNamespacePrefixMapper namespacePrefixMapper = getNamespacePrefixMapper(); if (namespacePrefixMapper == null) { diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/AbstractJsonLexicalProcessor.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/AbstractJsonLexicalProcessor.java index 5233b4cf91f..e385d7e96e5 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/AbstractJsonLexicalProcessor.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/AbstractJsonLexicalProcessor.java @@ -57,7 +57,7 @@ public abstract class AbstractJsonLexicalProcessor implements LexicalProcessor { private static final Trace LOGGER = TraceManager.getTrace(AbstractJsonLexicalProcessor.class); - + private static final String PROP_NAMESPACE = "@ns"; private static final String PROP_TYPE = "@type"; private static final String PROP_ELEMENT = "@element"; @@ -883,11 +883,11 @@ private String serializeNsIfNeeded(QName subNodeName, String globalNamespace, Js if (!subNodeNs.equals(globalNamespace)){ globalNamespace = subNodeNs; generator.writeStringField(PROP_NAMESPACE, globalNamespace); - + } } return globalNamespace; } //endregion - + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/DomElementSerializer.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/DomElementSerializer.java index b1ca413826b..eaeb52c6149 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/DomElementSerializer.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/DomElementSerializer.java @@ -11,7 +11,7 @@ import com.fasterxml.jackson.databind.jsontype.TypeSerializer; public class DomElementSerializer extends DOMSerializer { - + @Override public void serializeWithType(Node value, JsonGenerator jgen, SerializerProvider provider, TypeSerializer typeSer) throws IOException, JsonProcessingException { diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/ItemPathDeserializer.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/ItemPathDeserializer.java index 070893b8fce..f993eb897e0 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/ItemPathDeserializer.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/ItemPathDeserializer.java @@ -40,7 +40,7 @@ public ItemPath deserialize(JsonParser jp, DeserializationContext ctxt) throws I // if (pathItems.length == 1){ // return new ItemPath(QNameUtil.nullNamespace(pathItems[0])); // } -// +// // } else // } // return new ItemPath(new QName("http://midpoint.evolveum.com/xml/ns/test/foo-1.xsd", "name")); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/ItemPathSerializer.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/ItemPathSerializer.java index 494a0c06d83..c6c60d134ec 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/ItemPathSerializer.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/ItemPathSerializer.java @@ -16,9 +16,9 @@ public void serialize(ItemPath value, JsonGenerator jgen, SerializerProvider pro ItemPathHolder xpath = new ItemPathHolder(value, true); String path = xpath.getXPathWithDeclarations(); jgen.writeObject(path); - + } - + @Override public void serializeWithType(ItemPath value, JsonGenerator jgen, SerializerProvider provider, TypeSerializer typeSer) throws IOException { diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/ItemPathTypeDeserializer.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/ItemPathTypeDeserializer.java index 31836407aad..7aaf0ea06e7 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/ItemPathTypeDeserializer.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/ItemPathTypeDeserializer.java @@ -23,7 +23,7 @@ public ItemPathType deserialize(JsonParser jp, DeserializationContext ctxt) thro //System.out.println("current t: " +jp.getCurrentToken()); //System.out.println("cuuretn nmae " + jp.getCurrentName()); //System.out.println("item path type: " + jp.getText()); - + if (jp.getCurrentToken() != JsonToken.VALUE_STRING){ throw new JsonParseException("Cannot parse path value. Expected that the value will be string but it is: " + jp.getCurrentTokenId(), jp.getCurrentLocation()); } @@ -39,7 +39,7 @@ public ItemPathType deserialize(JsonParser jp, DeserializationContext ctxt) thro return itemPathType; // ItemPathType itemPathType = new ItemPathType(); // itemPathType.getContent().add(jp.getText()); -// +// // return itemPathType; } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/ItemPathTypeSerializer.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/ItemPathTypeSerializer.java index 682c66c4c2a..1b2c331ba6e 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/ItemPathTypeSerializer.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/ItemPathTypeSerializer.java @@ -33,9 +33,9 @@ public void serialize(@NotNull ItemPathType value, JsonGenerator jgen, Serialize ItemPathHolder xpath = new ItemPathHolder(value.getItemPath(), true); String path = xpath.getXPathWithDeclarations(); jgen.writeObject(path); - + } - + @Override public void serializeWithType(@NotNull ItemPathType value, JsonGenerator jgen, SerializerProvider provider, TypeSerializer typeSer) throws IOException { diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/JsonLexicalProcessor.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/JsonLexicalProcessor.java index 747a275a165..388e30e0ac6 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/JsonLexicalProcessor.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/JsonLexicalProcessor.java @@ -55,7 +55,7 @@ public boolean canRead(@NotNull File file) throws IOException { public boolean canRead(@NotNull String dataString) { return dataString.startsWith("{"); } - + @Override protected com.fasterxml.jackson.core.JsonParser createJacksonParser(InputStream stream) throws SchemaException, IOException { JsonFactory factory = new JsonFactory(); @@ -75,14 +75,14 @@ private JsonGenerator createJsonGenerator(StringWriter out) throws SchemaExcepti JsonGenerator generator = factory.createGenerator(out); generator.setPrettyPrinter(new DefaultPrettyPrinter()); generator.setCodec(configureMapperForSerialization()); - + return generator; } catch (IOException ex){ throw new SchemaException("Schema error during serializing to JSON.", ex); } } - + private ObjectMapper configureMapperForSerialization(){ ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); @@ -91,9 +91,9 @@ private ObjectMapper configureMapperForSerialization(){ mapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector()); return mapper; } - + private Module createSerializerModule(){ - SimpleModule module = new SimpleModule("MidpointModule", new Version(0, 0, 0, "aa")); + SimpleModule module = new SimpleModule("MidpointModule", new Version(0, 0, 0, "aa")); module.addSerializer(QName.class, new QNameSerializer()); module.addSerializer(PolyString.class, new PolyStringSerializer()); module.addSerializer(ItemPath.class, new ItemPathSerializer()); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/JsonNullValueParser.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/JsonNullValueParser.java index d103bfbb5d9..dc51b5a2c63 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/JsonNullValueParser.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/JsonNullValueParser.java @@ -31,7 +31,7 @@ public class JsonNullValueParser implements ValueParser { public JsonNullValueParser() { } - + @Override public T parse(QName typeName, XNodeProcessorEvaluationMode mode) throws SchemaException { Class clazz = XsdTypeMapper.toJavaType(typeName); @@ -40,7 +40,7 @@ public T parse(QName typeName, XNodeProcessorEvaluationMode mode) throws SchemaE } return (T) JavaTypeConverter.convert(clazz, ""); } - + @Override public boolean isEmpty() { return true; diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/JsonValueParser.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/JsonValueParser.java index 2edf199a42e..819eb8b430d 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/JsonValueParser.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/JsonValueParser.java @@ -22,12 +22,12 @@ public class JsonValueParser implements ValueParser { @NotNull private final JsonParser parser; private JsonNode node; - + public JsonValueParser(@NotNull JsonParser parser, JsonNode node) { this.parser = parser; this.node = node; } - + @NotNull public JsonParser getParser() { return parser; @@ -46,7 +46,7 @@ public T parse(QName typeName, XNodeProcessorEvaluationMode mode) throws SchemaE throw new SchemaException("Cannot parse value: " + e.getMessage(), e); } } - + @Override public boolean isEmpty() { return node == null || StringUtils.isBlank(node.asText()); // to be consistent with PrimitiveXNode.isEmpty for parsed values diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/PolyStringDeserializer.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/PolyStringDeserializer.java index 540fa8c5df1..8c76cf5590c 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/PolyStringDeserializer.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/PolyStringDeserializer.java @@ -21,5 +21,5 @@ public PolyString deserialize(JsonParser jp, DeserializationContext ctxt) throws return new PolyString(str); } - + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/PolyStringSerializer.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/PolyStringSerializer.java index f58fa60d494..d3c45f2157e 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/PolyStringSerializer.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/PolyStringSerializer.java @@ -19,15 +19,15 @@ public void serialize(PolyString value, JsonGenerator jgen, SerializerProvider p jgen.writeObject(value.getOrig()); // jgen.writeStringField("norm", value.getNorm()); // jgen.writeEndObject(); - + } - + @Override public void serializeWithType(PolyString value, JsonGenerator jgen, SerializerProvider provider, TypeSerializer typeSer) throws IOException, JsonProcessingException { // TODO Auto-generated method stub //System.out.println("polystring serialization with type"); - + // typeSer.writeCustomTypePrefixForScalar(value, jgen, "poluStr"); serialize(value, jgen, provider); // typeSer.writeCustomTypeSuffixForScalar(value, jgen, "tra"); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/QNameDeserializer.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/QNameDeserializer.java index 53f516486d9..5eb37c189a2 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/QNameDeserializer.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/QNameDeserializer.java @@ -20,12 +20,12 @@ public QName deserialize(JsonParser jp, DeserializationContext ctxt) throws IOEx JsonProcessingException { //System.out.println("tralalaaaaa QName deserializer"); // Object ob = jp.getEmbeddedObject(); - + // JsonNode node = jp.getCodec().readTree(jp); // JsonNode node = (JsonNode) ob; // TreeTraversingParser treeParser = (TreeTraversingParser) jp; // if (jp.getCurrentToken() == JsonToken.START_OBJECT){ - + // } // jp. ObjectMapper m = new ObjectMapper(); @@ -43,30 +43,30 @@ public QName deserialize(JsonParser jp, DeserializationContext ctxt) throws IOEx throw new IllegalStateException(); // break; } - + } - + private QName deserializeFromObject(JsonNode node){ JsonNode qnameNode = node.get("@namespace"); String namespace = null; if (qnameNode != null){ namespace = qnameNode.asText(); } - + qnameNode = node.get("@localPart"); String localPart = null; if (qnameNode != null){ localPart = qnameNode.asText(); - } + } return new QName(namespace, localPart); } - + private QName deserializeFromString(JsonNode node){ String qnameUri = node.asText(); return QNameUtil.uriToQName(qnameUri, true); // return new QName(node.asText()); } - + @Override public Object deserializeWithType(JsonParser jp, DeserializationContext ctxt, TypeDeserializer typeDeserializer) throws IOException, JsonProcessingException { diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/QNameSerializer.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/QNameSerializer.java index 381426c3365..d9532cf08cc 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/QNameSerializer.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/QNameSerializer.java @@ -22,5 +22,5 @@ public void serializeWithType(QName value, JsonGenerator jgen, SerializerProvide TypeSerializer typeSer) throws IOException { serialize(value, jgen, provider); } - + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/YamlLexicalProcessor.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/YamlLexicalProcessor.java index bd49c57ad1f..1e47d909d3a 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/YamlLexicalProcessor.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/YamlLexicalProcessor.java @@ -66,7 +66,7 @@ public boolean canRead(@NotNull File file) throws IOException { public boolean canRead(@NotNull String dataString) { return dataString.startsWith("---"); } - + public YAMLGenerator createJacksonGenerator(StringWriter out) throws SchemaException{ try { MidpointYAMLFactory factory = new MidpointYAMLFactory(); @@ -78,7 +78,7 @@ public YAMLGenerator createJacksonGenerator(StringWriter out) throws SchemaExcep throw new SchemaException("Schema error during serializing to JSON.", ex); } } - + private ObjectMapper configureMapperForSerialization(){ ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); @@ -93,12 +93,12 @@ private ObjectMapper configureMapperForSerialization(){ // mapper.enableDefaultTyping(DefaultTyping.NON_FINAL, As.EXISTING_PROPERTY); // //mapper.enableDefaultTyping(DefaultTyping.NON_FINAL, As.EXTERNAL_PROPERTY); // mapper.enableDefaultTyping(DefaultTyping.NON_FINAL, As.PROPERTY); - + return mapper; } - + private Module createSerializerModule(){ - SimpleModule module = new SimpleModule("MidpointModule", new Version(0, 0, 0, "aa")); + SimpleModule module = new SimpleModule("MidpointModule", new Version(0, 0, 0, "aa")); module.addSerializer(QName.class, new QNameSerializer()); module.addSerializer(PolyString.class, new PolyStringSerializer()); module.addSerializer(ItemPath.class, new ItemPathSerializer()); @@ -108,7 +108,7 @@ private Module createSerializerModule(){ module.addSerializer(Element.class, new DomElementSerializer()); return module; } - + @Override protected MidpointYAMLParser createJacksonParser(InputStream stream) throws SchemaException, IOException { MidpointYAMLFactory factory = new MidpointYAMLFactory(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/yaml/MidpointYAMLGenerator.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/yaml/MidpointYAMLGenerator.java index 0ca3d3b7521..f213a6f1175 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/yaml/MidpointYAMLGenerator.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/yaml/MidpointYAMLGenerator.java @@ -25,8 +25,10 @@ public MidpointYAMLGenerator(IOContext ctxt, int jsonFeatures, int yamlFeatures, /** * Brutal hack, as default behavior has lead to the following: + * {@code * - ! * ! '@element': "http://midpoint.evolveum.com/xml/ns/public/model/scripting-3#search" + * } * * (so we need to explicitly reset typeId after writing it) */ @@ -36,7 +38,7 @@ public void resetTypeId() { @Override protected ScalarEvent _scalarEvent(String value, Character style) { - if (value.contains("\n")) { + if (value.indexOf('\n') != -1) { style = Character.valueOf('|'); } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/yaml/MidpointYAMLParser.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/yaml/MidpointYAMLParser.java index c03e28502c9..fb45c68e1b1 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/yaml/MidpointYAMLParser.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/lex/json/yaml/MidpointYAMLParser.java @@ -16,7 +16,7 @@ public MidpointYAMLParser(IOContext ctxt, BufferRecycler br, int parserFeatures, super(ctxt, br, parserFeatures, csvFeatures, codec, reader); // TODO Auto-generated constructor stub } - + // @Override // public String getTypeId() throws IOException, JsonGenerationException // { diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/BeanMarshaller.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/BeanMarshaller.java index f745389be44..29923e31788 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/BeanMarshaller.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/BeanMarshaller.java @@ -120,7 +120,7 @@ private XNode marshalXmlType(Object bean, SerializationContext ctx) throws Schem if (valueField != null) { return marshallBeanToPrimitive(bean, ctx, valueField); } - + if (ctd != null && ctd.isListMarker()) { return marshalHeterogeneousList(bean, ctx); } else { @@ -129,7 +129,7 @@ private XNode marshalXmlType(Object bean, SerializationContext ctx) throws Schem } /** - * For cases when XSD complex type has a simple content. In that case the resulting class has @XmlValue annotation. + * For cases when XSD complex type has a simple content. In that case the resulting class has @XmlValue annotation. */ private PrimitiveXNode marshallBeanToPrimitive(Object bean, SerializationContext ctx, Field valueField) throws SchemaException { if (!valueField.isAccessible()) { @@ -195,7 +195,7 @@ private XNode marshalXmlTypeToMap(Object bean, SerializationContext ctx) throws if (namespace == null) { throw new IllegalArgumentException("Cannot determine namespace of "+beanClass); } - + List propOrder = inspector.getPropOrder(beanClass); for (String fieldName: propOrder) { @@ -204,11 +204,11 @@ private XNode marshalXmlTypeToMap(Object bean, SerializationContext ctx) throws throw new IllegalStateException("No getter for field "+fieldName+" in "+beanClass); } Object getterResult = getValue(bean, getter, fieldName); - + if (getterResult == null) { continue; } - + Field field = inspector.findPropertyField(beanClass, fieldName); boolean isAttribute = inspector.isAttribute(field, getter); @@ -266,11 +266,11 @@ private XNode marshalXmlTypeToMap(Object bean, SerializationContext ctx) throws } } xmap.put(elementName, marshaled); - + // setExplicitTypeDeclarationIfNeeded(getter, valueToMarshall, xmap, fieldTypeName); } } - + return xmap; } @@ -319,16 +319,16 @@ public void revive(Object bean, final PrismContext prismContext) throws SchemaEx throw e; } } - + public void visit(Object bean, Handler handler) { if (bean == null) { return; } - + Class beanClass = bean.getClass(); - + handler.handle(bean); - + if (beanClass.isEnum() || beanClass.isPrimitive()){ //nothing more to do return; @@ -341,7 +341,7 @@ public void visit(Object bean, Handler handler) { // no @XmlType annotation, we are not interested to go any deeper return; } - + List propOrder = inspector.getPropOrder(beanClass); for (String fieldName: propOrder) { Method getter = inspector.findPropertyGetter(beanClass, fieldName); @@ -349,32 +349,32 @@ public void visit(Object bean, Handler handler) { throw new IllegalStateException("No getter for field "+fieldName+" in "+beanClass); } Object getterResult = getValue(bean, getter, fieldName); - + if (getterResult == null) { continue; } - + if (getterResult instanceof Collection) { Collection col = (Collection)getterResult; if (col.isEmpty()) { continue; } - + for (Object element: col) { visitValue(element, handler); - + } } else { visitValue(getterResult, handler); } } } - + private void visitValue(Object element, Handler handler) { Object elementToMarshall = element; if (element instanceof JAXBElement){ elementToMarshall = ((JAXBElement) element).getValue(); - } + } visit(elementToMarshall, handler); } @@ -448,7 +448,7 @@ private XNode marshallValue(T value, QName valueType, boolean isAttribute, S return marshall(value, ctx); } } - + private PrimitiveXNode createPrimitiveXNode(T value, QName valueType, boolean isAttribute) { PrimitiveXNode xprim = new PrimitiveXNode<>(); xprim.setValue(value, valueType); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/BeanUnmarshaller.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/BeanUnmarshaller.java index 091a478ca3e..1e71703eb6b 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/BeanUnmarshaller.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/BeanUnmarshaller.java @@ -165,7 +165,7 @@ private T unmarshalInternal(@NotNull XNode xnode, @NotNull Class beanClas return unmarshallPrimitive(prim, beanClass, pc); } } else { - + if (beanClass.getPackage() == null || beanClass.getPackage().getName().equals("java.lang")) { // We obviously have primitive data type, but we are asked to unmarshall from map xnode // NOTE: this may happen in XML when we have "empty" element, but it has some whitespace in it @@ -177,7 +177,7 @@ private T unmarshalInternal(@NotNull XNode xnode, @NotNull Class beanClas // Therefore just ignore entire map content. return null; } - + @SuppressWarnings("unchecked") MapUnmarshaller unmarshaller = specialMapUnmarshallers.get(beanClass); if (xnode instanceof MapXNode && unmarshaller != null) { // TODO: what about special unmarshaller + hetero list? @@ -193,35 +193,35 @@ private T unmarshalInternal(@NotNull XNode xnode, @NotNull Class beanClas private T unmarshallPrimitive(PrimitiveXNode prim, Class beanClass, ParsingContext pc) throws SchemaException { if (prim.isEmpty()) { return instantiate(beanClass); // Special case. Just return empty object - } - + } + Field valueField = XNodeProcessorUtil.findXmlValueField(beanClass); - + if (valueField == null) { throw new SchemaException("Cannot convert primitive value to bean of type " + beanClass); } - + T instance = instantiate(beanClass); - + if (!valueField.isAccessible()) { valueField.setAccessible(true); } - + T value; if (prim.isParsed()) { - value = prim.getValue(); + value = prim.getValue(); } else { Class fieldType = valueField.getType(); QName xsdType = XsdTypeMapper.toXsdType(fieldType); value = prim.getParsedValue(xsdType, (Class) fieldType); } - + try { valueField.set(instance, value); } catch (IllegalArgumentException | IllegalAccessException e) { throw new SchemaException("Cannot set primitive value to field " + valueField.getName() + " of bean " + beanClass + ": "+e.getMessage(), e); } - + return instance; } @@ -1248,4 +1248,3 @@ private ProtectedByteArrayType unmarshalProtectedByteArray(PrimitiveXNode parentPath) { allSegments.addAll(toSegments()); return new ItemPathHolder(allSegments); } - - + + private void addExplicitNsDeclarations(StringBuilder sb) { if (explicitNamespaceDeclarations != null) { @@ -585,7 +585,7 @@ public boolean equals(Object obj) { return true; if (obj == null) return false; - + // Special case if (obj instanceof QName) { if (segments.size() != 1) { @@ -594,7 +594,7 @@ public boolean equals(Object obj) { PathHolderSegment segment = segments.get(0); return segment.getQName().equals((QName)obj); } - + if (getClass() != obj.getClass()) return false; ItemPathHolder other = (ItemPathHolder) obj; @@ -632,7 +632,7 @@ public boolean isBelow(ItemPathHolder path) { /** * Returns a list of segments that are the "tail" after specified path. * The path in the parameter is assumed to be a "superpath" to this path, e.i. - * this path is below specified path. This method returns all the segments + * this path is below specified path. This method returns all the segments * of this path that are below the specified path. * Returns null if the assumption is false. */ @@ -664,14 +664,14 @@ public static boolean isDefault(Element pathElement) { return false; } - + private Long idToLong(String stringVal) { if (stringVal == null) { return null; } return Long.valueOf(stringVal); } - + private String idToString(Long longVal) { if (longVal == null) { return null; diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/JaxbDomHack.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/JaxbDomHack.java index ab2e262527c..00973a5c714 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/JaxbDomHack.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/JaxbDomHack.java @@ -43,13 +43,13 @@ * This is a mix of DOM and JAXB code that allows the use of "any" methods on JAXB-generated objects. * Prism normally does not use of of that. But JAXB code (such as JAX-WS) can invoke it and therefore * it has to return correct DOM/JAXB elements as expected. - * + * * @author Radovan Semancik */ public class JaxbDomHack { - + private static final Trace LOGGER = TraceManager.getTrace(JaxbDomHack.class); - + private PrismContext prismContext; private DomLexicalProcessor domParser; @@ -71,8 +71,8 @@ private ItemDefinition locateItemDefinition( // Try to locate xsi:type definition in the element def = resolveDynamicItemDefinition(containerDefinition, elementQName, (Element) valueElements, prismContext); - } - + } + if (valueElements instanceof List){ List elements = (List) valueElements; if (elements.size() == 1){ @@ -146,23 +146,23 @@ private ItemDefinition resolveGlobalItemDefinition( // QName elementQName = JAXBUtil.getElementQName(firstElement); return prismContext.getSchemaRegistry().resolveGlobalItemDefinition(elementQName, containerDefinition); } - + /** - * This is used in a form of "fromAny" to parse elements from a JAXB getAny method to prism. + * This is used in a form of "fromAny" to parse elements from a JAXB getAny method to prism. */ public Item parseRawElement(Object element, PrismContainerDefinition definition) throws SchemaException { Validate.notNull(definition, "Attempt to parse raw element in a container without definition"); - + QName elementName = JAXBUtil.getElementQName(element); ItemDefinition itemDefinition = definition.findItemDefinition(elementName); - + if (itemDefinition == null) { itemDefinition = locateItemDefinition(definition, elementName, element); if (itemDefinition == null) { throw new SchemaException("No definition for item "+elementName); } } - + PrismContext prismContext = definition.getPrismContext(); Item subItem; if (element instanceof Element) { @@ -199,16 +199,16 @@ public } else{ throw new IllegalArgumentException("Unsupported JAXB bean" + jaxbBean); } - + } else { throw new IllegalArgumentException("Unsupported definition type "+itemDefinition.getClass()); } } else { throw new IllegalArgumentException("Unsupported element type "+element.getClass()); - } + } return subItem; } - + /** * Serializes prism value to JAXB "any" format as returned by JAXB getAny() methods. diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/PrismBeanInspector.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/PrismBeanInspector.java index 81cbfbd9d6d..bffe21bae96 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/PrismBeanInspector.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/PrismBeanInspector.java @@ -153,7 +153,7 @@ public Class get(Package p) { } }); } - + private Map _getObjectFactoryClassNamespace = Collections.synchronizedMap(new HashMap()); Class getObjectFactoryClass(String namespaceUri) { return find1(_getObjectFactoryClassNamespace, namespaceUri, new Getter1() { @@ -396,7 +396,7 @@ private Class getObjectFactoryClassUncached(Package pkg) { throw new IllegalArgumentException("Cannot find object factory class in package "+pkg.getName()+": "+e.getMessage(), e); } } - + private Class getObjectFactoryClassUncached(String namespaceUri) { SchemaDescription schemaDescription = prismContext.getSchemaRegistry().findSchemaDescriptionByNamespace(namespaceUri); if (schemaDescription == null) { @@ -446,7 +446,7 @@ private Field findField(Class classType, Handler selector) { } return findField(superclass, selector); } - + private Method findMethod(Class classType, Handler selector) { for (Method field: classType.getDeclaredMethods()) { if (selector.handle(field)) { @@ -587,11 +587,11 @@ private QName findFieldElementQNameUncached(String fieldName, Class beanClass, S return new QName(realNamespace, realLocalName); } //endregion - + public Field findAnyField(Class beanClass) { return findField(beanClass, field -> field.getAnnotation(XmlAnyElement.class) != null); } - + public Method findAnyMethod(Class beanClass) { return findMethod(beanClass, method -> method.getAnnotation(XmlAnyElement.class) != null); } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/PrismMarshaller.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/PrismMarshaller.java index 244f462d3cb..35bcf340efd 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/PrismMarshaller.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/PrismMarshaller.java @@ -44,9 +44,9 @@ * */ public class PrismMarshaller { - + private static final Trace LOGGER = TraceManager.getTrace(PrismMarshaller.class); - + @NotNull private final BeanMarshaller beanMarshaller; public PrismMarshaller(@NotNull BeanMarshaller beanMarshaller) { @@ -240,7 +240,7 @@ private MapXNode marshalContainerValue(PrismContainerV marshalContainerValue(xmap, containerVal, containerDefinition, ctx); return xmap; } - + private void marshalContainerValue(MapXNode xmap, PrismContainerValue containerVal, PrismContainerDefinition containerDefinition, SerializationContext ctx) throws SchemaException { Long id = containerVal.getId(); if (id != null) { @@ -354,7 +354,7 @@ private XNode serializeReferenceValue(PrismReferenceValue value, PrismReferenceD } EvaluationTimeType resolutionTime = value.getResolutionTime(); if (resolutionTime != null) { - xmap.put(createReferenceQName(XNode.KEY_REFERENCE_RESOLUTION_TIME, namespace), + xmap.put(createReferenceQName(XNode.KEY_REFERENCE_RESOLUTION_TIME, namespace), createPrimitiveXNode(resolutionTime.value(), DOMUtil.XSD_STRING)); } if (value.getTargetName() != null) { @@ -396,7 +396,7 @@ private XNode serializePropertyValue(@NotNull PrismPropertyValue value, P @Nullable QName typeName = definition != null ? definition.getTypeName() : typeNameIfNoDefinition; ExpressionWrapper expression = value.getExpression(); if (expression != null) { - // Store expression, not the value. In this case the value (if any) is + // Store expression, not the value. In this case the value (if any) is // a transient product of the expression evaluation. return createExpressionXNode(expression); } @@ -409,7 +409,7 @@ private XNode serializePropertyValue(@NotNull PrismPropertyValue value, P // Marshaling attempt may process the expression in raw element expression = value.getExpression(); if (expression != null) { - // Store expression, not the value. In this case the value (if any) is + // Store expression, not the value. In this case the value (if any) is // a transient product of the expression evaluation. return createExpressionXNode(expression); } @@ -472,7 +472,7 @@ private PrimitiveXNode createPrimitiveXNode(T val, QName type) { xprim.setValue(val, type); return xprim; } - + @NotNull private XNode createExpressionXNode(@NotNull ExpressionWrapper expression) throws SchemaException { return PrismUtil.serializeExpression(expression, beanMarshaller); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/PrismUnmarshaller.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/PrismUnmarshaller.java index 3fe514da117..fc29b7ddaa9 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/PrismUnmarshaller.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/PrismUnmarshaller.java @@ -377,7 +377,7 @@ private PrismPropertyValue parsePropertyValue(@NotNull XNode node, if (expression != null) { PrismPropertyValue ppv = new PrismPropertyValue<>(null, prismContext, null, null, expression); return ppv; - + } } PrismPropertyValue ppv = new PrismPropertyValue<>(realValue); @@ -483,7 +483,7 @@ private PrismReferenceValue parseReferenceValueAsReference(@NotNull XNode xnode, if (!pc.isAllowMissingRefTypes() && !allowMissingRefTypesOverride) { type = definition.getTargetTypeName(); if (type == null) { - throw new SchemaException("Target type in reference " + definition.getName() + + throw new SchemaException("Target type in reference " + definition.getName() + " not specified in reference nor in the schema"); } } @@ -494,7 +494,7 @@ private PrismReferenceValue parseReferenceValueAsReference(@NotNull XNode xnode, QName defTargetType = definition.getTargetTypeName(); if (defTargetType != null) { if (!(prismContext.getSchemaRegistry().isAssignableFrom(defTargetType, type))) { - throw new SchemaException("Target type specified in reference " + definition.getName() + + throw new SchemaException("Target type specified in reference " + definition.getName() + " (" + type + ") does not match target type in schema (" + defTargetType + ")"); } } @@ -514,7 +514,7 @@ private PrismReferenceValue parseReferenceValueAsReference(@NotNull XNode xnode, refVal.setDescription(map.getParsedPrimitiveValue(XNode.KEY_REFERENCE_DESCRIPTION, DOMUtil.XSD_STRING)); refVal.setFilter(parseFilter(map.get(XNode.KEY_REFERENCE_FILTER))); - + String resolutionTimeString = map.getParsedPrimitiveValue(XNode.KEY_REFERENCE_RESOLUTION_TIME, DOMUtil.XSD_STRING); if (resolutionTimeString != null) { EvaluationTimeType resolutionTime = EvaluationTimeType.fromValue(resolutionTimeString); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/QueryConvertor.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/QueryConvertor.java index 71a947809bf..bc610346697 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/QueryConvertor.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/QueryConvertor.java @@ -49,9 +49,9 @@ * Note that expressions are not serialized yet. */ public class QueryConvertor { - + private static final Trace LOGGER = TraceManager.getTrace(QueryConvertor.class); - + public static final String NS_QUERY = "http://prism.evolveum.com/xml/ns/public/query-3"; // TODO removed unused constants eventually @@ -109,14 +109,14 @@ public class QueryConvertor { private static final QName ELEMENT_FILTER = new QName(NS_QUERY, "filter"); /** - * Used by XNodeProcessor and similar code that does not have complete schema for the filter + * Used by XNodeProcessor and similar code that does not have complete schema for the filter */ public static ObjectFilter parseFilter(XNode xnode, PrismContext prismContext) throws SchemaException { Validate.notNull(prismContext); MapXNode xmap = toMap(xnode); return parseFilterInternal(xmap, null, false, prismContext); } - + public static ObjectFilter parseFilter(MapXNode xmap, PrismContainerDefinition objDef) throws SchemaException { Validate.notNull(objDef); if (xmap == null) { @@ -193,7 +193,7 @@ private static ObjectFilter parseFilterInternal(XNode } else if (QNameUtil.match(clauseQName, CLAUSE_NOT)) { return parseNotFilter(clauseXMap, pcd, preliminaryParsingOnly, prismContext); } - + // other complex filters if (QNameUtil.match(clauseQName, CLAUSE_TYPE)) { @@ -258,7 +258,7 @@ private static NotFilter parseNotFilter(MapXNode claus return NotFilter.createNot(subfilter); } } - + private static ObjectFilter parseComparisonFilter(QName clauseQName, MapXNode clauseXMap, PrismContainerDefinition pcd, boolean preliminaryParsingOnly, PrismContext prismContext) throws SchemaException { @@ -270,7 +270,7 @@ private static ObjectFilter parseComparisonFilter(QN ItemPath itemPath = getPath(clauseXMap); if (itemPath == null || itemPath.isEmpty()){ - throw new SchemaException("Could not convert query, because query does not contain item path."); + throw new SchemaException("Could not convert query, because query does not contain item path."); } QName itemName = ItemPath.getName(itemPath.last()); @@ -283,7 +283,7 @@ private static ObjectFilter parseComparisonFilter(QN if (itemDefinition != null) { itemName = itemDefinition.getName(); } - + if (valueXnode != null) { if (preliminaryParsingOnly) { return null; @@ -355,7 +355,7 @@ private static ObjectFilter parseComparisonFilter(QN } } } - + private static InOidFilter parseInOidFilter(MapXNode clauseXMap, PrismContainerDefinition pcd, boolean preliminaryParsingOnly, PrismContext prismContext) throws SchemaException{ boolean considerOwner = Boolean.TRUE.equals(clauseXMap.getParsedPrimitiveValue(ELEMENT_CONSIDER_OWNER, DOMUtil.XSD_BOOLEAN)); XNode valueXnode = clauseXMap.get(ELEMENT_VALUE); @@ -371,7 +371,7 @@ private static InOidFilter parseInOidFilter(MapXNode clauseXMap, PrismContainerD } } } - + private static FullTextFilter parseFullTextFilter(MapXNode clauseXMap, PrismContainerDefinition pcd, boolean preliminaryParsingOnly, PrismContext prismContext) throws SchemaException{ XNode valueXnode = clauseXMap.get(ELEMENT_VALUE); @@ -454,7 +454,7 @@ private static void checkExtraElements(MapXNode clauseXMap, QName... expected) t private static RefFilter parseRefFilter(MapXNode clauseXMap, PrismContainerDefinition pcd, boolean preliminaryParsingOnly, PrismContext prismContext) throws SchemaException{ ItemPath itemPath = getPath(clauseXMap); - + if (itemPath == null || itemPath.isEmpty()){ throw new SchemaException("Cannot convert query, because query does not contain property path."); } @@ -512,7 +512,7 @@ private static RefFilter parseRefFilter(MapXNode claus } } } - + private static ExpressionWrapper parseExpression(MapXNode xmap, PrismContext prismContext) throws SchemaException { Entry expressionEntry = xmap.getSingleEntryThatDoesNotMatch( ELEMENT_VALUE, ELEMENT_MATCHING, ELEMENT_ANCHOR_START, ELEMENT_ANCHOR_END, ELEMENT_PATH); @@ -590,7 +590,7 @@ private static OrgFilter parseOrgFilter(MapXNode claus return OrgFilter.createRootOrg(); } } - + XNode xorgrefnode = clauseXMap.get(ELEMENT_ORG_REF); if (xorgrefnode == null) { throw new SchemaException("No organization reference defined in the search query."); @@ -600,20 +600,20 @@ private static OrgFilter parseOrgFilter(MapXNode claus if (orgOid == null || StringUtils.isBlank(orgOid)) { throw new SchemaException("No oid attribute defined in the organization reference element."); } - + String scopeString = xorgrefmap.getParsedPrimitiveValue(ELEMENT_SCOPE, DOMUtil.XSD_STRING); // original (in my opinion incorrect) place if (scopeString == null) { scopeString = clauseXMap.getParsedPrimitiveValue(ELEMENT_SCOPE, DOMUtil.XSD_STRING); // here it is placed by the serializer } Scope scope = scopeString != null ? Scope.valueOf(scopeString) : null; - + if (preliminaryParsingOnly) { return null; } else { return OrgFilter.createOrg(orgOid, scope); } } - + private static Entry singleSubEntry(MapXNode xmap, String filterName) throws SchemaException { if (xmap == null || xmap.isEmpty()) { return null; @@ -634,7 +634,7 @@ private static PrimitiveXNode toPrimitive(XNode xnode, XNode context) throws Sch } return (PrimitiveXNode)xnode; } - + private static ItemPath getPath(MapXNode clauseXMap) throws SchemaException { return getPath(clauseXMap, ELEMENT_PATH); } @@ -662,8 +662,8 @@ private static QName getMatchingRule(MapXNode xmap) throws SchemaException{ } else { return null; } - } - + } + private static Item parseItem(RootXNode root, QName itemName, ItemDefinition itemDefinition, PrismContext prismContext) throws SchemaException{ Item item; if (prismContext == null) { @@ -679,10 +679,10 @@ private static Item parseItem(RootXNode root, QName itemName, ItemDefinition ite if (item.getValues().size() < 1 ) { throw new IllegalStateException("No values to search specified for item " + itemName); } - + return item; } - + private static ItemDefinition locateItemDefinition(XNode valueXnode, ItemPath itemPath, PrismContainerDefinition pcd, PrismContext prismContext) throws SchemaException{ ItemDefinition itemDefinition = null; if (pcd != null) { @@ -711,7 +711,7 @@ public static SearchFilterType createSearchFilterType(ObjectFilter filter, Prism public static MapXNode serializeFilter(ObjectFilter filter, PrismContext prismContext) throws SchemaException{ return serializeFilter(filter, prismContext.xnodeSerializer()); } - + private static MapXNode serializeFilter(ObjectFilter filter, PrismSerializer xnodeSerializer) throws SchemaException{ // null or primitive filters if (filter == null) { @@ -752,20 +752,20 @@ private static MapXNode serializeFilter(ObjectFilter filter, PrismSerializer xnodeSerilizer) throws SchemaException{ return createFilter(CLAUSE_AND, serializeNaryLogicalSubfilters(filter.getConditions(), xnodeSerilizer)); } private static MapXNode serializeOrFilter(OrFilter filter, PrismSerializer xnodeSerilizer) throws SchemaException{ MapXNode map = createFilter(CLAUSE_OR, serializeNaryLogicalSubfilters(filter.getConditions(), xnodeSerilizer)); - return map; + return map; } - + private static MapXNode serializeNaryLogicalSubfilters(List objectFilters, PrismSerializer xnodeSerilizer) throws SchemaException{ MapXNode filters = new MapXNode(); for (ObjectFilter of : objectFilters) { @@ -839,7 +839,7 @@ private static MapXNode serializeComparisonFilter(PropertyValueFilter fil map.put(clause, serializeValueFilter(filter, xnodeSerializer)); return map; } - + private static MapXNode serializeValueFilter(ValueFilter filter, PrismSerializer xnodeSerializer) throws SchemaException { MapXNode map = new MapXNode(); serializeMatchingRule(filter, map); @@ -866,15 +866,15 @@ private static MapXNode seriali if (filter.getRightHandSidePath() != null) { map.put(ELEMENT_RIGHT_HAND_SIDE_PATH, createPrimitiveXNode(filter.getRightHandSidePath().asItemPathType(), ItemPathType.COMPLEX_TYPE)); } - + ExpressionWrapper xexpression = filter.getExpression(); if (xexpression != null) { map.merge(PrismUtil.serializeExpression(xexpression, xnodeSerializer)); } - + return map; } - + private static MapXNode serializeRefFilter(RefFilter filter, PrismSerializer xnodeSerializer) throws SchemaException { MapXNode map = createFilter(CLAUSE_REF, serializeValueFilter(filter, xnodeSerializer)); return map; @@ -892,7 +892,7 @@ private static MapXNode serializeSubstringFilter(SubstringFilter filter, map.put(CLAUSE_SUBSTRING, content); return map; } - + private static MapXNode serializeTypeFilter(TypeFilter filter, PrismSerializer xnodeSerializer) throws SchemaException{ MapXNode content = new MapXNode(); content.put(ELEMENT_TYPE, createPrimitiveXNode(filter.getType(), DOMUtil.XSD_QNAME)); @@ -947,14 +947,14 @@ private static void serializeMatchingRule(ValueFilter filter, MapXNode map) { map.put(ELEMENT_MATCHING, matchingNode); } } - + private static void serializePath(MapXNode map, ItemPath path, ObjectFilter filter) { if (path == null) { throw new IllegalStateException("Cannot serialize filter " + filter + " because it does not contain path"); } map.put(ELEMENT_PATH, createPrimitiveXNode(path.asItemPathType(), ItemPathType.COMPLEX_TYPE)); } - + private static XNode serializePropertyValue(PrismPropertyValue value, PrismPropertyDefinition definition, BeanMarshaller beanConverter) throws SchemaException { QName typeQName = definition.getTypeName(); T realValue = value.getValue(); @@ -965,13 +965,13 @@ private static XNode serializePropertyValue(PrismPropertyValue value, Pri return createPrimitiveXNode(realValue, typeQName); } } - + private static PrimitiveXNode createPrimitiveXNode(T val, QName type) { PrimitiveXNode xprim = new PrimitiveXNode<>(); xprim.setValue(val, type); return xprim; } - + // TODO what with this? [med] public static void revive (ObjectFilter filter, final PrismContext prismContext) throws SchemaException { @@ -999,7 +999,7 @@ public static void revive (ObjectFilter filter, final PrismContext prismContext) * Tries to parse as much from filter as possible, without knowing the definition of object(s) to which the * filter will be applied. It is used mainly to parse path specifications, in order to avoid namespace loss * when serializing raw (unparsed) paths and QNames - see MID-1969. - * + * * @param xfilter * @param prismContext */ diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/TrivialItemPathParser.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/TrivialItemPathParser.java index 9d9bcbd833e..38a79353e5e 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/TrivialItemPathParser.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/TrivialItemPathParser.java @@ -30,6 +30,17 @@ * @author semancik */ public class TrivialItemPathParser { + // This is using regexp to "parse" the declarations. It is not ideal, + // it does not check the syntax, does not show reasonable errors, etc. + // But it was all done in like 20minutes. Good value/price ;-) + private static final String PARSE_REGEX = "(^|;)[\\s\\p{Z}]*declare[\\s\\p{Z}]+(default[\\s\\p{Z}]+)?namespace[\\s\\p{Z}]+((\\w+)[\\s\\p{Z}]*=[\\s\\p{Z}]*)?(['\"])([^'\"]*)\\5[\\s\\p{Z}]*(?=;)"; + private static final Pattern PARSE_PATTERN = Pattern.compile(PARSE_REGEX); + + private static final String NBWS_HEAD_REGEX = "^[\\p{Z}\\s]+"; + private static final Pattern NBSP_HEAD_PATTERN = Pattern.compile(NBWS_HEAD_REGEX); + + private static final String NBWS_TAIL_REGEX = "[\\p{Z}\\s]+$"; + private static final Pattern NBWS_TAIL_PATTERN = Pattern.compile(NBWS_TAIL_REGEX); private final Map namespaceMap = new HashMap<>(); private String pureItemPathString; @@ -42,13 +53,8 @@ public static TrivialItemPathParser parse(String itemPath) { TrivialItemPathParser parser = new TrivialItemPathParser(); - // This is using regexp to "parse" the declarations. It is not ideal, - // it does not check the syntax, does not show reasonable errors, etc. - // But it was all done in like 20minutes. Good value/price ;-) - String regexp = "(^|;)[\\s\\p{Z}]*declare[\\s\\p{Z}]+(default[\\s\\p{Z}]+)?namespace[\\s\\p{Z}]+((\\w+)[\\s\\p{Z}]*=[\\s\\p{Z}]*)?(['\"])([^'\"]*)\\5[\\s\\p{Z}]*(?=;)"; - Pattern pattern = Pattern.compile(regexp); - Matcher matcher = pattern.matcher(itemPath); + Matcher matcher = PARSE_PATTERN.matcher(itemPath); int lastEnd = 0; while (matcher.find()) { @@ -71,8 +77,7 @@ public static TrivialItemPathParser parse(String itemPath) { // Trim whitechars // trim() won't do here. it is not trimming non-breakable spaces. - - parser.pureItemPathString = parser.pureItemPathString.replaceFirst("^[\\p{Z}\\s]+", "").replaceFirst("[\\p{Z}\\s]+$", ""); + parser.pureItemPathString = NBWS_TAIL_PATTERN.matcher(NBSP_HEAD_PATTERN.matcher(parser.pureItemPathString).replaceFirst("")).replaceFirst(""); return parser; } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/XNodeProcessorEvaluationMode.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/XNodeProcessorEvaluationMode.java index 8305341f7ba..3684a0efdb9 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/XNodeProcessorEvaluationMode.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/XNodeProcessorEvaluationMode.java @@ -23,8 +23,8 @@ public enum XNodeProcessorEvaluationMode { /** * Strict mode. Any inconsistency of data with the schema is considered to be an error. */ - STRICT, - + STRICT, + /** * Compatibility mode. The processing will go on as long as the data are roughly compatible * with the schema. E.g. illegal values and unknown elements are silently ignored. diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/XNodeProcessorUtil.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/XNodeProcessorUtil.java index 51143d37074..9738e545739 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/XNodeProcessorUtil.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/marshaller/XNodeProcessorUtil.java @@ -79,10 +79,10 @@ public static void parseProtectedType(ProtectedDataType protectedType, Ma } return new QName(null, elementName); }); - + EncryptedDataType encryptedDataType = prismContext.parserFor(xConvertedEncryptedData).context(pc).parseRealValue(EncryptedDataType.class); protectedType.setEncryptedData(encryptedDataType); - + if (protectedType instanceof ProtectedStringType){ transformEncryptedValue(protectedType, prismContext); } @@ -117,7 +117,7 @@ public static void parseProtectedType(ProtectedDataType protectedType, Ma } } - + private static void transformEncryptedValue(ProtectedDataType protectedType, PrismContext prismContext) throws SchemaException{ Protector protector = prismContext.getDefaultProtector(); if (protector == null) { diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/DefaultMatchingRule.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/DefaultMatchingRule.java index 5775f931ca8..c69455a7d16 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/DefaultMatchingRule.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/DefaultMatchingRule.java @@ -25,11 +25,11 @@ /** * Default matching rule used as a fall-back if no explicit matching rule is specified. * It is simply using java equals() method to match values. - * + * * @author Radovan Semancik */ public class DefaultMatchingRule implements MatchingRule { - + public static final QName NAME = new QName(PrismConstants.NS_MATCHING_RULE, "default"); /* (non-Javadoc) @@ -48,7 +48,7 @@ public boolean isSupported(QName xsdType) { // We support everything. We are the default. return true; } - + /* (non-Javadoc) * @see com.evolveum.midpoint.model.match.MatchingRule#match(java.lang.Object, java.lang.Object) */ @@ -77,7 +77,7 @@ public T normalize(T original) { @Override public boolean matchRegex(T a, String regex) { - String valueToMatch = null; + String valueToMatch = null; if (a instanceof Matchable){ return ((Matchable) a).matches(regex); } else if (a instanceof String){ @@ -87,8 +87,8 @@ public boolean matchRegex(T a, String regex) { } else { valueToMatch = String.valueOf(a); } - + return Pattern.matches(regex, valueToMatch); } - + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/DistinguishedNameMatchingRule.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/DistinguishedNameMatchingRule.java index 92dc0ffb5ac..f2d1f8584e5 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/DistinguishedNameMatchingRule.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/DistinguishedNameMatchingRule.java @@ -30,12 +30,12 @@ /** * Matching rule for LDAP distinguished name (DN). - * + * * @author Radovan Semancik * */ public class DistinguishedNameMatchingRule implements MatchingRule { - + public static final QName NAME = new QName(PrismConstants.NS_MATCHING_RULE, "distinguishedName"); @Override @@ -93,14 +93,14 @@ public String normalize(String original) throws SchemaException { @Override public boolean matchRegex(String a, String regex) throws SchemaException { - + a = normalize(a); - + if (a == null){ return false; } - - // Simple case-insensitive match + + // Simple case-insensitive match Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(a); return matcher.matches(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/ExchangeEmailAddressesMatchingRule.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/ExchangeEmailAddressesMatchingRule.java index feb4ae38e75..dee4cca72d7 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/ExchangeEmailAddressesMatchingRule.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/ExchangeEmailAddressesMatchingRule.java @@ -25,12 +25,12 @@ /** * A specific matching rule for Microsoft Exchange EmailAddresses attribute consisting of SMTP:/smtp: prefix and email address. * It considers the case in the prefix but ignores the case in the email address. - * + * * @author Pavol Mederly * */ public class ExchangeEmailAddressesMatchingRule implements MatchingRule { - + public static final QName NAME = new QName(PrismConstants.NS_MATCHING_RULE, "exchangeEmailAddresses"); @Override diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/MatchingRule.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/MatchingRule.java index dca1ffce93c..c8c259d71d7 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/MatchingRule.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/MatchingRule.java @@ -23,7 +23,7 @@ * Interface for generic matching rules. The responsibility of a matching rule is to decide if * two objects of the same type match. This may seem a simple thing to do but the details may get * quite complex. E.g. comparing string in case sensitive or insensitive manner, comparing PolyStrings, etc. - * + * * @author Radovan Semancik * */ @@ -34,22 +34,22 @@ public interface MatchingRule { * it is an matching rule identifier. */ QName getName(); - + /** * Returns true if the rule can be applied to the specified XSD type. */ boolean isSupported(QName xsdType); - + /** - * Matches two objects. + * Matches two objects. */ boolean match(T a, T b) throws SchemaException; - + /** - * Matches value against given regex. + * Matches value against given regex. */ boolean matchRegex(T a, String regex) throws SchemaException; - + /** * Returns a normalized version of the value. * For normalized version the following holds: diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/MatchingRuleRegistry.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/MatchingRuleRegistry.java index f1fbfe3b005..ee568c87d64 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/MatchingRuleRegistry.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/MatchingRuleRegistry.java @@ -30,15 +30,15 @@ * */ public class MatchingRuleRegistry { - + @NotNull public final MatchingRule defaultMatchingRule; public Map> matchingRules = new HashMap<>(); - + public MatchingRuleRegistry() { super(); this.defaultMatchingRule = new DefaultMatchingRule<>(); } - + public MatchingRuleRegistry(Collection> matchingRules) { this(); for (MatchingRule matchingRule: matchingRules) { @@ -57,7 +57,7 @@ public MatchingRule getMatchingRule(QName ruleName, QName typeQName) thro //try match according to the localPart if (QNameUtil.matchAny(ruleName, matchingRules.keySet())){ ruleName = QNameUtil.resolveNs(ruleName, matchingRules.keySet()); - matchingRule = (MatchingRule) matchingRules.get(ruleName); + matchingRule = (MatchingRule) matchingRules.get(ruleName); } if (matchingRule == null) { throw new SchemaException("Unknown matching rule for name " + ruleName); @@ -68,7 +68,7 @@ public MatchingRule getMatchingRule(QName ruleName, QName typeQName) thro } return matchingRule; } - + public void registerMatchingRule(MatchingRule rule) { ((Map)this.matchingRules).put(rule.getName(), rule); } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/MatchingRuleRegistryFactory.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/MatchingRuleRegistryFactory.java index 40a88a66359..57ff8d736b8 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/MatchingRuleRegistryFactory.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/MatchingRuleRegistryFactory.java @@ -17,14 +17,14 @@ /** * Creates MatchingRuleRegistry populated with standard matching rules. - * + * * @author Radovan Semancik * */ public class MatchingRuleRegistryFactory { - + public static MatchingRuleRegistry createRegistry() { - + MatchingRuleRegistry registry = new MatchingRuleRegistry(); registry.registerMatchingRule(new StringIgnoreCaseMatchingRule()); registry.registerMatchingRule(new PolyStringStrictMatchingRule()); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/PolyStringNormMatchingRule.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/PolyStringNormMatchingRule.java index 34188aad427..9902f512969 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/PolyStringNormMatchingRule.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/PolyStringNormMatchingRule.java @@ -29,7 +29,7 @@ * */ public class PolyStringNormMatchingRule implements MatchingRule { - + public static final QName NAME = new QName(PrismConstants.NS_MATCHING_RULE, "polyStringNorm"); /* (non-Javadoc) @@ -59,7 +59,7 @@ public boolean match(PolyString a, PolyString b) { if (a == null || b == null) { return false; } - return MiscUtil.equals(a.getNorm(), b.getNorm()); + return MiscUtil.equals(a.getNorm(), b.getNorm()); } /* (non-Javadoc) @@ -75,7 +75,7 @@ public boolean matchRegex(PolyString a, String regex) { if (a == null){ return false; } - + return Pattern.matches(regex, a.getNorm()); } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/PolyStringOrigMatchingRule.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/PolyStringOrigMatchingRule.java index 84b690f4184..97f50755fad 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/PolyStringOrigMatchingRule.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/PolyStringOrigMatchingRule.java @@ -29,7 +29,7 @@ * */ public class PolyStringOrigMatchingRule implements MatchingRule { - + public static final QName NAME = new QName(PrismConstants.NS_MATCHING_RULE, "polyStringOrig"); /* (non-Javadoc) @@ -59,7 +59,7 @@ public boolean match(PolyString a, PolyString b) { if (a == null || b == null) { return false; } - return MiscUtil.equals(a.getOrig(), b.getOrig()); + return MiscUtil.equals(a.getOrig(), b.getOrig()); } /* (non-Javadoc) @@ -75,7 +75,7 @@ public boolean matchRegex(PolyString a, String regex) { if (a == null){ return false; } - + return Pattern.matches(regex, a.getOrig()); } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/PolyStringStrictMatchingRule.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/PolyStringStrictMatchingRule.java index e6dd9a71222..da3055a52d5 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/PolyStringStrictMatchingRule.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/PolyStringStrictMatchingRule.java @@ -29,7 +29,7 @@ * */ public class PolyStringStrictMatchingRule implements MatchingRule { - + public static final QName NAME = new QName(PrismConstants.NS_MATCHING_RULE, "polyStringStrict"); /* (non-Javadoc) @@ -59,7 +59,7 @@ public boolean match(PolyString a, PolyString b) { if (a == null || b == null) { return false; } - return MiscUtil.equals(a.getOrig(), b.getOrig()) && MiscUtil.equals(a.getNorm(), b.getNorm()); + return MiscUtil.equals(a.getOrig(), b.getOrig()) && MiscUtil.equals(a.getNorm(), b.getNorm()); } /* (non-Javadoc) @@ -75,7 +75,7 @@ public boolean matchRegex(PolyString a, String regex) { if (a == null){ return false; } - + return Pattern.matches(regex, a.getOrig()); } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/StringIgnoreCaseMatchingRule.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/StringIgnoreCaseMatchingRule.java index 903dbeb8e6d..6743f1384f2 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/StringIgnoreCaseMatchingRule.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/StringIgnoreCaseMatchingRule.java @@ -27,12 +27,12 @@ /** * String matching rule that ignores the case. - * + * * @author Radovan Semancik * */ public class StringIgnoreCaseMatchingRule implements MatchingRule { - + public static final QName NAME = new QName(PrismConstants.NS_MATCHING_RULE, "stringIgnoreCase"); @Override @@ -72,7 +72,7 @@ public boolean matchRegex(String a, String regex) { if (a == null){ return false; } - + Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(a); return matcher.matches(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/UuidMatchingRule.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/UuidMatchingRule.java index 455ee15c9ab..447443e05c9 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/UuidMatchingRule.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/UuidMatchingRule.java @@ -27,14 +27,14 @@ /** * Matching rule for universally unique identifier (UUID). - * + * * Currently it is (almost) simple case ignore matching. - * + * * @author Radovan Semancik * */ public class UuidMatchingRule implements MatchingRule { - + public static final QName NAME = new QName(PrismConstants.NS_MATCHING_RULE, "uuid"); @Override @@ -77,7 +77,7 @@ public boolean matchRegex(String a, String regex) { if (a == null){ return false; } - + Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(a); return matcher.matches(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/XmlMatchingRule.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/XmlMatchingRule.java index 19183c0d2d6..59e967f773a 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/XmlMatchingRule.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/match/XmlMatchingRule.java @@ -31,14 +31,14 @@ * The XML comparison is not schema aware. It will not handle * QNames in values correctly. The comparison ignores XML formatting * (whitespaces between elements). - * + * * @author Radovan Semancik * */ public class XmlMatchingRule implements MatchingRule { - + public static final Trace LOGGER = TraceManager.getTrace(XmlMatchingRule.class); - + public static final QName NAME = new QName(PrismConstants.NS_MATCHING_RULE, "xml"); @Override @@ -63,11 +63,11 @@ public boolean match(String a, String b) { return false; } try { - + Document docA = DOMUtil.parseDocument(a); Document docB = DOMUtil.parseDocument(b); return DOMUtil.compareDocument(docA, docB, false, false); - + } catch (IllegalStateException | IllegalArgumentException e) { LOGGER.warn("Invalid XML in XML matching rule: {}", e.getMessage()); // Invalid XML. We do not want to throw the exception from matching rule. @@ -85,12 +85,12 @@ public String normalize(String original) { return original; } try { - + Document doc = DOMUtil.parseDocument(original); DOMUtil.normalize(doc, false); String out = DOMUtil.printDom(doc, false, true).toString(); return out.trim(); - + } catch (IllegalStateException | IllegalArgumentException e) { LOGGER.warn("Invalid XML in XML matching rule: {}", e.getMessage()); return original.trim(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/path/IdItemPathSegment.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/path/IdItemPathSegment.java index 08f5e511de0..5a9f7487bf9 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/path/IdItemPathSegment.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/path/IdItemPathSegment.java @@ -20,11 +20,11 @@ * */ public class IdItemPathSegment extends ItemPathSegment { - - public static final IdItemPathSegment WILDCARD = IdItemPathSegment.createWildcard(); - + + public static final IdItemPathSegment WILDCARD = IdItemPathSegment.createWildcard(); + private Long id; - + public IdItemPathSegment() { this.id = null; } @@ -42,7 +42,7 @@ public IdItemPathSegment(Long id) { public Long getId() { return id; } - + @Override public String toString() { return "[" + ( isWildcard() ? "*" : id ) + "]"; @@ -83,5 +83,5 @@ public IdItemPathSegment clone() { clone.id = this.id; return clone; } - + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/path/ItemPath.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/path/ItemPath.java index ca7b96cfa01..6a95532dc20 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/path/ItemPath.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/path/ItemPath.java @@ -48,7 +48,7 @@ private static ItemPath createEmpty() { public void setNamespaceMap(Map namespaceMap) { this.namespaceMap = namespaceMap; } - + public Map getNamespaceMap() { return namespaceMap; } @@ -57,7 +57,7 @@ public Map getNamespaceMap() { private ItemPath() { segments = new ArrayList<>(); // to provide room for growth } - + public ItemPath(QName... qnames) { this.segments = new ArrayList<>(qnames.length); for (QName qname : qnames) { @@ -114,24 +114,24 @@ public ItemPath(ItemPath parentPath, ItemPath childPath) { segments.addAll(childPath.segments); } - + public ItemPath(List segments) { this.segments = new ArrayList<>(segments.size()); this.segments.addAll(segments); } - + public ItemPath(List segments, ItemPathSegment subSegment) { this.segments = new ArrayList<>(segments.size()+1); this.segments.addAll(segments); this.segments.add(subSegment); } - + public ItemPath(List segments, QName subName) { this.segments = new ArrayList<>(segments.size()+1); this.segments.addAll(segments); add(subName); } - + public ItemPath(List segments, List additionalSegments) { this.segments = new ArrayList<>(segments.size()+additionalSegments.size()); this.segments.addAll(segments); @@ -153,7 +153,7 @@ public ItemPath(ItemPath parentPath, ItemPathSegment subSegment) { this.segments.addAll(parentPath.segments); this.segments.add(subSegment); } - + public ItemPath subPath(QName subName) { return new ItemPath(segments, subName); } @@ -165,7 +165,7 @@ public ItemPath subPath(Object... components) { public ItemPath subPath(Long id) { return subPath(new IdItemPathSegment(id)); } - + public ItemPath subPath(ItemPathSegment subSegment) { return new ItemPath(segments, subSegment); } @@ -175,9 +175,9 @@ public ItemPath subPath(ItemPath subPath) { newPath.segments.addAll(subPath.getSegments()); return newPath; } - + /** - * Null-proof static version. + * Null-proof static version. */ public static ItemPath subPath(ItemPath prefix, ItemPathSegment subSegment) { if (prefix == null && subSegment == null) { @@ -212,7 +212,7 @@ public static ItemPathSegment createSegment(QName qname, boolean variable) { public List getSegments() { return segments; } - + public ItemPathSegment first() { if (segments.size() == 0) { return null; @@ -248,7 +248,7 @@ public ItemPathSegment last() { public ItemPath head() { return new ItemPath(first()); } - + /** * Returns path containing all segments except the first N. */ @@ -328,9 +328,9 @@ public int size() { public boolean isEmpty() { return segments.isEmpty(); } - + /** - * Makes the path "normal" by inserting null Id segments where they were omitted. + * Makes the path "normal" by inserting null Id segments where they were omitted. */ public ItemPath normalize() { ItemPath normalizedPath = new ItemPath(); @@ -338,7 +338,7 @@ public ItemPath normalize() { Iterator iterator = segments.iterator(); while (iterator.hasNext()) { ItemPathSegment origSegment = iterator.next(); - if (lastSegment != null && !(lastSegment instanceof IdItemPathSegment) && + if (lastSegment != null && !(lastSegment instanceof IdItemPathSegment) && !(origSegment instanceof IdItemPathSegment)) { normalizedPath.segments.add(new IdItemPathSegment()); } @@ -476,10 +476,10 @@ public static boolean containsEquivalent(Collection paths, ItemPath pa * Returns true if the collection contains a superpath of or equivalent path to the given path. * I.e. having collection = { A/B, A/C } * then the method for this collection and 'path' returns: - * - path = A/B -> true - * - path = A -> true - * - path = A/B/C -> false - * - path = X -> false + * - path = A/B -> true + * - path = A -> true + * - path = A/B/C -> false + * - path = X -> false */ public static boolean containsSuperpathOrEquivalent(Collection paths, ItemPath pathToBeFound) { return paths.stream().anyMatch(p -> p.isSuperPathOrEquivalent(pathToBeFound)); @@ -489,10 +489,10 @@ public static boolean containsSuperpathOrEquivalent(Collection paths, * Returns true if the collection contains a superpath of the given path. * I.e. having collection = { A/B, A/C } * then the method for this collection and 'path' returns: - * - path = A/B -> false - * - path = A -> true - * - path = A/B/C -> false - * - path = X -> false + * - path = A/B -> false + * - path = A -> true + * - path = A/B/C -> false + * - path = X -> false */ public static boolean containsSuperpath(Collection paths, ItemPath pathToBeFound) { return paths.stream().anyMatch(p -> p.isSuperPath(pathToBeFound)); @@ -502,10 +502,10 @@ public static boolean containsSuperpath(Collection paths, ItemPath pat * Returns true if the collection contains a subpath of or equivalent path to the given path. * I.e. having collection = { A/B, A/C } * then the method for this collection and 'path' returns: - * - path = A/B -> true - * - path = A -> false - * - path = A/B/C -> true - * - path = X -> false + * - path = A/B -> true + * - path = A -> false + * - path = A/B/C -> true + * - path = X -> false */ public static boolean containsSubpathOrEquivalent(Collection paths, ItemPath pathToBeFound) { return paths.stream().anyMatch(p -> p.isSubPathOrEquivalent(pathToBeFound)); @@ -515,10 +515,10 @@ public static boolean containsSubpathOrEquivalent(Collection paths, It * Returns true if the collection contains a superpath of the given path. * I.e. having collection = { A/B, A/C } * then the method for this collection and 'path' returns: - * - path = A/B -> false - * - path = A -> false - * - path = A/B/C -> true - * - path = X -> false + * - path = A/B -> false + * - path = A -> false + * - path = A/B/C -> true + * - path = X -> false */ public static boolean containsSubpath(Collection paths, ItemPath pathToBeFound) { return paths.stream().anyMatch(p -> p.isSubPath(pathToBeFound)); @@ -554,7 +554,7 @@ public boolean startsWith(Class clazz) { public boolean startsWith(ItemPath other) { return other == null || other.isSubPathOrEquivalent(this); } - + public boolean startsWithName(QName name) { return !isEmpty() && startsWith(NameItemPathSegment.class) @@ -616,11 +616,11 @@ public static List fromStringList(List pathsAsStrings) { public enum CompareResult { EQUIVALENT, SUPERPATH, SUBPATH, NO_RELATION } - + public boolean isSubPath(ItemPath otherPath) { return compareComplex(otherPath) == CompareResult.SUBPATH; } - + public boolean isSuperPath(ItemPath otherPath) { return compareComplex(otherPath) == CompareResult.SUPERPATH; } @@ -685,7 +685,7 @@ public static Collection remainder(Collection paths, ItemPat } return rv; } - + /** * Convenience static method with checks * @throws IllegalArgumentException If the argument is an item path segment other than a named one @@ -699,7 +699,7 @@ public static QName getName(ItemPathSegment segment) { } return ((NameItemPathSegment)segment).getName(); } - + public static IdItemPathSegment getFirstIdSegment(ItemPath itemPath) { ItemPathSegment first = itemPath.first(); if (first instanceof IdItemPathSegment) { @@ -707,14 +707,14 @@ public static IdItemPathSegment getFirstIdSegment(ItemPath itemPath) { } return null; } - + public static NameItemPathSegment getFirstNameSegment(ItemPath itemPath) { if (itemPath == null) { return null; } return itemPath.getFirstNameSegment(); } - + public NameItemPathSegment getFirstNameSegment() { ItemPathSegment first = first(); if (first instanceof NameItemPathSegment) { @@ -725,14 +725,14 @@ public NameItemPathSegment getFirstNameSegment() { } return null; } - + public static QName getFirstName(ItemPath itemPath) { if (itemPath == null) { return null; } return itemPath.getFirstName(); } - + public QName getFirstName() { NameItemPathSegment nameSegment = getFirstNameSegment(); if (nameSegment == null) { @@ -740,7 +740,7 @@ public QName getFirstName() { } return nameSegment.getName(); } - + public static ItemPath pathRestStartingWithName(ItemPath path) { ItemPathSegment pathSegment = path.first(); if (pathSegment instanceof NameItemPathSegment) { @@ -760,7 +760,7 @@ public boolean containsName(QName name) { } return false; } - + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/path/ItemPathSegment.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/path/ItemPathSegment.java index 737c52498d4..774e8586889 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/path/ItemPathSegment.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/path/ItemPathSegment.java @@ -22,7 +22,7 @@ * */ public abstract class ItemPathSegment implements Serializable, Cloneable { - + private boolean wildcard = false; public boolean isWildcard() { diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/path/NameItemPathSegment.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/path/NameItemPathSegment.java index e66bcd1c835..489eb89adba 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/path/NameItemPathSegment.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/path/NameItemPathSegment.java @@ -26,12 +26,12 @@ * */ public class NameItemPathSegment extends ItemPathSegment { - + public static final NameItemPathSegment WILDCARD = NameItemPathSegment.createWildcard(); - + @NotNull private final QName name; private boolean isVariable = false; - + public NameItemPathSegment(@NotNull QName name) { this.name = name; } @@ -147,5 +147,5 @@ public NameItemPathSegment clone() { clone.setWildcard(this.isWildcard()); return clone; } - + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/polystring/PolyString.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/polystring/PolyString.java index d5b1f4f52da..69feabb8928 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/polystring/PolyString.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/polystring/PolyString.java @@ -37,11 +37,11 @@ * composed of the full Unicode character set. The other versions may be * normalized to trim it, normalize character case, normalize spaces, * remove national characters or even transliterate the string. - * + * * PolyString is (almost) immutable. The original value is immutable, but the * other normalized values can be changed. However the only way to change them * is to recompute them from the original value. - * + * * @author Radovan Semancik */ public class PolyString implements Matchable, Recomputable, Structured, DebugDumpable, Serializable, Comparable { @@ -52,7 +52,7 @@ public class PolyString implements Matchable, Recomputable, Structur private final String orig; private String norm = null; - + public PolyString(String orig) { super(); if (orig == null) { @@ -60,7 +60,7 @@ public PolyString(String orig) { } this.orig = orig; } - + public PolyString(String orig, String norm) { super(); if (orig == null) { @@ -77,22 +77,22 @@ public String getOrig() { public String getNorm() { return norm; } - + public boolean isEmpty() { if (orig == null) { return true; } return orig.isEmpty(); } - + public void recompute(PolyStringNormalizer normalizer) { norm = normalizer.normalize(orig); } - + public boolean isComputed() { return !(norm == null); } - + @Override public Object resolve(ItemPath subpath) { if (subpath == null || subpath.isEmpty()) { @@ -128,12 +128,12 @@ public PolyString plus(Object other) { } return new PolyString(this.orig + other.toString()); } - + // Groovy operator overload public PolyString getAt(int index) { return new PolyString(this.orig.substring(index, index+1)); } - + @Override public int compareTo(Object other) { if (other == null) { @@ -142,7 +142,7 @@ public int compareTo(Object other) { String otherString = other.toString(); return this.orig.compareTo(otherString); } - + // public PolyString getAt(Range at) { // // TODO // } @@ -150,15 +150,15 @@ public int compareTo(Object other) { // public PolyString getAt(IntRange at) { // // TODO // } - + public int length() { return orig.length(); } - + public PolyString trim() { return new PolyString(orig.trim(), norm.trim()); } - + public String substring(int from, int to) { return this.orig.substring(from,to); } @@ -215,7 +215,7 @@ public boolean equalsOriginalValue(Recomputable obj) { public String toString() { return orig; } - + @Override public String debugDump() { return debugDump(0); @@ -249,7 +249,7 @@ public boolean match(PolyString other) { return true; if (other == null) return false; - + if (norm == null) { if (other.norm != null) return false; @@ -257,7 +257,7 @@ public boolean match(PolyString other) { return false; return true; } - + @Override public boolean matches(String regex) { return Pattern.matches(regex, norm) || Pattern.matches(regex, orig); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/polystring/PolyStringNormalizer.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/polystring/PolyStringNormalizer.java index 8f87930e6ba..5ab4d6cbd37 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/polystring/PolyStringNormalizer.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/polystring/PolyStringNormalizer.java @@ -19,7 +19,7 @@ * Normalizer for PolyStrings. Classes implementing this interface are able to take an * original string (in the PolyString sense) and return a normalized version of the * string. - * + * * @see PolyString * @author Radovan Semancik */ diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/polystring/PrismDefaultPolyStringNormalizer.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/polystring/PrismDefaultPolyStringNormalizer.java index 629de8bcd2f..4813b8e30de 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/polystring/PrismDefaultPolyStringNormalizer.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/polystring/PrismDefaultPolyStringNormalizer.java @@ -16,7 +16,7 @@ package com.evolveum.midpoint.prism.polystring; import java.text.Normalizer; - +import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; /** @@ -24,6 +24,10 @@ * */ public class PrismDefaultPolyStringNormalizer implements PolyStringNormalizer { + private static final String MALFORMED_REGEX = "[^\\w\\s\\d]"; + private static final Pattern MALFORMED_PATTERN = Pattern.compile(MALFORMED_REGEX); + private static final String WHITESPACE_REGEX = "\\s+"; + private static final Pattern WHITESPACE_PATTERN = Pattern.compile(WHITESPACE_REGEX); /* (non-Javadoc) * @see com.evolveum.midpoint.prism.polystring.PolyStringNormalizer#normalize(java.lang.String) @@ -35,8 +39,8 @@ public String normalize(String orig) { } String s = StringUtils.trim(orig); s = Normalizer.normalize(s, Normalizer.Form.NFKD); - s = s.replaceAll("[^\\w\\s\\d]", ""); - s = s.replaceAll("\\s+", " "); + s = MALFORMED_PATTERN.matcher(s).replaceAll(""); + s = WHITESPACE_PATTERN.matcher(s).replaceAll(" "); if (StringUtils.isBlank(s)) { s = ""; } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/ExistsFilter.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/ExistsFilter.java index a1a19b9f86d..4efe3baf77c 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/ExistsFilter.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/ExistsFilter.java @@ -88,7 +88,7 @@ public ExistsFilter cloneEmpty() { public boolean match(PrismContainerValue value, MatchingRuleRegistry matchingRuleRegistry) throws SchemaException { throw new UnsupportedOperationException(); } - + @Override public void checkConsistence(boolean requireDefinitions) { if (fullPath.isEmpty()) { diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/FullTextFilter.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/FullTextFilter.java index f04d6aacd6b..835c5e5350c 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/FullTextFilter.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/FullTextFilter.java @@ -45,7 +45,7 @@ private FullTextFilter(ExpressionWrapper expression) { public static FullTextFilter createFullText(Collection values){ return new FullTextFilter(values); } - + public static FullTextFilter createFullText(String... values){ return new FullTextFilter(Arrays.asList(values)); } @@ -102,7 +102,7 @@ public String debugDump(int indent) { } return sb.toString(); } - + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/InOidFilter.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/InOidFilter.java index 8c8a10e43bb..acc40863a28 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/InOidFilter.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/InOidFilter.java @@ -35,12 +35,12 @@ public class InOidFilter extends ObjectFilter { private Collection oids; private ExpressionWrapper expression; private boolean considerOwner; // temporary hack (checks owner OID) - + private InOidFilter(boolean considerOwner, Collection oids) { this.considerOwner = considerOwner; this.oids = oids; } - + private InOidFilter(boolean considerOwner, ExpressionWrapper expression){ this.considerOwner = considerOwner; this.expression = expression; @@ -53,7 +53,7 @@ public static InOidFilter createInOid(boolean considerOwner, Collection public static InOidFilter createInOid(Collection oids){ return new InOidFilter(false, oids); } - + public static InOidFilter createInOid(String... oids){ return new InOidFilter(false, Arrays.asList(oids)); } @@ -69,11 +69,11 @@ public static InOidFilter createOwnerHasOidIn(String... oids){ public static InOidFilter createInOid(boolean considerOwner, ExpressionWrapper expression){ return new InOidFilter(considerOwner, expression); } - + public Collection getOids() { return oids; } - + public void setOids(Collection oids) { this.oids = oids; } @@ -85,11 +85,11 @@ public boolean isConsiderOwner() { public ExpressionWrapper getExpression() { return expression; } - + public void setExpression(ExpressionWrapper expression) { this.expression = expression; } - + @Override public void checkConsistence(boolean requireDefinitions) { if (oids == null) { @@ -120,11 +120,11 @@ public String debugDump(int indent) { } else { sb.append(" null"); } - + return sb.toString(); - + } - + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -139,7 +139,7 @@ public String toString() { sb.append(value); } sb.append("; "); - + } } return sb.toString(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/ItemFilter.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/ItemFilter.java index 7260e8f5231..a8499eafe1c 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/ItemFilter.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/ItemFilter.java @@ -21,7 +21,7 @@ @FunctionalInterface public interface ItemFilter { - + @NotNull ItemPath getFullPath(); } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/ObjectPaging.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/ObjectPaging.java index 9ec6e22d145..2a8b9e2d0f6 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/ObjectPaging.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/ObjectPaging.java @@ -207,12 +207,12 @@ public String debugDump(int indent) { if (getOffset() != null) { sb.append("\n"); DebugUtil.indentDebugDump(sb, indent + 1); - sb.append("Offset: " + getOffset()); + sb.append("Offset: ").append(getOffset()); } if (getMaxSize() != null) { sb.append("\n"); DebugUtil.indentDebugDump(sb, indent + 1); - sb.append("Max size: " + getMaxSize()); + sb.append("Max size: ").append(getMaxSize()); } if (hasOrdering()) { sb.append("\n"); @@ -222,7 +222,7 @@ public String debugDump(int indent) { if (getCookie() != null) { sb.append("\n"); DebugUtil.indentDebugDump(sb, indent + 1); - sb.append("Cookie: " + getCookie()); + sb.append("Cookie: ").append(getCookie()); } return sb.toString(); } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/TypeFilter.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/TypeFilter.java index 928fac50fe2..6e8b82571eb 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/TypeFilter.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/TypeFilter.java @@ -101,7 +101,7 @@ public boolean match(PrismContainerValue value, MatchingRuleRegistry matchingRul return filter.match(value, matchingRuleRegistry); } } - + @Override public void checkConsistence(boolean requireDefinitions) { if (type == null) { diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/UndefinedFilter.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/UndefinedFilter.java index 86c37eb8906..1cc1a10a74b 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/UndefinedFilter.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/UndefinedFilter.java @@ -29,7 +29,7 @@ public UndefinedFilter() { public static UndefinedFilter createUndefined() { return new UndefinedFilter(); } - + @Override public UndefinedFilter clone() { return new UndefinedFilter(); @@ -53,7 +53,7 @@ public String debugDump(int indent) { return sb.toString(); } - + @Override public String toString() { return "UNDEFINED"; diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/ValueFilter.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/ValueFilter.java index 7581cf23b9d..f1b613079d7 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/ValueFilter.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/ValueFilter.java @@ -177,7 +177,7 @@ public V getSingleValue() { } /** - * @pre value has to be parent-less + * @param value value, has to be parent-less */ public void setValue(V value) { this.values = new ArrayList<>(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/Visitor.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/Visitor.java index 41496fd9df5..ceb1b5193a5 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/Visitor.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/Visitor.java @@ -20,5 +20,5 @@ public interface Visitor { void visit(ObjectFilter filter); - + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/builder/R_AtomicFilter.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/builder/R_AtomicFilter.java index 2934cccc59b..97bb7de31ce 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/builder/R_AtomicFilter.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/query/builder/R_AtomicFilter.java @@ -218,7 +218,7 @@ public S_MatchingRuleEntry containsPoly(String orig, String norm) { public S_MatchingRuleEntry containsPoly(String orig) { return contains(new PolyString(orig)); } - + @Override public S_AtomicFilterExit ref(QName relation) { PrismReferenceValue ref = new PrismReferenceValue(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/DomToSchemaProcessor.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/DomToSchemaProcessor.java index 2939c07c0bc..221d90ba99f 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/DomToSchemaProcessor.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/DomToSchemaProcessor.java @@ -61,11 +61,11 @@ /** * Parser for DOM-represented XSD, creates midPoint Schema representation. - * + * * It will parse schema in several passes. It has special handling if the schema * is "resource schema", which will create ResourceObjectDefinition and * ResourceObjectAttributeDefinition instead of PropertyContainer and Property. - * + * * @author lazyman * @author Radovan Semancik */ @@ -139,8 +139,8 @@ public void setAllowDelayedItemDefinitions(boolean allowDelayedItemDefinitions) /** * Main entry point. - * - * + * + * * @param xsdSchema * DOM-represented XSD schema * @return parsed midPoint schema @@ -248,10 +248,10 @@ private XSOMParser createSchemaParser() { /** * Create ComplexTypeDefinitions from all top-level complexType definitions * in the XSD. - * + * * These definitions are the reused later to fit inside PropertyContainer * definitions. - * + * * @param set * XS Schema Set */ @@ -280,7 +280,7 @@ private ComplexTypeDefinition getOrProcessComplexType(QName typeName) throws Sch /** * Creates ComplexTypeDefinition object from a single XSD complexType * definition. - * + * * @param complexType * XS complex type definition */ @@ -448,7 +448,7 @@ private void extractDocumentation(Definition definition, XSAnnotation annotation * complexType definition. This is a recursive method. It can create * "anonymous" internal PropertyContainerDefinitions. The definitions will * be added to the ComplexTypeDefinition provided as parameter. - * + * * @param group * XSD XSModelGroup * @param ctd @@ -645,10 +645,10 @@ private void setMultiplicity(ItemDefinition itemDef, XSParticle particle, XSAnno * a potential PropertyContainer. The element name will be set as name of * the PropertyContainer, element type will become type (indirectly through * ComplexTypeDefinition). - * + * * No need to recurse here. All the work was already done while creating * ComplexTypeDefinitions. - * + * * @param set * XS Schema Set * @throws SchemaException @@ -937,7 +937,7 @@ private boolean isObjectDefinition(XSType xsType) { * PropertyContainerDefinition itself or one of its subclasses * (ResourceObjectDefinition). This method also takes care of parsing all * the annotations and similar fancy stuff. - * + * * We need to pass createResourceObject flag explicitly here. Because even * if we are in resource schema, we want PropertyContainers inside * ResourceObjects, not ResourceObjects inside ResouceObjects. @@ -1052,7 +1052,7 @@ private PrismPropertyDefinitionImpl createPropertyDefinition(XSType xsTyp QName matchingRule = XmlTypeConverter.toJavaValue(matchingRuleElement, QName.class); propDef.setMatchingRuleQName(matchingRule); } - + Element valueEnumerationRefElement = SchemaProcessorUtil.getAnnotationElement(annotation, A_VALUE_ENUMERATION_REF); if (valueEnumerationRefElement != null) { String oid = valueEnumerationRefElement.getAttribute(PrismConstants.ATTRIBUTE_OID_LOCAL_NAME); @@ -1139,7 +1139,7 @@ private Collection> parseEnumAllowedValues(QNa descriptionE != null ? descriptionE.getTextContent() : null); } - + } else { edv = new DisplayableValueImpl(value, label, descriptionE != null ? descriptionE.getTextContent() : null); @@ -1198,7 +1198,7 @@ private void parseItemDefinitionAnnotations(ItemDefinitionImpl itemDef, XSAnnota if (help != null) { itemDef.setHelp(help.getTextContent()); } - + // emphasized Boolean emphasized = SchemaProcessorUtil.getAnnotationBooleanMarker(annotation, A_EMPHASIZED); if (emphasized != null) { diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/PrismSchemaImpl.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/PrismSchemaImpl.java index 10ed6910a70..e971bff1c84 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/PrismSchemaImpl.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/PrismSchemaImpl.java @@ -34,14 +34,14 @@ /** * * @author Radovan Semancik - * + * */ public class PrismSchemaImpl implements PrismSchema { //private static final long serialVersionUID = 5068618465625931984L; //private static final Trace LOGGER = TraceManager.getTrace(PrismSchema.class); - + @NotNull protected final Collection definitions = new ArrayList<>(); @NotNull private final Map> itemDefinitionMap = new HashMap<>(); // key is the item name (qualified or unqualified) protected String namespace; // may be null if not properly initialized @@ -55,7 +55,7 @@ public class PrismSchemaImpl implements PrismSchema { protected PrismSchemaImpl(PrismContext prismContext) { this.prismContext = prismContext; } - + public PrismSchemaImpl(@NotNull String namespace, PrismContext prismContext) { if (StringUtils.isEmpty(namespace)) { throw new IllegalArgumentException("Namespace can't be null or empty."); @@ -111,7 +111,7 @@ public void add(@NotNull Definition def) { itemDefinitionMap.put(itemDef.getName(), itemDef); } } - + @Override public PrismContext getPrismContext() { return prismContext; @@ -124,16 +124,16 @@ public static PrismSchema parse(Element element, boolean isRuntime, String short return parse(element, prismContext.getEntityResolver(), new PrismSchemaImpl(prismContext), isRuntime, shortDescription, false, prismContext); } - + public static PrismSchema parse(Element element, EntityResolver resolver, boolean isRuntime, String shortDescription, boolean allowDelayedItemDefinitions, PrismContext prismContext) throws SchemaException { return parse(element, resolver, new PrismSchemaImpl(prismContext), isRuntime, shortDescription, allowDelayedItemDefinitions, prismContext); } - + protected static PrismSchema parse(Element element, PrismSchemaImpl schema, boolean isRuntime, String shortDescription, PrismContext prismContext) throws SchemaException { return parse(element, prismContext.getEntityResolver(), schema, isRuntime, shortDescription, false, prismContext); } - + private static PrismSchema parse(Element element, EntityResolver resolver, PrismSchemaImpl schema, boolean isRuntime, String shortDescription, boolean allowDelayedItemDefinitions, PrismContext prismContext) throws SchemaException { if (element == null) { @@ -162,9 +162,9 @@ public Document serializeToXsd() throws SchemaException { //region Creating definitions /** * Creates a new property container definition and adds it to the schema. - * + * * This is a preferred way how to create definition in the schema. - * + * * @param localTypeName * type name "relative" to schema namespace * @return new property container definition @@ -178,7 +178,7 @@ public PrismContainerDefinitionImpl createPropertyContainerDefinition(String loc add(def); return def; } - + public PrismContainerDefinitionImpl createPropertyContainerDefinition(String localElementName, String localTypeName) { QName typeName = new QName(getNamespace(), localTypeName); QName name = new QName(getNamespace(), localElementName); @@ -191,7 +191,7 @@ public PrismContainerDefinitionImpl createPropertyContainerDefinition(String loc add(def); return def; } - + public ComplexTypeDefinition createComplexTypeDefinition(QName typeName) { ComplexTypeDefinition cTypeDef = new ComplexTypeDefinitionImpl(typeName, prismContext); add(cTypeDef); @@ -200,9 +200,9 @@ public ComplexTypeDefinition createComplexTypeDefinition(QName typeName) { /** * Creates a top-level property definition and adds it to the schema. - * + * * This is a preferred way how to create definition in the schema. - * + * * @param localName * element name "relative" to schema namespace * @param typeName @@ -216,9 +216,9 @@ public PrismPropertyDefinition createPropertyDefinition(String localName, QName /* * Creates a top-level property definition and adds it to the schema. - * + * * This is a preferred way how to create definition in the schema. - * + * * @param localName * element name "relative" to schema namespace * @param localTypeName @@ -233,9 +233,9 @@ public PrismPropertyDefinition createPropertyDefinition(String localName, QName /** * Creates a top-level property definition and adds it to the schema. - * + * * This is a preferred way how to create definition in the schema. - * + * * @param name * element name * @param typeName diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaDefinitionFactory.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaDefinitionFactory.java index 416354bde72..7f3797fe0e6 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaDefinitionFactory.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaDefinitionFactory.java @@ -38,7 +38,7 @@ public class SchemaDefinitionFactory { public ComplexTypeDefinition createComplexTypeDefinition(XSComplexType complexType, PrismContext prismContext, XSAnnotation annotation) throws SchemaException { - + QName typeName = new QName(complexType.getTargetNamespace(),complexType.getName()); return new ComplexTypeDefinitionImpl(typeName, prismContext); } @@ -63,17 +63,17 @@ public PrismPropertyDefinition createPropertyDefinition(QName elementName PrismContext prismContext, XSAnnotation annotation, XSParticle elementParticle) throws SchemaException { return new PrismPropertyDefinitionImpl(elementName, typeName, prismContext); } - + public PrismPropertyDefinition createPropertyDefinition(QName elementName, QName typeName, ComplexTypeDefinition complexTypeDefinition, PrismContext prismContext, XSAnnotation annotation, XSParticle elementParticle, Collection> allowedValues, T defaultValue) throws SchemaException { return new PrismPropertyDefinitionImpl(elementName, typeName, prismContext, allowedValues, defaultValue); } - + public PrismReferenceDefinition createReferenceDefinition(QName primaryElementName, QName typeName, ComplexTypeDefinition complexTypeDefinition, PrismContext prismContext, XSAnnotation annotation, XSParticle elementParticle) throws SchemaException { return new PrismReferenceDefinitionImpl(primaryElementName, typeName, prismContext); } - + public PrismContainerDefinitionImpl createContainerDefinition(QName elementName, ComplexTypeDefinition complexTypeDefinition, PrismContext prismContext, Class compileTimeClass) throws SchemaException { return new PrismContainerDefinitionImpl<>(elementName, complexTypeDefinition, prismContext, compileTimeClass); @@ -89,7 +89,7 @@ public PrismObjectDefinitionImpl createObjectDefinitio * This is used e.g. to create object class definitions in midPoint */ public PrismContainerDefinition createExtraDefinitionFromComplexType(XSComplexType complexType, - ComplexTypeDefinition complexTypeDefinition, PrismContext prismContext, + ComplexTypeDefinition complexTypeDefinition, PrismContext prismContext, XSAnnotation annotation) throws SchemaException { // Create nothing by default return null; @@ -124,5 +124,5 @@ public void addExtraPropertyAnnotations(PrismPropertyDefinition definition, Elem public void addExtraReferenceAnnotations(PrismReferenceDefinition definition, Element appinfo, SchemaToDomProcessor schemaToDomProcessor) { // Nothing to do by default } - + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaDescription.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaDescription.java index bf869af080e..e2d15d815ce 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaDescription.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaDescription.java @@ -49,7 +49,7 @@ public class SchemaDescription implements DebugDumpable { private String usualPrefix; private String namespace; private String sourceDescription; - private InputStreamable streamable; + private InputStreamable streamable; private Node node; private boolean isPrismSchema = false; private boolean isDefault = false; @@ -85,7 +85,7 @@ public String getUsualPrefix() { public void setUsualPrefix(String usualPrefix) { this.usualPrefix = usualPrefix; } - + public String getSourceDescription() { return sourceDescription; } @@ -101,11 +101,11 @@ public void setPath(String path) { public boolean isPrismSchema() { return isPrismSchema; } - + public void setPrismSchema(boolean isMidPointSchema) { this.isPrismSchema = isMidPointSchema; } - + public boolean isDefault() { return isDefault; } @@ -137,7 +137,7 @@ public Package getCompileTimeClassesPackage() { public void setCompileTimeClassesPackage(Package compileTimeClassesPackage) { this.compileTimeClassesPackage = compileTimeClassesPackage; } - + public Map> getXsdTypeTocompileTimeClassMap() { return xsdTypeTocompileTimeClassMap; } @@ -232,7 +232,7 @@ public InputStream openInputStream() { desc.parseFromInputStream(); return desc; } - + private void parseFromInputStream() throws SchemaException { InputStream inputStream = streamable.openInputStream(); try { @@ -249,7 +249,7 @@ public static SchemaDescription parseNode(Node node, String sourceDescription) t desc.fetchBasicInfoFromSchema(); return desc; } - + private void fetchBasicInfoFromSchema() throws SchemaException { Element rootElement = getDomElement(); if (DOMUtil.XSD_SCHEMA_ELEMENT.equals(DOMUtil.getQName(rootElement))) { @@ -263,11 +263,11 @@ private void fetchBasicInfoFromSchema() throws SchemaException { throw new SchemaException("Schema "+sourceDescription+" does not start with xsd:schema element"); } } - + public boolean canInputStream() { return (streamable != null); } - + public InputStream openInputStream() { if (!canInputStream()) { throw new IllegalStateException("Schema "+sourceDescription+" cannot provide input stream"); @@ -288,14 +288,14 @@ public Source getSource() { source.setSystemId(path); return source; } - + public Element getDomElement() { if (node instanceof Element) { return (Element)node; } return DOMUtil.getFirstChildElement(node); } - + @FunctionalInterface private interface InputStreamable { InputStream openInputStream(); @@ -305,7 +305,7 @@ private interface InputStreamable { public String debugDump() { return debugDump(0); } - + @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaHandler.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaHandler.java index 4a3b478ff26..ec68bdd03d6 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaHandler.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaHandler.java @@ -31,9 +31,9 @@ /** * Implements {@link EntityResolver} and {@link ErrorHandler} that reports sax * errors to log. - * + * * @author Vilo Repan - * + * */ public class SchemaHandler implements ErrorHandler, EntityResolver { @@ -79,7 +79,7 @@ private void print(String header, SAXParseException e) { /* * (non-Javadoc) - * + * * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, * java.lang.String) */ diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaProcessorUtil.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaProcessorUtil.java index eb5b1999d36..5ca7757dacb 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaProcessorUtil.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaProcessorUtil.java @@ -32,12 +32,12 @@ /** * Class to be used by schema processor but also by SchemaDefinitionFactory subclasses. - * + * * @author Radovan Semancik * */ public class SchemaProcessorUtil { - + public static final String MULTIPLICITY_UNBOUNDED = "unbounded"; public static boolean hasAnnotation(XSType xsType, QName annotationElementName) { @@ -53,7 +53,7 @@ public static boolean hasAnnotation(XSType xsType, QName annotationElementName) } return false; } - + public static Element getAnnotationElement(XSAnnotation annotation, QName qname) { if (annotation == null) { return null; @@ -90,9 +90,9 @@ public static QName getAnnotationQName(XSAnnotation annotation, QName qname) { } return DOMUtil.getQNameValue(element); } - + /** - * Parses "marker" boolean annotation. This means: + * Parses "marker" boolean annotation. This means: * no element: false * empty element: true * non-empty element: parse element content as boolean @@ -130,5 +130,5 @@ public static Integer parseMultiplicity(String stringMultiplicity) { } return Integer.parseInt(stringMultiplicity); } - + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaRegistryImpl.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaRegistryImpl.java index 36a00f36c1a..6b4f1076780 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaRegistryImpl.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaRegistryImpl.java @@ -72,23 +72,23 @@ /** * Registry and resolver of schema files and resources. - * - * + * + * * @author Radovan Semancik * */ public class SchemaRegistryImpl implements DebugDumpable, SchemaRegistry { - + private static final QName DEFAULT_XSD_TYPE = DOMUtil.XSD_STRING; private static final String DEFAULT_RUNTIME_CATALOG_RESOURCE = "META-INF/catalog-runtime.xml"; private File[] catalogFiles; // overrides catalog resource name private String catalogResourceName = DEFAULT_RUNTIME_CATALOG_RESOURCE; - + private javax.xml.validation.SchemaFactory schemaFactory; private javax.xml.validation.Schema javaxSchema; - private EntityResolver builtinSchemaResolver; + private EntityResolver builtinSchemaResolver; final private List schemaDescriptions = new ArrayList<>(); final private Map parsedSchemas = new HashMap<>(); final private Map extensionSchemas = new HashMap<>(); @@ -100,7 +100,7 @@ public class SchemaRegistryImpl implements DebugDumpable, SchemaRegistry { @Autowired // TODO does this work? private PrismContext prismContext; - + private static final Trace LOGGER = TraceManager.getTrace(SchemaRegistry.class); @Override @@ -167,7 +167,7 @@ public void registerSchemaResource(String resourcePath, String usualPrefix) thro desc.setUsualPrefix(usualPrefix); registerSchemaDescription(desc); } - + /** * Must be called before call to initialize() */ @@ -252,7 +252,7 @@ public void registerSchema(Node node, String sourceDescription, String usualPref desc.setUsualPrefix(usualPrefix); registerSchemaDescription(desc); } - + public void registerPrismSchemaFile(File file) throws FileNotFoundException, SchemaException { loadPrismSchemaFileDescription(file); } @@ -290,7 +290,7 @@ private void registerSchemaDescription(SchemaDescription desc) { parsedSchemas.put(desc.getNamespace(), desc); schemaDescriptions.add(desc); } - + public void registerPrismSchemasFromDirectory(File directory) throws FileNotFoundException, SchemaException { File[] fileArray = directory.listFiles(); if (fileArray != null) { @@ -312,7 +312,7 @@ public void registerPrismSchemasFromDirectory(File directory) throws FileNotFoun } } } - + /** * This can be used to read additional schemas even after the registry was initialized. */ @@ -334,7 +334,7 @@ public void loadPrismSchemasFromDirectory(File directory) throws FileNotFoundExc } } } - + public void loadPrismSchemaFile(File file) throws FileNotFoundException, SchemaException { SchemaDescription desc = loadPrismSchemaFileDescription(file); parsePrismSchema(desc, false); @@ -349,7 +349,7 @@ public void loadPrismSchemaResource(String resourcePath) throws SchemaException /** * This can be used to read additional schemas even after the registry was initialized. - */ + */ @Override public void initialize() throws SAXException, IOException, SchemaException { if (prismContext == null) { @@ -369,7 +369,7 @@ public void initialize() throws SAXException, IOException, SchemaException { compileCompileTimeClassList(); LOGGER.trace("compileCompileTimeClassList() done"); initialized = true; - + } catch (SAXException ex) { if (ex instanceof SAXParseException) { SAXParseException sex = (SAXParseException)ex; @@ -420,7 +420,7 @@ private void resolveMissingTypeDefinitionsInGlobalItemDefinitions(PrismSchemaImp private void parsePrismSchema(SchemaDescription schemaDescription, boolean allowDelayedItemDefinitions) throws SchemaException { String namespace = schemaDescription.getNamespace(); - + Element domElement = schemaDescription.getDomElement(); boolean isRuntime = schemaDescription.getCompileTimeClassesPackage() == null; long started = System.currentTimeMillis(); @@ -451,7 +451,7 @@ private void detectExtensionSchema(PrismSchema schema) throws SchemaException { } } } - + private void applySchemaExtensions() throws SchemaException { for (Entry entry: extensionSchemas.entrySet()) { QName typeQName = entry.getKey(); @@ -466,9 +466,9 @@ private void applySchemaExtensions() throws SchemaException { ((PrismContainerDefinitionImpl) extensionContainer).setTypeName(extensionCtd.getTypeName()); } } - + private void compileCompileTimeClassList() { - for (SchemaDescription schemaDescription : schemaDescriptions) { + for (SchemaDescription schemaDescription : schemaDescriptions) { Package pkg = schemaDescription.getCompileTimeClassesPackage(); if (pkg != null) { Map> map = createXsdTypeMap(pkg); @@ -512,7 +512,7 @@ private void initResolver() throws IOException { public javax.xml.validation.Schema getJavaxSchema() { return javaxSchema; } - + @Override public Collection getCompileTimePackages() { Collection compileTimePackages = new ArrayList(schemaDescriptions.size()); @@ -523,7 +523,7 @@ public Collection getCompileTimePackages() { } return compileTimePackages; } - + private Map> createXsdTypeMap(Package pkg) { Map> map = new HashMap>(); for (Class clazz: ClassPathUtil.listClasses(pkg)) { @@ -552,7 +552,7 @@ private SchemaDescription lookupSchemaDescription(String namespace) { public String debugDump() { return debugDump(0); } - + @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); @@ -574,19 +574,19 @@ public String debugDump(int indent) { public void applyDefinition(PrismContainer container, Class type) throws SchemaException { applyDefinition(container, type, true); } - + @Override public void applyDefinition(PrismContainer container, Class compileTimeClass, boolean force) throws SchemaException { PrismContainerDefinition definition = determineDefinitionFromClass(compileTimeClass); container.applyDefinition(definition, force); } - + @Override public void applyDefinition(ObjectDelta objectDelta, Class compileTimeClass, boolean force) throws SchemaException { PrismObjectDefinition objectDefinition = determineDefinitionFromClass(compileTimeClass); objectDelta.applyDefinition(objectDefinition, force); } - + @Override public void applyDefinition(PrismContainerValue prismContainerValue, Class compileTimeClass, ItemPath path, boolean force) throws SchemaException { diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaToDomProcessor.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaToDomProcessor.java index 8947335f693..5a928d6e57f 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaToDomProcessor.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/schema/SchemaToDomProcessor.java @@ -46,13 +46,13 @@ /** * Takes a midPoint Schema definition and produces a XSD schema (in a DOM form). - * + * * Great pains were taken to make sure that the output XML is "nice" and human readable. * E.g. the namespace prefixes are unified using the definitions in SchemaRegistry. * Please do not ruin this if you would update this class. - * + * * Single use class. Not thread safe. Create new instance for each run. - * + * * @author lazyman * @author Radovan Semancik */ @@ -71,7 +71,7 @@ public class SchemaToDomProcessor { SchemaToDomProcessor() { importNamespaces = new HashSet(); } - + public PrismContext getPrismContext() { return prismContext; } @@ -91,22 +91,22 @@ public DynamicNamespacePrefixMapper getNamespacePrefixMapper() { public void setNamespacePrefixMapper(DynamicNamespacePrefixMapper namespacePrefixMapper) { this.namespacePrefixMapper = namespacePrefixMapper; } - + private SchemaDefinitionFactory getDefinitionFactory() { return ((PrismContextImpl) prismContext).getDefinitionFactory(); } - + private String getNamespace() { return schema.getNamespace(); } - + private boolean isMyNamespace(QName qname) { return getNamespace().equals(qname.getNamespaceURI()); } /** * Main entry point. - * + * * @param schema midPoint schema * @return XSD schema in DOM form * @throws SchemaException error parsing the midPoint schema or converting values @@ -119,36 +119,36 @@ Document parseSchema(PrismSchema schema) throws SchemaException { this.schema = schema; try { - + init(); // here the document is initialized - - // Process complex types first. + + // Process complex types first. Collection complexTypes = schema.getDefinitions(ComplexTypeDefinition.class); for (ComplexTypeDefinition complexTypeDefinition: complexTypes) { addComplexTypeDefinition(complexTypeDefinition, document.getDocumentElement()); } - + Collection definitions = schema.getDefinitions(); for (Definition definition : definitions) { - + if (definition instanceof PrismContainerDefinition) { // Add property container definition. This will add and definitions to XSD addContainerDefinition((PrismContainerDefinition) definition, document.getDocumentElement(), document.getDocumentElement()); - + } else if (definition instanceof PrismPropertyDefinition) { // Add top-level property definition. It will create XSD definition addPropertyDefinition((PrismPropertyDefinition) definition, document.getDocumentElement()); - + } else if (definition instanceof ComplexTypeDefinition){ // Skip this. Already processed above. - + } else { throw new IllegalArgumentException("Encountered unsupported definition in schema: " + definition); } - + // TODO: process unprocessed ComplexTypeDefinitions } @@ -166,15 +166,15 @@ Document parseSchema(PrismSchema schema) throws SchemaException { * Adds XSD definitions from PropertyContainerDefinition. This is complexType and element. * If the property container is an ResourceObjectDefinition, it will add only annotated * complexType definition. - * + * * @param definition PropertyContainerDefinition to process * @param parent element under which the XSD definition will be added */ private void addContainerDefinition(PrismContainerDefinition definition, Element elementParent, Element complexTypeParent) { - + ComplexTypeDefinition complexTypeDefinition = definition.getComplexTypeDefinition(); - + if (complexTypeDefinition != null && // Check if the complex type is a top-level complex type. If it is then it was already processed and we can skip it schema.findComplexTypeDefinition(complexTypeDefinition.getTypeName()) == null && @@ -186,7 +186,7 @@ private void addContainerDefinition(PrismContainerDefinition definition, Element elementElement = addElementDefinition(definition.getName(), definition.getTypeName(), definition.getMinOccurs(), definition.getMaxOccurs(), elementParent); - + if (complexTypeDefinition == null || !complexTypeDefinition.isContainerMarker()) { // Need to add a:container annotation to the element as the complex type does not have it addAnnotationToDefinition(elementElement, A_PROPERTY_CONTAINER); @@ -227,7 +227,7 @@ private void addPropertyDefinition(PrismPropertyDefinition definition, Element p annotation.appendChild(appinfo); addCommonDefinitionAnnotations(definition, appinfo); - + if (!definition.canAdd() || !definition.canRead() || !definition.canModify()) { // read-write-create attribute is the default. If any of this flags is missing, we must // add appropriate annotations. @@ -241,28 +241,28 @@ private void addPropertyDefinition(PrismPropertyDefinition definition, Element p addAnnotation(A_ACCESS, A_ACCESS_UPDATE, appinfo); } } - + if (definition.isIndexed() != null) { addAnnotation(A_INDEXED, XmlTypeConverter.toXmlTextContent(definition.isIndexed(), A_INDEXED), appinfo); } - + if (definition.getMatchingRuleQName() != null) { addAnnotation(A_MATCHING_RULE, definition.getMatchingRuleQName(), appinfo); } - + if (definition.getValueEnumerationRef() != null) { addAnnotation(A_VALUE_ENUMERATION_REF, definition.getValueEnumerationRef(), appinfo); } - + SchemaDefinitionFactory definitionFactory = getDefinitionFactory(); definitionFactory.addExtraPropertyAnnotations(definition, appinfo, this); - + if (!appinfo.hasChildNodes()) { // remove unneeded element property.removeChild(annotation); } } - + /** * Adds XSD element definition created from the PrismReferenceDefinition. * TODO: need to finish @@ -296,11 +296,11 @@ private void addReferenceDefinition(PrismReferenceDefinition definition, Element if (definition.getTargetTypeName() != null) { addAnnotation(A_OBJECT_REFERENCE_TARGET_TYPE, definition.getTargetTypeName(), appinfo); } - + if (definition.getCompositeObjectElementName() == null) { return; } - + property = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "element")); // Add to document first, so following methods will be able to resolve namespaces parent.appendChild(property); @@ -327,12 +327,12 @@ private void addReferenceDefinition(PrismReferenceDefinition definition, Element if (definition.isComposite()) { addAnnotation(A_COMPOSITE, definition.isComposite(), appinfo); } - + SchemaDefinitionFactory definitionFactory = getDefinitionFactory(); definitionFactory.addExtraReferenceAnnotations(definition, appinfo, this); } - + /** * Adds XSD element definition. * @param name element QName @@ -342,10 +342,10 @@ private void addReferenceDefinition(PrismReferenceDefinition definition, Element private Element addElementDefinition(QName name, QName typeName, int minOccurs, int maxOccurs, Element parent) { Element elementDef = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "element")); parent.appendChild(elementDef); - + if (isMyNamespace(name)) { setAttribute(elementDef, "name", name.getLocalPart()); - + if (typeName.equals(DOMUtil.XSD_ANY)) { addSequenceXsdAnyDefinition(elementDef); } else { @@ -359,10 +359,10 @@ private Element addElementDefinition(QName name, QName typeName, int minOccurs, addAnnotationToDefinition(elementDef, A_TYPE, typeName); } } - + setMultiplicityAttribute(elementDef, "minOccurs", minOccurs); setMultiplicityAttribute(elementDef, "maxOccurs", maxOccurs); - + return elementDef; } @@ -373,7 +373,7 @@ private void addSequenceXsdAnyDefinition(Element elementDef) { complexContextElement.appendChild(sequenceElement); addXsdAnyDefinition(sequenceElement); } - + private void addXsdAnyDefinition(Element elementDef) { Element anyElement = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "any")); elementDef.appendChild(anyElement); @@ -406,7 +406,7 @@ private Element addComplexTypeDefinition(ComplexTypeDefinition definition, setAttribute(complexType, "name", definition.getTypeName().getLocalPart()); Element annotation = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "annotation")); complexType.appendChild(annotation); - + Element containingElement = complexType; if (definition.getSuperType() != null) { Element complexContent = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "complexContent")); @@ -427,20 +427,20 @@ private Element addComplexTypeDefinition(ComplexTypeDefinition definition, } else if (def instanceof PrismContainerDefinition) { PrismContainerDefinition contDef = (PrismContainerDefinition)def; addContainerDefinition(contDef, sequence, parent); - } else if (def instanceof PrismReferenceDefinition) { + } else if (def instanceof PrismReferenceDefinition) { addReferenceDefinition((PrismReferenceDefinition) def, sequence); } else { throw new IllegalArgumentException("Uknown definition "+def+"("+def.getClass().getName()+") in complex type definition "+def); } } - + if (definition.isXsdAnyMarker()) { addXsdAnyDefinition(sequence); } - + Element appinfo = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "appinfo")); annotation.appendChild(appinfo); - + if (definition.isObjectMarker()) { // annotation: propertyContainer addAnnotation(A_OBJECT, definition.getDisplayName(), appinfo); @@ -448,46 +448,46 @@ private Element addComplexTypeDefinition(ComplexTypeDefinition definition, // annotation: propertyContainer addAnnotation(A_PROPERTY_CONTAINER, definition.getDisplayName(), appinfo); } - + addCommonDefinitionAnnotations(definition, appinfo); - + SchemaDefinitionFactory definitionFactory = getDefinitionFactory(); definitionFactory.addExtraComplexTypeAnnotations(definition, appinfo, this); - + if (!appinfo.hasChildNodes()) { // remove unneeded element complexType.removeChild(annotation); } - + return complexType; } - + private void addCommonDefinitionAnnotations(Definition definition, Element appinfoElement) { if (definition.isIgnored()) { addAnnotation(A_IGNORE, "true", appinfoElement); } - + if ((definition instanceof ItemDefinition) && ((ItemDefinition)definition).isOperational()) { addAnnotation(A_OPERATIONAL, "true", appinfoElement); } - + if (definition.getDisplayName() != null) { addAnnotation(A_DISPLAY_NAME, definition.getDisplayName(), appinfoElement); } - + if (definition.getDisplayOrder() != null) { addAnnotation(A_DISPLAY_ORDER, definition.getDisplayOrder().toString(), appinfoElement); } - + if (definition.getHelp() != null) { addAnnotation(A_HELP, definition.getHelp(), appinfoElement); } - + if (definition.isEmphasized()) { addAnnotation(A_EMPHASIZED, "true", appinfoElement); } } - + /** * Add generic annotation element. * @param qname QName of the element @@ -503,20 +503,20 @@ public Element addAnnotation(QName qname, String value, Element parent) { } return annotation; } - + public Element addAnnotation(QName qname, boolean value, Element parent) { Element annotation = createElement(qname); parent.appendChild(annotation); annotation.setTextContent(Boolean.toString(value)); return annotation; } - + public Element addAnnotation(QName qname, Element parent) { Element annotation = createElement(qname); parent.appendChild(annotation); return annotation; } - + public Element addAnnotation(QName qname, QName value, Element parent) { Element annotation = createElement(qname); parent.appendChild(annotation); @@ -525,7 +525,7 @@ public Element addAnnotation(QName qname, QName value, Element parent) { } return annotation; } - + public Element addAnnotation(QName qname, PrismReferenceValue value, Element parent) { Element annotation = createElement(qname); parent.appendChild(annotation); @@ -535,11 +535,11 @@ public Element addAnnotation(QName qname, PrismReferenceValue value, Element par } return annotation; } - + private void addAnnotationToDefinition(Element definitionElement, QName qname) { addAnnotationToDefinition(definitionElement, qname, null); } - + private void addAnnotationToDefinition(Element definitionElement, QName qname, QName value) { Element annotationElement = getOrCreateElement(new QName(W3C_XML_SCHEMA_NS_URI, "annotation"), definitionElement); Element appinfoElement = getOrCreateElement(new QName(W3C_XML_SCHEMA_NS_URI, "appinfo"), annotationElement); @@ -549,7 +549,7 @@ private void addAnnotationToDefinition(Element definitionElement, QName qname, Q addAnnotation(qname, value, appinfoElement); } } - + private Element getOrCreateElement(QName qName, Element parentElement) { NodeList elements = parentElement.getElementsByTagNameNS(qName.getNamespaceURI(), qName.getLocalPart()); if (elements.getLength() == 0) { @@ -586,15 +586,15 @@ private void init() throws ParserConfigurationException { // TODO: clone? namespacePrefixMapper = ((SchemaRegistryImpl) prismContext.getSchemaRegistry()).getNamespacePrefixMapper(); } - + // We don't want the "tns" prefix to be kept in the mapper namespacePrefixMapper = namespacePrefixMapper.clone(); namespacePrefixMapper.registerPrefixLocal(getNamespace(), "tns"); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Using namespace prefix mapper to serialize schema:\n{}",DebugUtil.dump(namespacePrefixMapper)); } - + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(false); @@ -603,18 +603,18 @@ private void init() throws ParserConfigurationException { document = db.newDocument(); Element root = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "schema")); document.appendChild(root); - + rootXsdElement = document.getDocumentElement(); setAttribute(rootXsdElement, "targetNamespace", getNamespace()); setAttribute(rootXsdElement, "elementFormDefault", "qualified"); - + DOMUtil.setNamespaceDeclaration(rootXsdElement, "tns", getNamespace()); - + if (attributeQualified) { setAttribute(rootXsdElement, "attributeFormDefault", "qualified"); } } - + /** * Create DOM document with a root element. */ @@ -648,11 +648,11 @@ public Element createElement(QName qname) { private void setAttribute(Element element, String attrName, String attrValue) { setAttribute(element, new QName(W3C_XML_SCHEMA_NS_URI, attrName), attrValue); } - + private void setAttribute(Element element, String attrName, QName attrValue) { setAttribute(element, new QName(W3C_XML_SCHEMA_NS_URI, attrName), attrValue); } - + private void setMultiplicityAttribute(Element element, String attrName, int attrValue) { if (attrValue == 1) { return; @@ -674,7 +674,7 @@ private void setAttribute(Element element, QName attr, String attrValue) { element.setAttribute(attr.getLocalPart(), attrValue); } } - + private void setAttribute(Element element, QName attr, QName attrValue) { if (attributeQualified) { DOMUtil.setQNameAttribute(element, attr, attrValue, rootXsdElement); @@ -683,11 +683,11 @@ private void setAttribute(Element element, QName attr, QName attrValue) { DOMUtil.setQNameAttribute(element, attr.getLocalPart(), attrValue, rootXsdElement); } } - + /** * Set attribute in the DOM element to a QName value. This will make sure that the * appropriate namespace definition for the QName exists. - * + * * @param element element element element where to set attribute * @param attrName attribute name (String) * @param value attribute value (Qname) @@ -697,7 +697,7 @@ private void setQNameAttribute(Element element, String attrName, QName value) { DOMUtil.setQNameAttribute(element, attrName, valueWithPrefix, rootXsdElement); addToImport(value.getNamespaceURI()); } - + /** * Make sure that the namespace will be added to import definitions. * @param namespace namespace to import @@ -723,11 +723,11 @@ private void addImports() { //we don't want to import target namespace continue; } - + rootXsdElement.insertBefore(createImport(namespace), rootXsdElement.getFirstChild()); } } - + /** * Create single import XSD element. */ diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/CloneUtil.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/CloneUtil.java index ccc98e98065..3622a066aaa 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/CloneUtil.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/CloneUtil.java @@ -49,7 +49,7 @@ public class CloneUtil { private static final Trace PERFORMANCE_ADVISOR = TraceManager.getPerformanceAdvisorTrace(); - + public static T clone(T orig) { if (orig == null) { return null; @@ -114,7 +114,7 @@ public static T clone(T orig) { T clone = javaLangClone(orig); if (clone != null) { return clone; - } + } } if (orig instanceof Serializable) { // Brute force diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/ItemPathUtil.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/ItemPathUtil.java index 709275c6bdb..db150b6feea 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/ItemPathUtil.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/ItemPathUtil.java @@ -10,22 +10,22 @@ import java.util.Map; public class ItemPathUtil { - + private ItemPathUtil(){ - + } - + public static boolean isDefault(ItemPathType itemPathType){ if (itemPathType == null){ return true; } - + ItemPath itemPath = itemPathType.getItemPath(); - + if (itemPath == null){ return true; } - + return itemPath.isEmpty(); } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/JavaTypeConverter.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/JavaTypeConverter.java index b6f870bc3b0..310c2bcbbb7 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/JavaTypeConverter.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/JavaTypeConverter.java @@ -40,11 +40,11 @@ * of a number to int, PolyString to string, etc. This is supposed to work in a fashion similar to * many scripting languages (e.g. perl) where the programmer does not really care about the type * and the type conversion is done automatically. - * + * * @author Radovan Semancik */ public class JavaTypeConverter { - + final static String[] DATE_FORMATS = { "yyyy-MM-dd'T'HH:mm:ss.SSSX", "yyyy-MM-dd'T'HH:mm:ssz", @@ -76,9 +76,9 @@ public static Object convert(Class expectedType, Object rawValue, boolean fai if (rawValue == null || expectedType.isInstance(rawValue)) { return rawValue; } - + // Primitive types - + // boolean if (expectedType == boolean.class && rawValue instanceof Boolean) { return ((Boolean)rawValue); @@ -98,7 +98,7 @@ public static Object convert(Class expectedType, Object rawValue, boolean fai if (expectedType == String.class && rawValue instanceof Boolean) { return rawValue.toString(); } - + // int if (expectedType == int.class && rawValue instanceof Integer) { return ((Integer)rawValue); @@ -115,7 +115,7 @@ public static Object convert(Class expectedType, Object rawValue, boolean fai if (expectedType == int.class && rawValue instanceof Long) { return (Integer)((Long)rawValue).intValue(); } - + if (expectedType == long.class && rawValue instanceof Long) { return (rawValue); } @@ -128,7 +128,7 @@ public static Object convert(Class expectedType, Object rawValue, boolean fai if (expectedType == String.class && rawValue instanceof Long) { return rawValue.toString(); } - + if (expectedType == float.class && rawValue instanceof Float) { return ((Float)rawValue); } @@ -141,7 +141,7 @@ public static Object convert(Class expectedType, Object rawValue, boolean fai if (expectedType == String.class && rawValue instanceof Float) { return rawValue.toString(); } - + if (expectedType == double.class && rawValue instanceof Double) { return ((Double)rawValue); } @@ -154,7 +154,7 @@ public static Object convert(Class expectedType, Object rawValue, boolean fai if (expectedType == String.class && rawValue instanceof Float) { return rawValue.toString(); } - + if (expectedType == byte.class && rawValue instanceof Byte) { return ((Byte)rawValue); } @@ -174,14 +174,14 @@ public static Object convert(Class expectedType, Object rawValue, boolean fai if (expectedType == String.class && rawValue instanceof BigInteger) { return rawValue.toString().trim(); } - + if (expectedType == BigDecimal.class && rawValue instanceof String) { return new BigDecimal(((String)rawValue).trim()); } if (expectedType == String.class && rawValue instanceof BigDecimal) { return ((BigDecimal)rawValue).toString().trim(); } - + if (expectedType == PolyString.class && rawValue instanceof String) { return new PolyString((String)rawValue); } @@ -210,7 +210,7 @@ public static Object convert(Class expectedType, Object rawValue, boolean fai PolyStringType polyStringType = new PolyStringType(((Integer)rawValue).toString()); return polyStringType; } - + // Date and time if (expectedType == XMLGregorianCalendar.class && rawValue instanceof Long) { XMLGregorianCalendar xmlCalType = XmlTypeConverter.createXMLGregorianCalendar((Long)rawValue); @@ -226,7 +226,7 @@ public static Object convert(Class expectedType, Object rawValue, boolean fai if (expectedType == Long.class && rawValue instanceof XMLGregorianCalendar) { return (Long) XmlTypeConverter.toMillis((XMLGregorianCalendar)rawValue); } - + // XML Enums (JAXB) if (expectedType.isEnum() && expectedType.getAnnotation(XmlEnum.class) != null && rawValue instanceof String) { return XmlTypeConverter.toXmlEnum(expectedType, ((String)rawValue).trim()); @@ -234,7 +234,7 @@ public static Object convert(Class expectedType, Object rawValue, boolean fai if (expectedType == String.class && rawValue.getClass().isEnum() && rawValue.getClass().getAnnotation(XmlEnum.class) != null) { return XmlTypeConverter.fromXmlEnum(rawValue); } - + // Java Enums if (expectedType.isEnum() && rawValue instanceof String) { return Enum.valueOf((Class)expectedType, ((String)rawValue).trim()); @@ -242,7 +242,7 @@ public static Object convert(Class expectedType, Object rawValue, boolean fai if (expectedType == String.class && rawValue.getClass().isEnum()) { return rawValue.toString(); } - + //QName if (expectedType == QName.class && rawValue instanceof QName){ return rawValue; diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/JaxbTestUtil.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/JaxbTestUtil.java index 7af94ff48ff..ff78066d1b3 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/JaxbTestUtil.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/JaxbTestUtil.java @@ -75,9 +75,9 @@ * JAXB testing util. Only for use in tests. DO NOT USE IN PRODUCTION CODE. * This util is used to test the ablility of prism JAXB representation to be used by * native (Sun) JAXB code. - * + * * Note: this is what used to be PrismJaxbProcessor. Therefore there may be still a lot of junk to clean up. - * + * * @author Radovan Semancik */ @Deprecated @@ -86,7 +86,7 @@ public class JaxbTestUtil { private static final QName DEFAULT_ELEMENT_NAME = new QName("http://midpoint.evolveum.com/xml/ns/test/whatever-1.xsd", "whatever"); private static final Trace LOGGER = TraceManager.getTrace(JaxbTestUtil.class); - + private PrismContext prismContext; private JAXBContext context; @@ -103,7 +103,7 @@ public static JaxbTestUtil getInstance() { private JaxbTestUtil() { } - + public PrismContext getPrismContext() { return prismContext; } @@ -111,7 +111,7 @@ public PrismContext getPrismContext() { private SchemaRegistry getSchemaRegistry() { return prismContext.getSchemaRegistry(); } - + public void initialize() { StringBuilder sb = new StringBuilder(); Iterator iterator = getSchemaRegistry().getCompileTimePackages().iterator(); @@ -141,7 +141,7 @@ public JAXBContext getContext() { public void setContext(JAXBContext context) { this.context = context; } - + public boolean isJaxbClass(Class clazz) { if (clazz == null) { throw new IllegalArgumentException("No class, no fun"); @@ -158,11 +158,11 @@ public boolean isJaxbClass(Class clazz) { } return false; } - + public boolean canConvert(Class clazz) { return isJaxbClass(clazz); } - + public boolean canConvert(QName xsdType) { SchemaDescription schemaDesc = getSchemaRegistry().findSchemaDescriptionByNamespace(xsdType.getNamespaceURI()); if (schemaDesc == null) { @@ -192,14 +192,14 @@ public Class getCompileTimeClass(QName xsdType) { } return (Class) map.get(xsdType); } - + public T toJavaValue(Element element, Class typeClass) throws JAXBException { QName type = JAXBUtil.getTypeQName(typeClass); return (T) toJavaValue(element, type); } - + /** - * Used to convert property values from DOM + * Used to convert property values from DOM */ public Object toJavaValue(Element element, QName xsdType) throws JAXBException { Class declaredType = getCompileTimeClass(xsdType); @@ -229,7 +229,7 @@ private Marshaller createMarshaller(Map jaxbProperties) throws J return marshaller; } - + /** * Allow for pooling and other fancy stuff. Now it dumb, creates in every call. */ @@ -240,7 +240,7 @@ private Marshaller getMarshaller() throws JAXBException { private Unmarshaller createUnmarshaller() throws JAXBException { return context.createUnmarshaller(); } - + /** * Allow for pooling and other fancy stuff. Now it dumb, creates in every call. */ @@ -251,7 +251,7 @@ public Unmarshaller getUnmarshaller() throws JAXBException { public String marshalToString(Objectable objectable) throws JAXBException { return marshalToString(objectable, new HashMap()); } - + public String marshalToString(Objectable objectable, Map properties) throws JAXBException { QName elementQName = determineElementQName(objectable); JAXBElement jaxbElement = new JAXBElement(elementQName, (Class) objectable.getClass(), objectable); @@ -261,7 +261,7 @@ public String marshalToString(Objectable objectable, Map propert public String marshalElementToString(JAXBElement jaxbElement) throws JAXBException { return marshalElementToString(jaxbElement, new HashMap()); } - + public String marshalElementToString(JAXBElement jaxbElement, Map properties) throws JAXBException { StringWriter writer = new StringWriter(); Marshaller marshaller = getMarshaller(); @@ -275,7 +275,7 @@ public String marshalElementToString(JAXBElement jaxbElement, Map()); } - + /** * Serializes DOM or JAXB element to string */ @@ -308,7 +308,7 @@ public String marshalElementToString(Object element, QName elementName) throws J return marshalElementToString(jaxbElement); } } - + public void marshalToDom(Objectable objectable, Node parentNode) throws JAXBException { QName elementQName = determineElementQName(objectable); JAXBElement jaxbElement = new JAXBElement(elementQName, (Class) objectable.getClass(), objectable); @@ -316,9 +316,9 @@ public void marshalToDom(Objectable objectable, Node parentNode) throws JAXBExce } public void marshalElementToDom(JAXBElement jaxbElement, Node parentNode) throws JAXBException { - getMarshaller().marshal(jaxbElement, parentNode); + getMarshaller().marshal(jaxbElement, parentNode); } - + public Element marshalElementToDom(JAXBElement jaxbElement, Document doc) throws JAXBException { if (doc == null) { doc = DOMUtil.getDocument(); @@ -355,14 +355,14 @@ public Element marshalObjectToDom(T jaxbObject, QName elementQName, Document return (Element) element.getFirstChild(); } - + public void marshalObjectToDom(T jaxbObject, QName elementQName, Element parentElement) throws JAXBException { JAXBElement jaxbElement = new JAXBElement(elementQName, (Class) jaxbObject.getClass(), jaxbObject); marshalElementToDom(jaxbElement, parentElement); } - + public Element toDomElement(Object element) throws JAXBException { return toDomElement(element, DOMUtil.getDocument()); } @@ -370,7 +370,7 @@ public Element toDomElement(Object element) throws JAXBException { public Element toDomElement(Object jaxbElement, Document doc) throws JAXBException { return toDomElement(jaxbElement,doc,false,false,false); } - + @SuppressWarnings({ "rawtypes", "unchecked" }) public Element toDomElement(Object jaxbElement, Document doc, boolean adopt, boolean clone, boolean deep) throws JAXBException { if (jaxbElement == null) { @@ -409,7 +409,7 @@ public JAXBElement unmarshalElement(String xmlString, Class type) thro StringReader reader = null; try { - reader = new StringReader(xmlString); + reader = new StringReader(xmlString); JAXBElement element = unmarshalElement(reader, type); adopt(element); return element; @@ -419,42 +419,42 @@ public JAXBElement unmarshalElement(String xmlString, Class type) thro } } } - + public T unmarshalObject(InputStream input, Class type) throws JAXBException, SchemaException { Object object = getUnmarshaller().unmarshal(input); JAXBElement jaxbElement = (JAXBElement) object; adopt(jaxbElement); - + if (jaxbElement == null) { return null; } T value = jaxbElement.getValue(); // adopt not needed, already adopted in unmarshalElement call above return value; - + } - + public T unmarshalObject(InputStream input) throws JAXBException, SchemaException { Object object = getUnmarshaller().unmarshal(input); JAXBElement jaxbElement = (JAXBElement) object; adopt(jaxbElement); - + if (jaxbElement == null) { return null; } T value = jaxbElement.getValue(); // adopt not needed, already adopted in unmarshalElement call above return value; - + } - + public JAXBElement unmarshalElement(Reader reader, Class type) throws JAXBException, SchemaException { Object object = getUnmarshaller().unmarshal(reader); JAXBElement jaxbElement = (JAXBElement) object; adopt(jaxbElement); return jaxbElement; } - + public T unmarshalToObject(Node node, Class type) throws JAXBException, SchemaException { JAXBElement element = unmarshalElement(node, type); if (element == null) { @@ -463,7 +463,7 @@ public T unmarshalToObject(Node node, Class type) throws JAXBException, S adopt(element); return element.getValue(); } - + public JAXBElement unmarshalElement(Node node, Class type) throws JAXBException, SchemaException { Object object = createUnmarshaller().unmarshal(node); JAXBElement jaxbElement = (JAXBElement) object; @@ -483,11 +483,11 @@ public T unmarshalObject(File file, Class type) throws JAXBException, Sch } return value; } - + public Object unmarshalObjects(File file) throws JAXBException{ return createUnmarshaller().unmarshal(file); } - + public T unmarshalObject(String stringXml, Class type) throws JAXBException, SchemaException { JAXBElement element = unmarshalElement(stringXml, type); if (element == null) { @@ -549,7 +549,7 @@ public T unmarshalObject(Object domOrJaxbElement, Class type) throws Sche adopt(value, type); return value; } - + public JAXBElement unmarshalElement(File file, Class type) throws SchemaException, FileNotFoundException, JAXBException { if (file == null) { throw new IllegalArgumentException("File argument must not be null."); @@ -569,9 +569,9 @@ public JAXBElement unmarshalElement(File file, Class type) throws Sche } } } - + public JAXBElement unmarshalElement(InputStream is, Class type) throws SchemaException, FileNotFoundException, JAXBException { - + try { JAXBElement element = (JAXBElement) getUnmarshaller().unmarshal(is); adopt(element); @@ -582,7 +582,7 @@ public JAXBElement unmarshalElement(InputStream is, Class type) throws } } } - + public T unmarshalRootObject(File file, Class type) throws JAXBException, FileNotFoundException, SchemaException { Validate.notNull(file, "File must not be null."); InputStream is = null; @@ -597,7 +597,7 @@ public T unmarshalRootObject(File file, Class type) throws JAXBException, } } } - + public boolean compareAny(List a, List b) { if (a == b) { return true; @@ -618,7 +618,7 @@ public boolean compareAny(List a, List b) { } return true; } - + @SuppressWarnings("unchecked") private boolean compareElement(Object a, Object b) { if (a == b) { @@ -667,17 +667,17 @@ private boolean compareElement(Object a, Object b) { return DOMUtil.compareElement(ae, be, true); } - + public T fromElement(Object element, Class type) throws SchemaException { - + if (element == null) { return null; } - + if (type.isAssignableFrom(element.getClass())) { return (T) element; } - + if (element instanceof JAXBElement) { if (((JAXBElement) element).getValue() == null) { return null; @@ -686,7 +686,7 @@ public T fromElement(Object element, Class type) throws SchemaException { return (T) ((JAXBElement) element).getValue(); } } - + if (element instanceof Element) { try { JAXBElement unmarshalledElement = unmarshalElement((Element)element, type); @@ -695,10 +695,10 @@ public T fromElement(Object element, Class type) throws SchemaException { throw new IllegalArgumentException("Unmarshall failed: " + e.getMessage(),e); } } - + throw new IllegalArgumentException("Unknown element type "+element.getClass().getName()); } - + private QName determineElementQName(Objectable objectable) { PrismObject prismObject = objectable.asPrismObject(); if (prismObject.getElementName() != null) { @@ -727,13 +727,13 @@ private QName determineElementQName(Containerable containerable) { private boolean isObjectable(Class type) { return Objectable.class.isAssignableFrom(type); } - + private void adopt(T object, Class type) throws SchemaException { if (object instanceof Objectable) { getPrismContext().adopt(((Objectable)object)); } } - + private void adopt(Object object) throws SchemaException { if (object instanceof JAXBElement) { adopt(((JAXBElement)object).getValue()); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismAsserts.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismAsserts.java index 863d9b08512..3ede91b5437 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismAsserts.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismAsserts.java @@ -82,60 +82,60 @@ /** * Set of prism-related asserts. - * + * * DO NOT use this in the main code. Although it is placed in "main" for convenience, is should only be used in tests. - * + * * @author Radovan Semancik * */ public class PrismAsserts { - + private static final Trace LOGGER = TraceManager.getTrace(PrismAsserts.class); - + // VALUE asserts - + public static void assertPropertyValue(PrismContainer container, QName propQName, T... realPropValues) { PrismContainerValue containerValue = container.getValue(); assertSame("Wrong parent for value of container "+container, container, containerValue.getParent()); assertPropertyValue(containerValue, propQName, realPropValues); } - + public static void assertPropertyValueMatch(PrismContainer container, QName propQName, MatchingRule matchingRule, T... realPropValues) throws SchemaException { PrismContainerValue containerValue = container.getValue(); assertSame("Wrong parent for value of container "+container, container, containerValue.getParent()); assertPropertyValueMatch(containerValue, propQName, matchingRule, realPropValues); } - + public static void assertPropertyValue(PrismContainerValue containerValue, QName propQName, T... realPropValues) { PrismProperty property = containerValue.findProperty(propQName); assertNotNull("Property " + propQName + " not found in " + containerValue.getParent(), property); assertSame("Wrong parent for property " + property, containerValue, property.getParent()); assertPropertyValueDesc(property, containerValue.getParent().toString(), realPropValues); } - + public static void assertPropertyValueMatch(PrismContainerValue containerValue, QName propQName, MatchingRule matchingRule, T... realPropValues) throws SchemaException { PrismProperty property = containerValue.findProperty(propQName); assertNotNull("Property " + propQName + " not found in " + containerValue.getParent(), property); assertSame("Wrong parent for property " + property, containerValue, property.getParent()); assertPropertyValueDesc(property, matchingRule, containerValue.getParent().toString(), realPropValues); } - + public static void assertPropertyValue(PrismContainer container, ItemPath propPath, T... realPropValues) { PrismContainerValue containerValue = container.getValue(); assertSame("Wrong parent for value of container "+container, container, containerValue.getParent()); assertPropertyValue(containerValue, propPath, realPropValues); } - + public static void assertPropertyValue(PrismContainerValue containerValue, ItemPath propPath, T... realPropValues) { PrismProperty property = containerValue.findProperty(propPath); assertNotNull("Property " + propPath + " not found in " + containerValue.getParent(), property); assertPropertyValueDesc(property, containerValue.getParent().toString(), realPropValues); } - + public static void assertPropertyValue(PrismProperty property, T... expectedPropValues) { assertPropertyValueDesc(property, null, expectedPropValues); } - + public static void assertPropertyValueDesc(PrismProperty property, String contextDescrition, T... expectedPropValues) { try { assertPropertyValueDesc(property, null, contextDescrition, expectedPropValues); @@ -144,15 +144,15 @@ public static void assertPropertyValueDesc(PrismProperty property, String throw new RuntimeException(e.getMessage(), e); } } - + public static void assertPropertyValueDesc(PrismProperty property, MatchingRule matchingRule, String contextDescrition, T... expectedPropValues) throws SchemaException { Collection> pvals = property.getValues(); QName propQName = property.getElementName(); assert pvals != null && !pvals.isEmpty() : "Empty property "+propQName; - assertSet("property "+propQName + (contextDescrition == null ? "" : " in " + contextDescrition), + assertSet("property "+propQName + (contextDescrition == null ? "" : " in " + contextDescrition), "value", matchingRule, pvals, expectedPropValues); } - + public static void assertPropertyValues(String message, Collection expected, Collection> results) { assertEquals(message+" - unexpected number of results", expected.size(), results.size()); @@ -173,7 +173,7 @@ public static void assertReferenceValues(PrismReference ref, String... oids) { assertReferenceValue(ref, oid); } } - + public static void assertReferenceValue(PrismReference ref, String oid) { for (PrismReferenceValue val: ref.getValues()) { if (oid.equals(val.getOid())) { @@ -182,7 +182,7 @@ public static void assertReferenceValue(PrismReference ref, String oid) { } fail("Oid "+oid+" not found in reference "+ref); } - + public static void assertNoItem(PrismContainer object, QName itemName) { assertNoItem(object, new ItemPath(itemName)); } @@ -191,11 +191,11 @@ public static void assertNoItem(PrismContainer object, ItemPath itemPath) { Item item = object.findItem(itemPath); assert item == null : "Unexpected item "+item+" in "+object; } - + public static void assertNotEmpty(Item item) { assert !item.isEmpty() : "Item "+item+" is empty"; } - + public static void assertNoEmptyItem(PrismContainer container) { Visitor visitor = new Visitor() { @Override @@ -209,7 +209,7 @@ public void visit(Visitable visitable) { } // DEFINITION asserts - + public static void assertObjectDefinition(PrismObjectDefinition objDef, QName elementName, QName typeName, Class compileTimeClass) { assertNotNull("No definition", objDef); @@ -217,23 +217,23 @@ public static void assertObjectDefinition(PrismObjectDefi assertEquals("Wrong typeName for "+objDef, typeName, objDef.getTypeName()); assertEquals("Wrong compileTimeClass for " + objDef, compileTimeClass, objDef.getCompileTimeClass()); } - + public static void assertDefinition(Item item, QName type, int minOccurs, int maxOccurs) { ItemDefinition definition = item.getDefinition(); assertDefinition(definition, item.getElementName(), type, minOccurs, maxOccurs); } - + public static void assertPropertyDefinition(PrismContainer container, QName propertyName, QName type, int minOccurs, int maxOccurs) { PrismProperty findProperty = container.findProperty(propertyName); PrismPropertyDefinition definition = findProperty.getDefinition(); assertDefinition(definition, propertyName, type, minOccurs, maxOccurs); } - + public static void assertPropertyDefinition(ComplexTypeDefinition container, QName propertyName, QName type, int minOccurs, int maxOccurs) { PrismPropertyDefinition definition = container.findPropertyDefinition(propertyName); assertDefinition(definition, propertyName, type, minOccurs, maxOccurs); } - + public static void assertPropertyDefinition(PrismProperty property, QName type, int minOccurs, int maxOccurs, Boolean indexed) { assertDefinition(property, type, minOccurs, maxOccurs); @@ -247,7 +247,7 @@ public static void assertPropertyDefinition(PrismContainerDefinition containe PrismPropertyDefinition definition = containerDef.findPropertyDefinition(propertyName); assert equals(indexed, definition.isIndexed()) : "Property should have indexed=" + indexed + ", but it has indexed=" + definition.isIndexed(); } - + public static void assertPropertyDefinition(PrismContainerDefinition containerDef, QName propertyName, QName type, int minOccurs, int maxOccurs) { PrismPropertyDefinition definition = containerDef.findPropertyDefinition(propertyName); assertDefinition(definition, propertyName, type, minOccurs, maxOccurs); @@ -258,7 +258,7 @@ public static void assertItemDefinitionDisplayName(PrismContainerDefinition c assert equals(expectedDisplayName, definition.getDisplayName()) : "Wrong display name for item "+propertyName+", expected " + expectedDisplayName + ", was " + definition.getDisplayName(); } - + public static void assertItemDefinitionDisplayName(ComplexTypeDefinition containerDef, QName propertyName, String expectedDisplayName) { ItemDefinition definition = containerDef.findItemDefinition(propertyName, ItemDefinition.class); assert equals(expectedDisplayName, definition.getDisplayName()) : "Wrong display name for item "+propertyName+", expected " + @@ -270,19 +270,19 @@ public static void assertItemDefinitionDisplayOrder(PrismContainerDefinition assert equals(expectedDisplayOrder, definition.getDisplayOrder()) : "Wrong display order for item "+propertyName+", expected " + expectedDisplayOrder + ", was " + definition.getDisplayOrder(); } - + public static void assertItemDefinitionDisplayOrder(ComplexTypeDefinition containerDef, QName propertyName, Integer expectedDisplayOrder) { ItemDefinition definition = containerDef.findItemDefinition(propertyName, ItemDefinition.class); assert equals(expectedDisplayOrder, definition.getDisplayOrder()) : "Wrong display order for item "+propertyName+", expected " + expectedDisplayOrder + ", was " + definition.getDisplayOrder(); } - + public static void assertItemDefinitionHelp(PrismContainerDefinition containerDef, QName propertyName, String expectedHelp) { ItemDefinition definition = containerDef.findItemDefinition(propertyName); assert equals(expectedHelp, definition.getHelp()) : "Wrong help for item "+propertyName+", expected " + expectedHelp + ", was " + definition.getHelp(); } - + public static void assertDefinition(ItemDefinition definition, QName itemName, QName type, int minOccurs, int maxOccurs) { assertNotNull("No definition for "+itemName, definition); assertEquals("Wrong definition type for "+itemName, type, definition.getTypeName()); @@ -297,7 +297,7 @@ public static void assertDefinitionTypeLoose(ItemDefinition definition, QName it assertEquals("Wrong definition minOccurs for "+itemName, minOccurs, definition.getMinOccurs()); assertEquals("Wrong definition maxOccurs for "+itemName, maxOccurs, definition.getMaxOccurs()); } - + public static void assertIndexed(PrismContainerDefinition containerDef, QName itemQName, Boolean expected) { PrismPropertyDefinition propertyDefinition = containerDef.findPropertyDefinition(itemQName); @@ -307,13 +307,13 @@ public static void assertIndexed(PrismContainerDefinition containerDef, QName itemQName, Boolean expected) { PrismPropertyDefinition propertyDefinition = containerDef.findPropertyDefinition(itemQName); assertEquals("Wrong value of 'emphasized' in property '"+PrettyPrinter.prettyPrint(itemQName)+" in "+containerDef, expected, propertyDefinition.isEmphasized()); } - + public static void assertValueId(Long expectedId, PrismContainer container) { List ids = new ArrayList(); for (PrismContainerValue value: container.getValues()) { @@ -325,9 +325,9 @@ public static void assertValueId(Long expectedId, Prism assert false : "Expected that container "+container+" will have value id '"+expectedId+"' but it has not; existing IDs: "+ids; } - + // MISC asserts - + public static void assertParentConsistency(PrismContainerValue pval) { if (pval.getItems() != null) { for (Item item : pval.getItems()) { @@ -345,13 +345,13 @@ public static void assertParentConsistency(Item item) { } } } - + // DELTA asserts - + public static void assertModifications(ObjectDelta objectDelta, int expectedNumberOfModifications) { assertModifications(null, objectDelta, expectedNumberOfModifications); } - + public static void assertModifications(String message, ObjectDelta objectDelta, int expectedNumberOfModifications) { assertIsModify(objectDelta); assert objectDelta.getModifications().size() == expectedNumberOfModifications : @@ -363,16 +363,16 @@ public static void assertModifications(String message, ObjectDelta objectDelt public static void assertIsModify(ObjectDelta objectDelta) { assert objectDelta.isModify() : "Expected that object delta "+objectDelta+" is MODIFY, but it is "+objectDelta.getChangeType(); } - + public static void assertIsAdd(ObjectDelta objectDelta) { assert objectDelta.isAdd() : "Expected that object delta "+objectDelta+" is ADD, but it is "+objectDelta.getChangeType(); assert objectDelta.getObjectToAdd() != null : "Object to add is null in add delta " + objectDelta; } - + public static void assertIsDelete(ObjectDelta objectDelta) { assert objectDelta.isDelete() : "Expected that object delta "+objectDelta+" is DELETE, but it is "+objectDelta.getChangeType(); } - + public static void assertEmpty(ObjectDelta objectDelta) { assert objectDelta.isEmpty() : "Expected that object delta "+objectDelta+" is empty, but it is not"; } @@ -402,7 +402,7 @@ public static void assertPropertyAdd(ObjectDelta objectDelta, QName propertyN assertNotNull("Property delta for "+propertyName+" not found",propertyDelta); assertSet("delta "+propertyDelta+" for "+propertyName, "add", propertyDelta.getValuesToAdd(), expectedValues); } - + public static void assertPropertyDelete(ObjectDelta objectDelta, QName propertyName, Object... expectedValues) { PropertyDelta propertyDelta = objectDelta.findPropertyDelta(propertyName); assertNotNull("Property delta for "+propertyName+" not found",propertyDelta); @@ -420,11 +420,11 @@ public static void assertPropertyAdd(ObjectDelta userDelta, ItemPath property assertNotNull("Property delta for "+propertyPath+" not found",propertyDelta); assertAdd(propertyDelta, expectedValues); } - + public static void assertAdd(PropertyDelta propertyDelta, T... expectedValues) { assertSet("delta "+propertyDelta+" for "+propertyDelta.getElementName(), "add", propertyDelta.getValuesToAdd(), expectedValues); } - + public static void assertDelete(PropertyDelta propertyDelta, T... expectedValues) { assertSet("delta "+propertyDelta+" for "+propertyDelta.getElementName(), "delete", propertyDelta.getValuesToDelete(), expectedValues); } @@ -434,7 +434,7 @@ public static void assertPropertyDelete(ObjectDelta userDelta, ItemPath prope assertNotNull("Property delta for "+propertyPath+" not found",propertyDelta); assertSet("delta "+propertyDelta+" for "+propertyPath.last(), "delete", propertyDelta.getValuesToDelete(), expectedValues); } - + public static void assertPropertyReplace(Collection modifications, ItemPath propertyPath, Object... expectedValues) { PropertyDelta propertyDelta = ItemDelta.findPropertyDelta(modifications, propertyPath); assertNotNull("Property delta for "+propertyPath+" not found",propertyDelta); @@ -446,19 +446,19 @@ public static void assertPropertyAdd(Collection modificatio assertNotNull("Property delta for "+propertyPath+" not found",propertyDelta); assertSet("delta "+propertyDelta+" for "+propertyPath.last(), "add", propertyDelta.getValuesToAdd(), expectedValues); } - + public static void assertPropertyDelete(Collection modifications, ItemPath propertyPath, Object... expectedValues) { PropertyDelta propertyDelta = ItemDelta.findPropertyDelta(modifications, propertyPath); assertNotNull("Property delta for "+propertyPath+" not found",propertyDelta); assertSet("delta "+propertyDelta+" for "+propertyPath.last(), "delete", propertyDelta.getValuesToDelete(), expectedValues); } - + public static void assertReferenceAdd(ObjectDelta objectDelta, QName refName, String... expectedOids) { ReferenceDelta refDelta = objectDelta.findReferenceModification(refName); assertNotNull("Reference delta for "+refName+" not found",refDelta); assertOidSet("delta "+refDelta+" for "+refName, "add", refDelta.getValuesToAdd(), expectedOids); } - + public static void assertReferenceDelete(ObjectDelta objectDelta, QName refName, String... expectedOids) { ReferenceDelta refDelta = objectDelta.findReferenceModification(refName); assertNotNull("Reference delta for "+refName+" not found",refDelta); @@ -474,14 +474,14 @@ public static void assertReferenceReplace(ObjectDelta objectDelta, QName refN public static void assertNoItemDelta(ObjectDelta objectDelta, QName itemName) { assertNoItemDelta(objectDelta, new ItemPath(itemName)); } - + public static void assertNoItemDelta(ObjectDelta objectDelta, ItemPath itemPath) { if (objectDelta == null) { return; } assert !objectDelta.hasItemDelta(itemPath) : "Delta for item "+itemPath+" present while not expecting it"; } - + public static void assertPropertyDelta(PropertyDelta delta, T[] expectedOldValues, T[] expectedAddValues, T[] expectedDeleteValues, T[] expectedReplaceValues) { assertNotNull("No delta",delta); assertSet("delta "+delta, "old", delta.getEstimatedOldValues(), expectedOldValues); @@ -489,11 +489,11 @@ public static void assertPropertyDelta(PropertyDelta delta, T[] expectedO assertSet("delta "+delta, "delete", delta.getValuesToDelete(), expectedDeleteValues); assertSet("delta "+delta, "replace", delta.getValuesToReplace(), expectedReplaceValues); } - + public static ContainerDelta assertContainerAddGetContainerDelta(ObjectDelta objectDelta, QName name) { return assertContainerAddGetContainerDelta(objectDelta, new ItemPath(name)); } - + public static ContainerDelta assertContainerAddGetContainerDelta(ObjectDelta objectDelta, ItemPath propertyPath) { ContainerDelta delta = objectDelta.findContainerDelta(propertyPath); assertNotNull("Container delta for "+propertyPath+" not found",delta); @@ -506,7 +506,7 @@ public static ContainerDelta assertContainerAddGetContainerDelta(ObjectDelta< public static ContainerDelta assertContainerDeleteGetContainerDelta(ObjectDelta objectDelta, QName name) { return assertContainerDeleteGetContainerDelta(objectDelta, new ItemPath(name)); } - + public static ContainerDelta assertContainerDeleteGetContainerDelta(ObjectDelta objectDelta, ItemPath propertyPath) { ContainerDelta delta = objectDelta.findContainerDelta(propertyPath); assertNotNull("Container delta for "+propertyPath+" not found",delta); @@ -515,23 +515,23 @@ public static ContainerDelta assertContainerDeleteGetContainerDelta(ObjectDel assert !delta.getValuesToDelete().isEmpty() : "Container delta for "+propertyPath+" has empty values to delete"; return delta; } - + public static void assertContainerAdd(ObjectDelta objectDelta, QName itemName, C... containerables) { assertContainerAdd(objectDelta, new ItemPath(itemName), containerables); } - + public static void assertContainerAdd(ObjectDelta objectDelta, ItemPath propertyPath, C... containerables) { List> expectedCVals = new ArrayList<>(); for (C expectedContainerable: containerables) { expectedCVals.add(expectedContainerable.asPrismContainerValue()); } } - + public static void assertContainerAdd(ObjectDelta objectDelta, QName itemName, PrismContainerValue... expectedCVals) { assertContainerAdd(objectDelta, new ItemPath(itemName), expectedCVals); } - + public static void assertContainerAdd(ObjectDelta objectDelta, ItemPath propertyPath, PrismContainerValue... expectedCVals) { ContainerDelta delta = objectDelta.findContainerDelta(propertyPath); @@ -539,10 +539,10 @@ public static void assertContainerAdd(ObjectDelta o assert !delta.isEmpty() : "Container delta for "+propertyPath+" is empty"; assert delta.getValuesToAdd() != null : "Container delta for "+propertyPath+" has null values to add"; assert !delta.getValuesToAdd().isEmpty() : "Container delta for "+propertyPath+" has empty values to add"; - assertEquivalentContainerValues("Wrong values in container delta for "+propertyPath, + assertEquivalentContainerValues("Wrong values in container delta for "+propertyPath, delta.getValuesToAdd(), expectedCVals); } - + private static void assertEquivalentContainerValues(String message, Collection> haveValues, PrismContainerValue[] expectedCVals) { List> expectedValues = Arrays.asList(expectedCVals); @@ -560,12 +560,12 @@ public static void assertOrigin(ItemDelta itemDelta, final OriginType. public static void assertOrigin(Visitable visitableItem, final OriginType... expectedOriginTypes) { assertOrigin(visitableItem, null, expectedOriginTypes); } - + public static void assertOrigin(ObjectDelta objectDelta, final Objectable expectedOriginObject, final OriginType... expectedOriginTypes) { Visitor visitor = createOriginVisitor(objectDelta, expectedOriginObject, expectedOriginTypes); objectDelta.accept(visitor, false); } - + public static void assertOrigin(ItemDelta itemDelta, final Objectable expectedOriginObject, final OriginType... expectedOriginTypes) { Visitor visitor = createOriginVisitor(itemDelta, expectedOriginObject, expectedOriginTypes); itemDelta.accept(visitor, false); @@ -575,12 +575,12 @@ public static void assertOrigin(Visitable visitableItem, final Objectable ex Visitor visitor = createOriginVisitor(visitableItem, expectedOriginObject, expectedOriginTypes); visitableItem.accept(visitor); } - + private static Visitor createOriginVisitor(final Visitable visitableItem, final Objectable expectedOriginObject, final OriginType... expectedOriginTypes) { return (visitable) -> { if (visitable instanceof PrismValue) { PrismValue pval = (PrismValue)visitable; - + assert MiscUtil.contains(pval.getOriginType(), expectedOriginTypes) : "Wrong origin type in "+visitable+" in "+visitableItem+ "; expected "+Arrays.asList(expectedOriginTypes)+", was "+pval.getOriginType(); if (expectedOriginObject != null) { @@ -590,7 +590,7 @@ private static Visitor createOriginVisitor(final Visitable visitableItem, fi } }; } - + public static void asserHasDelta(String message, Collection> deltas, ChangeType expectedChangeType, Class expectedClass) { for (ObjectDelta delta: deltas) { if (delta.getObjectTypeClass() == expectedClass && delta.getChangeType() == expectedChangeType) { @@ -599,15 +599,15 @@ public static void asserHasDelta(String message, Collection void assertNoReplace(ItemDelta delta) { assertNoReplace(null, delta); } - + public static void assertNoReplace(String message, ItemDelta delta) { assertNoSet(message, "replace", delta.getValuesToReplace()); } - + public static void assertNoAdd(ItemDelta delta) { assertNoAdd(null, delta); } @@ -615,7 +615,7 @@ public static void assertNoAdd public static void assertNoAdd(String message, ItemDelta delta) { assertNoSet(message, "add", delta.getValuesToAdd()); } - + public static void assertNoDelete(ItemDelta delta) { assertNoDelete(null, delta); } @@ -627,14 +627,14 @@ public static void assertNoDel private static void assertNoSet(String message, String type, Collection set) { assert set == null : (message == null ? "" : message + ": ") + "Delta "+type+" set expected to be null but it is "+set; } - + public static void assertNoDelta(String message, ObjectDelta delta) { assert delta == null : "Unexpected "+message+"; got "+delta; } - + // DeltaSetTriple asserts - + public static void assertTriplePlus(PrismValueDeltaSetTriple triple, T... expectedValues) { assert triple != null : "triple is null"; assertTripleSet("plus set", triple.getPlusSet(), expectedValues); @@ -649,7 +649,7 @@ public static void assertTripleMinus(PrismValueDeltaSe assert triple != null : "triple is null"; assertTripleSet("minus set", triple.getMinusSet(), expectedValues); } - + public static void assertTripleSet(String setName, Collection tripleSet, T... expectedValues) { assert tripleSet.size() == expectedValues.length : "Unexpected number of elements in triple "+setName+", expected "+ expectedValues.length + ", was " + tripleSet.size() + ": "+tripleSet; @@ -671,7 +671,7 @@ public static void assertTripleSet(String setName, Col } } } - + public static void assertTripleNoPlus(DeltaSetTriple triple) { assert triple != null : "triple is null"; assertTripleNoSet("plus set", triple.getPlusSet()); @@ -686,17 +686,17 @@ public static void assertTripleNoMinus(DeltaSetTriple triple) { assert triple != null : "triple is null"; assertTripleNoSet("minus set", triple.getMinusSet()); } - + public static void assertTripleNoSet(String setName, Collection set) { assert set == null || set.isEmpty() : "Expected triple "+setName+" to be empty, but it was: "+set; } - + public static void assertTripleEmpty(DeltaSetTriple triple) { assert triple != null : "triple is null (expected it to be empty)"; assert triple.isEmpty() : "triple is not empty, it is: "+triple; } - + public static void assertEquals(String message, PolyString expected, PolyString actual) { assert expected.equals(actual) : message + "; expected " + DebugUtil.dump(expected) + ", was " + DebugUtil.dump(actual); @@ -718,15 +718,15 @@ public static void assertEqualsPolyString(String message, String expectedOrig, P expected.recompute(PrismTestUtil.getPrismContext().getDefaultPolyStringNormalizer()); assert MiscUtil.equals(expected.getNorm(), actual.getNorm()) : message+"; expected norm '"+expected.getNorm()+ "' but was '" + actual.getNorm() + "'"; } - + public static void assertEqualsPolyString(String message, PolyStringType expected, PolyStringType actual) { assert actual != null : message + ": null value"; assert MiscUtil.equals(expected.getOrig(), actual.getOrig()) : message+"; expected orig '"+expected.getOrig()+ "' but was '" + actual.getOrig() + "'"; assert MiscUtil.equals(expected.getNorm(), actual.getNorm()) : message+"; expected norm '"+expected.getNorm()+ "' but was '" + actual.getNorm() + "'"; - } + } // Calendar asserts - + public static void assertEquals(String message, XMLGregorianCalendar expected, Object actual) { if (actual instanceof XMLGregorianCalendar) { XMLGregorianCalendar actualXmlCal = (XMLGregorianCalendar)actual; @@ -737,43 +737,43 @@ public static void assertEquals(String message, XMLGregorianCalendar expected, O } // Misc - + public static void assertClass(String message, Class expectedClass, PrismObject actualObject) { assert actualObject != null : message + "is null"; Class actualCompileTimeClass = actualObject.getCompileTimeClass(); assert actualCompileTimeClass == expectedClass : message+" wrong class, expected "+expectedClass+" but was "+actualCompileTimeClass; } - + public static void assertClass(String message, Class expectedClass, Objectable actualObject) { assert actualObject != null : message + "is null"; Class actualCompileTimeClass = actualObject.getClass(); assert actualCompileTimeClass == expectedClass : message+" wrong class, expected "+expectedClass+" but was "+actualCompileTimeClass; } - + public static void assertClass(String message, Class expectedClass, ObjectDelta actualDelta) { assert actualDelta != null : message + "is null"; Class actualCompileTimeClass = actualDelta.getObjectTypeClass(); assert actualCompileTimeClass == expectedClass : message+" wrong class, expected "+expectedClass+" but was "+actualCompileTimeClass; } - + // OBJECT asserts - + public static void assertElementsEquals(Object expected, Object actual) throws SchemaException { assertEquals(elementToPrism(expected), elementToPrism(actual)); } - + public static void assertEquals(File fileNewXml, String objectString) throws SchemaException, IOException { assertEquals(toPrism(fileNewXml), toPrism(objectString)); } - + public static void assertEquals(Objectable expected, Objectable actual) throws SchemaException { assertEquals(actual.asPrismObject(), actual.asPrismObject()); } - + public static void assertEquals(File fileNewXml, Objectable objectable) throws SchemaException, IOException { assertEquals(toPrism(fileNewXml), objectable.asPrismObject()); } - + public static void assertEquals(File fileNewXml, PrismObject actual) throws SchemaException, IOException { PrismObject expected = toPrism(fileNewXml); assertEquals(expected, actual); @@ -782,7 +782,7 @@ public static void assertEquals(File fileNewXml, PrismObj public static void assertEquals(PrismObject prism1, PrismObject prism2) { assertEquals(null, prism1, prism2); } - + public static void assertEquals(String message, PrismObject expected, PrismObject actual) { if (expected == null && actual == null) { return; @@ -807,16 +807,16 @@ public static void assertEquals(String message, PrismObje LOGGER.error("ASSERT: {}: {} and {} not equals, delta:\n{}", message, expected, actual, delta.debugDump()); assert false: message + ": " + suffix; } - + public static void assertEquivalent(File expectedFile, PrismObject actual) throws SchemaException, IOException { assertEquivalent("Object "+actual+" not equivalent to that from file "+expectedFile,expectedFile,actual); } - + public static void assertEquivalent(String message, File expectedFile, PrismObject actual) throws SchemaException, IOException { PrismObject expected = toPrism(expectedFile); assertEquivalent(message, expected, actual); } - + public static void assertEquivalent(String message, PrismObject expected, PrismObject actual) { if (expected == null && actual == null) { return; @@ -847,11 +847,11 @@ public static void assertEquivalent(String message, Prism private static void assertSet(String inMessage, String setName, MatchingRule matchingRule, Collection> actualPValues, T[] expectedValues) throws SchemaException { assertValues(setName + " set in " + inMessage, matchingRule, actualPValues, expectedValues); } - + private static void assertSet(String inMessage, String setName, Collection> actualPValues, T[] expectedValues) { assertValues(setName + " set in " + inMessage, actualPValues, expectedValues); } - + public static void assertValues(String message, Collection> actualPValues, T... expectedValues) { try { assertValues(message, null, actualPValues, expectedValues); @@ -860,7 +860,7 @@ public static void assertValues(String message, Collection void assertValues(String message, MatchingRule matchingRule, Collection> actualPValues, T... expectedValues) throws SchemaException { if (expectedValues == null) { assertNull("Unexpected set in" +message+": "+actualPValues, actualPValues); @@ -884,11 +884,11 @@ public static void assertValues(String message, MatchingRule matchingRule } } } - + private static void assertOidSet(String inMessage, String setName, Collection actualPValues, String... expectedOids) { assertOidValues(setName + " set in " + inMessage, actualPValues, expectedOids); } - + public static void assertOidValues(String message, Collection actualRValues, String... expectedOids) { assertNotNull("Null set in " + message, actualRValues); if (expectedOids.length != actualRValues.size()) { @@ -908,7 +908,7 @@ public static void assertOidValues(String message, Collection void assertSets(String message, Collection actualValues, T... expectedValues) { try { assertSets(message, null, actualValues, expectedValues); @@ -917,7 +917,7 @@ public static void assertSets(String message, Collection actualValues, T. throw new IllegalStateException(e.getMessage(), e); } } - + public static void assertSets(String message, MatchingRule matchingRule, Collection actualValues, T... expectedValues) throws SchemaException { assertNotNull("Null set in " + message, actualValues); assertEquals("Wrong number of values in " + message+ "; expected (real values) " @@ -942,7 +942,7 @@ public static void assertSets(String message, MatchingRule matchingRule, } } } - + private static PrismObject toPrism(String objectString) throws SchemaException { return PrismTestUtil.parseObject(objectString); } @@ -950,7 +950,7 @@ private static PrismObject toPrism(String objectString private static PrismObject toPrism(File objectFile) throws SchemaException, IOException { return PrismTestUtil.parseObject(objectFile); } - + private static PrismObject toPrism(Element domNode) throws SchemaException { return PrismTestUtil.parseObject(domNode); } @@ -970,7 +970,7 @@ private static PrismObject elementToPrism(Object eleme throw new IllegalArgumentException("Unknown element type "+element); } } - + public static void assertOids(Collection> objects, String... expectedOids) { if ((objects == null || objects.isEmpty()) && expectedOids.length == 0) { return; @@ -994,23 +994,23 @@ public static void assertOids(Collection> objects, Stri } } } - + // XNode asserts - + public static void assertSize(MapXNode xmap, int expectedSize) { assertEquals("Wrong size of "+xmap, expectedSize, xmap.size()); } - + public static void assertSize(ListXNode xlist, int expectedSize) { assertEquals("Wrong size of "+xlist, expectedSize, xlist.size()); } - + public static void assertSubnode(MapXNode xmap, QName key, Class expectedClass) { XNode xsubnode = xmap.get(key); assert xsubnode != null : "No subnode "+key+" in "+xmap; assert expectedClass.isAssignableFrom(xsubnode.getClass()) : "Wrong class of subnode "+key+" in "+xmap+"; expected "+expectedClass+", got "+xsubnode.getClass(); } - + public static void assertAllParsedNodes(XNode xnode) { Visitor visitor = new Visitor() { @Override @@ -1022,9 +1022,9 @@ public void visit(Visitable visitable) { }; xnode.accept(visitor); } - + // Query asserts - + public static void assertOrFilter(ObjectFilter filter, int conditions) { assertEquals("Wrong filter class", OrFilter.class, filter.getClass()); assertEquals("Wrong number of filter conditions", conditions, ((OrFilter) filter).getConditions().size()); @@ -1034,7 +1034,7 @@ public static void assertAndFilter(ObjectFilter filter, int conditions) { assertEquals("Wrong filter class", AndFilter.class, filter.getClass()); assertEquals("Wrong number of filter conditions", conditions, ((AndFilter) filter).getConditions().size()); } - + public static void assertEqualsFilter(ObjectFilter objectFilter, QName expectedFilterDef, QName expectedTypeName, ItemPath path) { assertEquals("Wrong filter class", EqualFilter.class, objectFilter.getClass()); @@ -1046,7 +1046,7 @@ public static void assertEqualsFilter(ObjectFilter objectFilter, QName expectedF } assertPathEquivalent("Wrong filter path", path, filter.getFullPath()); } - + public static void assertEqualsFilterValue(EqualFilter filter, T value) { List values = filter.getValues(); assertEquals("Wrong number of filter values", 1, values.size()); @@ -1055,7 +1055,7 @@ public static void assertEqualsFilterValue(EqualFilter filter, T value) { assertEquals("Wrong filter value", value, val.getValue()); } - + public static void assertRefFilter(ObjectFilter objectFilter, QName expectedFilterDef, QName expectedTypeName, ItemPath path) { assertEquals("Wrong filter class", RefFilter.class, objectFilter.getClass()); @@ -1064,13 +1064,13 @@ public static void assertRefFilter(ObjectFilter objectFilter, QName expectedFilt assertEquals("Wrong filter definition type", expectedTypeName, filter.getDefinition().getTypeName()); assertPathEquivalent("Wrong filter path", path, filter.getFullPath()); } - + // Local version of JUnit assers to avoid pulling JUnit dependecy to main - + static void assertNotNull(String string, Object object) { assert object != null : string; } - + static void assertNull(String string, Object object) { assert object == null : string; } @@ -1080,27 +1080,27 @@ private static void assertTrue(String message, boolean test) { } public static void assertEquals(String message, Object expected, Object actual) { - assert MiscUtil.equals(expected, actual) : message + assert MiscUtil.equals(expected, actual) : message + ": expected " + MiscUtil.getValueWithClass(expected) + ", was " + MiscUtil.getValueWithClass(actual); } - + public static void assertEquals(String message, MatchingRule matchingRule, T expected, T actual) throws SchemaException { - assert equals(matchingRule, expected, actual) : message + assert equals(matchingRule, expected, actual) : message + ": expected " + MiscUtil.getValueWithClass(expected) + ", was " + MiscUtil.getValueWithClass(actual); } - + static void assertSame(String message, Object expected, Object actual) { - assert expected == actual : message - + ": expected ("+expected.getClass().getSimpleName() + ")" + expected + assert expected == actual : message + + ": expected ("+expected.getClass().getSimpleName() + ")" + expected + ", was (" + actual.getClass().getSimpleName() + ")" + actual; } - + static void fail(String message) { assert false: message; } - + private static boolean equals(MatchingRule matchingRule, T a, T b) throws SchemaException { if (a == null && b == null) { return true; @@ -1124,14 +1124,14 @@ private static boolean equals(Object a, Object b) { } return a.equals(b); } - + public static void assertEqualsUnordered(String message, Stream actualStream, T... expectedValues) { List expectedCollection = Arrays.asList(expectedValues); Collection actualCollection = actualStream.collect(Collectors.toList()); assert MiscUtil.unorderedCollectionEquals(actualCollection, expectedCollection) : message + ": expected "+expectedCollection+ "; was "+actualCollection; } - + public static void assertEqualsCollectionUnordered(String message, Collection actualCollection, T... expectedValues) { List expectedCollection = Arrays.asList(expectedValues); assert MiscUtil.unorderedCollectionEquals(actualCollection, expectedCollection) : message + ": expected "+expectedCollection+ @@ -1200,8 +1200,8 @@ public static void assertRefEquivalent(String message, PrismReferenceValue expec public static void assertInstanceOf(Class expectedClass, Object object) { assertNotNull("Expected that object will be instance of "+expectedClass+", but it is null", object); - assertTrue("Expected that "+object+" will be instance of "+expectedClass+", but it is "+object.getClass(), - expectedClass.isAssignableFrom(object.getClass())); + assertTrue("Expected that "+object+" will be instance of "+expectedClass+", but it is "+object.getClass(), + expectedClass.isAssignableFrom(object.getClass())); } public static void assertDuration(String message, String durationString, long start, XMLGregorianCalendar end, Long precision) { diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismContextFactory.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismContextFactory.java index 9fc9f7ed350..aeafd974c2c 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismContextFactory.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismContextFactory.java @@ -26,9 +26,9 @@ */ @FunctionalInterface public interface PrismContextFactory { - + /** - * Returns UNINITIALIZED prism context. + * Returns UNINITIALIZED prism context. */ public PrismContext createPrismContext() throws SchemaException, FileNotFoundException; diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismMonitor.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismMonitor.java index 370ff375ed1..83fd8e66876 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismMonitor.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismMonitor.java @@ -23,15 +23,15 @@ * interface are called when selected important (usually expensive) operations * take place in prism. This can be used for gathering stats, making assertions * in the test code, etc. - * + * * @author semancik */ public interface PrismMonitor { void recordPrismObjectCompareCount(PrismObject thisObject, Object thatObject); - + void beforeObjectClone(PrismObject orig); - + void afterObjectClone(PrismObject orig, PrismObject clone); - + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismPrettyPrinter.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismPrettyPrinter.java index 01a62a42952..090bb69f5f2 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismPrettyPrinter.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismPrettyPrinter.java @@ -24,15 +24,18 @@ import com.evolveum.prism.xml.ns._public.types_3.RawType; import javax.xml.namespace.QName; +import java.util.regex.Pattern; import java.util.stream.Collectors; /** - * + * * @author mederly */ public class PrismPrettyPrinter { private static final Trace LOGGER = TraceManager.getTrace(PrismPrettyPrinter.class); + private static final String CRLF_REGEX = "(\\r|\\n|\\r\\n)+"; + private static final Pattern CRLF_PATTERN = Pattern.compile(CRLF_REGEX); public static String prettyPrint(RawType raw) { if (raw.getAlreadyParsedValue() != null) { @@ -41,7 +44,7 @@ public static String prettyPrint(RawType raw) { if (raw.getXnode() != null && raw.getPrismContext() != null) { try { String jsonText = raw.getPrismContext().jsonSerializer().serialize(raw.getRootXNode(new QName("value"))); - return jsonText.replaceAll("(\\r|\\n|\\r\\n)+", ""); + return CRLF_PATTERN.matcher(jsonText).replaceAll(""); } catch (Throwable t) { LoggingUtils.logException(LOGGER, "Couldn't serialize raw value for pretty printing, using 'toString' instead: {}", t, raw.getXnode()); } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismTestUtil.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismTestUtil.java index 702e6fb6326..c1d2843c4a7 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismTestUtil.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismTestUtil.java @@ -44,8 +44,8 @@ /** * Class that statically instantiates the prism contexts and provides convenient static version of the PrismContext - * and processor classes. - * + * and processor classes. + * * This is usable for tests. DO NOT use this in the main code. Although it is placed in "main" for convenience, * is should only be used in tests. * @@ -56,7 +56,7 @@ public class PrismTestUtil { private static final Trace LOGGER = TraceManager.getTrace(PrismTestUtil.class); private static final QName DEFAULT_ELEMENT_NAME = new QName("http://midpoint.evolveum.com/xml/ns/test/whatever-1.xsd", "whatever"); - + private static PrismContext prismContext; private static PrismContextFactory prismContextFactory; @@ -68,7 +68,7 @@ public static void resetPrismContext(PrismContextFactory newPrismContextFactory) setFactory(newPrismContextFactory); resetPrismContext(); } - + public static void setFactory(PrismContextFactory newPrismContextFactory) { PrismTestUtil.prismContextFactory = newPrismContextFactory; } @@ -90,30 +90,30 @@ public static PrismContext createInitializedPrismContext() throws SchemaExceptio newPrismContext.initialize(); return newPrismContext; } - + public static PrismContext getPrismContext() { if (prismContext == null) { throw new IllegalStateException("Prism context is not set in PrismTestUtil. Maybe a missing call to resetPrismContext(..) in test initialization?"); } return prismContext; } - + public static SchemaRegistry getSchemaRegistry() { return prismContext.getSchemaRegistry(); } - + // ========================== // == parsing // ========================== - + public static PrismObject parseObject(File file) throws SchemaException, IOException { return getPrismContext().parseObject(file); } - + public static PrismObject parseObject(String xmlString) throws SchemaException { return getPrismContext().parseObject(xmlString); } - + @Deprecated public static PrismObject parseObject(Element element) throws SchemaException { return getPrismContext().parserFor(element).parse(); @@ -127,7 +127,7 @@ public static T parseObjectable(File file, Class clazz public static List> parseObjects(File file) throws SchemaException, IOException { return getPrismContext().parserFor(file).parseObjects(); } - + // ========================== // == Serializing // ========================== @@ -200,18 +200,18 @@ public static void displayTestTitle(String testName) { System.out.println("\n\n===[ "+testName+" ]===\n"); LOGGER.info("===[ {} ]===",testName); } - + public static SearchFilterType unmarshalFilter(File file) throws Exception { return prismContext.parserFor(file).parseRealValue(SearchFilterType.class); } - + public static ObjectFilter getFilterCondition(ObjectFilter filter, int index) { if (!(filter instanceof NaryLogicalFilter)) { throw new IllegalArgumentException("Filter not an instance of n-ary logical filter."); } return ((LogicalFilter) filter).getConditions().get(index); } - + public static void displayQuery(ObjectQuery query) { LOGGER.trace("object query: {}", query); System.out.println("object query: " + query); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismUtil.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismUtil.java index bb3c1cd0bf0..64d94ef8160 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismUtil.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismUtil.java @@ -64,14 +64,14 @@ public static void recomputeRealValue(T realValue, PrismContext prismContext polyStringVal.recompute(prismContext.getDefaultPolyStringNormalizer()); } } - + public static void recomputePrismPropertyValue(PrismPropertyValue pValue, PrismContext prismContext) { if (pValue == null) { return; } recomputeRealValue(pValue.getValue(), prismContext); } - + /** * Super-mega-giga-ultra hack. This is used to "fortify" XML namespace declaration in a non-standard way. * It is useful in case that someone will try some stupid kind of schema-less XML normalization that removes @@ -100,7 +100,7 @@ private static void fortifyNamespaceDeclarations(Element definitionElement, Elem } } } - + public static void unfortifyNamespaceDeclarations(Element definitionElement) { Map namespaces = new HashMap(); for(Element childElement: DOMUtil.listChildElements(definitionElement)) { @@ -112,7 +112,7 @@ public static void unfortifyNamespaceDeclarations(Element definitionElement) { } else { unfortifyNamespaceDeclarations(definitionElement, childElement, namespaces); namespaces = new HashMap(); - } + } } } @@ -175,7 +175,7 @@ public static PrismProperty convertProperty(PrismProperty srcProp, P return targetProp; } } - + public static void setDeltaOldValue(PrismObject oldObject, ItemDelta itemDelta) { if (oldObject == null) { return; @@ -185,13 +185,13 @@ public static void setDeltaOldValue(PrismObject oldObj itemDelta.setEstimatedOldValues((Collection) PrismValue.cloneCollection(itemOld.getValues())); } } - + public static void setDeltaOldValue(PrismObject oldObject, Collection itemDeltas) { for(ItemDelta itemDelta: itemDeltas) { setDeltaOldValue(oldObject, itemDelta); } } - + public static boolean equals(T a, T b, MatchingRule matchingRule) throws SchemaException { if (a == null && b == null) { return true; @@ -248,7 +248,7 @@ public String toString() { } }; } - + public static ExpressionWrapper parseExpression(XNode node, PrismContext prismContext) throws SchemaException { if (!(node instanceof MapXNode)) { return null; @@ -263,7 +263,7 @@ public static ExpressionWrapper parseExpression(XNode node, PrismContext prismCo } return null; } - + public static ExpressionWrapper parseExpression(Entry expressionEntry, PrismContext prismContext) throws SchemaException { if (expressionEntry == null) { return null; @@ -273,7 +273,7 @@ public static ExpressionWrapper parseExpression(Entry expressionEn ExpressionWrapper expressionWrapper = new ExpressionWrapper(expressionEntry.getKey(), expressionPropertyValue.getValue()); return expressionWrapper; } - + @NotNull public static MapXNode serializeExpression(@NotNull ExpressionWrapper expressionWrapper, BeanMarshaller beanMarshaller) throws SchemaException { MapXNode xmap = new MapXNode(); @@ -288,7 +288,7 @@ public static MapXNode serializeExpression(@NotNull ExpressionWrapper expression xmap.put(expressionWrapper.getElementName(), expressionXnode); return xmap; } - + // TODO: Unify the two serializeExpression() methods public static MapXNode serializeExpression(ExpressionWrapper expressionWrapper, PrismSerializer xnodeSerializer) throws SchemaException { MapXNode xmap = new MapXNode(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismValidate.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismValidate.java index 27153753e7f..5048ab3eb86 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismValidate.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/PrismValidate.java @@ -23,7 +23,7 @@ * */ public class PrismValidate { - + public static void notEmpty(PolyString value, String message) { if (value == null || value.isEmpty()) { throw new IllegalArgumentException(message); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/RawTypeUtil.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/RawTypeUtil.java index 9495ddb5e55..77d6d80fbfb 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/RawTypeUtil.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/util/RawTypeUtil.java @@ -40,11 +40,11 @@ public class RawTypeUtil { - + public static Item getParsedItem(ID itemDefinition, List values, QName elementQName, PrismContainerDefinition containerDef) throws SchemaException{ - + Item subItem = null; - + List parsedValues = new ArrayList(); for (RawType rawValue : values){ if (itemDefinition == null && containerDef != null){ @@ -63,14 +63,14 @@ public static Item getP if (prismContext == null && itemDefinition != null) { prismContext = itemDefinition.getPrismContext(); } - + if (itemDefinition == null){ PrismProperty property = new PrismProperty(elementQName, prismContext); property.addAll(PrismValue.cloneCollection(parsedValues)); return property; } - - + + if (itemDefinition instanceof PrismPropertyDefinition) { // property PrismProperty property = ((PrismPropertyDefinition) itemDefinition).instantiate(); @@ -78,7 +78,7 @@ public static Item getP property.add((PrismPropertyValue) val.clone()); } subItem = (Item) property; - + } else if (itemDefinition instanceof PrismContainerDefinition) { PrismContainer container = ((PrismContainerDefinition) itemDefinition) .instantiate(); @@ -114,10 +114,10 @@ public static Item getP } else { throw new IllegalArgumentException("Unsupported definition type " + itemDefinition.getClass()); } - + return subItem; } - + // public static Object toAny(PrismValue value, Document document, PrismContext prismContext) throws SchemaException{ // DomParser domProcessor = prismContext.getParserDom(); //// Document document = DOMUtil.getDocument(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/AnyArrayList.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/AnyArrayList.java index 482170bd1c4..0f8fde109e8 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/AnyArrayList.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/AnyArrayList.java @@ -40,7 +40,7 @@ * It is quite a bad way to use getAny() methods from the JAXB classes, it is much better to use * prism facet instead. However we need this to be fully JAXB compliant and therefore support * XML marshalling/unmarshalling. This is important e.g. for JAX-WS. - * + * * @author Radovan Semancik */ public class AnyArrayList extends AbstractList { @@ -133,7 +133,7 @@ public Object remove(int index) { if (index < item.getValues().size()) { item.remove(index); } else { - index -= item.getValues().size(); + index -= item.getValues().size(); } } throw new IndexOutOfBoundsException(); @@ -153,7 +153,7 @@ public boolean remove(Object element) { } } } - + @Override public boolean removeAll(Collection objects) { boolean changed = false; @@ -166,19 +166,19 @@ public boolean removeAll(Collection objects) { } return changed; } - + private boolean isSchemaless() { return containerValue.getComplexTypeDefinition() == null; } - + private PrismContainer getContainer() { return containerValue.getContainer(); } - + private PrismContext getPrismContext() { return getContainer().getPrismContext(); } - + private Object asElement(PrismValue itemValue) { PrismContext prismContext = containerValue.getPrismContext(); if (prismContext == null) { @@ -190,6 +190,6 @@ private Object asElement(PrismValue itemValue) { throw new SystemException("Unexpected schema problem: "+e.getMessage(),e); } } - + } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/JaxbTypeConverter.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/JaxbTypeConverter.java index b76c9b6e0d3..9b1873d8593 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/JaxbTypeConverter.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/JaxbTypeConverter.java @@ -23,7 +23,7 @@ * */ public class JaxbTypeConverter { - + public static T mapPropertyRealValueToJaxb(Object propertyRealValue) { // TODO: check for type compatibility if (propertyRealValue instanceof PolyString) { @@ -31,7 +31,7 @@ public static T mapPropertyRealValueToJaxb(Object propertyRealValue) { } return (T)propertyRealValue; } - + private static PolyStringType toPolyStringType(PolyString polyString) { if (polyString == null) { return null; diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/PrismContainerArrayList.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/PrismContainerArrayList.java index 8c7a8524d0e..c4f92f74262 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/PrismContainerArrayList.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/PrismContainerArrayList.java @@ -43,7 +43,7 @@ public abstract class PrismContainerArrayList extends A // For deserialization public PrismContainerArrayList() { } - + public PrismContainerArrayList(PrismContainer container) { Validate.notNull(container); this.container = container; diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/PrismForJAXBUtil.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/PrismForJAXBUtil.java index 51f5b6edf38..2a7cb488f8c 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/PrismForJAXBUtil.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/PrismForJAXBUtil.java @@ -61,9 +61,9 @@ private static T getPropertyValue(PrismProperty property, Class reques if (pvalue == null) { return null; } - + Object propertyRealValue = pvalue.getValue(); - + if (propertyRealValue instanceof Element) { if (requestedType.isAssignableFrom(Element.class)) { return (T) propertyRealValue; @@ -87,10 +87,10 @@ private static T getPropertyValue(PrismProperty property, Class reques } return requestedTypeInstance; } - + return JaxbTypeConverter.mapPropertyRealValueToJaxb(propertyRealValue); } - + private static Field getAnyField(Class clazz) { for (Field field: clazz.getDeclaredFields()) { XmlAnyElement xmlAnyElementAnnotation = field.getAnnotation(XmlAnyElement.class); @@ -100,7 +100,7 @@ private static Field getAnyField(Class clazz) { } return null; } - + public static List getPropertyValues(PrismContainerValue container, QName name, Class clazz) { Validate.notNull(container, "Container must not be null."); Validate.notNull(name, "QName must not be null."); @@ -119,7 +119,7 @@ public static List getPropertyValues(PrismContainerValue container, QN return new PropertyArrayList<>(property, container); } - + public static void setPropertyValue(PrismContainerValue container, QName name, T value) { Validate.notNull(container, "Container must not be null."); Validate.notNull(name, "QName must not be null."); @@ -368,7 +368,7 @@ public static MapXNode getReferenceFilterClauseXNode(PrismReferenceValue rval) { } return filter.getFilterClauseXNode(); } - + public static PolyStringType getReferenceTargetName(PrismReferenceValue rval) { PolyString targetName = rval.getTargetName(); if (targetName == null) { @@ -376,7 +376,7 @@ public static PolyStringType getReferenceTargetName(PrismReferenceValue rval) { } return new PolyStringType(targetName); } - + public static void setReferenceTargetName(PrismReferenceValue rval, PolyStringType name) { if (name == null) { rval.setTargetName((PolyString) null); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/PrismReferenceArrayList.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/PrismReferenceArrayList.java index 94b821f664c..e444b770a9e 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/PrismReferenceArrayList.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/PrismReferenceArrayList.java @@ -44,7 +44,7 @@ public PrismReferenceArrayList(PrismReference reference, PrismContainerValue this.reference = reference; this.parent = parent; } - + protected PrismReference getReference() { return reference; } @@ -128,7 +128,7 @@ public boolean addAll(Collection ts) { } return changed; } - + /** * JAXB unmarshaller is calling clear() on lists even though they were just * created. As the references should be visible as two JAXB fields, clearing one diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/PropertyArrayList.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/PropertyArrayList.java index c68eacf52d9..d1e4555fc05 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/PropertyArrayList.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xjc/PropertyArrayList.java @@ -30,7 +30,7 @@ /** * This class is used to wrap {@link PrismProperty} values for JAXB objects with * {@link java.util.List} properties. - *

+ *

* This list implementation is based on {@link java.util.Set} so indexes are * not guaranteed. Objects positions can change in time :) * diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xml/DynamicNamespacePrefixMapper.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xml/DynamicNamespacePrefixMapper.java index 11c9405a942..d3b90964222 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xml/DynamicNamespacePrefixMapper.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xml/DynamicNamespacePrefixMapper.java @@ -24,30 +24,29 @@ /** * Maps namespaces to preferred prefixes. Should be used through the code to * avoid generation of prefixes. - * - * @see MID-349 - * + * + * @see MID-349 + * * @author Igor Farinic * @author Radovan Semancik - * */ public interface DynamicNamespacePrefixMapper extends DebugDumpable { void registerPrefix(String namespace, String prefix, boolean defaultNamespace); - + void registerPrefixLocal(String namespace, String prefix); - + String getPrefix(String namespace); - + QName setQNamePrefix(QName qname); - + /** * Makes sure that there is explicit prefix and not a default namespace prefix. */ QName setQNamePrefixExplicit(QName qname); - + DynamicNamespacePrefixMapper clone(); - + // Follwing two methods are kind of a hack to force JAXB to always use prefixes. // This works around the JAXB bug with default namespaces boolean isAlwaysExplicit(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xml/GlobalDynamicNamespacePrefixMapper.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xml/GlobalDynamicNamespacePrefixMapper.java index 51dbd2ba679..903fda1a791 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xml/GlobalDynamicNamespacePrefixMapper.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xml/GlobalDynamicNamespacePrefixMapper.java @@ -35,15 +35,14 @@ /** * Maps namespaces to preferred prefixes. Should be used through the code to * avoid generation of prefixes. - * + * * Although this is usually used as singleton (static), it can also be instantiated to locally * override some namespace mappings. This is useful for prefixes like "tns" (schema) or "ri" (resource schema). - * - * @see MID-349 - * + * + * @see MID-349 + * * @author Igor Farinic * @author Radovan Semancik - * */ public class GlobalDynamicNamespacePrefixMapper extends NamespacePrefixMapper implements DynamicNamespacePrefixMapper, DebugDumpable { @@ -52,7 +51,7 @@ public class GlobalDynamicNamespacePrefixMapper extends NamespacePrefixMapper im private String defaultNamespace = null; private boolean alwaysExplicit = false; private final Set prefixesDeclaredByDefault = new HashSet<>(); - + public String getDefaultNamespace() { return defaultNamespace; } @@ -60,7 +59,7 @@ public String getDefaultNamespace() { public synchronized void setDefaultNamespace(String defaultNamespace) { this.defaultNamespace = defaultNamespace; } - + @Override public boolean isAlwaysExplicit() { return alwaysExplicit; @@ -95,16 +94,16 @@ public synchronized void registerPrefix(String namespace, String prefix, boolean defaultNamespace = namespace; } } - + private static synchronized void registerPrefixGlobal(String namespace, String prefix) { globalNamespacePrefixMap.put(namespace, prefix); } - + @Override public synchronized void registerPrefixLocal(String namespace, String prefix) { localNamespacePrefixMap.put(namespace, prefix); } - + @Override public String getPrefix(String namespace) { if (defaultNamespace != null && defaultNamespace.equals(namespace) && !alwaysExplicit) { @@ -112,7 +111,7 @@ public String getPrefix(String namespace) { } return getPrefixExplicit(namespace); } - + public synchronized String getPrefixExplicit(String namespace) { String prefix = localNamespacePrefixMap.get(namespace); if (prefix == null) { @@ -120,7 +119,7 @@ public synchronized String getPrefixExplicit(String namespace) { } return prefix; } - + @Override public QName setQNamePrefix(QName qname) { String namespace = qname.getNamespaceURI(); @@ -130,7 +129,7 @@ public QName setQNamePrefix(QName qname) { } return new QName(qname.getNamespaceURI(),qname.getLocalPart(),prefix); } - + @Override public QName setQNamePrefixExplicit(QName qname) { String namespace = qname.getNamespaceURI(); @@ -146,12 +145,12 @@ public String getPreferredPrefix(String namespaceUri, String suggestion, boolean //for JAXB we are mapping midpoint common namespace to default namespace if (defaultNamespace != null && defaultNamespace.equals(namespaceUri) && !alwaysExplicit) { return ""; - } + } return getPreferredPrefix(namespaceUri, suggestion); } /** - * + * * @param namespace * @return preferred prefix for the namespace, if no prefix is assigned yet, * then it will assign a prefix and return it. @@ -189,7 +188,7 @@ public static synchronized String getPreferredPrefix(String namespace, String hi return prefix; } - + @Override public synchronized GlobalDynamicNamespacePrefixMapper clone() { GlobalDynamicNamespacePrefixMapper clone = new GlobalDynamicNamespacePrefixMapper(); @@ -214,7 +213,7 @@ private Map clonePrefixMap(Map map) { public String debugDump() { return debugDump(0); } - + @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xml/TypedValue.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xml/TypedValue.java index 04b68c97643..18fae3e5022 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xml/TypedValue.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xml/TypedValue.java @@ -19,32 +19,30 @@ /** * @author Radovan Semancik - * */ public class TypedValue { private Object value; private QName xsdType; private QName elementName; - - /** - * - */ + public TypedValue() { super(); } + /** - * @param value - * @param xsdType + * @param value the value + * @param xsdType the xsdType */ public TypedValue(Object value, QName xsdType) { super(); this.value = value; this.xsdType = xsdType; } + /** - * @param javaValue - * @param xsiType - * @param qName + * @param value the value + * @param xsdType the xsdType + * @param elementName the elementName */ public TypedValue(Object value, QName xsdType, QName elementName) { super(); @@ -52,41 +50,46 @@ public TypedValue(Object value, QName xsdType, QName elementName) { this.xsdType = xsdType; this.elementName = elementName; } + /** * @return the value */ public Object getValue() { return value; } + /** * @param value the value to set */ public void setValue(Object value) { this.value = value; } + /** * @return the xsdType */ public QName getXsdType() { return xsdType; } + /** * @param xsdType the xsdType to set */ public void setXsdType(QName xsdType) { this.xsdType = xsdType; } + /** * @return the elementName */ public QName getElementName() { return elementName; } + /** * @param elementName the elementName to set */ public void setElementName(QName elementName) { this.elementName = elementName; } - } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xml/XmlTypeConverter.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xml/XmlTypeConverter.java index 64801fb1277..5d4163dd16a 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xml/XmlTypeConverter.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xml/XmlTypeConverter.java @@ -47,9 +47,9 @@ /** * Simple implementation that converts XSD primitive types to Java (and vice * versa). - *

+ *

* It convert type names (xsd types to java classes) and also the values. - *

+ *

* The implementation is very simple now. In fact just a bunch of ifs. We don't * need much more now. If more complex thing will be needed, we will extend the * implementation later. @@ -57,7 +57,7 @@ * @author Radovan Semancik */ public class XmlTypeConverter { - + private static DatatypeFactory datatypeFactory = null; private static final Trace LOGGER = TraceManager.getTrace(XmlTypeConverter.class); @@ -72,7 +72,7 @@ private static DatatypeFactory getDatatypeFactory() { } return datatypeFactory; } - + public static T toJavaValue(Element xmlElement, Class type) throws SchemaException { if (type.equals(Element.class)) { return (T) xmlElement; @@ -92,11 +92,11 @@ public static T toJavaValue(Element xmlElement, Class type) throws Schema return javaValue; } } - + public static T toJavaValue(String stringContent, Class type) { return toJavaValue(stringContent, type, false); } - + public static T toJavaValue(String stringContent, QName typeQName) { Class javaClass = XsdTypeMapper.getXsdToJavaMapping(typeQName); return toJavaValue(stringContent, javaClass, false); @@ -171,7 +171,6 @@ public static Object toJavaValue(Element xmlElement, QName type) throws SchemaEx * * @param xmlElement * @return - * @throws JAXBException */ public static Object toJavaValue(Element xmlElement) throws SchemaException { return toTypedJavaValueWithDefaultType(xmlElement, null).getValue(); @@ -181,10 +180,9 @@ public static Object toJavaValue(Element xmlElement) throws SchemaException { * Try to locate element type from xsi:type, fall back to specified default * type. * - * @param element + * @param xmlElement * @param defaultType * @return converted java value - * @throws JAXBException * @throws SchemaException if no xsi:type or default type specified */ public static TypedValue toTypedJavaValueWithDefaultType(Element xmlElement, QName defaultType) throws SchemaException { @@ -246,7 +244,7 @@ public static Element toXsdElement(Object val, QName elementName, Document doc, toXsdElement(val, element, recordType); return element; } - + public static void toXsdElement(Object val, Element element, boolean recordType) throws SchemaException { if (val instanceof Element) { return; @@ -263,7 +261,7 @@ public static void toXsdElement(Object val, Element element, boolean recordType) DOMUtil.setXsiType(element, xsdType); } } - + public static String toXmlTextContent(Object val, QName elementName) { if (val == null) { // if no value is specified, do not create element @@ -323,11 +321,11 @@ public static String toXmlTextContent(Object val, QName elementName) { public static boolean canConvert(Class clazz) { return (XsdTypeMapper.getJavaToXsdMapping(clazz) != null); } - + public static boolean canConvert(QName xsdType) { return (XsdTypeMapper.getXsdToJavaMapping(xsdType) != null); } - + public static boolean isMatchingType(Class expectedClass, Class actualClass) { if (expectedClass.isAssignableFrom(actualClass)) { return true; @@ -480,7 +478,7 @@ public static XMLGregorianCalendar createXMLGregorianCalendar(long timeInMillis) gregorianCalendar.setTimeInMillis(timeInMillis); return createXMLGregorianCalendar(gregorianCalendar); } - + public static XMLGregorianCalendar createXMLGregorianCalendar(Date date) { if (date == null) { return null; @@ -489,11 +487,11 @@ public static XMLGregorianCalendar createXMLGregorianCalendar(Date date) { gregorianCalendar.setTime(date); return createXMLGregorianCalendar(gregorianCalendar); } - + public static XMLGregorianCalendar createXMLGregorianCalendar(String string) { return getDatatypeFactory().newXMLGregorianCalendar(string); } - + public static XMLGregorianCalendar createXMLGregorianCalendar(GregorianCalendar cal) { return getDatatypeFactory().newXMLGregorianCalendar(cal); } @@ -505,12 +503,12 @@ public static XMLGregorianCalendar createXMLGregorianCalendar(XMLGregorianCalend } return getDatatypeFactory().newXMLGregorianCalendar(cal.toGregorianCalendar()); // TODO find a better way } - + public static XMLGregorianCalendar createXMLGregorianCalendar(int year, int month, int day, int hour, int minute, int second, int millisecond, int timezone) { return getDatatypeFactory().newXMLGregorianCalendar(year, month, day, hour, minute, second, millisecond, timezone); } - + public static XMLGregorianCalendar createXMLGregorianCalendar(int year, int month, int day, int hour, int minute, int second) { return getDatatypeFactory().newXMLGregorianCalendar(year, month, day, hour, minute, second, 0, 0); @@ -526,11 +524,11 @@ public static long toMillis(XMLGregorianCalendar xmlCal) { public static Date toDate(XMLGregorianCalendar xmlCal) { return xmlCal != null ? new Date(xmlCal.toGregorianCalendar().getTimeInMillis()) : null; } - + public static Duration createDuration(long durationInMilliSeconds) { return getDatatypeFactory().newDuration(durationInMilliSeconds); } - + public static Duration createDuration(String lexicalRepresentation) { return lexicalRepresentation != null ? getDatatypeFactory().newDuration(lexicalRepresentation) : null; } @@ -538,7 +536,7 @@ public static Duration createDuration(String lexicalRepresentation) { public static Duration createDuration(boolean isPositive, int years, int months, int days, int hours, int minutes, int seconds) { return getDatatypeFactory().newDuration(isPositive, years, months, days, hours, minutes, seconds); } - + /** * Parse PolyString from DOM element. */ @@ -562,7 +560,7 @@ private static PolyString polyStringToJava(Element polyStringElement) throws Sch } return new PolyString(orig, norm); } - + /** * Serialize PolyString to DOM element. */ @@ -574,9 +572,9 @@ private static void polyStringToElement(Element polyStringElement, PolyString po if (polyString.getNorm() != null) { Element origElement = DOMUtil.createSubElement(polyStringElement, PrismConstants.POLYSTRING_ELEMENT_NORM_QNAME); origElement.setTextContent(polyString.getNorm()); - } + } } - + public static T toXmlEnum(Class expectedType, String stringValue) { if (stringValue == null) { return null; @@ -597,7 +595,7 @@ public static T toXmlEnum(Class expectedType, String stringValue) { } throw new IllegalArgumentException("No enum value '"+stringValue+"' in "+expectedType); } - + public static String fromXmlEnum(T enumValue) { if (enumValue == null) { return null; @@ -620,7 +618,7 @@ public static XMLGregorianCalendar addDuration(XMLGregorianCalendar now, Duratio later.add(duration); return later; } - + public static XMLGregorianCalendar addDuration(XMLGregorianCalendar now, String duration) { XMLGregorianCalendar later = createXMLGregorianCalendar(toMillis(now)); later.add(createDuration(duration)); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xml/XsdTypeMapper.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xml/XsdTypeMapper.java index 19e41fad4f8..b157e11af80 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xml/XsdTypeMapper.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xml/XsdTypeMapper.java @@ -88,11 +88,11 @@ private static void initTypeMap() throws IOException, ClassNotFoundException { addMapping(GregorianCalendar.class, DOMUtil.XSD_DATETIME, true); addMapping(XMLGregorianCalendar.class, DOMUtil.XSD_DATETIME, true); addMapping(Duration.class, DOMUtil.XSD_DURATION, true); - + addMapping(ItemPathType.class, ItemPathType.COMPLEX_TYPE, true); addMapping(ItemPath.class, ItemPathType.COMPLEX_TYPE, false); addMapping(QName.class, DOMUtil.XSD_QNAME, true); - + addMapping(PolyString.class, PrismConstants.POLYSTRING_TYPE_QNAME, true); addMappingExt(ItemPathType.class, ItemPathType.COMPLEX_TYPE, true); // TODO remove @@ -122,7 +122,7 @@ public static QName toXsdType(Class javaClass) { } return xsdType; } - + public static QName getJavaToXsdMapping(Class type) { if (javaToXsdTypeMap.containsKey(type)) { return javaToXsdTypeMap.get(type); @@ -133,7 +133,7 @@ public static QName getJavaToXsdMapping(Class type) { } return null; } - + public static QName determineQNameWithNs(QName xsdType){ if (StringUtils.isNotBlank(xsdType.getNamespaceURI())){ return xsdType; @@ -147,7 +147,7 @@ public static QName determineQNameWithNs(QName xsdType){ } return null; } - + public static Class getXsdToJavaMapping(QName xsdType) { Class clazz = xsdToJavaTypeMap.get(xsdType); if (clazz == null){ @@ -222,7 +222,7 @@ private static Class toJavaType(Map map, @NotNull QName xsd Class typedClass = (Class) javaType; return typedClass; } - + public static String multiplicityToString(Integer integer) { if (integer == null) { return null; @@ -252,7 +252,7 @@ public static boolean isMatchingMultiplicity(int number, int min, int max) { } return true; } - + static { try { initTypeMap(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/ListXNode.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/ListXNode.java index 2922fc8f62b..6ada2689f48 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/ListXNode.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/ListXNode.java @@ -25,7 +25,7 @@ import com.evolveum.midpoint.util.DebugUtil; public class ListXNode extends XNode implements List { - + private final List subnodes = new ArrayList<>(); @Override @@ -142,7 +142,7 @@ public ListIterator listIterator(int index) { public List subList(int fromIndex, int toIndex) { return subnodes.subList(fromIndex, toIndex); } - + @Override public void accept(Visitor visitor) { visitor.visit(this); @@ -166,7 +166,7 @@ public String debugDump(int indent) { public String getDesc() { return "list"; } - + @Override public String toString() { return "XNode(list:"+subnodes.size()+" elements)"; diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/MapXNode.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/MapXNode.java index a489e4f9c7e..169c80345a4 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/MapXNode.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/MapXNode.java @@ -37,7 +37,7 @@ import org.jetbrains.annotations.NotNull; public class MapXNode extends XNode implements Map, Serializable { - + // We want to maintain ordering, hence the List private List subnodes = new ArrayList(); @@ -123,19 +123,19 @@ public Collection values() { } return values; } - + public java.util.Map.Entry getSingleSubEntry(String errorContext) throws SchemaException { if (isEmpty()) { return null; } - + if (size() > 1) { throw new SchemaException("More than one element in " + errorContext +" : "+dumpKeyNames()); } - + return subnodes.get(0); } - + public Entry getSingleEntryThatDoesNotMatch(QName... excludedKeys) throws SchemaException { Entry found = null; OUTER: for (Entry subentry: subnodes) { @@ -224,7 +224,7 @@ public void clear() { }; return entries; } - + public T getParsedPrimitiveValue(QName key, QName typeName) throws SchemaException { XNode xnode = get(key); if (xnode == null) { @@ -236,7 +236,7 @@ public T getParsedPrimitiveValue(QName key, QName typeName) throws SchemaExc PrimitiveXNode xprim = (PrimitiveXNode)xnode; return xprim.getParsedValue(typeName, null); // TODO expected class } - + public void merge(MapXNode other) { for (java.util.Map.Entry otherEntry: other.entrySet()) { QName otherKey = otherEntry.getKey(); @@ -277,7 +277,7 @@ public void accept(Visitor visitor) { } } } - + public boolean equals(Object o) { if (!(o instanceof MapXNode)){ return false; @@ -307,7 +307,7 @@ public String debugDump(int indent) { public String getDesc() { return "map"; } - + @Override public String toString() { return "XNode(map:"+subnodes.size()+" entries)"; @@ -342,7 +342,7 @@ private XNode removeEntry(QName key) { } return null; } - + public String dumpKeyNames() { StringBuilder sb = new StringBuilder(); Iterator iterator = subnodes.iterator(); @@ -393,7 +393,7 @@ private class Entry implements Map.Entry, Serializable { private QName key; private XNode value; - + public Entry(QName key) { super(); this.key = key; diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/PrimitiveXNode.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/PrimitiveXNode.java index 1709d8d7c9f..f69f0ecb250 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/PrimitiveXNode.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/PrimitiveXNode.java @@ -51,14 +51,14 @@ public class PrimitiveXNode extends XNode implements Serializable { */ private T value; private ValueParser valueParser; - + /** * If set to true then this primitive value either came from an attribute * or we prefer this to be represented as an attribute (if the target format * is capable of representing attributes) */ private boolean isAttribute = false; - + public PrimitiveXNode() { super(); } @@ -100,7 +100,7 @@ public T getParsedValue(@NotNull QName typeName, @Nullable Class expectedClas throw new SchemaException("Expected " + expectedClass + " but got " + value.getClass() + " instead. Value is " + value); } } - + public ValueParser getValueParser() { return valueParser; } @@ -125,7 +125,7 @@ public void setValue(T value, QName typeQName) { this.value = value; this.valueParser = null; } - + public boolean isParsed() { return valueParser == null; } @@ -137,7 +137,7 @@ public boolean isAttribute() { public void setAttribute(boolean isAttribute) { this.isAttribute = isAttribute; } - + public boolean isEmpty() { if (!isParsed()) { return valueParser.isEmpty(); @@ -217,11 +217,11 @@ private String formatValue(T value) { if (value instanceof DisplayableValue) { return ((DisplayableValue) value).getValue().toString(); } - + if (value != null && value.getClass().isEnum()){ return value.toString(); } - + return XmlTypeConverter.toXmlTextContent(value, null); } @@ -229,7 +229,7 @@ private String formatValue(T value) { public void accept(Visitor visitor) { visitor.visit(this); } - + @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); @@ -241,12 +241,12 @@ public String debugDump(int indent) { } return sb.toString(); } - + @Override public String getDesc() { return "primitive"; } - + @Override public String toString() { StringBuilder sb = new StringBuilder("XNode(primitive:"); @@ -334,7 +334,7 @@ public boolean equals(Object obj) { if (!(obj instanceof PrimitiveXNode)) { return false; } - + PrimitiveXNode other = (PrimitiveXNode) obj; if (other.isParsed() && isParsed()){ return value.equals(other.value); @@ -352,7 +352,7 @@ public boolean equals(Object obj) { String otherStringValue = other.getStringValue(); return thisStringValue.equals(otherStringValue); } - + return false; } diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/RootXNode.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/RootXNode.java index d32aff59767..5fa1ffc0d36 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/RootXNode.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/RootXNode.java @@ -27,7 +27,7 @@ public class RootXNode extends XNode { @NotNull private QName rootElementName; private XNode subnode; - + public RootXNode(@NotNull QName rootElementName) { this.rootElementName = rootElementName; } @@ -93,7 +93,7 @@ public void accept(Visitor visitor) { subnode.accept(visitor); } } - + @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); @@ -111,12 +111,12 @@ public String debugDump(int indent) { } return sb.toString(); } - + @Override public String getDesc() { return "root"; } - + @Override public String toString() { return "XNode(root:"+subnode+")"; diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/SchemaXNode.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/SchemaXNode.java index 4a4378f1927..81b57d13653 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/SchemaXNode.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/SchemaXNode.java @@ -28,7 +28,7 @@ public class SchemaXNode extends XNode { private Element schemaElement; - + public Element getSchemaElement() { return schemaElement; } @@ -41,7 +41,7 @@ public void setSchemaElement(Element schemaElement) { public boolean isEmpty() { return schemaElement == null || DOMUtil.isEmpty(schemaElement); } - + @Override public void accept(Visitor visitor) { visitor.visit(this); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/ValueParser.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/ValueParser.java index cf948d0fe37..c109d27be98 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/ValueParser.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/ValueParser.java @@ -31,7 +31,7 @@ public interface ValueParser { T parse(QName typeName, XNodeProcessorEvaluationMode mode) throws SchemaException; - + // This has to work even without the type boolean isEmpty(); diff --git a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/XNode.java b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/XNode.java index e7d55700d70..e0b02df397d 100644 --- a/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/XNode.java +++ b/infra/prism/src/main/java/com/evolveum/midpoint/prism/xnode/XNode.java @@ -31,7 +31,7 @@ * */ public abstract class XNode implements DebugDumpable, Visitable, Cloneable, Serializable { - + public static final QName KEY_OID = new QName(null, "oid"); public static final QName KEY_VERSION = new QName(null, "version"); public static final QName KEY_CONTAINER_ID = new QName(null, "id"); @@ -48,7 +48,7 @@ public abstract class XNode implements DebugDumpable, Visitable, Cloneable, Seri // Common fields protected XNode parent; - + /** * If set to true that the element came from the explicit type definition * (e.g. xsi:type in XML) on the parsing side; or that it the explicit type @@ -61,7 +61,7 @@ public abstract class XNode implements DebugDumpable, Visitable, Cloneable, Seri private File originFile; private String originDescription; private int lineNumber; - + // These may be detected in parsed file and are also used for serialization protected QName typeQName; protected QName elementName; // Filled if and only if this is a member of heterogeneous list. @@ -133,7 +133,7 @@ public Integer getMaxOccurs() { public void setMaxOccurs(Integer maxOccurs) { this.maxOccurs = maxOccurs; } - + public abstract boolean isEmpty(); public boolean isExplicitTypeDeclaration() { @@ -143,7 +143,7 @@ public boolean isExplicitTypeDeclaration() { public void setExplicitTypeDeclaration(boolean explicitTypeDeclaration) { this.explicitTypeDeclaration = explicitTypeDeclaration; } - + public abstract void accept(Visitor visitor); public XNode clone() { @@ -201,7 +201,7 @@ public String debugDump() { } public abstract String getDesc(); - + protected String dumpSuffix() { StringBuilder sb = new StringBuilder(); if (elementName != null) { diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/annotation_3/AccessAnnotationType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/annotation_3/AccessAnnotationType.java index 19535b34f37..9d02cebeeb5 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/annotation_3/AccessAnnotationType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/annotation_3/AccessAnnotationType.java @@ -8,19 +8,18 @@ /** *

Java class for AccessAnnotationType. - * + * *

The following schema fragment specifies the expected content contained within this class. *

*

- * <simpleType name="AccessAnnotationType">
- *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
- *     <enumeration value="read"/>
- *     <enumeration value="update"/>
- *     <enumeration value="create"/>
- *   </restriction>
- * </simpleType>
+ * <simpleType name="AccessAnnotationType">
+ *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
+ *     <enumeration value="read"/>
+ *     <enumeration value="update"/>
+ *     <enumeration value="create"/>
+ *   </restriction>
+ * </simpleType>
  * 
- * */ @XmlType(name = "AccessAnnotationType", namespace = "http://prism.evolveum.com/xml/ns/public/annotation-2") @XmlEnum diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/annotation_3/ObjectFactory.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/annotation_3/ObjectFactory.java index bd0eeb876b9..4195e5f319b 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/annotation_3/ObjectFactory.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/annotation_3/ObjectFactory.java @@ -8,18 +8,18 @@ /** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the com.evolveum.prism.xml.ns._public.annotation_2 package. - *

An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are + * This object contains factory methods for each + * Java content interface and Java element interface + * generated in the com.evolveum.prism.xml.ns._public.annotation_2 package. + *

An ObjectFactory allows you to programatically + * construct new instances of the Java representation + * for XML content. The Java representation of XML + * content can consist of schema derived interfaces + * and classes representing the binding of schema + * type definitions, element declarations and model + * groups. Factory methods for each of these are * provided in this class. - * + * */ @XmlRegistry public class ObjectFactory { @@ -43,14 +43,14 @@ public class ObjectFactory { /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.evolveum.prism.xml.ns._public.annotation_2 - * + * */ public ObjectFactory() { } /** * Create an instance of {@link JAXBElement }{@code <}{@link QName }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/annotation-3", name = "extension") public JAXBElement createExtension(QName value) { @@ -59,7 +59,7 @@ public JAXBElement createExtension(QName value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link AccessAnnotationType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/annotation-3", name = "access") public JAXBElement createAccess(AccessAnnotationType value) { @@ -68,7 +68,7 @@ public JAXBElement createAccess(AccessAnnotationType value /** * Create an instance of {@link JAXBElement }{@code <}{@link Boolean }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/annotation-3", name = "deprecated") public JAXBElement createDeprecated(Boolean value) { @@ -77,7 +77,7 @@ public JAXBElement createDeprecated(Boolean value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link Boolean }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/annotation-3", name = "ignore") public JAXBElement createIgnore(Boolean value) { @@ -86,7 +86,7 @@ public JAXBElement createIgnore(Boolean value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link Boolean }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/annotation-3", name = "indexed") public JAXBElement createIndexed(Boolean value) { @@ -95,7 +95,7 @@ public JAXBElement createIndexed(Boolean value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link Object }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/annotation-3", name = "container") public JAXBElement createContainer(Object value) { @@ -104,7 +104,7 @@ public JAXBElement createContainer(Object value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link Boolean }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/annotation-3", name = "operational") public JAXBElement createOperational(Boolean value) { @@ -113,7 +113,7 @@ public JAXBElement createOperational(Boolean value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link Boolean }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/annotation-3", name = "composite") public JAXBElement createComposite(Boolean value) { @@ -122,7 +122,7 @@ public JAXBElement createComposite(Boolean value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/annotation-3", name = "help") public JAXBElement createHelp(String value) { @@ -131,7 +131,7 @@ public JAXBElement createHelp(String value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link QName }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/annotation-3", name = "objectReferenceTargetType") public JAXBElement createObjectReferenceTargetType(QName value) { @@ -140,7 +140,7 @@ public JAXBElement createObjectReferenceTargetType(QName value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link Integer }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/annotation-3", name = "displayOrder") public JAXBElement createDisplayOrder(Integer value) { @@ -149,7 +149,7 @@ public JAXBElement createDisplayOrder(Integer value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/annotation-3", name = "displayName") public JAXBElement createDisplayName(String value) { @@ -158,7 +158,7 @@ public JAXBElement createDisplayName(String value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/annotation-3", name = "maxOccurs") public JAXBElement createMaxOccurs(String value) { @@ -167,7 +167,7 @@ public JAXBElement createMaxOccurs(String value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link Object }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/annotation-3", name = "object") public JAXBElement createObject(Object value) { @@ -176,7 +176,7 @@ public JAXBElement createObject(Object value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link Object }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/annotation-3", name = "objectReference") public JAXBElement createObjectReference(Object value) { @@ -185,7 +185,7 @@ public JAXBElement createObjectReference(Object value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link QName }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/annotation-3", name = "type") public JAXBElement createType(QName value) { diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/annotation_3/package-info.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/annotation_3/package-info.java index ea373eddfed..766ca0d6806 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/annotation_3/package-info.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/annotation_3/package-info.java @@ -1,5 +1,5 @@ /** - * + * */ /** * @author semancik diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/FilterClauseType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/FilterClauseType.java index d2d37427e66..4c3ea3199ec 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/FilterClauseType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/FilterClauseType.java @@ -24,22 +24,20 @@ /** *

Java class for FilterType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="FilterType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="matching" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
+ * <complexType name="FilterType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="matching" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "FilterType", propOrder = { @@ -62,7 +60,7 @@ public class FilterClauseType implements Serializable, Cloneable, Equals, HashCo /** * Creates a new {@code FilterType} instance. - * + * */ public FilterClauseType() { // CC-XJC Version 2.0 Build 2011-09-16T18:27:24+0000 @@ -71,8 +69,8 @@ public FilterClauseType() { /** * Creates a new {@code FilterType} instance by deeply copying a given {@code FilterType} instance. - * - * + * + * * @param o * The instance to copy. * @throws NullPointerException @@ -90,11 +88,11 @@ public FilterClauseType(final FilterClauseType o) { /** * Gets the value of the matching property. - * + * * @return * possible object is * {@link String } - * + * */ public String getMatching() { return matching; @@ -102,11 +100,11 @@ public String getMatching() { /** * Sets the value of the matching property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setMatching(String value) { this.matching = value; @@ -115,7 +113,7 @@ public void setMatching(String value) { /** * Generates a String representation of the contents of this type. * This is an extension method, produced by the 'ts' xjc plugin - * + * */ @Override public String toString() { @@ -164,8 +162,8 @@ public boolean equals(Object object) { /** * Creates and returns a deep copy of this object. - * - * + * + * * @return * A deep copy of this object. */ diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/LogicalOperatorFilterType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/LogicalOperatorFilterType.java index 19dc1693fcb..e317e66eba7 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/LogicalOperatorFilterType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/LogicalOperatorFilterType.java @@ -23,19 +23,17 @@ /** *

Java class for LogicalOperatorFilterType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="LogicalOperatorFilterType">
- *   <complexContent>
- *     <extension base="{http://prism.evolveum.com/xml/ns/public/query-2}FilterType">
- *     </extension>
- *   </complexContent>
- * </complexType>
+ * <complexType name="LogicalOperatorFilterType">
+ *   <complexContent>
+ *     <extension base="{http://prism.evolveum.com/xml/ns/public/query-2}FilterType">
+ *     </extension>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "LogicalOperatorFilterType") @@ -53,7 +51,7 @@ public abstract class LogicalOperatorFilterType /** * Creates a new {@code LogicalOperatorFilterType} instance. - * + * */ public LogicalOperatorFilterType() { // CC-XJC Version 2.0 Build 2011-09-16T18:27:24+0000 @@ -62,8 +60,8 @@ public LogicalOperatorFilterType() { /** * Creates a new {@code LogicalOperatorFilterType} instance by deeply copying a given {@code LogicalOperatorFilterType} instance. - * - * + * + * * @param o * The instance to copy. * @throws NullPointerException @@ -80,7 +78,7 @@ public LogicalOperatorFilterType(final LogicalOperatorFilterType o) { /** * Generates a String representation of the contents of this type. * This is an extension method, produced by the 'ts' xjc plugin - * + * */ @Override public String toString() { @@ -117,8 +115,8 @@ public boolean equals(Object object) { /** * Creates and returns a deep copy of this object. - * - * + * + * * @return * A deep copy of this object. */ diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/NAryLogicalOperatorFilterType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/NAryLogicalOperatorFilterType.java index 52d558dd112..738ad2ad51d 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/NAryLogicalOperatorFilterType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/NAryLogicalOperatorFilterType.java @@ -28,22 +28,20 @@ /** *

Java class for NAryLogicalOperatorFilterType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="NAryLogicalOperatorFilterType">
- *   <complexContent>
- *     <extension base="{http://prism.evolveum.com/xml/ns/public/query-2}LogicalOperatorFilterType">
- *       <sequence>
- *         <element ref="{http://prism.evolveum.com/xml/ns/public/query-2}filter" maxOccurs="unbounded"/>
- *       </sequence>
- *     </extension>
- *   </complexContent>
- * </complexType>
+ * <complexType name="NAryLogicalOperatorFilterType">
+ *   <complexContent>
+ *     <extension base="{http://prism.evolveum.com/xml/ns/public/query-2}LogicalOperatorFilterType">
+ *       <sequence>
+ *         <element ref="{http://prism.evolveum.com/xml/ns/public/query-2}filter" maxOccurs="unbounded"/>
+ *       </sequence>
+ *     </extension>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "NAryLogicalOperatorFilterType", propOrder = { @@ -61,7 +59,7 @@ public class NAryLogicalOperatorFilterType /** * Creates a new {@code NAryLogicalOperatorFilterType} instance. - * + * */ public NAryLogicalOperatorFilterType() { // CC-XJC Version 2.0 Build 2011-09-16T18:27:24+0000 @@ -70,8 +68,8 @@ public NAryLogicalOperatorFilterType() { /** * Creates a new {@code NAryLogicalOperatorFilterType} instance by deeply copying a given {@code NAryLogicalOperatorFilterType} instance. - * - * + * + * * @param o * The instance to copy. * @throws NullPointerException @@ -91,25 +89,25 @@ public NAryLogicalOperatorFilterType(final NAryLogicalOperatorFilterType o) { /** * Gets the value of the filter property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the filter property. - * + * *

* For example, to add a new item, do as follows: *

      *    getFilter().add(newItem);
      * 
- * - * + * + * *

* Objects of the following type(s) are allowed in the list * {@link Element } - * - * + * + * */ public List getFilter() { if (filter == null) { @@ -121,7 +119,7 @@ public List getFilter() { /** * Generates a String representation of the contents of this type. * This is an extension method, produced by the 'ts' xjc plugin - * + * */ @Override public String toString() { @@ -173,7 +171,7 @@ public boolean equals(Object object) { /** * Copies all values of property {@code Filter} deeply. - * + * * @param source * The source to copy from. * @param target @@ -200,8 +198,8 @@ private static void copyFilter(final List source, final List t /** * Creates and returns a deep copy of this object. - * - * + * + * * @return * A deep copy of this object. */ diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/ObjectFactory.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/ObjectFactory.java index 59520828b7a..488381eafae 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/ObjectFactory.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/ObjectFactory.java @@ -8,18 +8,18 @@ /** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the com.evolveum.prism.xml.ns._public.query_3 package. - *

An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are + * This object contains factory methods for each + * Java content interface and Java element interface + * generated in the com.evolveum.prism.xml.ns._public.query_3 package. + *

An ObjectFactory allows you to programatically + * construct new instances of the Java representation + * for XML content. The Java representation of XML + * content can consist of schema derived interfaces + * and classes representing the binding of schema + * type definitions, element declarations and model + * groups. Factory methods for each of these are * provided in this class. - * + * */ @XmlRegistry public class ObjectFactory { @@ -47,14 +47,14 @@ public class ObjectFactory { /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.evolveum.prism.xml.ns._public.query_3 - * + * */ public ObjectFactory() { } /** * Create an instance of {@link NAryLogicalOperatorFilterType } - * + * */ public NAryLogicalOperatorFilterType createNAryLogicalOperatorFilterType() { return new NAryLogicalOperatorFilterType(); @@ -62,7 +62,7 @@ public NAryLogicalOperatorFilterType createNAryLogicalOperatorFilterType() { /** * Create an instance of {@link FilterClauseType } - * + * */ public FilterClauseType createFilterType() { return new FilterClauseType(); @@ -70,7 +70,7 @@ public FilterClauseType createFilterType() { /** * Create an instance of {@link QueryType } - * + * */ public QueryType createQueryType() { return new QueryType(); @@ -78,7 +78,7 @@ public QueryType createQueryType() { /** * Create an instance of {@link PropertyNoValueFilterType } - * + * */ public PropertyNoValueFilterType createPropertyNoValueFilterType() { return new PropertyNoValueFilterType(); @@ -86,7 +86,7 @@ public PropertyNoValueFilterType createPropertyNoValueFilterType() { /** * Create an instance of {@link PropertyComplexValueFilterType } - * + * */ public PropertyComplexValueFilterType createPropertyComplexValueFilterType() { return new PropertyComplexValueFilterType(); @@ -94,7 +94,7 @@ public PropertyComplexValueFilterType createPropertyComplexValueFilterType() { /** * Create an instance of {@link PropertySimpleValueFilterType } - * + * */ public PropertySimpleValueFilterType createPropertySimpleValueFilterType() { return new PropertySimpleValueFilterType(); @@ -102,7 +102,7 @@ public PropertySimpleValueFilterType createPropertySimpleValueFilterType() { /** * Create an instance of {@link UriFilterType } - * + * */ public UriFilterType createUriFilterType() { return new UriFilterType(); @@ -110,7 +110,7 @@ public UriFilterType createUriFilterType() { /** * Create an instance of {@link UnaryLogicalOperatorFilterType } - * + * */ public UnaryLogicalOperatorFilterType createUnaryLogicalOperatorFilterType() { return new UnaryLogicalOperatorFilterType(); @@ -118,7 +118,7 @@ public UnaryLogicalOperatorFilterType createUnaryLogicalOperatorFilterType() { /** * Create an instance of {@link ValueType } - * + * */ public ValueType createValueType() { return new ValueType(); @@ -126,7 +126,7 @@ public ValueType createValueType() { /** * Create an instance of {@link PagingType } - * + * */ public PagingType createPagingType() { return new PagingType(); @@ -134,7 +134,7 @@ public PagingType createPagingType() { /** * Create an instance of {@link JAXBElement }{@code <}{@link PropertyNoValueFilterType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/query-3", name = "present", substitutionHeadNamespace = "http://prism.evolveum.com/xml/ns/public/query-3", substitutionHeadName = "filterClause") public JAXBElement createPresent(PropertyNoValueFilterType value) { @@ -143,7 +143,7 @@ public JAXBElement createPresent(PropertyNoValueFilte /** * Create an instance of {@link JAXBElement }{@code <}{@link UnaryLogicalOperatorFilterType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/query-3", name = "not", substitutionHeadNamespace = "http://prism.evolveum.com/xml/ns/public/query-3", substitutionHeadName = "filterClause") public JAXBElement createNot(UnaryLogicalOperatorFilterType value) { @@ -152,7 +152,7 @@ public JAXBElement createNot(UnaryLogicalOperato /** * Create an instance of {@link JAXBElement }{@code <}{@link NAryLogicalOperatorFilterType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/query-3", name = "or", substitutionHeadNamespace = "http://prism.evolveum.com/xml/ns/public/query-3", substitutionHeadName = "filterClause") public JAXBElement createOr(NAryLogicalOperatorFilterType value) { @@ -161,7 +161,7 @@ public JAXBElement createOr(NAryLogicalOperatorFi /** * Create an instance of {@link JAXBElement }{@code <}{@link PropertySimpleValueFilterType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/query-3", name = "substring", substitutionHeadNamespace = "http://prism.evolveum.com/xml/ns/public/query-3", substitutionHeadName = "filterClause") public JAXBElement createSubstring(PropertySimpleValueFilterType value) { @@ -170,7 +170,7 @@ public JAXBElement createSubstring(PropertySimple /** * Create an instance of {@link JAXBElement }{@code <}{@link PropertySimpleValueFilterType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/query-3", name = "ref", substitutionHeadNamespace = "http://prism.evolveum.com/xml/ns/public/query-3", substitutionHeadName = "filterClause") public JAXBElement createRef(PropertySimpleValueFilterType value) { @@ -179,7 +179,7 @@ public JAXBElement createRef(PropertySimpleValueF /** * Create an instance of {@link JAXBElement }{@code <}{@link PropertyNoValueFilterType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/query-3", name = "true", substitutionHeadNamespace = "http://prism.evolveum.com/xml/ns/public/query-3", substitutionHeadName = "filterClause") public JAXBElement createTrue(PropertyNoValueFilterType value) { @@ -188,7 +188,7 @@ public JAXBElement createTrue(PropertyNoValueFilterTy /** * Create an instance of {@link JAXBElement }{@code <}{@link PropertySimpleValueFilterType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/query-3", name = "minDepth", substitutionHeadNamespace = "http://prism.evolveum.com/xml/ns/public/query-3", substitutionHeadName = "filterClause") public JAXBElement createMinDepth(PropertySimpleValueFilterType value) { @@ -197,7 +197,7 @@ public JAXBElement createMinDepth(PropertySimpleV /** * Create an instance of {@link JAXBElement }{@code <}{@link PropertyComplexValueFilterType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/query-3", name = "org", substitutionHeadNamespace = "http://prism.evolveum.com/xml/ns/public/query-3", substitutionHeadName = "filterClause") public JAXBElement createOrg(PropertyComplexValueFilterType value) { @@ -206,13 +206,13 @@ public JAXBElement createOrg(PropertyComplexValu /** * Create an instance of {@link JAXBElement }{@code <}{@link QueryType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/query-3", name = "query") public JAXBElement createQuery(QueryType value) { return new JAXBElement(_Query_QNAME, QueryType.class, null, value); } - + @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/query-3", name = "filter") public JAXBElement createFilter(SearchFilterType value) { return new JAXBElement(_Filter_QNAME, SearchFilterType.class, null, value); @@ -220,7 +220,7 @@ public JAXBElement createFilter(SearchFilterType value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link PropertySimpleValueFilterType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/query-3", name = "greaterOrEqual", substitutionHeadNamespace = "http://prism.evolveum.com/xml/ns/public/query-3", substitutionHeadName = "filterClause") public JAXBElement createGreaterOrEqual(PropertySimpleValueFilterType value) { @@ -229,7 +229,7 @@ public JAXBElement createGreaterOrEqual(PropertyS /** * Create an instance of {@link JAXBElement }{@code <}{@link FilterClauseType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/query-3", name = "filterClause") public JAXBElement createFilterClause(FilterClauseType value) { @@ -238,7 +238,7 @@ public JAXBElement createFilterClause(FilterClauseType value) /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/query-3", name = "matching") public JAXBElement createMatching(String value) { @@ -247,7 +247,7 @@ public JAXBElement createMatching(String value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link NAryLogicalOperatorFilterType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/query-3", name = "and", substitutionHeadNamespace = "http://prism.evolveum.com/xml/ns/public/query-3", substitutionHeadName = "filterClause") public JAXBElement createAnd(NAryLogicalOperatorFilterType value) { @@ -256,7 +256,7 @@ public JAXBElement createAnd(NAryLogicalOperatorF /** * Create an instance of {@link JAXBElement }{@code <}{@link PropertySimpleValueFilterType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/query-3", name = "lessOrEqual", substitutionHeadNamespace = "http://prism.evolveum.com/xml/ns/public/query-3", substitutionHeadName = "filterClause") public JAXBElement createLessOrEqual(PropertySimpleValueFilterType value) { @@ -265,7 +265,7 @@ public JAXBElement createLessOrEqual(PropertySimp /** * Create an instance of {@link JAXBElement }{@code <}{@link ValueType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/query-3", name = "value") public JAXBElement createValue(ValueType value) { @@ -274,7 +274,7 @@ public JAXBElement createValue(ValueType value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link UriFilterType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/query-3", name = "type", substitutionHeadNamespace = "http://prism.evolveum.com/xml/ns/public/query-3", substitutionHeadName = "filterClause") public JAXBElement createType(UriFilterType value) { @@ -283,7 +283,7 @@ public JAXBElement createType(UriFilterType value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link PropertySimpleValueFilterType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/query-3", name = "maxDepth", substitutionHeadNamespace = "http://prism.evolveum.com/xml/ns/public/query-3", substitutionHeadName = "filterClause") public JAXBElement createMaxDepth(PropertySimpleValueFilterType value) { @@ -292,7 +292,7 @@ public JAXBElement createMaxDepth(PropertySimpleV /** * Create an instance of {@link JAXBElement }{@code <}{@link PropertyComplexValueFilterType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/query-3", name = "equal", substitutionHeadNamespace = "http://prism.evolveum.com/xml/ns/public/query-3", substitutionHeadName = "filterClause") public JAXBElement createEqual(PropertyComplexValueFilterType value) { @@ -301,7 +301,7 @@ public JAXBElement createEqual(PropertyComplexVa /** * Create an instance of {@link JAXBElement }{@code <}{@link PropertySimpleValueFilterType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/query-3", name = "orgRef", substitutionHeadNamespace = "http://prism.evolveum.com/xml/ns/public/query-3", substitutionHeadName = "filterClause") public JAXBElement createOrgRef(PropertySimpleValueFilterType value) { diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/OrderDirectionType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/OrderDirectionType.java index ed92eecd111..125316193c4 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/OrderDirectionType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/OrderDirectionType.java @@ -8,18 +8,17 @@ /** *

Java class for OrderDirectionType. - * + * *

The following schema fragment specifies the expected content contained within this class. *

*

- * <simpleType name="OrderDirectionType">
- *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
- *     <enumeration value="ascending"/>
- *     <enumeration value="descending"/>
- *   </restriction>
- * </simpleType>
+ * <simpleType name="OrderDirectionType">
+ *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
+ *     <enumeration value="ascending"/>
+ *     <enumeration value="descending"/>
+ *   </restriction>
+ * </simpleType>
  * 
- * */ @XmlType(name = "OrderDirectionType") @XmlEnum diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/PagingType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/PagingType.java index 8793de5448f..08cc9d665c2 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/PagingType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/PagingType.java @@ -25,33 +25,31 @@ /** - * + * * Parameters limiting the number of returned * entries, offset, etc. * Used in the web service operations * such as list or search - * - * + * + * *

Java class for PagingType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="PagingType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="orderBy" type="{http://prism.evolveum.com/xml/ns/public/types-3}XPathType" minOccurs="0"/>
- *         <element name="orderDirection" type="{http://prism.evolveum.com/xml/ns/public/query-2}OrderDirectionType" minOccurs="0"/>
- *         <element name="offset" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- *         <element name="maxSize" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
+ * <complexType name="PagingType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="orderBy" type="{http://prism.evolveum.com/xml/ns/public/types-3}XPathType" minOccurs="0"/>
+ *         <element name="orderDirection" type="{http://prism.evolveum.com/xml/ns/public/query-2}OrderDirectionType" minOccurs="0"/>
+ *         <element name="offset" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ *         <element name="maxSize" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PagingType", propOrder = { @@ -78,7 +76,7 @@ public class PagingType implements Serializable, Cloneable, Equals, HashCode /** * Creates a new {@code PagingType} instance. - * + * */ public PagingType() { // CC-XJC Version 2.0 Build 2011-09-16T18:27:24+0000 @@ -87,8 +85,8 @@ public PagingType() { /** * Creates a new {@code PagingType} instance by deeply copying a given {@code PagingType} instance. - * - * + * + * * @param o * The instance to copy. * @throws NullPointerException @@ -111,11 +109,11 @@ public PagingType(final PagingType o) { /** * Gets the value of the orderBy property. - * + * * @return * possible object is * {@link Element } - * + * */ public ItemPathType getOrderBy() { return orderBy; @@ -123,11 +121,11 @@ public ItemPathType getOrderBy() { /** * Sets the value of the orderBy property. - * + * * @param value * allowed object is * {@link Element } - * + * */ public void setOrderBy(ItemPathType value) { this.orderBy = value; @@ -135,11 +133,11 @@ public void setOrderBy(ItemPathType value) { /** * Gets the value of the orderDirection property. - * + * * @return * possible object is * {@link OrderDirectionType } - * + * */ public OrderDirectionType getOrderDirection() { return orderDirection; @@ -147,11 +145,11 @@ public OrderDirectionType getOrderDirection() { /** * Sets the value of the orderDirection property. - * + * * @param value * allowed object is * {@link OrderDirectionType } - * + * */ public void setOrderDirection(OrderDirectionType value) { this.orderDirection = value; @@ -159,11 +157,11 @@ public void setOrderDirection(OrderDirectionType value) { /** * Gets the value of the offset property. - * + * * @return * possible object is * {@link Integer } - * + * */ public Integer getOffset() { return offset; @@ -171,11 +169,11 @@ public Integer getOffset() { /** * Sets the value of the offset property. - * + * * @param value * allowed object is * {@link Integer } - * + * */ public void setOffset(Integer value) { this.offset = value; @@ -183,11 +181,11 @@ public void setOffset(Integer value) { /** * Gets the value of the maxSize property. - * + * * @return * possible object is * {@link Integer } - * + * */ public Integer getMaxSize() { return maxSize; @@ -195,11 +193,11 @@ public Integer getMaxSize() { /** * Sets the value of the maxSize property. - * + * * @param value * allowed object is * {@link Integer } - * + * */ public void setMaxSize(Integer value) { this.maxSize = value; @@ -208,7 +206,7 @@ public void setMaxSize(Integer value) { /** * Generates a String representation of the contents of this type. * This is an extension method, produced by the 'ts' xjc plugin - * + * */ @Override public String toString() { @@ -299,8 +297,8 @@ public boolean equals(Object object) { /** * Creates and returns a deep copy of this object. - * - * + * + * * @return * A deep copy of this object. */ diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/PropertyComplexValueFilterType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/PropertyComplexValueFilterType.java index cb175ec4386..bb7a4021d27 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/PropertyComplexValueFilterType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/PropertyComplexValueFilterType.java @@ -54,26 +54,24 @@ /** *

Java class for PropertyComplexValueFilterType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="PropertyComplexValueFilterType">
- *   <complexContent>
- *     <extension base="{http://prism.evolveum.com/xml/ns/public/query-2}FilterType">
- *       <sequence>
- *         <element ref="{http://prism.evolveum.com/xml/ns/public/query-2}path" minOccurs="0"/>
- *         <choice>
- *           <element ref="{http://prism.evolveum.com/xml/ns/public/query-2}value"/>
- *           <any namespace='##other'/>
- *         </choice>
- *       </sequence>
- *     </extension>
- *   </complexContent>
- * </complexType>
+ * <complexType name="PropertyComplexValueFilterType">
+ *   <complexContent>
+ *     <extension base="{http://prism.evolveum.com/xml/ns/public/query-2}FilterType">
+ *       <sequence>
+ *         <element ref="{http://prism.evolveum.com/xml/ns/public/query-2}path" minOccurs="0"/>
+ *         <choice>
+ *           <element ref="{http://prism.evolveum.com/xml/ns/public/query-2}value"/>
+ *           <any namespace='##other'/>
+ *         </choice>
+ *       </sequence>
+ *     </extension>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PropertyComplexValueFilterType", propOrder = { @@ -97,7 +95,7 @@ public class PropertyComplexValueFilterType /** * Creates a new {@code PropertyComplexValueFilterType} instance. - * + * */ public PropertyComplexValueFilterType() { // CC-XJC Version 2.0 Build 2011-09-16T18:27:24+0000 @@ -106,8 +104,8 @@ public PropertyComplexValueFilterType() { /** * Creates a new {@code PropertyComplexValueFilterType} instance by deeply copying a given {@code PropertyComplexValueFilterType} instance. - * - * + * + * * @param o * The instance to copy. * @throws NullPointerException @@ -129,11 +127,11 @@ public PropertyComplexValueFilterType(final PropertyComplexValueFilterType o) { /** * Gets the value of the path property. - * + * * @return * possible object is * {@link Element } - * + * */ public Element getPath() { return path; @@ -141,11 +139,11 @@ public Element getPath() { /** * Sets the value of the path property. - * + * * @param value * allowed object is * {@link Element } - * + * */ public void setPath(Element value) { this.path = value; @@ -153,11 +151,11 @@ public void setPath(Element value) { /** * Gets the value of the value property. - * + * * @return * possible object is * {@link ValueType } - * + * */ public ValueType getValue() { return value; @@ -165,11 +163,11 @@ public ValueType getValue() { /** * Sets the value of the value property. - * + * * @param value * allowed object is * {@link ValueType } - * + * */ public void setValue(ValueType value) { this.value = value; @@ -177,11 +175,11 @@ public void setValue(ValueType value) { /** * Gets the value of the any property. - * + * * @return * possible object is * {@link Object } - * + * */ public Object getAny() { return any; @@ -189,11 +187,11 @@ public Object getAny() { /** * Sets the value of the any property. - * + * * @param value * allowed object is * {@link Object } - * + * */ public void setAny(Object value) { this.any = value; @@ -202,7 +200,7 @@ public void setAny(Object value) { /** * Generates a String representation of the contents of this type. * This is an extension method, produced by the 'ts' xjc plugin - * + * */ @Override public String toString() { @@ -282,7 +280,7 @@ public boolean equals(Object object) { /** * Creates and returns a deep copy of a given object. - * + * * @param o * The instance to copy or {@code null}. * @return @@ -420,7 +418,7 @@ private static Object copyOf(final Object o) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -465,7 +463,7 @@ private static Object copyOfArray(final Object array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -483,7 +481,7 @@ private static boolean[] copyOf(final boolean[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -501,7 +499,7 @@ private static byte[] copyOf(final byte[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -519,7 +517,7 @@ private static char[] copyOf(final char[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -537,7 +535,7 @@ private static double[] copyOf(final double[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -555,7 +553,7 @@ private static float[] copyOf(final float[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -573,7 +571,7 @@ private static int[] copyOf(final int[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -591,7 +589,7 @@ private static long[] copyOf(final long[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -609,7 +607,7 @@ private static short[] copyOf(final short[] array) { /** * Creates and returns a deep copy of a given {@code JAXBElement} instance. - * + * * @param element * The instance to copy or {@code null}. * @return @@ -629,7 +627,7 @@ private static JAXBElement copyOf(final JAXBElement element) { /** * Creates and returns a deep copy of a given {@code Serializable}. - * + * * @param serializable * The instance to copy or {@code null}. * @return @@ -669,8 +667,8 @@ private static Serializable copyOf(final Serializable serializable) { /** * Creates and returns a deep copy of this object. - * - * + * + * * @return * A deep copy of this object. */ diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/PropertyNoValueFilterType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/PropertyNoValueFilterType.java index 4135f0a3455..dd17a916187 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/PropertyNoValueFilterType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/PropertyNoValueFilterType.java @@ -25,22 +25,20 @@ /** *

Java class for PropertyNoValueFilterType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="PropertyNoValueFilterType">
- *   <complexContent>
- *     <extension base="{http://prism.evolveum.com/xml/ns/public/query-2}FilterType">
- *       <sequence>
- *         <element name="property" type="{http://prism.evolveum.com/xml/ns/public/types-3}XPathType"/>
- *       </sequence>
- *     </extension>
- *   </complexContent>
- * </complexType>
+ * <complexType name="PropertyNoValueFilterType">
+ *   <complexContent>
+ *     <extension base="{http://prism.evolveum.com/xml/ns/public/query-2}FilterType">
+ *       <sequence>
+ *         <element name="property" type="{http://prism.evolveum.com/xml/ns/public/types-3}XPathType"/>
+ *       </sequence>
+ *     </extension>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PropertyNoValueFilterType", propOrder = { @@ -58,7 +56,7 @@ public class PropertyNoValueFilterType /** * Creates a new {@code PropertyNoValueFilterType} instance. - * + * */ public PropertyNoValueFilterType() { // CC-XJC Version 2.0 Build 2011-09-16T18:27:24+0000 @@ -67,8 +65,8 @@ public PropertyNoValueFilterType() { /** * Creates a new {@code PropertyNoValueFilterType} instance by deeply copying a given {@code PropertyNoValueFilterType} instance. - * - * + * + * * @param o * The instance to copy. * @throws NullPointerException @@ -86,11 +84,11 @@ public PropertyNoValueFilterType(final PropertyNoValueFilterType o) { /** * Gets the value of the property property. - * + * * @return * possible object is * {@link Element } - * + * */ public Element getProperty() { return property; @@ -98,11 +96,11 @@ public Element getProperty() { /** * Sets the value of the property property. - * + * * @param value * allowed object is * {@link Element } - * + * */ public void setProperty(Element value) { this.property = value; @@ -111,7 +109,7 @@ public void setProperty(Element value) { /** * Generates a String representation of the contents of this type. * This is an extension method, produced by the 'ts' xjc plugin - * + * */ @Override public String toString() { @@ -163,8 +161,8 @@ public boolean equals(Object object) { /** * Creates and returns a deep copy of this object. - * - * + * + * * @return * A deep copy of this object. */ diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/PropertySimpleValueFilterType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/PropertySimpleValueFilterType.java index b393c25931c..b90ed81a060 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/PropertySimpleValueFilterType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/PropertySimpleValueFilterType.java @@ -55,26 +55,26 @@ /** *

Java class for PropertySimpleValueFilterType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="PropertySimpleValueFilterType">
- *   <complexContent>
- *     <extension base="{http://prism.evolveum.com/xml/ns/public/query-2}FilterType">
- *       <sequence>
- *         <element name="property" type="{http://prism.evolveum.com/xml/ns/public/types-3}XPathType"/>
- *         <choice>
- *           <element name="value" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
- *           <any namespace='##other'/>
- *         </choice>
- *       </sequence>
- *     </extension>
- *   </complexContent>
- * </complexType>
+ * <complexType name="PropertySimpleValueFilterType">
+ *   <complexContent>
+ *     <extension base="{http://prism.evolveum.com/xml/ns/public/query-2}FilterType">
+ *       <sequence>
+ *         <element name="property" type="{http://prism.evolveum.com/xml/ns/public/types-3}XPathType"/>
+ *         <choice>
+ *           <element name="value" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
+ *           <any namespace='##other'/>
+ *         </choice>
+ *       </sequence>
+ *     </extension>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * + * + * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PropertySimpleValueFilterType", propOrder = { @@ -99,7 +99,7 @@ public class PropertySimpleValueFilterType /** * Creates a new {@code PropertySimpleValueFilterType} instance. - * + * */ public PropertySimpleValueFilterType() { // CC-XJC Version 2.0 Build 2011-09-16T18:27:24+0000 @@ -108,8 +108,8 @@ public PropertySimpleValueFilterType() { /** * Creates a new {@code PropertySimpleValueFilterType} instance by deeply copying a given {@code PropertySimpleValueFilterType} instance. - * - * + * + * * @param o * The instance to copy. * @throws NullPointerException @@ -131,11 +131,11 @@ public PropertySimpleValueFilterType(final PropertySimpleValueFilterType o) { /** * Gets the value of the property property. - * + * * @return * possible object is * {@link Element } - * + * */ public Element getProperty() { return property; @@ -143,11 +143,11 @@ public Element getProperty() { /** * Sets the value of the property property. - * + * * @param value * allowed object is * {@link Element } - * + * */ public void setProperty(Element value) { this.property = value; @@ -155,11 +155,11 @@ public void setProperty(Element value) { /** * Gets the value of the value property. - * + * * @return * possible object is * {@link Object } - * + * */ public Object getValue() { return value; @@ -167,11 +167,11 @@ public Object getValue() { /** * Sets the value of the value property. - * + * * @param value * allowed object is * {@link Object } - * + * */ public void setValue(Object value) { this.value = value; @@ -179,11 +179,11 @@ public void setValue(Object value) { /** * Gets the value of the any property. - * + * * @return * possible object is * {@link Object } - * + * */ public Object getAny() { return any; @@ -191,11 +191,11 @@ public Object getAny() { /** * Sets the value of the any property. - * + * * @param value * allowed object is * {@link Object } - * + * */ public void setAny(Object value) { this.any = value; @@ -204,7 +204,7 @@ public void setAny(Object value) { /** * Generates a String representation of the contents of this type. * This is an extension method, produced by the 'ts' xjc plugin - * + * */ @Override public String toString() { @@ -284,7 +284,7 @@ public boolean equals(Object object) { /** * Creates and returns a deep copy of a given object. - * + * * @param o * The instance to copy or {@code null}. * @return @@ -422,7 +422,7 @@ private static Object copyOf(final Object o) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -467,7 +467,7 @@ private static Object copyOfArray(final Object array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -485,7 +485,7 @@ private static boolean[] copyOf(final boolean[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -503,7 +503,7 @@ private static byte[] copyOf(final byte[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -521,7 +521,7 @@ private static char[] copyOf(final char[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -539,7 +539,7 @@ private static double[] copyOf(final double[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -557,7 +557,7 @@ private static float[] copyOf(final float[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -575,7 +575,7 @@ private static int[] copyOf(final int[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -593,7 +593,7 @@ private static long[] copyOf(final long[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -611,7 +611,7 @@ private static short[] copyOf(final short[] array) { /** * Creates and returns a deep copy of a given {@code JAXBElement} instance. - * + * * @param element * The instance to copy or {@code null}. * @return @@ -631,7 +631,7 @@ private static JAXBElement copyOf(final JAXBElement element) { /** * Creates and returns a deep copy of a given {@code Serializable}. - * + * * @param serializable * The instance to copy or {@code null}. * @return @@ -671,8 +671,8 @@ private static Serializable copyOf(final Serializable serializable) { /** * Creates and returns a deep copy of this object. - * - * + * + * * @return * A deep copy of this object. */ diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/QueryType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/QueryType.java index eb31159f3a0..9445816d671 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/QueryType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/QueryType.java @@ -46,29 +46,27 @@ /** - * + * * TODO - * - * + * + * *

Java class for QueryType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="QueryType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- *         <element ref="{http://prism.evolveum.com/xml/ns/public/query-2}filter"/>
- *         <element name="paging" type="{http://prism.evolveum.com/xml/ns/public/query-2}PagingType" minOccurs="0"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
+ * <complexType name="QueryType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ *         <element ref="{http://prism.evolveum.com/xml/ns/public/query-2}filter"/>
+ *         <element name="paging" type="{http://prism.evolveum.com/xml/ns/public/query-2}PagingType" minOccurs="0"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "QueryType", propOrder = { @@ -88,16 +86,16 @@ public class QueryType implements Serializable, Cloneable, DebugDumpable @XmlElement(required = true) protected SearchFilterType filter; protected PagingType paging; - - + + /** * Gets the value of the description property. - * + * * @return * possible object is * {@link String } - * + * */ public String getDescription() { return description; @@ -105,11 +103,11 @@ public String getDescription() { /** * Sets the value of the description property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setDescription(String value) { this.description = value; @@ -122,11 +120,11 @@ public QueryType description(String value) { /** * Gets the value of the filter property. - * + * * @return * possible object is * {@link SearchFilterType } - * + * */ public SearchFilterType getFilter() { return filter; @@ -134,11 +132,11 @@ public SearchFilterType getFilter() { /** * Sets the value of the filter property. - * + * * @param value * allowed object is * {@link SearchFilterType } - * + * */ public void setFilter(SearchFilterType value) { this.filter = value; @@ -151,11 +149,11 @@ public QueryType filter(SearchFilterType value) { /** * Gets the value of the paging property. - * + * * @return * possible object is * {@link PagingType } - * + * */ public PagingType getPaging() { return paging; @@ -163,11 +161,11 @@ public PagingType getPaging() { /** * Sets the value of the paging property. - * + * * @param value * allowed object is * {@link PagingType } - * + * */ public void setPaging(PagingType value) { this.paging = value; @@ -214,10 +212,10 @@ public boolean equals(Object obj) { return false; return true; } - + /** * Creates and returns a deep copy of a given object. - * + * * @param o * The instance to copy or {@code null}. * @return @@ -355,7 +353,7 @@ private static Object copyOf(final Object o) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -400,7 +398,7 @@ private static Object copyOfArray(final Object array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -418,7 +416,7 @@ private static boolean[] copyOf(final boolean[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -436,7 +434,7 @@ private static byte[] copyOf(final byte[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -454,7 +452,7 @@ private static char[] copyOf(final char[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -472,7 +470,7 @@ private static double[] copyOf(final double[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -490,7 +488,7 @@ private static float[] copyOf(final float[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -508,7 +506,7 @@ private static int[] copyOf(final int[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -526,7 +524,7 @@ private static long[] copyOf(final long[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -544,7 +542,7 @@ private static short[] copyOf(final short[] array) { /** * Creates and returns a deep copy of a given {@code Serializable}. - * + * * @param serializable * The instance to copy or {@code null}. * @return @@ -584,8 +582,8 @@ private static Serializable copyOf(final Serializable serializable) { /** * Creates and returns a deep copy of this object. - * - * + * + * * @return * A deep copy of this object. */ diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/SearchFilterType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/SearchFilterType.java index 211f86a4b44..edaffb3bca2 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/SearchFilterType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/SearchFilterType.java @@ -81,13 +81,13 @@ public class SearchFilterType implements Serializable, Cloneable, Equals, HashCo // this one is not exposed via JAXB protected MapXNode filterClauseXNode; // single-subnode map node (key = filter element qname, value = contents) - + public final static QName COMPLEX_TYPE = new QName(PrismConstants.NS_QUERY, "SearchFilterType"); public static final QName F_DESCRIPTION = new QName(PrismConstants.NS_QUERY, "description"); /** * Creates a new {@code QueryType} instance. - * + * */ public SearchFilterType() { // CC-XJC Version 2.0 Build 2011-09-16T18:27:24+0000 @@ -96,8 +96,8 @@ public SearchFilterType() { /** * Creates a new {@code QueryType} instance by deeply copying a given {@code QueryType} instance. - * - * + * + * * @param o * The instance to copy. * @throws NullPointerException @@ -228,7 +228,7 @@ public MapXNode serializeToXNode() throws SchemaException { /** * Generates a String representation of the contents of this type. * This is an extension method, produced by the 'ts' xjc plugin - * + * */ @Override public String toString() { @@ -264,7 +264,7 @@ public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Obje return false; } else if (!filterClauseXNode.equals(that.filterClauseXNode)) return false; - + return true; } @@ -275,7 +275,7 @@ public boolean equals(Object object) { /** * Creates and returns a deep copy of a given object. - * + * * @param o * The instance to copy or {@code null}. * @return @@ -413,7 +413,7 @@ private static Object copyOf(final Object o) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -458,7 +458,7 @@ private static Object copyOfArray(final Object array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -476,7 +476,7 @@ private static boolean[] copyOf(final boolean[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -494,7 +494,7 @@ private static byte[] copyOf(final byte[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -512,7 +512,7 @@ private static char[] copyOf(final char[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -530,7 +530,7 @@ private static double[] copyOf(final double[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -548,7 +548,7 @@ private static float[] copyOf(final float[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -566,7 +566,7 @@ private static int[] copyOf(final int[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -584,7 +584,7 @@ private static long[] copyOf(final long[] array) { /** * Creates and returns a deep copy of a given array. - * + * * @param array * The array to copy or {@code null}. * @return @@ -602,7 +602,7 @@ private static short[] copyOf(final short[] array) { /** * Creates and returns a deep copy of a given {@code JAXBElement} instance. - * + * * @param element * The instance to copy or {@code null}. * @return @@ -622,7 +622,7 @@ private static JAXBElement copyOf(final JAXBElement element) { /** * Creates and returns a deep copy of a given {@code Serializable}. - * + * * @param serializable * The instance to copy or {@code null}. * @return @@ -662,8 +662,8 @@ private static Serializable copyOf(final Serializable serializable) { /** * Creates and returns a deep copy of this object. - * - * + * + * * @return * A deep copy of this object. */ diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/UnaryLogicalOperatorFilterType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/UnaryLogicalOperatorFilterType.java index 0a04bfeb980..2946273827c 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/UnaryLogicalOperatorFilterType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/UnaryLogicalOperatorFilterType.java @@ -25,22 +25,20 @@ /** *

Java class for UnaryLogicalOperatorFilterType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="UnaryLogicalOperatorFilterType">
- *   <complexContent>
- *     <extension base="{http://prism.evolveum.com/xml/ns/public/query-2}LogicalOperatorFilterType">
- *       <sequence>
- *         <element ref="{http://prism.evolveum.com/xml/ns/public/query-2}filter"/>
- *       </sequence>
- *     </extension>
- *   </complexContent>
- * </complexType>
+ * <complexType name="UnaryLogicalOperatorFilterType">
+ *   <complexContent>
+ *     <extension base="{http://prism.evolveum.com/xml/ns/public/query-2}LogicalOperatorFilterType">
+ *       <sequence>
+ *         <element ref="{http://prism.evolveum.com/xml/ns/public/query-2}filter"/>
+ *       </sequence>
+ *     </extension>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "UnaryLogicalOperatorFilterType", propOrder = { @@ -58,7 +56,7 @@ public class UnaryLogicalOperatorFilterType /** * Creates a new {@code UnaryLogicalOperatorFilterType} instance. - * + * */ public UnaryLogicalOperatorFilterType() { // CC-XJC Version 2.0 Build 2011-09-16T18:27:24+0000 @@ -67,8 +65,8 @@ public UnaryLogicalOperatorFilterType() { /** * Creates a new {@code UnaryLogicalOperatorFilterType} instance by deeply copying a given {@code UnaryLogicalOperatorFilterType} instance. - * - * + * + * * @param o * The instance to copy. * @throws NullPointerException @@ -86,11 +84,11 @@ public UnaryLogicalOperatorFilterType(final UnaryLogicalOperatorFilterType o) { /** * Gets the value of the filter property. - * + * * @return * possible object is * {@link Element } - * + * */ public Element getFilter() { return filter; @@ -98,11 +96,11 @@ public Element getFilter() { /** * Sets the value of the filter property. - * + * * @param value * allowed object is * {@link Element } - * + * */ public void setFilter(Element value) { this.filter = value; @@ -111,7 +109,7 @@ public void setFilter(Element value) { /** * Generates a String representation of the contents of this type. * This is an extension method, produced by the 'ts' xjc plugin - * + * */ @Override public String toString() { @@ -163,8 +161,8 @@ public boolean equals(Object object) { /** * Creates and returns a deep copy of this object. - * - * + * + * * @return * A deep copy of this object. */ diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/UriFilterType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/UriFilterType.java index dabb565b398..39716ae77e1 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/UriFilterType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/UriFilterType.java @@ -25,20 +25,18 @@ /** *

Java class for UriFilterType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="UriFilterType">
- *   <complexContent>
- *     <extension base="{http://prism.evolveum.com/xml/ns/public/query-2}FilterType">
- *       <attribute name="uri" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
- *     </extension>
- *   </complexContent>
- * </complexType>
+ * <complexType name="UriFilterType">
+ *   <complexContent>
+ *     <extension base="{http://prism.evolveum.com/xml/ns/public/query-2}FilterType">
+ *       <attribute name="uri" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
+ *     </extension>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "UriFilterType") @@ -56,7 +54,7 @@ public class UriFilterType /** * Creates a new {@code UriFilterType} instance. - * + * */ public UriFilterType() { // CC-XJC Version 2.0 Build 2011-09-16T18:27:24+0000 @@ -65,8 +63,8 @@ public UriFilterType() { /** * Creates a new {@code UriFilterType} instance by deeply copying a given {@code UriFilterType} instance. - * - * + * + * * @param o * The instance to copy. * @throws NullPointerException @@ -84,11 +82,11 @@ public UriFilterType(final UriFilterType o) { /** * Gets the value of the uri property. - * + * * @return * possible object is * {@link String } - * + * */ public String getUri() { return uri; @@ -96,11 +94,11 @@ public String getUri() { /** * Sets the value of the uri property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setUri(String value) { this.uri = value; @@ -109,7 +107,7 @@ public void setUri(String value) { /** * Generates a String representation of the contents of this type. * This is an extension method, produced by the 'ts' xjc plugin - * + * */ @Override public String toString() { @@ -161,8 +159,8 @@ public boolean equals(Object object) { /** * Creates and returns a deep copy of this object. - * - * + * + * * @return * A deep copy of this object. */ diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/ValueType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/ValueType.java index 15b84bec6fc..aaa0b469647 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/ValueType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/ValueType.java @@ -29,22 +29,20 @@ /** *

Java class for ValueType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="ValueType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <any processContents='lax' maxOccurs="unbounded" minOccurs="0"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
+ * <complexType name="ValueType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <any processContents='lax' maxOccurs="unbounded" minOccurs="0"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ValueType", propOrder = { @@ -61,7 +59,7 @@ public class ValueType implements Serializable, Cloneable, Equals, HashCode /** * Creates a new {@code ValueType} instance. - * + * */ public ValueType() { // CC-XJC Version 2.0 Build 2011-09-16T18:27:24+0000 @@ -70,8 +68,8 @@ public ValueType() { /** * Creates a new {@code ValueType} instance by deeply copying a given {@code ValueType} instance. - * - * + * + * * @param o * The instance to copy. * @throws NullPointerException @@ -91,26 +89,26 @@ public ValueType(final ValueType o) { /** * Gets the value of the content property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the content property. - * + * *

* For example, to add a new item, do as follows: *

      *    getContent().add(newItem);
      * 
- * - * + * + * *

* Objects of the following type(s) are allowed in the list * {@link String } * {@link Element } - * - * + * + * */ public List getContent() { if (content == null) { @@ -122,7 +120,7 @@ public List getContent() { /** * Generates a String representation of the contents of this type. * This is an extension method, produced by the 'ts' xjc plugin - * + * */ @Override public String toString() { @@ -171,7 +169,7 @@ public boolean equals(Object object) { /** * Copies all values of property {@code Content} deeply. - * + * * @param source * The source to copy from. * @param target @@ -203,8 +201,8 @@ private static void copyContent(final List source, final List ta /** * Creates and returns a deep copy of this object. - * - * + * + * * @return * A deep copy of this object. */ diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ChangeTypeType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ChangeTypeType.java index 0c77aa15e7b..4fc38b05afd 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ChangeTypeType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ChangeTypeType.java @@ -15,10 +15,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.05.20 at 05:41:15 PM CEST +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.05.20 at 05:41:15 PM CEST // @@ -33,19 +33,18 @@ /** *

Java class for ChangeTypeType. - * + * *

The following schema fragment specifies the expected content contained within this class. *

*

- * <simpleType name="ChangeTypeType">
- *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
- *     <enumeration value="add"/>
- *     <enumeration value="modify"/>
- *     <enumeration value="delete"/>
- *   </restriction>
- * </simpleType>
+ * <simpleType name="ChangeTypeType">
+ *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
+ *     <enumeration value="add"/>
+ *     <enumeration value="modify"/>
+ *     <enumeration value="delete"/>
+ *   </restriction>
+ * </simpleType>
  * 
- * */ @XmlType(name = "ChangeTypeType") @XmlEnum diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/CipherDataType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/CipherDataType.java index 568555021ad..048e43d3058 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/CipherDataType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/CipherDataType.java @@ -1,8 +1,8 @@ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2014.02.04 at 01:34:24 PM CET +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.02.04 at 01:34:24 PM CET // @@ -18,31 +18,29 @@ /** - * + * * TODO - * + * * Loosely based on XML encryption standard. But we cannot use full * standard as we are not bound to XML. We need this to work also for * JSON and YAML and other languages. - * - * + * + * *

Java class for CipherDataType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="CipherDataType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="cipherValue" type="{http://www.w3.org/2001/XMLSchema}base64Binary"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
+ * <complexType name="CipherDataType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="cipherValue" type="{http://www.w3.org/2001/XMLSchema}base64Binary"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CipherDataType", propOrder = { @@ -55,7 +53,7 @@ public class CipherDataType implements Serializable, Cloneable { /** * Gets the value of the cipherValue property. - * + * * @return * possible object is * byte[] @@ -66,7 +64,7 @@ public byte[] getCipherValue() { /** * Sets the value of the cipherValue property. - * + * * @param value * allowed object is * byte[] diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/DigestMethodType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/DigestMethodType.java index 0db44b7aabb..079f980c761 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/DigestMethodType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/DigestMethodType.java @@ -28,7 +28,7 @@ /** * JAXB representation of DigestMethodType. * Manually created (not generated) - * + * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DigestMethodType", propOrder = { @@ -41,20 +41,20 @@ public class DigestMethodType implements Serializable, Cloneable { @XmlElement(required = true) @XmlSchemaType(name = "anyURI") protected String algorithm; - + @XmlElement(required = false) protected byte[] salt; - + @XmlElement(required = false) protected Integer workFactor; /** * Gets the value of the algorithm property. - * + * * @return * possible object is * {@link String } - * + * */ public String getAlgorithm() { return algorithm; @@ -62,11 +62,11 @@ public String getAlgorithm() { /** * Sets the value of the algorithm property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setAlgorithm(String value) { this.algorithm = value; diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/EncryptedDataType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/EncryptedDataType.java index 7f73ad1bd9e..bf0794fbc05 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/EncryptedDataType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/EncryptedDataType.java @@ -1,8 +1,8 @@ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2014.02.04 at 01:34:24 PM CET +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.02.04 at 01:34:24 PM CET // @@ -16,34 +16,32 @@ /** - * + * * TODO * Contains data protected by (reversible) encryption. - * + * * Loosely based on XML encryption standard. But we cannot use full * standard as we are not bound to XML. We need this to work also for * JSON and YAML and other languages. - * - * + * + * *

Java class for EncryptedDataType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="EncryptedDataType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="encryptionMethod" type="{http://prism.evolveum.com/xml/ns/public/types-3}EncryptionMethodType" minOccurs="0"/>
- *         <element name="keyInfo" type="{http://prism.evolveum.com/xml/ns/public/types-3}KeyInfoType" minOccurs="0"/>
- *         <element name="cipherData" type="{http://prism.evolveum.com/xml/ns/public/types-3}CipherDataType" minOccurs="0"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
+ * <complexType name="EncryptedDataType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="encryptionMethod" type="{http://prism.evolveum.com/xml/ns/public/types-3}EncryptionMethodType" minOccurs="0"/>
+ *         <element name="keyInfo" type="{http://prism.evolveum.com/xml/ns/public/types-3}KeyInfoType" minOccurs="0"/>
+ *         <element name="cipherData" type="{http://prism.evolveum.com/xml/ns/public/types-3}CipherDataType" minOccurs="0"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EncryptedDataType", propOrder = { @@ -59,11 +57,11 @@ public class EncryptedDataType implements Serializable, Cloneable { /** * Gets the value of the encryptionMethod property. - * + * * @return * possible object is * {@link EncryptionMethodType } - * + * */ public EncryptionMethodType getEncryptionMethod() { return encryptionMethod; @@ -71,11 +69,11 @@ public EncryptionMethodType getEncryptionMethod() { /** * Sets the value of the encryptionMethod property. - * + * * @param value * allowed object is * {@link EncryptionMethodType } - * + * */ public void setEncryptionMethod(EncryptionMethodType value) { this.encryptionMethod = value; @@ -83,11 +81,11 @@ public void setEncryptionMethod(EncryptionMethodType value) { /** * Gets the value of the keyInfo property. - * + * * @return * possible object is * {@link KeyInfoType } - * + * */ public KeyInfoType getKeyInfo() { return keyInfo; @@ -95,11 +93,11 @@ public KeyInfoType getKeyInfo() { /** * Sets the value of the keyInfo property. - * + * * @param value * allowed object is * {@link KeyInfoType } - * + * */ public void setKeyInfo(KeyInfoType value) { this.keyInfo = value; @@ -107,11 +105,11 @@ public void setKeyInfo(KeyInfoType value) { /** * Gets the value of the cipherData property. - * + * * @return * possible object is * {@link CipherDataType } - * + * */ public CipherDataType getCipherData() { return cipherData; @@ -119,16 +117,16 @@ public CipherDataType getCipherData() { /** * Sets the value of the cipherData property. - * + * * @param value * allowed object is * {@link CipherDataType } - * + * */ public void setCipherData(CipherDataType value) { this.cipherData = value; } - + @Override public int hashCode() { final int prime = 31; diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/EncryptionMethodType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/EncryptionMethodType.java index 2088becab5d..7bbaf54a9f4 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/EncryptionMethodType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/EncryptionMethodType.java @@ -1,8 +1,8 @@ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2014.02.04 at 01:34:24 PM CET +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.02.04 at 01:34:24 PM CET // @@ -18,31 +18,29 @@ /** - * + * * TODO - * + * * Loosely based on XML encryption standard. But we cannot use full * standard as we are not bound to XML. We need this to work also for * JSON and YAML and other languages. - * - * + * + * *

Java class for EncryptionMethodType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="EncryptionMethodType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="algorithm" type="{http://www.w3.org/2001/XMLSchema}anyURI"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
+ * <complexType name="EncryptionMethodType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="algorithm" type="{http://www.w3.org/2001/XMLSchema}anyURI"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EncryptionMethodType", propOrder = { @@ -56,11 +54,11 @@ public class EncryptionMethodType implements Serializable, Cloneable { /** * Gets the value of the algorithm property. - * + * * @return * possible object is * {@link String } - * + * */ public String getAlgorithm() { return algorithm; @@ -68,11 +66,11 @@ public String getAlgorithm() { /** * Sets the value of the algorithm property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setAlgorithm(String value) { this.algorithm = value; diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/EvaluationTimeType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/EvaluationTimeType.java index 0215c21368c..1c21e9be731 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/EvaluationTimeType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/EvaluationTimeType.java @@ -8,7 +8,7 @@ /** *

Java class for EvaluationTimeType. - * + * *

The following schema fragment specifies the expected content contained within this class. *

*

@@ -19,7 +19,7 @@
  *   </restriction>
  * </simpleType>
  * 
- * + * */ @XmlType(name = "EvaluationTimeType") @XmlEnum @@ -27,28 +27,28 @@ public enum EvaluationTimeType { /** - * + * *
      * <?xml version="1.0" encoding="UTF-8"?><p xmlns:a="http://prism.evolveum.com/xml/ns/public/annotation-3" xmlns:c="http://midpoint.evolveum.com/xml/ns/public/common/common-3" xmlns:cap="http://midpoint.evolveum.com/xml/ns/public/resource/capabilities-3" xmlns:icfs="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/resource-schema-3" xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" xmlns:q="http://prism.evolveum.com/xml/ns/public/query-3" xmlns:t="http://prism.evolveum.com/xml/ns/public/types-3" xmlns:tns="http://midpoint.evolveum.com/xml/ns/public/common/common-3" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      *                 			Import-time. Evaluation happens when the object is imported
      *                 			into midPoint repository.
      *                 		</p>
      * 
- * - * + * + * */ @XmlEnumValue("import") IMPORT("import"), /** - * + * *
      * <?xml version="1.0" encoding="UTF-8"?><p xmlns:a="http://prism.evolveum.com/xml/ns/public/annotation-3" xmlns:c="http://midpoint.evolveum.com/xml/ns/public/common/common-3" xmlns:cap="http://midpoint.evolveum.com/xml/ns/public/resource/capabilities-3" xmlns:icfs="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/resource-schema-3" xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" xmlns:q="http://prism.evolveum.com/xml/ns/public/query-3" xmlns:t="http://prism.evolveum.com/xml/ns/public/types-3" xmlns:tns="http://midpoint.evolveum.com/xml/ns/public/common/common-3" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      * 	                		Run-time. Evaluation happens every time when the object is used.
      *                 		</p>
      * 
- * - * + * + * */ @XmlEnumValue("run") RUN("run"); diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/Extension.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/Extension.java index 06f0b6431fb..add9628e163 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/Extension.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/Extension.java @@ -15,10 +15,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.05.20 at 05:41:15 PM CEST +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.05.20 at 05:41:15 PM CEST // @@ -38,22 +38,20 @@ /** *

Java class for extension complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="extension">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
+ * <complexType name="extension">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "extension", propOrder = { @@ -66,26 +64,26 @@ public class Extension implements Serializable { /** * Gets the value of the any property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the any property. - * + * *

* For example, to add a new item, do as follows: *

      *    getAny().add(newItem);
      * 
- * - * + * + * *

* Objects of the following type(s) are allowed in the list * {@link Element } * {@link Object } - * - * + * + * */ public List getAny() { if (any == null) { diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/HashedDataType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/HashedDataType.java index 9eac9a8c971..f0f41d08397 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/HashedDataType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/HashedDataType.java @@ -27,7 +27,7 @@ /** * JAXB representation of HashedDataType. * Manually created (not generated) - * + * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "HashedDataType", propOrder = { @@ -38,7 +38,7 @@ public class HashedDataType implements Serializable, Cloneable { @XmlElement(required = true) protected DigestMethodType digestMethod; - + @XmlElement(required = true) protected byte[] digestValue; diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ItemDeltaType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ItemDeltaType.java index 57dd0f61573..de285743ec2 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ItemDeltaType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ItemDeltaType.java @@ -15,10 +15,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.05.20 at 05:41:15 PM CEST +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.05.20 at 05:41:15 PM CEST // @@ -51,43 +51,41 @@ /** - * + * * Describe a change to a single attribute. * In this case the path expression used in the "property" * attribute must select exactly one property. - * + * * TODO: this should be renamed to ItemDeltaType - * - * + * + * *

Java class for ItemDeltaType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="ItemDeltaType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="modificationType" type="{http://prism.evolveum.com/xml/ns/public/types-3}ModificationTypeType"/>
- *         <element name="path" type="{http://prism.evolveum.com/xml/ns/public/types-3}XPathType" minOccurs="0"/>
- *         <element name="value">
- *           <complexType>
- *             <complexContent>
- *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *                 <sequence>
- *                   <any processContents='lax' maxOccurs="unbounded" minOccurs="0"/>
- *                 </sequence>
- *               </restriction>
- *             </complexContent>
- *           </complexType>
- *         </element>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
+ * <complexType name="ItemDeltaType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="modificationType" type="{http://prism.evolveum.com/xml/ns/public/types-3}ModificationTypeType"/>
+ *         <element name="path" type="{http://prism.evolveum.com/xml/ns/public/types-3}XPathType" minOccurs="0"/>
+ *         <element name="value">
+ *           <complexType>
+ *             <complexContent>
+ *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                 <sequence>
+ *                   <any processContents='lax' maxOccurs="unbounded" minOccurs="0"/>
+ *                 </sequence>
+ *               </restriction>
+ *             </complexContent>
+ *           </complexType>
+ *         </element>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ItemDeltaType", propOrder = { @@ -101,7 +99,7 @@ public class ItemDeltaType implements Serializable, Cloneable { public static final QName COMPLEX_TYPE = new QName("http://prism.evolveum.com/xml/ns/public/types-3", "ItemDeltaType"); public static final QName F_PATH = new QName("http://prism.evolveum.com/xml/ns/public/types-3", "path"); public static final QName F_VALUE = new QName("http://prism.evolveum.com/xml/ns/public/types-3", "value"); - + @XmlElement(required = true) protected ModificationTypeType modificationType; // @XmlAnyElement @@ -110,18 +108,18 @@ public class ItemDeltaType implements Serializable, Cloneable { @XmlElement(required = true) @Raw protected List value; // Object is here to show as xsd:anyType in WSDL - + @XmlElement(required = true) @Raw protected List estimatedOldValue; // Object is here to show as xsd:anyType in WSDL /** * Gets the value of the modificationType property. - * + * * @return * possible object is * {@link ModificationTypeType } - * + * */ public ModificationTypeType getModificationType() { return modificationType; @@ -129,11 +127,11 @@ public ModificationTypeType getModificationType() { /** * Sets the value of the modificationType property. - * + * * @param value * allowed object is * {@link ModificationTypeType } - * + * */ public void setModificationType(ModificationTypeType value) { this.modificationType = value; @@ -141,11 +139,11 @@ public void setModificationType(ModificationTypeType value) { /** * Gets the value of the path property. - * + * * @return * possible object is * {@link Element } - * + * */ public ItemPathType getPath() { return path; @@ -153,11 +151,11 @@ public ItemPathType getPath() { /** * Sets the value of the path property. - * + * * @param value * allowed object is * {@link Element } - * + * */ public void setPath(ItemPathType value) { this.path = value; @@ -165,11 +163,11 @@ public void setPath(ItemPathType value) { /** * Gets the value of the value property. - * + * * @return * possible object is * {@link ItemDeltaType.Value } - * + * */ @NotNull public List getValue() { @@ -178,7 +176,7 @@ public List getValue() { } return (List) (List) value; // brutal hack } - + // public List getAnyValues(){ // List vals = new ArrayList(); // for (Object raw : value){ @@ -187,14 +185,14 @@ public List getValue() { // return vals; // } - /** - * Sets the value of the value property. - * - * @param value - * allowed object is - * {@link ItemDeltaType.Value } - * - */ +// /** +// * Sets the value of the value property. +// * +// * @param value +// * allowed object is +// * {@link ItemDeltaType.Value } +// * +// */ // public void setValue(List value) { // this.value = value; // } @@ -210,22 +208,20 @@ public List getEstimatedOldValue() { /** *

Java class for anonymous complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

-     * <complexType>
-     *   <complexContent>
-     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
-     *       <sequence>
-     *         <any processContents='lax' maxOccurs="unbounded" minOccurs="0"/>
-     *       </sequence>
-     *     </restriction>
-     *   </complexContent>
-     * </complexType>
+     * <complexType>
+     *   <complexContent>
+     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+     *       <sequence>
+     *         <any processContents='lax' maxOccurs="unbounded" minOccurs="0"/>
+     *       </sequence>
+     *     </restriction>
+     *   </complexContent>
+     * </complexType>
      * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { @@ -238,26 +234,26 @@ public static class Value implements Serializable, Cloneable { /** * Gets the value of the any property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the any property. - * + * *

* For example, to add a new item, do as follows: *

          *    getAny().add(newItem);
          * 
- * - * + * + * *

* Objects of the following type(s) are allowed in the list * {@link Element } * {@link Object } - * - * + * + * */ public List getAny() { if (any == null) { @@ -273,7 +269,7 @@ public Value clone() { return value; } - + @Override public int hashCode() { final int prime = 31; @@ -303,8 +299,8 @@ public boolean equals(Object obj) { public String toString() { return "Value(any=" + any + ")"; } - - + + } @Override @@ -558,7 +554,7 @@ private static JAXBElement copyOfStringElement(final JAXBElement } return null; } - + @Override public int hashCode() { final int prime = 31; @@ -604,5 +600,5 @@ public String toString() { return "ItemDeltaType(modificationType=" + modificationType + ", path=" + path + ", value=" + value + ", estimatedOldValue=" + estimatedOldValue + ")"; } - + } diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ItemPathType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ItemPathType.java index f88d9499d50..21bee537ea6 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ItemPathType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ItemPathType.java @@ -32,28 +32,26 @@ import java.io.Serializable; /** - * + * * Defines a type for XPath-like item pointer. It points to a specific part * of the prism object. - * - * + * + * *

Java class for ItemPathType complex type. * *

The following schema fragment specifies the expected content contained within this class. * *

- * <complexType name="ItemPathType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <any/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
+ * <complexType name="ItemPathType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <any/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ // TODO it is questionable whether to treat ItemPathType as XmlType any more (similar to RawType) @@ -61,16 +59,16 @@ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ItemPathType") public class ItemPathType implements Serializable, Equals, Cloneable { - + public static final QName COMPLEX_TYPE = new QName("http://prism.evolveum.com/xml/ns/public/types-3", "ItemPathType"); - + @XmlTransient private ItemPath itemPath; @Deprecated // use one of the content-filling constructors instead public ItemPathType() { } - + public ItemPathType(ItemPath itemPath) { this.itemPath = itemPath; } @@ -87,7 +85,7 @@ public ItemPath getItemPath() { } return itemPath; } - + public void setItemPath(ItemPath itemPath){ this.itemPath = itemPath; } @@ -132,19 +130,19 @@ public boolean equivalent(Object other) { @Override public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object that, EqualsStrategy equalsStrategy) { - + if (!(that instanceof ItemPathType)){ return false; } - + ItemPathType other = (ItemPathType) that; - + ItemPath thisPath = getItemPath(); ItemPath otherPath = other.getItemPath(); return thisPath.equals(otherPath); } - + @Override public int hashCode() { final int prime = 31; diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/KeyInfoType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/KeyInfoType.java index f89d5ccca37..a051aae84a3 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/KeyInfoType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/KeyInfoType.java @@ -1,8 +1,8 @@ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2014.02.04 at 01:34:24 PM CET +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.02.04 at 01:34:24 PM CET // @@ -16,31 +16,29 @@ /** - * + * * TODO - * + * * Loosely based on XML digital signature standard. But we cannot use full * standard as we are not bound to XML. We need this to work also for * JSON and YAML and other languages. - * - * + * + * *

Java class for KeyInfoType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="KeyInfoType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="keyName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
+ * <complexType name="KeyInfoType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="keyName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "KeyInfoType", propOrder = { @@ -52,11 +50,11 @@ public class KeyInfoType implements Serializable, Cloneable { /** * Gets the value of the keyName property. - * + * * @return * possible object is * {@link String } - * + * */ public String getKeyName() { return keyName; @@ -64,11 +62,11 @@ public String getKeyName() { /** * Sets the value of the keyName property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setKeyName(String value) { this.keyName = value; diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ModificationTypeType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ModificationTypeType.java index 227c1cf2f34..e8dacaa9f7a 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ModificationTypeType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ModificationTypeType.java @@ -15,10 +15,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.05.20 at 05:41:15 PM CEST +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.05.20 at 05:41:15 PM CEST // @@ -33,19 +33,18 @@ /** *

Java class for ModificationTypeType. - * + * *

The following schema fragment specifies the expected content contained within this class. *

*

- * <simpleType name="ModificationTypeType">
- *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
- *     <enumeration value="add"/>
- *     <enumeration value="replace"/>
- *     <enumeration value="delete"/>
- *   </restriction>
- * </simpleType>
+ * <simpleType name="ModificationTypeType">
+ *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
+ *     <enumeration value="add"/>
+ *     <enumeration value="replace"/>
+ *     <enumeration value="delete"/>
+ *   </restriction>
+ * </simpleType>
  * 
- * */ @XmlType(name = "ModificationTypeType") @XmlEnum diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ObjectDeltaType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ObjectDeltaType.java index 3e75f7d55a2..2b2864313da 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ObjectDeltaType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ObjectDeltaType.java @@ -15,10 +15,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2013.01.25 at 04:55:44 PM CET +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2013.01.25 at 04:55:44 PM CET // @@ -45,41 +45,39 @@ /** - * + * * Describes a change of a specific object. * - * + * *

Java class for ObjectDeltaType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="ObjectDeltaType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="changeType" type="{http://prism.evolveum.com/xml/ns/public/types-3}ChangeTypeType"/>
- *         <element name="objectType" type="{http://www.w3.org/2001/XMLSchema}QName"/>
- *         <element name="objectToAdd" minOccurs="0">
- *           <complexType>
- *             <complexContent>
- *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *                 <sequence>
- *                   <any processContents='lax'/>
- *                 </sequence>
- *               </restriction>
- *             </complexContent>
- *           </complexType>
- *         </element>
- *         <element name="oid" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="modification" type="{http://prism.evolveum.com/xml/ns/public/types-3}ItemDeltaType" maxOccurs="unbounded" minOccurs="0"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
+ * <complexType name="ObjectDeltaType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="changeType" type="{http://prism.evolveum.com/xml/ns/public/types-3}ChangeTypeType"/>
+ *         <element name="objectType" type="{http://www.w3.org/2001/XMLSchema}QName"/>
+ *         <element name="objectToAdd" minOccurs="0">
+ *           <complexType>
+ *             <complexContent>
+ *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                 <sequence>
+ *                   <any processContents='lax'/>
+ *                 </sequence>
+ *               </restriction>
+ *             </complexContent>
+ *           </complexType>
+ *         </element>
+ *         <element name="oid" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="modification" type="{http://prism.evolveum.com/xml/ns/public/types-3}ItemDeltaType" maxOccurs="unbounded" minOccurs="0"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ObjectDeltaType", propOrder = { @@ -105,18 +103,18 @@ public class ObjectDeltaType implements Serializable { public final static QName F_OBJECT_TYPE = new QName(PrismConstants.NS_TYPES, "objectType"); public final static QName F_OBJECT_TO_ADD = new QName(PrismConstants.NS_TYPES, "objectToAdd"); public final static QName F_ITEM_DETLA = new QName(PrismConstants.NS_TYPES, "itemDelta"); - - - + + + /** * Gets the value of the changeType property. - * + * * @return * possible object is * {@link ChangeTypeType } - * + * */ public ChangeTypeType getChangeType() { return changeType; @@ -124,11 +122,11 @@ public ChangeTypeType getChangeType() { /** * Sets the value of the changeType property. - * + * * @param value * allowed object is * {@link ChangeTypeType } - * + * */ public void setChangeType(ChangeTypeType value) { this.changeType = value; @@ -136,11 +134,11 @@ public void setChangeType(ChangeTypeType value) { /** * Gets the value of the objectType property. - * + * * @return * possible object is * {@link QName } - * + * */ public QName getObjectType() { return objectType; @@ -148,11 +146,11 @@ public QName getObjectType() { /** * Sets the value of the objectType property. - * + * * @param value * allowed object is * {@link QName } - * + * */ public void setObjectType(QName value) { this.objectType = value; @@ -160,11 +158,11 @@ public void setObjectType(QName value) { /** * Gets the value of the objectToAdd property. - * + * * @return * possible object is * {@link ObjectDeltaType.ObjectToAdd } - * + * */ public ObjectType getObjectToAdd() { return objectToAdd; @@ -172,11 +170,11 @@ public ObjectType getObjectToAdd() { /** * Sets the value of the objectToAdd property. - * + * * @param value * allowed object is * {@link ObjectDeltaType.ObjectToAdd } - * + * */ public void setObjectToAdd(T value) { this.objectToAdd = value; @@ -184,11 +182,11 @@ public void setObjectToAdd(T value) { /** * Gets the value of the oid property. - * + * * @return * possible object is * {@link String } - * + * */ public String getOid() { return oid; @@ -196,11 +194,11 @@ public String getOid() { /** * Sets the value of the oid property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setOid(String value) { this.oid = value; @@ -208,25 +206,25 @@ public void setOid(String value) { /** * Gets the value of the modification property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the modification property. - * + * *

* For example, to add a new item, do as follows: *

      *    getModification().add(newItem);
      * 
- * - * + * + * *

* Objects of the following type(s) are allowed in the list * {@link ItemDeltaType } - * - * + * + * */ public List getItemDelta() { return this.itemDelta; @@ -286,22 +284,20 @@ public String toString() { /** *

Java class for anonymous complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

-     * <complexType>
-     *   <complexContent>
-     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
-     *       <sequence>
-     *         <any processContents='lax'/>
-     *       </sequence>
-     *     </restriction>
-     *   </complexContent>
-     * </complexType>
+     * <complexType>
+     *   <complexContent>
+     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+     *       <sequence>
+     *         <any processContents='lax'/>
+     *       </sequence>
+     *     </restriction>
+     *   </complexContent>
+     * </complexType>
      * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { @@ -314,12 +310,12 @@ public static class ObjectToAdd implements Serializable { /** * Gets the value of the any property. - * + * * @return * possible object is * {@link Object } * {@link Element } - * + * */ public JAXBElement getAny() { return any; @@ -327,12 +323,12 @@ public JAXBElement getAny() { /** * Sets the value of the any property. - * + * * @param value * allowed object is * {@link Object } * {@link Element } - * + * */ public void setAny(JAXBElement value) { this.any = value; diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ObjectFactory.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ObjectFactory.java index dff1b211c30..20de5b2a61d 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ObjectFactory.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ObjectFactory.java @@ -15,10 +15,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.05.20 at 05:41:15 PM CEST +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.05.20 at 05:41:15 PM CEST // @@ -35,18 +35,18 @@ /** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the com.evolveum.prism.xml.ns._public.types_3 package. - *

An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are + * This object contains factory methods for each + * Java content interface and Java element interface + * generated in the com.evolveum.prism.xml.ns._public.types_3 package. + *

An ObjectFactory allows you to programatically + * construct new instances of the Java representation + * for XML content. The Java representation of XML + * content can consist of schema derived interfaces + * and classes representing the binding of schema + * type definitions, element declarations and model + * groups. Factory methods for each of these are * provided in this class. - * + * */ @XmlRegistry public class ObjectFactory implements Serializable { @@ -61,14 +61,14 @@ public class ObjectFactory implements Serializable { /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.evolveum.prism.xml.ns._public.types_3 - * + * */ public ObjectFactory() { } /** * Create an instance of {@link ObjectReferenceType } - * + * */ public ObjectReferenceType createObjectReferenceType() { return new ObjectReferenceType(); @@ -76,7 +76,7 @@ public ObjectReferenceType createObjectReferenceType() { /** * Create an instance of {@link ItemDeltaType } - * + * */ public ItemDeltaType createItemDeltaType() { return new ItemDeltaType(); @@ -84,7 +84,7 @@ public ItemDeltaType createItemDeltaType() { /** * Create an instance of {@link ObjectDeltaType } - * + * */ public ObjectDeltaType createObjectDeltaType() { return new ObjectDeltaType(); @@ -92,7 +92,7 @@ public ObjectDeltaType createObjectDeltaType() { /** * Create an instance of {@link KeyInfoType } - * + * */ public KeyInfoType createKeyInfoType() { return new KeyInfoType(); @@ -100,15 +100,15 @@ public KeyInfoType createKeyInfoType() { /** * Create an instance of {@link ProtectedByteArrayType } - * + * */ public ProtectedByteArrayType createProtectedByteArrayType() { return new ProtectedByteArrayType(); } - + /** * Create an instance of {@link EncryptedDataType } - * + * */ public EncryptedDataType createEncryptedDataType() { return new EncryptedDataType(); @@ -116,7 +116,7 @@ public EncryptedDataType createEncryptedDataType() { /** * Create an instance of {@link CipherDataType } - * + * */ public CipherDataType createCipherDataType() { return new CipherDataType(); @@ -124,19 +124,19 @@ public CipherDataType createCipherDataType() { /** * Create an instance of {@link ProtectedStringType } - * + * */ public ProtectedStringType createProtectedStringType() { return new ProtectedStringType(); } - + // public ObjectType createObjectType() { // return new ObjectType(); // } /** * Create an instance of {@link EncryptionMethodType } - * + * */ public EncryptionMethodType createEncryptionMethodType() { return new EncryptionMethodType(); @@ -144,16 +144,16 @@ public EncryptionMethodType createEncryptionMethodType() { /** * Create an instance of {@link ItemPathType } - * + * */ public ItemPathType createItemPathType() { return new ItemPathType(); } - + /** * Create an instance of {@link Extension } - * + * */ public Extension createExtension() { return new Extension(); @@ -161,7 +161,7 @@ public Extension createExtension() { /** * Create an instance of {@link PolyStringType } - * + * */ public PolyStringType createPolyStringType() { return new PolyStringType(); @@ -174,11 +174,11 @@ public PolyStringType createPolyStringType() { // public XPathType createXPathType() { // return new XPathType(); // } - + /** * Create an instance of {@link ObjectReferenceType.Filter } - * + * */ public ObjectReferenceType.Filter createObjectReferenceTypeFilter() { return new ObjectReferenceType.Filter(); @@ -186,7 +186,7 @@ public ObjectReferenceType.Filter createObjectReferenceTypeFilter() { /** * Create an instance of {@link ItemDeltaType.Value } - * + * */ public ItemDeltaType.Value createItemDeltaTypeValue() { return new ItemDeltaType.Value(); @@ -194,25 +194,25 @@ public ItemDeltaType.Value createItemDeltaTypeValue() { /** * Create an instance of {@link ObjectDeltaType.ObjectToAdd } - * + * */ public ObjectDeltaType.ObjectToAdd createObjectDeltaTypeObjectToAdd() { return new ObjectDeltaType.ObjectToAdd(); } - + /** * Create an instance of {@link JAXBElement }{@code <}{@link ObjectDeltaType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/types-3", name = "objectDelta") public JAXBElement createObjectDelta(ObjectDeltaType value) { return new JAXBElement(_ObjectDelta_QNAME, ObjectDeltaType.class, null, value); } - + /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/types-3", name = "norm", scope = PolyStringType.class) public JAXBElement createPolyStringTypeNorm(String value) { @@ -221,7 +221,7 @@ public JAXBElement createPolyStringTypeNorm(String value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/types-3", name = "orig", scope = PolyStringType.class) public JAXBElement createPolyStringTypeOrig(String value) { @@ -230,40 +230,40 @@ public JAXBElement createPolyStringTypeOrig(String value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link EncryptedDataType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/types-3", name = "encryptedData", scope = ProtectedDataType.class) public JAXBElement createProtectedDataTypeEncryptedData(EncryptedDataType value) { return new JAXBElement(_ProtectedDataTypeEncryptedData_QNAME, EncryptedDataType.class, ProtectedDataType.class, value); } - + @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/types-3", name = "encryptedData", scope = ProtectedStringType.class) public JAXBElement createProtectedStringTypeEncryptedData(EncryptedDataType value) { return new JAXBElement(_ProtectedDataTypeEncryptedData_QNAME, EncryptedDataType.class, ProtectedStringType.class, value); } - + /** * Create an instance of {@link JAXBElement }{@code <}{@link HashedDataType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/types-3", name = "hashedData", scope = ProtectedDataType.class) public JAXBElement createProtectedDataTypeHashedData(HashedDataType value) { return new JAXBElement(_ProtectedDataTypeHashedData_QNAME, HashedDataType.class, ProtectedDataType.class, value); } - + @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/types-3", name = "hashedData", scope = ProtectedStringType.class) public JAXBElement createProtectedStringTypeHashedData(HashedDataType value) { return new JAXBElement(_ProtectedDataTypeHashedData_QNAME, HashedDataType.class, ProtectedStringType.class, value); } - + @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/types-3", name = "path", scope = ItemPathType.class) public JAXBElement createItemPathType(ItemPath value) { return new JAXBElement(_ItemPathType_QNAME, ItemPath.class, ItemPathType.class, value); } - + /** * Create an instance of {@link JAXBElement }{@code <}{@link ObjectType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://prism.evolveum.com/xml/ns/public/types-3a", name = "object") public JAXBElement createObject(ObjectType value) { @@ -272,7 +272,7 @@ public JAXBElement createObject(ObjectType value) { /** * Create an instance of {@link SchemaDefinitionType } - * + * */ public SchemaDefinitionType createSchemaDefinitionType() { return new SchemaDefinitionType(); diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ObjectReferenceType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ObjectReferenceType.java index 6f5a51631d2..0e3338d4ebf 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ObjectReferenceType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ObjectReferenceType.java @@ -15,10 +15,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.05.20 at 05:41:15 PM CEST +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.05.20 at 05:41:15 PM CEST // @@ -62,11 +62,11 @@ public class ObjectReferenceType implements Serializable { /** * Gets the value of the description property. - * + * * @return * possible object is * {@link String } - * + * */ public String getDescription() { return description; @@ -74,11 +74,11 @@ public String getDescription() { /** * Sets the value of the description property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setDescription(String value) { this.description = value; @@ -86,11 +86,11 @@ public void setDescription(String value) { /** * Gets the value of the filter property. - * + * * @return * possible object is * {@link ObjectReferenceType.Filter } - * + * */ public ObjectReferenceType.Filter getFilter() { return filter; @@ -98,11 +98,11 @@ public ObjectReferenceType.Filter getFilter() { /** * Sets the value of the filter property. - * + * * @param value * allowed object is * {@link ObjectReferenceType.Filter } - * + * */ public void setFilter(ObjectReferenceType.Filter value) { this.filter = value; @@ -110,11 +110,11 @@ public void setFilter(ObjectReferenceType.Filter value) { /** * Gets the value of the oid property. - * + * * @return * possible object is * {@link String } - * + * */ public String getOid() { return oid; @@ -122,11 +122,11 @@ public String getOid() { /** * Sets the value of the oid property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setOid(String value) { this.oid = value; @@ -134,11 +134,11 @@ public void setOid(String value) { /** * Gets the value of the type property. - * + * * @return * possible object is * {@link QName } - * + * */ public QName getType() { return type; @@ -146,11 +146,11 @@ public QName getType() { /** * Sets the value of the type property. - * + * * @param value * allowed object is * {@link QName } - * + * */ public void setType(QName value) { this.type = value; @@ -159,22 +159,20 @@ public void setType(QName value) { /** *

Java class for anonymous complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

-     * <complexType>
-     *   <complexContent>
-     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
-     *       <sequence>
-     *         <any processContents='lax' maxOccurs="unbounded" minOccurs="0"/>
-     *       </sequence>
-     *     </restriction>
-     *   </complexContent>
-     * </complexType>
+     * <complexType>
+     *   <complexContent>
+     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+     *       <sequence>
+     *         <any processContents='lax' maxOccurs="unbounded" minOccurs="0"/>
+     *       </sequence>
+     *     </restriction>
+     *   </complexContent>
+     * </complexType>
      * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { @@ -187,26 +185,26 @@ public static class Filter { /** * Gets the value of the any property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the any property. - * + * *

* For example, to add a new item, do as follows: *

          *    getAny().add(newItem);
          * 
- * - * + * + * *

* Objects of the following type(s) are allowed in the list * {@link Element } * {@link Object } - * - * + * + * */ public List getAny() { if (any == null) { diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ObjectType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ObjectType.java index e9fb87ecb91..5402cdc25e9 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ObjectType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ObjectType.java @@ -15,10 +15,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.05.20 at 05:41:15 PM CEST +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.05.20 at 05:41:15 PM CEST // diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/PolyStringType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/PolyStringType.java index d44b8d5a28a..26106c9baa9 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/PolyStringType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/PolyStringType.java @@ -15,10 +15,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.05.20 at 05:41:15 PM CEST +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.05.20 at 05:41:15 PM CEST // @@ -54,35 +54,33 @@ /** - * + * * Polymorphic string. String that may have more than one representation at * the same time. The primary representation is the original version that is * composed of the full Unicode character set. The other versions may be * normalized to trim it, normalize character case, normalize spaces, * remove national characters or even transliterate the string. - * - * WARNING: THIS IS NOT A GENERATED CODE - * Although it was originally generated, it has local modifications. - * + * + * WARNING: THIS IS NOT GENERATED CODE + * Although it was originally generated, it has local modifications. + * *

Java class for PolyStringType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="PolyStringType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="orig" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="norm" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- *         <any namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
+ * <complexType name="PolyStringType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="orig" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="norm" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ *         <any namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PolyStringType", propOrder = { @@ -91,25 +89,25 @@ "any" }) public class PolyStringType implements DebugDumpable, Serializable, Cloneable { - - public static final QName COMPLEX_TYPE = new QName("http://prism.evolveum.com/xml/ns/public/types-3", "PolyStringType"); + + public static final QName COMPLEX_TYPE = new QName("http://prism.evolveum.com/xml/ns/public/types-3", "PolyStringType"); @XmlElement(required = true) protected String orig; protected String norm; @XmlAnyElement(lax = true) protected List any; - + public PolyStringType() { this.orig = null; this.norm = null; } - + public PolyStringType(String orig) { this.orig = orig; this.norm = null; } - + public PolyStringType(PolyString polyString) { this.orig = polyString.getOrig(); this.norm = polyString.getNorm(); @@ -117,11 +115,11 @@ public PolyStringType(PolyString polyString) { /** * Gets the value of the orig property. - * + * * @return * possible object is * {@link String } - * + * */ public String getOrig() { return orig; @@ -129,11 +127,11 @@ public String getOrig() { /** * Sets the value of the orig property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setOrig(String value) { this.orig = value; @@ -141,11 +139,11 @@ public void setOrig(String value) { /** * Gets the value of the norm property. - * + * * @return * possible object is * {@link String } - * + * */ public String getNorm() { return norm; @@ -153,11 +151,11 @@ public String getNorm() { /** * Sets the value of the norm property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setNorm(String value) { this.norm = value; @@ -165,25 +163,25 @@ public void setNorm(String value) { /** * Gets the value of the any property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the any property. - * + * *

* For example, to add a new item, do as follows: *

      *    getAny().add(newItem);
      * 
- * - * + * + * *

* Objects of the following type(s) are allowed in the list * {@link Object } - * - * + * + * */ public List getAny() { if (any == null) { @@ -191,7 +189,7 @@ public List getAny() { } return this.any; } - + /** * Plus method for ease of use of PolyStrings in groovy (mapped from + operator). */ @@ -201,14 +199,14 @@ public PolyStringType plus(String operand) { } return new PolyStringType(getOrig() + operand); } - + public PolyStringType plus(PolyStringType operand) { if (operand == null) { return this; } return new PolyStringType(getOrig() + operand.getOrig()); } - + public PolyString toPolyString() { return new PolyString(orig, norm); } @@ -217,7 +215,7 @@ public PolyString toPolyString() { * toString is tweaked to provide convenience and compatibility with normal strings. * If PolyStringType is used in expressions that target the entire PolyString, the result * will be the "orig" value of PolyString. - * + * * WARNING: This method was NOT generated. If the code is re-generated then it must be * manually re-introduced to the code. */ diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ProtectedByteArrayType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ProtectedByteArrayType.java index b7bc02e0060..e68a1a002c6 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ProtectedByteArrayType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ProtectedByteArrayType.java @@ -1,8 +1,8 @@ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2014.02.04 at 01:34:24 PM CET +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.02.04 at 01:34:24 PM CET // @@ -16,27 +16,25 @@ /** - * + * * Specific subtype for protected binary byte array data. - * - * + * + * *

Java class for ProtectedByteArrayType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="ProtectedByteArrayType">
- *   <complexContent>
- *     <extension base="{http://prism.evolveum.com/xml/ns/public/types-3}ProtectedDataType">
- *       <sequence>
- *         <element name="clearValue" type="{http://www.w3.org/2001/XMLSchema}base64Binary" minOccurs="0"/>
- *       </sequence>
- *     </extension>
- *   </complexContent>
- * </complexType>
+ * <complexType name="ProtectedByteArrayType">
+ *   <complexContent>
+ *     <extension base="{http://prism.evolveum.com/xml/ns/public/types-3}ProtectedDataType">
+ *       <sequence>
+ *         <element name="clearValue" type="{http://www.w3.org/2001/XMLSchema}base64Binary" minOccurs="0"/>
+ *       </sequence>
+ *     </extension>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProtectedByteArrayType") diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ProtectedDataType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ProtectedDataType.java index 6f2375d7514..fc145ad119f 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ProtectedDataType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ProtectedDataType.java @@ -45,7 +45,7 @@ /** * This class was originally generated. But it was heavily modified by hand. - * + * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProtectedDataType", propOrder = { @@ -56,12 +56,12 @@ ProtectedStringType.class }) public abstract class ProtectedDataType implements ProtectedData, Serializable { - + public static final QName COMPLEX_TYPE = new QName("http://prism.evolveum.com/xml/ns/public/types-3", "ProtectedDataType"); public final static QName F_ENCRYPTED_DATA = new QName("http://prism.evolveum.com/xml/ns/public/types-3", "encryptedData"); public final static QName F_HASHED_DATA = new QName("http://prism.evolveum.com/xml/ns/public/types-3", "hashedData"); public final static QName F_CLEAR_VALUE = new QName("http://prism.evolveum.com/xml/ns/public/types-3", "clearValue"); - + public static final String NS_XML_ENC = "http://www.w3.org/2001/04/xmlenc#"; public static final String NS_XML_DSIG = "http://www.w3.org/2000/09/xmldsig#"; public static final QName F_XML_ENC_ENCRYPTED_DATA = new QName(NS_XML_ENC, "EncryptedData"); @@ -72,14 +72,14 @@ public abstract class ProtectedDataType implements ProtectedData, Serializ public static final QName F_XML_ENC_CIPHER_VALUE = new QName(NS_XML_ENC, "CipherValue"); public static final QName F_XML_DSIG_KEY_INFO = new QName(NS_XML_DSIG, "KeyInfo"); public static final QName F_XML_DSIG_KEY_NAME = new QName(NS_XML_DSIG, "KeyName"); - - + + @XmlTransient private EncryptedDataType encryptedDataType; - + @XmlTransient private HashedDataType hashedDataType; - + @XmlTransient private T clearValue; @@ -89,36 +89,36 @@ public abstract class ProtectedDataType implements ProtectedData, Serializ protected List content; /** - * + * * TODO * May be either encrypted or hashed or provided in the clear (e.g. for debugging). - * + * * This type is marked as "mixed" because it may have alternative representation where * just the plaintext value is presented as the only value. - * + * * This is considered to be primitive built-in type for prism objects. * Gets the value of the content property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the content property. - * + * *

* For example, to add a new item, do as follows: *

      *    getContent().add(newItem);
      * 
- * - * + * + * *

* Objects of the following type(s) are allowed in the list * {@link Object } * {@link String } * {@link JAXBElement }{@code <}{@link EncryptedDataType }{@code >} - * - * + * + * */ public List getContent() { if (content == null) { @@ -136,12 +136,12 @@ public EncryptedDataType getEncryptedDataType() { public void setEncryptedData(EncryptedDataType encryptedDataType) { this.encryptedDataType = encryptedDataType; } - + @Override public boolean isEncrypted() { return encryptedDataType != null; } - + @Override public HashedDataType getHashedDataType() { return hashedDataType; @@ -151,17 +151,17 @@ public HashedDataType getHashedDataType() { public void setHashedData(HashedDataType hashedDataType) { this.hashedDataType = hashedDataType; } - + @Override public boolean isHashed() { return hashedDataType != null; } - + @Override public T getClearValue() { return clearValue; } - + @Override public void setClearValue(T clearValue) { this.clearValue = clearValue; @@ -171,26 +171,26 @@ public void setClearValue(T clearValue) { public boolean canGetCleartext() { return clearValue != null || encryptedDataType != null; } - + @Override public void destroyCleartext() { // Not perfect. But OK for now. clearValue = null; } - + private JAXBElement toJaxbElement(EncryptedDataType encryptedDataType) { return new JAXBElement(F_ENCRYPTED_DATA, EncryptedDataType.class, encryptedDataType); } - + private JAXBElement toJaxbElement(HashedDataType hashedDataType) { return new JAXBElement(F_ENCRYPTED_DATA, HashedDataType.class, hashedDataType); } - + private void clearContent() { encryptedDataType = null; hashedDataType = null; } - + private boolean addContent(Object newObject) { if (newObject instanceof String){ String s = (String) newObject; @@ -226,7 +226,7 @@ private boolean addContent(Object newObject) { throw new IllegalArgumentException("Attempt to add unknown object "+newObject+" ("+newObject.getClass()+")"); } } - + private EncryptedDataType convertXmlEncToEncryptedDate(Element eEncryptedData) { EncryptedDataType encryptedDataType = new EncryptedDataType(); Element eEncryptionMethod = DOMUtil.getChildElement(eEncryptedData, F_XML_ENC_ENCRYPTION_METHOD); @@ -263,7 +263,7 @@ private EncryptedDataType convertXmlEncToEncryptedDate(Element eEncryptedData) { } return encryptedDataType; } - + public boolean isEmpty() { return encryptedDataType == null && hashedDataType == null && clearValue == null; } @@ -338,7 +338,7 @@ protected void cloneTo(ProtectedDataType cloned) { cloned.clearValue = CloneUtil.clone(clearValue); cloned.encryptedDataType = CloneUtil.clone(encryptedDataType); cloned.hashedDataType = CloneUtil.clone(hashedDataType); - + // content is virtual, there is no point in copying it } @@ -519,6 +519,6 @@ public ListIterator listIterator(int index) { public List subList(int fromIndex, int toIndex) { throw new UnsupportedOperationException("we are too lazy for this"); } - + } } diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ProtectedStringType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ProtectedStringType.java index 14020391fb8..09faf34bab5 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ProtectedStringType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/ProtectedStringType.java @@ -33,13 +33,13 @@ public class ProtectedStringType extends ProtectedDataType implements Cloneable { public static final QName COMPLEX_TYPE = new QName("http://prism.evolveum.com/xml/ns/public/types-3", "ProtectedStringType"); - + private static final String CHARSET = "UTF-8"; - + public ProtectedStringType() { content = new ContentList(); } - + @Override public byte[] getClearBytes() { String clearValue = getClearValue(); @@ -66,12 +66,12 @@ public boolean canSupportType(Class type) { return String.class.isAssignableFrom(type); } - + @Override public boolean equals(Object obj) { return super.equals(obj); } - + @Override public int hashCode() { return super.hashCode(); diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/RawType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/RawType.java index fbe6b09003f..3d412cf282b 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/RawType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/RawType.java @@ -116,7 +116,7 @@ public IV getParsedValue(@Null return null; } } - + public V getParsedRealValue(ID itemDefinition, ItemPath itemPath) throws SchemaException { if (parsed == null && xnode != null) { if (itemDefinition == null) { @@ -125,7 +125,7 @@ public V getParsedRealValue(ID itemDefinition, Ite QName itemName = ItemPath.getName(itemPath.lastNamed()); getParsedValue(itemDefinition, itemName); } - } + } if (parsed != null) { return parsed.getRealValue(); } @@ -149,7 +149,7 @@ public T getParsedRealValue(@NotNull Class clazz) throws SchemaException return null; } } - + public Item getParsedItem(ID itemDefinition) throws SchemaException { Validate.notNull(itemDefinition); return getParsedItem(itemDefinition, itemDefinition.getName()); @@ -208,7 +208,7 @@ public RawType clone() { } return clone; } - + @Override public int hashCode() { final int prime = 31; diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/SchemaDefinitionType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/SchemaDefinitionType.java index e2ff1dd85a2..af8541c22a8 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/SchemaDefinitionType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/SchemaDefinitionType.java @@ -1,8 +1,8 @@ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2014.02.06 at 06:55:18 PM CET +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.02.06 at 06:55:18 PM CET // @@ -27,29 +27,27 @@ /** - * + * * Type for prism schema definition. It currently contains * XSD schema definition. But other languages may be supported * later. - * - * + * + * *

Java class for SchemaDefinitionType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="SchemaDefinitionType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <any namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
+ * <complexType name="SchemaDefinitionType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <any namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SchemaDefinitionType", propOrder = { @@ -58,13 +56,13 @@ public class SchemaDefinitionType implements Cloneable, Serializable { public static final QName COMPLEX_TYPE = new QName("http://prism.evolveum.com/xml/ns/public/types-3", "SchemaDefinitionType"); - + @XmlAnyElement protected List any; @XmlTransient protected Element schema; - + public Element getSchema() { return schema; } @@ -87,7 +85,7 @@ public int hashCode() { result = prime * result + ((schema == null) ? 0 : schema.hashCode()); return result; } - + @Override public boolean equals(Object obj) { return equals(obj, false); diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/XPathType.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/XPathType.java index ea6b42fa51b..eaaee860445 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/XPathType.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/XPathType.java @@ -1,8 +1,8 @@ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2014.02.10 at 04:33:35 PM CET +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.02.10 at 04:33:35 PM CET // @@ -15,43 +15,41 @@ /** - * + * * Defines a type for XPath pointer. It points to a specific part * of the XML tree. Only a path expressions should be used in * this type, as it is used as an l-value, i.e. pointing to a * part of XML where an value can be assigned. - * + * * XPath expression selecting the property container. * It must select exactly one XML element. It must not be used to * select XML constructs inside a property, unless such property is * in itself an object. - * + * * The root of the path is assumed to be the element of the * top-most ObjectType. Path attribute may be omitted. In that * case it is assumed to be "/". The path should be absolute, * starting with leading slash ("/"). If the leading slash is * not present, it should be assumed, but warning message * should be logged in such case. - * + * * DEPRECATED. use ItemPathType instead - * + * * cf. ExpressionType - * - * + * + * *

Java class for XPathType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

- * <complexType name="XPathType">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *     </restriction>
- *   </complexContent>
- * </complexType>
+ * <complexType name="XPathType">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
  * 
- * - * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "XPathType", propOrder = { @@ -63,33 +61,33 @@ public class XPathType { protected String content; /** - * + * * Defines a type for XPath pointer. It points to a specific part * of the XML tree. Only a path expressions should be used in * this type, as it is used as an l-value, i.e. pointing to a * part of XML where an value can be assigned. - * + * * XPath expression selecting the property container. * It must select exactly one XML element. It must not be used to * select XML constructs inside a property, unless such property is * in itself an object. - * + * * The root of the path is assumed to be the element of the * top-most ObjectType. Path attribute may be omitted. In that * case it is assumed to be "/". The path should be absolute, * starting with leading slash ("/"). If the leading slash is * not present, it should be assumed, but warning message * should be logged in such case. - * + * * DEPRECATED. use ItemPathType instead - * + * * cf. ExpressionType - * - * + * + * * @return * possible object is * {@link String } - * + * */ public String getContent() { return content; @@ -97,40 +95,40 @@ public String getContent() { /** * Sets the value of the content property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setContent(String value) { this.content = value; } - + @Override public boolean equals(Object obj) { if (!(obj instanceof XPathType)){ return false; } - + XPathType other = (XPathType) obj; String otherValue = other.getContent(); String thisValue = content; - + if (thisValue == null && otherValue == null){ return true; } - + if (thisValue == null || otherValue == null){ return false; } - + return thisValue.equals(otherValue); -// -// +// +// // return super.equals(obj); } - + @Override public String toString() { return "[path: "+content+"]"; diff --git a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/package-info.java b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/package-info.java index dd45c84ff71..5db24af8d99 100644 --- a/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/package-info.java +++ b/infra/prism/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/package-info.java @@ -15,10 +15,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.05.20 at 05:41:15 PM CEST +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.05.20 at 05:41:15 PM CEST // @javax.xml.bind.annotation.XmlSchema(namespace = "http://prism.evolveum.com/xml/ns/public/types-3", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/Generator.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/Generator.java index e2fdd1788d8..7bc1fc784a1 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/Generator.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/Generator.java @@ -12,11 +12,11 @@ public class Generator { @Test public void f() { } - + @Test public void test() throws Exception{ File[] files = new File[]{new File(COMMON_DIR_PATH, "root-foo.xml")}; - File ff = new File(EXTRA_SCHEMA_DIR, "root.xsd"); + File ff = new File(EXTRA_SCHEMA_DIR, "root.xsd"); System.out.println("extra schema " + ff.getAbsolutePath()); PrismContext prismContext = constructInitializedPrismContext(ff); // SchemaRegistry reg = prismContext.getSchemaRegistry(); @@ -25,31 +25,31 @@ public void test() throws Exception{ for (File f : files){ System.out.println("parsing file " + f.getName()); PrismObject o = prismContext.parseObject(f); -// +// String s = prismContext.serializeObjectToString(o, PrismContext.LANG_YAML); System.out.println("parsed: " + s); String fname = f.getName(); fname = fname.replace(".xml", ".yaml"); - + FileOutputStream bos = (new FileOutputStream(new File("src/test/resources/common/yaml/"+fname))); OutputStreamWriter writer = new OutputStreamWriter(bos, "UTF-8"); - + writer.write(s); writer.flush(); writer.close(); - + s = prismContext.serializeObjectToString(o, PrismContext.LANG_JSON); System.out.println("parsed: " + s); fname = fname.replace(".yaml", ".json"); - + bos = (new FileOutputStream(new File("src/test/resources/common/json/"+fname))); writer = new OutputStreamWriter(bos, "UTF-8"); - + writer.write(s); writer.flush(); writer.close(); - + } } diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/PerfRecorder.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/PerfRecorder.java index 0c0d5a1e3bb..6bea206e2df 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/PerfRecorder.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/PerfRecorder.java @@ -28,7 +28,7 @@ public class PerfRecorder { private Double min = null; private Double max = null; private Double sum = 0D; - + public PerfRecorder(String name) { super(); this.name = name; @@ -68,12 +68,12 @@ public double getAverage() { public void assertAverageBelow(double expected) { AssertJUnit.assertTrue(name+ ": Expected average below "+expected+" but was "+getAverage(), getAverage() < expected); } - + public void assertMaxBelow(double expected) { - AssertJUnit.assertTrue(name+ ": Expected maximum below "+expected+" but was "+max, max < expected); + AssertJUnit.assertTrue(name+ ": Expected maximum below "+expected+" but was "+max, max < expected); } - + public String dump() { return name + ": min / avg / max = "+min+" / "+getAverage()+" / "+max + " (sum="+sum+", count="+count+")"; } diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/PrismInternalTestUtil.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/PrismInternalTestUtil.java index fb64b0f451c..63d5f77bcdd 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/PrismInternalTestUtil.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/PrismInternalTestUtil.java @@ -71,9 +71,9 @@ public class PrismInternalTestUtil implements PrismContextFactory { public static final File COMMON_DIR = new File(COMMON_DIR_PATH); public static File SCHEMA_DIR = new File("src/test/resources/schema"); public static File EXTRA_SCHEMA_DIR = new File("src/test/resources/schema-extra"); - + public static final File COMMON_DIR_XML = new File(COMMON_DIR, "xml"); - + // User: jack public static final String USER_JACK_FILE_BASENAME = "user-jack"; public static final File USER_JACK_FILE_XML = new File(COMMON_DIR_XML, USER_JACK_FILE_BASENAME+".xml"); @@ -82,23 +82,23 @@ public class PrismInternalTestUtil implements PrismContextFactory { public static final String USER_JACK_OBJECT_BASENAME = "user-jack-object"; public static final File USER_JACK_OBJECT_FILE = new File(COMMON_DIR_XML, "user-jack-object.xml"); - + public static final String USER_JACK_MODIFIED_FILE_BASENAME = "user-jack-modified"; public static final File USER_JACK_MODIFIED_FILE = new File(COMMON_DIR_PATH, "user-jack-modified.xml"); - + public static final String USER_JACK_ADHOC_BASENAME = "user-jack-adhoc"; public static final File USER_JACK_ADHOC_FILE = new File(COMMON_DIR_XML, "user-jack-adhoc.xml"); - + public static final String USER_JACK_OID = "c0c010c0-d34d-b33f-f00d-111111111111"; public static final XMLGregorianCalendar USER_JACK_VALID_FROM = XmlTypeConverter.createXMLGregorianCalendar(1975, 5, 30, 21, 30, 0); public static final String USER_JACK_DESCRIPTION = "This must be the best pirate the world has ever seen"; public static final String USER_JACK_POLYNAME_ORIG = "Džek Sperou"; public static final String USER_JACK_POLYNAME_NORM = "dzek sperou"; - + // User: barbossa (very simple user) public static final String USER_BARBOSSA_FILE_BASENAME = "user-barbossa"; public static final File USER_BARBOSSA_FILE = new File(COMMON_DIR_XML, "user-barbossa.xml"); - + // User: will (has all the extensions) public static final String USER_WILL_FILE_BASENAME = "user-will"; public static final File USER_WILL_FILE = new File(COMMON_DIR_XML, "user-will.xml"); @@ -107,7 +107,7 @@ public class PrismInternalTestUtil implements PrismContextFactory { public static final String RESOURCE_RUM_FILE_BASENAME = "resource-rum"; public static final String RESOURCE_RUM_OID = "c0c010c0-d34d-b33f-f00d-222222220001"; - + // Namespaces public static final String DEFAULT_NAMESPACE_PREFIX = "http://midpoint.evolveum.com/xml/ns"; public static final String NS_FOO = "http://midpoint.evolveum.com/xml/ns/test/foo-1.xsd"; @@ -119,17 +119,17 @@ public class PrismInternalTestUtil implements PrismContextFactory { public static final String NS_ADHOC = "http://midpoint.evolveum.com/xml/ns/test/adhoc-1.xsd"; public static final String NS_WEAPONS = "http://midpoint.evolveum.com/xml/ns/test/weapons"; public static final String NS_WEAPONS_PREFIX = "w"; - + // FOO schema public static final QName USER_QNAME = new QName(NS_FOO,"user"); public static final QName USER_TYPE_QNAME = new QName(NS_FOO,"UserType"); - + public static final QName OBJECT_REFERENCE_TYPE_QNAME = new QName(NS_FOO, "ObjectReferenceType"); - + public static final QName USER_EXTENSION_QNAME = new QName(NS_FOO,"extension"); public static final QName USER_PARENT_ORG_QNAME = new QName(NS_FOO,"parentOrg"); public static final QName USER_PARENT_ORG_REF_QNAME = new QName(NS_FOO,"parentOrgRef"); - + public static final QName USER_NAME_QNAME = new QName(NS_FOO,"name"); public static final QName USER_FULLNAME_QNAME = new QName(NS_FOO,"fullName"); public static final QName USER_GIVENNAME_QNAME = new QName(NS_FOO,"givenName"); @@ -145,7 +145,7 @@ public class PrismInternalTestUtil implements PrismContextFactory { public static final ItemPath USER_VALID_FROM_PATH = new ItemPath(USER_ACTIVATION_QNAME, USER_VALID_FROM_QNAME); public static final QName USER_VALID_TO_QNAME = new QName(NS_FOO,"validTo"); public static final QName ACTIVATION_TYPE_QNAME = new QName(NS_FOO,"ActivationType"); - + public static final QName USER_ASSIGNMENT_QNAME = new QName(NS_FOO,"assignment"); public static final QName USER_DESCRIPTION_QNAME = new QName(NS_FOO,"description"); public static final ItemPath USER_ASSIGNMENT_DESCRIPTION_PATH = new ItemPath(USER_ASSIGNMENT_QNAME, USER_DESCRIPTION_QNAME); @@ -154,20 +154,20 @@ public class PrismInternalTestUtil implements PrismContextFactory { public static final Long USER_ASSIGNMENT_1_ID = 1111L; public static final Long USER_ASSIGNMENT_2_ID = 1112L; public static final Long USER_ASSIGNMENT_3_ID = 1113L; - + public static final QName ACCOUNT_CONSTRUCTION_TYPE_QNAME = new QName(NS_FOO,"AccountConstructionType"); - + public static final QName USER_ACCOUNTREF_QNAME = new QName(NS_FOO,"accountRef"); public static final QName USER_ACCOUNT_QNAME = new QName(NS_FOO,"account"); - + public static final QName ACCOUNT_TYPE_QNAME = new QName(NS_FOO,"AccountType"); - + public static final QName ACCOUNT_NAME_QNAME = new QName(NS_FOO,"name"); public static final QName ACCOUNT_DESCRIPTION_QNAME = new QName(NS_FOO,"description"); public static final QName ACCOUNT_ATTRIBUTES_QNAME = new QName(NS_FOO,"attributes"); - + public static final QName ATTRIBUTES_TYPE_QNAME = new QName(NS_FOO,"AttributesType"); - + public static final QName DUMMY_PROTECTED_STRING_TYPE = new QName(NS_FOO, "DummyProtectedStringType"); public static final QName RESOURCE_QNAME = new QName(NS_FOO,"resource"); @@ -211,28 +211,28 @@ public class PrismInternalTestUtil implements PrismContextFactory { public static final QName USER_EXT_MULTI_ELEMENT = new QName(NS_USER_EXT, "multi"); public static final QName USER_ADHOC_BOTTLES_ELEMENT = new QName(NS_ADHOC, "bottles"); - + public static final QName WEAPONS_WEAPON_BRAND_TYPE_QNAME = new QName(NS_WEAPONS, "WeaponBrandType"); - + public static final String KEYSTORE_PATH = "src/test/resources/keystore.jceks"; public static final String KEYSTORE_PASSWORD = "changeit"; - + public static PrismContextImpl constructInitializedPrismContext() throws SchemaException, SAXException, IOException { PrismContextImpl context = constructPrismContext(); context.initialize(); return context; } - + public static PrismContext constructInitializedPrismContext(File extraSchema) throws SchemaException, SAXException, IOException { PrismContext context = constructPrismContext(extraSchema); context.initialize(); return context; } - + public static PrismContextImpl constructPrismContext() throws SchemaException, FileNotFoundException { return constructPrismContext(null); } - + public static PrismContextImpl constructPrismContext(File extraSchema) throws SchemaException, FileNotFoundException { SchemaRegistryImpl schemaRegistry = new SchemaRegistryImpl(); schemaRegistry.setCatalogResourceName(TEST_CATALOG_RESOURCE_NAME); @@ -262,11 +262,11 @@ public static PrismContextImpl constructPrismContext(File extraSchema) throws Sc public PrismContext createPrismContext() throws SchemaException, FileNotFoundException { return constructPrismContext(); } - + public static PrismObjectDefinition getUserTypeDefinition() { return PrismTestUtil.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); } - + public static void assertVisitor(Visitable visitable, int expectedVisits) { final List visits = new ArrayList(); Visitor visitor = new Visitor() { @@ -279,7 +279,7 @@ public void visit(Visitable visitable) { visitable.accept(visitor); assertEquals("Wrong number of visits", expectedVisits, visits.size()); } - + public static void assertPathVisitor(PathVisitable visitable, final ItemPath path, final boolean recursive, int expectedVisits) { final List visits = new ArrayList(); Visitor visitor = new Visitor() { @@ -292,7 +292,7 @@ public void visit(Visitable visitable) { visitable.accept(visitor, path, recursive); assertEquals("Wrong number of visits for path "+path, expectedVisits, visits.size()); } - + public static void displayTestTitle(String testName) { PrismTestUtil.displayTestTitle(testName); } @@ -303,14 +303,14 @@ public static void assertUserJack(PrismObject user, boolean expectRawI assertUserJackContent(user, expectRawInConstructions); assertUserJackExtension(user); assertVisitor(user, 71); - + assertPathVisitor(user, new ItemPath(UserType.F_ASSIGNMENT), true, 9); assertPathVisitor(user, new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(USER_ASSIGNMENT_1_ID)), true, 3); assertPathVisitor(user, new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ENABLED), true, 2); assertPathVisitor(user, new ItemPath(UserType.F_EXTENSION), true, 15); - + assertPathVisitor(user, new ItemPath(UserType.F_ASSIGNMENT), false, 1); assertPathVisitor(user, new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), @@ -324,14 +324,14 @@ public static void assertUserJack(PrismObject user, boolean expectRawI new NameItemPathSegment(UserType.F_EXTENSION), NameItemPathSegment.WILDCARD), false, 5); } - + public static void assertUserJackContent(PrismObject user, boolean expectRawInConstructions) throws SchemaException { - + assertEquals("Wrong oid", USER_JACK_OID, user.getOid()); assertEquals("Wrong version", "42", user.getVersion()); PrismAsserts.assertObjectDefinition(user.getDefinition(), USER_QNAME, USER_TYPE_QNAME, UserType.class); PrismAsserts.assertParentConsistency(user); - + assertPropertyValue(user, "fullName", "cpt. Jack Sparrow"); assertPropertyDefinition(user, "fullName", DOMUtil.XSD_STRING, 1, 1); assertPropertyValue(user, "givenName", "Jack"); @@ -343,21 +343,21 @@ public static void assertUserJackContent(PrismObject user, boolean exp assertPropertyValue(user, "special", "got it!"); assertPropertyDefinition(user, "special", DOMUtil.XSD_STRING, 0, 1); - + assertPropertyValue(user, "polyName", new PolyString("Džek Sperou","dzek sperou")); assertPropertyDefinition(user, "polyName", PolyStringType.COMPLEX_TYPE, 0, 1); - + ItemPath enabledPath = USER_ENABLED_PATH; PrismProperty enabledProperty1 = user.findProperty(enabledPath); assertNotNull("No enabled property", enabledProperty1); PrismAsserts.assertDefinition(enabledProperty1.getDefinition(), USER_ENABLED_QNAME, DOMUtil.XSD_BOOLEAN, 0, 1); assertNotNull("Property "+enabledPath+" not found", enabledProperty1); PrismAsserts.assertPropertyValue(enabledProperty1, true); - + PrismProperty validFromProperty = user.findProperty(USER_VALID_FROM_PATH); assertNotNull("Property "+USER_VALID_FROM_PATH+" not found", validFromProperty); PrismAsserts.assertPropertyValue(validFromProperty, USER_JACK_VALID_FROM); - + QName actName = new QName(NS_FOO,"activation"); // Use path ItemPath actPath = new ItemPath(actName); @@ -371,12 +371,12 @@ public static void assertUserJackContent(PrismObject user, boolean exp assertEquals("Wrong activation name",actName,actContainer2.getElementName()); // Compare assertEquals("Eh?",actContainer1,actContainer2); - + PrismProperty enabledProperty2 = actContainer1.findProperty(new QName(NS_FOO,"enabled")); assertNotNull("Property enabled not found", enabledProperty2); PrismAsserts.assertPropertyValue(enabledProperty2, true); assertEquals("Eh?",enabledProperty1,enabledProperty2); - + QName assName = new QName(NS_FOO,"assignment"); QName descriptionName = new QName(NS_FOO,"description"); QName accountConstructionName = new QName(NS_FOO,"accountConstruction"); @@ -384,7 +384,7 @@ public static void assertUserJackContent(PrismObject user, boolean exp assertEquals("Wrong assignement 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()); - + ItemPath a1Path = new ItemPath( new NameItemPathSegment(assName), new IdItemPathSegment(USER_ASSIGNMENT_1_ID), @@ -430,11 +430,11 @@ public static void assertUserJackContent(PrismObject user, boolean exp assertEquals("Wrong oid for accountRef", "c0c010c0-d34d-b33f-f00d-aaaaaaaa1112", accountRefVal2.getOid()); assertEquals("Wrong accountRef description", "This is a reference with a filter", accountRefVal2.getDescription()); assertNotNull("No filter in accountRef", accountRefVal2.getFilter()); - + } - + private static void assertUserJackExtension(PrismObject user) throws SchemaException { - + PrismContainer extension = user.getExtension(); assertContainerDefinition(extension, "extension", DOMUtil.XSD_ANY, 0, 1); PrismContainerValue extensionValue = extension.getValue(); @@ -454,7 +454,7 @@ private static void assertUserJackExtension(PrismObject user) throws S PrismPropertyDefinition indexedStringPropertyDef = indexedString.getDefinition(); PrismAsserts.assertDefinition(indexedStringPropertyDef, EXTENSION_SINGLE_STRING_TYPE_ELEMENT, DOMUtil.XSD_STRING, 0, -1); assertEquals("'Indexed' attribute on 'singleStringType' property is wrong", Boolean.FALSE, indexedStringPropertyDef.isIndexed()); - + ItemPath barPath = new ItemPath(new QName(NS_FOO,"extension"), EXTENSION_BAR_ELEMENT); PrismProperty barProperty = user.findProperty(barPath); assertNotNull("Property "+barPath+" not found", barProperty); @@ -487,11 +487,11 @@ public static void assertContainerDefinition(PrismContainer container, String co QName qName = new QName(NS_FOO, contName); PrismAsserts.assertDefinition(container.getDefinition(), qName, xsdType, minOccurs, maxOccurs); } - + public static PrismSchema getFooSchema(PrismContext prismContext) { return prismContext.getSchemaRegistry().findSchemaByNamespace(NS_FOO); } - + public static Protector createProtector(String xmlCipher){ ProtectorImpl protector = new ProtectorImpl(); protector.setKeyStorePassword(KEYSTORE_PASSWORD); diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestCompare.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestCompare.java index 812b6ffa212..c42fd03f81e 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestCompare.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestCompare.java @@ -47,57 +47,57 @@ * */ public abstract class TestCompare { - + private static final QName REF_QNAME = new QName(NS_FOO, "ref"); private static final QName REF_TYPE_QNAME = new QName(NS_FOO, "RefType");; protected abstract String getSubdirName(); - + protected abstract String getFilenameSuffix(); - + protected File getCommonSubdir() { return new File(COMMON_DIR_PATH, getSubdirName()); } - + protected File getFile(String baseName) { return new File(getCommonSubdir(), baseName+"."+getFilenameSuffix()); } - + @BeforeSuite public void setupDebug() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(DEFAULT_NAMESPACE_PREFIX); PrismTestUtil.resetPrismContext(new PrismInternalTestUtil()); } - + /** * Parse the same files twice, compare the results. */ @Test public void testCompareJack() throws SchemaException, SAXException, IOException { System.out.println("===[ testCompareJack ]==="); - + // GIVEN PrismContext prismContext = constructInitializedPrismContext(); - + // Document document = DOMUtil.parseFile(USER_JACK_FILE_XML); // Element userElement = DOMUtil.getFirstChildElement(document); - + PrismObject user1 = prismContext.parseObject(getFile(USER_JACK_FILE_BASENAME)); PrismObject user2 = prismContext.parseObject(getFile(USER_JACK_FILE_BASENAME)); - + // WHEN, THEN - + assertTrue("Users not the same (PrismObject)(1)", user1.equals(user2)); assertTrue("Users not the same (PrismObject)(2)", user2.equals(user1)); - - // Following line won't work here. We don't have proper generated classes here. + + // Following line won't work here. We don't have proper generated classes here. // It is tested in the "schema" project that has a proper code generation // assertTrue("Users not the same (Objectable)", user1.asObjectable().equals(user2.asObjectable())); - + assertTrue("Users not equivalent (1)", user1.equivalent(user2)); assertTrue("Users not equivalent (2)", user2.equivalent(user1)); } - + /** * Parse original jack and modified Jack. Diff and assert if the resulting * delta is OK. @@ -105,57 +105,57 @@ public void testCompareJack() throws SchemaException, SAXException, IOException @Test public void testDiffJack() throws Exception { System.out.println("===[ testDiffJack ]==="); - + // GIVEN PrismContext prismContext = constructInitializedPrismContext(); - + PrismObject jackOriginal = prismContext.parseObject(getFile(USER_JACK_FILE_BASENAME)); - + PrismObject jackModified = prismContext.parseObject(getFile(USER_JACK_MODIFIED_FILE_BASENAME)); - + // WHEN ObjectDelta jackDelta = jackOriginal.diff (jackModified); - + // THEN System.out.println("Jack delta:"); System.out.println(jackDelta.debugDump()); - + jackDelta.assertDefinitions(); jackDelta.checkConsistence(true, true, true); - + assertEquals("Wrong delta type", ChangeType.MODIFY, jackDelta.getChangeType()); assertEquals("Wrong delta OID", USER_JACK_OID, jackDelta.getOid()); assertEquals("Wrong number of modificaitions", 8, jackDelta.getModifications().size()); - + PrismAsserts.assertPropertyReplace(jackDelta, USER_FULLNAME_QNAME, "Jack Sparrow"); - + PrismAsserts.assertPropertyDelete(jackDelta, new ItemPath(USER_EXTENSION_QNAME, EXTENSION_MULTI_ELEMENT), "dva"); PrismAsserts.assertPropertyAdd(jackDelta, new ItemPath(USER_EXTENSION_QNAME, EXTENSION_MULTI_ELEMENT), "osem"); // TODO: assert BAR - + PrismAsserts.assertPropertyDelete(jackDelta, USER_ADDITIONALNAMES_QNAME, "Captain"); - + PrismAsserts.assertPropertyAdd(jackDelta, USER_LOCALITY_QNAME, "World's End"); - + // There won't be any activation deltas. Activation is operational. PrismAsserts.assertNoItemDelta(jackDelta, USER_ENABLED_PATH); PrismAsserts.assertNoItemDelta(jackDelta, USER_VALID_FROM_PATH); - - PrismAsserts.assertPropertyReplace(jackDelta, + + PrismAsserts.assertPropertyReplace(jackDelta, new ItemPath( new NameItemPathSegment(USER_ASSIGNMENT_QNAME), new IdItemPathSegment(USER_ASSIGNMENT_2_ID), - new NameItemPathSegment(USER_DESCRIPTION_QNAME)), + new NameItemPathSegment(USER_DESCRIPTION_QNAME)), "Assignment II"); - + ContainerDelta assignment3Delta = PrismAsserts.assertContainerAddGetContainerDelta(jackDelta, new ItemPath(USER_ASSIGNMENT_QNAME)); PrismContainerValue assignment3DeltaAddValue = assignment3Delta.getValuesToAdd().iterator().next(); assertEquals("Assignment 3 wrong ID", USER_ASSIGNMENT_3_ID, assignment3DeltaAddValue.getId()); - + // TODO assert assignment[i1112]/accountConstruction } - - + + /** * Parse original jack and modified Jack. Diff and assert if the resulting * delta is OK. @@ -164,66 +164,66 @@ public void testDiffJack() throws Exception { @Test public void testDiffJackLiteral() throws Exception { System.out.println("===[ testDiffJackLiteral ]==="); - + // GIVEN PrismContext prismContext = constructInitializedPrismContext(); - + PrismObject jackOriginal = prismContext.parseObject(getFile(USER_JACK_FILE_BASENAME)); - + PrismObject jackModified = prismContext.parseObject(getFile(USER_JACK_MODIFIED_FILE_BASENAME)); - + // WHEN ObjectDelta jackDelta = jackOriginal.diff(jackModified, true, true); - + // THEN System.out.println("Jack delta:"); System.out.println(jackDelta.debugDump()); - + jackDelta.assertDefinitions(); jackDelta.checkConsistence(true, true, true); - + assertEquals("Wrong delta type", ChangeType.MODIFY, jackDelta.getChangeType()); assertEquals("Wrong delta OID", USER_JACK_OID, jackDelta.getOid()); assertEquals("Wrong number of modificaitions", 10, jackDelta.getModifications().size()); - + PrismAsserts.assertPropertyReplace(jackDelta, USER_FULLNAME_QNAME, "Jack Sparrow"); - + PrismAsserts.assertPropertyDelete(jackDelta, new ItemPath(USER_EXTENSION_QNAME, EXTENSION_MULTI_ELEMENT), "dva"); PrismAsserts.assertPropertyAdd(jackDelta, new ItemPath(USER_EXTENSION_QNAME, EXTENSION_MULTI_ELEMENT), "osem"); // TODO: assert BAR - + PrismAsserts.assertPropertyDelete(jackDelta, USER_ADDITIONALNAMES_QNAME, "Captain"); - + PrismAsserts.assertPropertyAdd(jackDelta, USER_LOCALITY_QNAME, "World's End"); - + PrismAsserts.assertPropertyReplace(jackDelta, USER_ENABLED_PATH, false); PrismAsserts.assertPropertyDelete(jackDelta, USER_VALID_FROM_PATH, USER_JACK_VALID_FROM); - - PrismAsserts.assertPropertyReplace(jackDelta, + + PrismAsserts.assertPropertyReplace(jackDelta, new ItemPath( new NameItemPathSegment(USER_ASSIGNMENT_QNAME), new IdItemPathSegment(USER_ASSIGNMENT_2_ID), - new NameItemPathSegment(USER_DESCRIPTION_QNAME)), + new NameItemPathSegment(USER_DESCRIPTION_QNAME)), "Assignment II"); - + ContainerDelta assignment3Delta = PrismAsserts.assertContainerAddGetContainerDelta(jackDelta, new ItemPath(USER_ASSIGNMENT_QNAME)); PrismContainerValue assignment3DeltaAddValue = assignment3Delta.getValuesToAdd().iterator().next(); assertEquals("Assignment 3 wrong ID", USER_ASSIGNMENT_3_ID, assignment3DeltaAddValue.getId()); - + // TODO assert assignment[i1112]/accountConstruction } - + @Test public void testDiffPatchRoundTrip() throws SchemaException, SAXException, IOException { System.out.println("===[ testDiffPatchRoundTrip ]==="); - + // GIVEN PrismContext prismContext = constructInitializedPrismContext(); - + PrismObject jackOriginal = prismContext.parseObject(getFile(USER_JACK_FILE_BASENAME)); - + PrismObject jackModified = prismContext.parseObject(getFile(USER_JACK_MODIFIED_FILE_BASENAME)); - + ObjectDelta jackDelta = jackOriginal.diff(jackModified); // System.out.println("jackOriginal:\n" + prismContext.getXnodeProcessor().serializeObject(jackOriginal).debugDump(1)); @@ -232,7 +232,7 @@ public void testDiffPatchRoundTrip() throws SchemaException, SAXException, IOExc jackDelta.assertDefinitions(); jackDelta.checkConsistence(true, true, true); - + // WHEN jackDelta.applyTo(jackOriginal); @@ -241,67 +241,67 @@ public void testDiffPatchRoundTrip() throws SchemaException, SAXException, IOExc // THEN assertTrue("Roundtrip failed", jackOriginal.equivalent(jackModified)); } - + @Test public void testEqualsReferenceValues() throws Exception { System.out.println("===[ testEqualsReferenceValues ]==="); - + PrismContext prismContext = constructInitializedPrismContext(); - + PrismReferenceValue val11 = new PrismReferenceValue("oid1"); val11.setTargetType(ACCOUNT_TYPE_QNAME); - + PrismReferenceValue val12 = new PrismReferenceValue("oid1"); val12.setTargetType(ACCOUNT_TYPE_QNAME); - + PrismReferenceValue val13 = new PrismReferenceValue("oid1"); // No type - + PrismReferenceValue val21 = new PrismReferenceValue(); val21.setTargetType(ACCOUNT_TYPE_QNAME); - + PrismReferenceValue val22 = new PrismReferenceValue(); val22.setTargetType(ACCOUNT_TYPE_QNAME); - + PrismReferenceValue val23 = new PrismReferenceValue(); // No type - + PrismObject user = prismContext.parseObject(getFile(USER_JACK_FILE_BASENAME)); - + PrismReferenceValue val31 = new PrismReferenceValue(); val31.setObject(user); - + PrismReferenceValue val32 = new PrismReferenceValue(); val32.setObject(user.clone()); - + PrismReferenceValue val33 = new PrismReferenceValue(); // No type, no object - + PrismReferenceValue val34 = new PrismReferenceValue(); PrismObject differentUser = user.clone(); differentUser.setOid(null); differentUser.setPropertyRealValue(UserType.F_FULL_NAME, "Jack Different"); val34.setObject(differentUser); - + PrismReferenceValue val35 = new PrismReferenceValue(); PrismObject yetAnotherDifferentUser = user.clone(); yetAnotherDifferentUser.setOid(null); yetAnotherDifferentUser.setPropertyRealValue(UserType.F_FULL_NAME, "John J Random"); val35.setObject(yetAnotherDifferentUser); - + assertTrue("val11 - val11", val11.equals(val11)); assertTrue("val11 - val12", val11.equals(val12)); assertTrue("val12 - val11", val12.equals(val11)); assertFalse("val11 - val13", val11.equals(val13)); assertFalse("val13 - val11", val13.equals(val11)); - + assertTrue("val21 - val21", val21.equals(val21)); assertTrue("val21 - val22", val21.equals(val22)); assertTrue("val22 - val21", val22.equals(val21)); assertFalse("val21 - val23", val21.equals(val23)); assertFalse("val23 - val21", val23.equals(val21)); - + assertTrue("val31 - val31", val31.equals(val31)); assertTrue("val31 - val32", val31.equals(val32)); assertTrue("val32 - val31", val32.equals(val31)); @@ -313,112 +313,112 @@ public void testEqualsReferenceValues() throws Exception { assertFalse("val35 - val31", val35.equals(val31)); assertFalse("val34 - val35", val34.equals(val35)); assertFalse("val35 - val34", val35.equals(val34)); - + } - + @Test public void testEqualsReferenceValuesSchema() throws Exception { System.out.println("===[ testEqualsReferenceValuesSchema ]==="); - + PrismContext prismContext = constructInitializedPrismContext(); - + PrismReferenceDefinitionImpl ref1Def = new PrismReferenceDefinitionImpl(REF_QNAME, REF_TYPE_QNAME, prismContext); ref1Def.setTargetTypeName(ACCOUNT_TYPE_QNAME); PrismReference ref1 = new PrismReference(REF_QNAME, ref1Def, prismContext); - + PrismReferenceValue val11 = new PrismReferenceValue("oid1"); val11.setTargetType(ACCOUNT_TYPE_QNAME); ref1.add(val11); - + PrismReferenceValue val12 = new PrismReferenceValue("oid1"); val12.setTargetType(ACCOUNT_TYPE_QNAME); ref1.add(val12); - + PrismReferenceValue val13 = new PrismReferenceValue("oid1"); // No type ref1.add(val13); - + PrismReferenceValue val14 = new PrismReferenceValue("oid1"); // No type ref1.add(val14); - + PrismReferenceDefinition ref2Def = new PrismReferenceDefinitionImpl(REF_QNAME, REF_TYPE_QNAME, prismContext); // no target type def PrismReference ref2 = new PrismReference(REF_QNAME, ref2Def, prismContext); - + PrismReferenceValue val21 = new PrismReferenceValue("oid1"); val21.setTargetType(ACCOUNT_TYPE_QNAME); ref2.add(val21); - + PrismReferenceValue val22 = new PrismReferenceValue("oid1"); val22.setTargetType(ACCOUNT_TYPE_QNAME); ref2.add(val22); - + PrismReferenceValue val23 = new PrismReferenceValue("oid1"); // No type ref2.add(val23); - + // No def in val4x - + PrismReferenceValue val41 = new PrismReferenceValue("oid1"); val41.setTargetType(ACCOUNT_TYPE_QNAME); - + PrismReferenceValue val42 = new PrismReferenceValue("oid1"); val42.setTargetType(ACCOUNT_TYPE_QNAME); - + PrismReferenceValue val43 = new PrismReferenceValue("oid1"); // No type - + assertTrue("val11 - val11", val11.equals(val11)); assertTrue("val11 - val12", val11.equals(val12)); assertTrue("val12 - val11", val12.equals(val11)); assertTrue("val11 - val13", val11.equals(val13)); assertTrue("val13 - val11", val13.equals(val11)); assertTrue("val13 - val14", val13.equals(val14)); - + assertTrue("val21 - val21", val21.equals(val21)); assertTrue("val21 - val22", val21.equals(val22)); assertTrue("val22 - val21", val22.equals(val21)); assertFalse("val21 - val23", val21.equals(val23)); assertFalse("val23 - val21", val23.equals(val21)); - + assertTrue("val41 - val41", val41.equals(val41)); assertTrue("val41 - val42", val41.equals(val42)); assertTrue("val42 - val41", val42.equals(val41)); assertFalse("val41 - val43", val41.equals(val43)); assertFalse("val43 - val41", val43.equals(val41)); - + assertTrue("val11 - val21", val11.equals(val21)); assertTrue("val11 - val41", val11.equals(val41)); - + assertTrue("val41 - val11", val41.equals(val11)); assertTrue("val41 - val21", val41.equals(val12)); - + assertTrue("val13 - val21", val13.equals(val21)); assertTrue("val13 - val41", val13.equals(val41)); assertFalse("val43 - val11", val43.equals(val11)); assertFalse("val43 - val12", val43.equals(val12)); assertFalse("val43 - val13", val43.equals(val13)); - + assertFalse("val43 - val21", val43.equals(val21)); assertFalse("val43 - val22", val43.equals(val22)); assertTrue("val43 - val23", val43.equals(val23)); - - + + // assertTrue("val11 - val11", val11.equals(val11)); // assertTrue("val11 - val11", val11.equals(val11)); // assertTrue("val11 - val11", val11.equals(val11)); // assertTrue("val11 - val11", val11.equals(val11)); - - + + } - + @Test(enabled = false) // normalization no longer removes empty values public void testEqualsBrokenAssignmentActivation() throws Exception { System.out.println("===[ testEqualsReferenceValues ]==="); - + // GIVEN PrismObjectDefinition userDef = PrismInternalTestUtil.getUserTypeDefinition(); PrismContainerDefinition assignmentDef = userDef.findContainerDefinition(UserType.F_ASSIGNMENT); @@ -428,15 +428,15 @@ public void testEqualsBrokenAssignmentActivation() throws Exception { // lets break one of these ... PrismContainerValue emptyValue = new PrismContainerValue(PrismTestUtil.getPrismContext()); brokenAssignment.add(emptyValue); - + // WHEN assertFalse("Unexpected equals", goodAssignment.equals(brokenAssignment)); - + brokenAssignment.normalize(); assertEquals("Not equals after normalize(bad)", goodAssignment, brokenAssignment); - + goodAssignment.normalize(); assertEquals("Not equals after normalize(good)", goodAssignment, brokenAssignment); - + } } diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestCompareJson.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestCompareJson.java index cd3805a5ab3..f5a1d9b82e5 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestCompareJson.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestCompareJson.java @@ -28,7 +28,7 @@ protected String getSubdirName() { protected String getFilenameSuffix() { return "json"; } - + @Test public void test(){ } diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestDelta.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestDelta.java index a04ec78c7e8..365b3e97dc5 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestDelta.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestDelta.java @@ -51,7 +51,7 @@ * */ public class TestDelta { - + private static final String USER_FOO_OID = "01234567"; @BeforeSuite @@ -59,17 +59,17 @@ public void setupDebug() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(DEFAULT_NAMESPACE_PREFIX); PrismTestUtil.resetPrismContext(new PrismInternalTestUtil()); } - + @Test public void testDeltaPaths() throws Exception { System.out.println("\n\n===[ testDeltaPaths ]===\n"); - - PrismPropertyDefinition descDefinition = new PrismPropertyDefinitionImpl<>(UserType.F_DESCRIPTION, + + PrismPropertyDefinition descDefinition = new PrismPropertyDefinitionImpl<>(UserType.F_DESCRIPTION, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); PropertyDelta delta1 = new PropertyDelta(descDefinition, PrismTestUtil.getPrismContext()); delta1.addValueToAdd(new PrismPropertyValue("add1")); assertPath(delta1, new ItemPath(UserType.F_DESCRIPTION)); - + PrismReferenceDefinitionImpl referenceDefinition = new PrismReferenceDefinitionImpl(UserType.F_PARENT_ORG_REF, OBJECT_REFERENCE_TYPE_QNAME, PrismTestUtil.getPrismContext()); ReferenceDelta delta2 = new ReferenceDelta(referenceDefinition, PrismTestUtil.getPrismContext()); @@ -79,44 +79,44 @@ public void testDeltaPaths() throws Exception { PrismContainerValue assignmentValue1 = new PrismContainerValue(PrismTestUtil.getPrismContext()); // The value id is null assignmentValue1.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "jamalalicha patlama paprtala", PrismTestUtil.getPrismContext()); - ObjectDelta assObjDelta1 = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, + ObjectDelta assObjDelta1 = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, UserType.F_ASSIGNMENT, PrismTestUtil.getPrismContext(), assignmentValue1); ItemDelta assDelta1 = assObjDelta1.getModifications().iterator().next(); assertPath(assDelta1, new ItemPath(UserType.F_ASSIGNMENT)); - + PrismContainerValue assignmentValue2 = new PrismContainerValue(PrismTestUtil.getPrismContext()); assignmentValue1.setId(USER_ASSIGNMENT_1_ID); assignmentValue1.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "jamalalicha patlama paprtala", PrismTestUtil.getPrismContext()); - ObjectDelta assObjDelta2 = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, + ObjectDelta assObjDelta2 = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, UserType.F_ASSIGNMENT, PrismTestUtil.getPrismContext(), assignmentValue2); ItemDelta assDelta2 = assObjDelta2.getModifications().iterator().next(); assertPath(assDelta2, new ItemPath(UserType.F_ASSIGNMENT)); - - PrismPropertyDefinition assDescDefinition = new PrismPropertyDefinitionImpl<>(AssignmentType.F_DESCRIPTION, + + PrismPropertyDefinition assDescDefinition = new PrismPropertyDefinitionImpl<>(AssignmentType.F_DESCRIPTION, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); ItemPath itemPathAssDescNoId = new ItemPath(UserType.F_ASSIGNMENT, AssignmentType.F_DESCRIPTION); PropertyDelta propDelta2 = new PropertyDelta(itemPathAssDescNoId, descDefinition, PrismTestUtil.getPrismContext()); assertPath(propDelta2, itemPathAssDescNoId); - + ItemPath itemPathAssDesc1Id = new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(USER_ASSIGNMENT_1_ID), new NameItemPathSegment(AssignmentType.F_DESCRIPTION)); PropertyDelta propDelta3 = new PropertyDelta(itemPathAssDesc1Id, descDefinition, PrismTestUtil.getPrismContext()); assertPath(propDelta3, itemPathAssDesc1Id); - + } - + private void assertPath(ItemDelta delta, ItemPath expectedPath) { assertEquals("Wrong path in "+delta, expectedPath, delta.getPath()); } - + @Test public void testPropertyDeltaMerge01() throws Exception { System.out.println("\n\n===[ testPropertyDeltaMerge01 ]===\n"); - + // GIVEN - PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, + PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); PropertyDelta delta1 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); @@ -124,10 +124,10 @@ public void testPropertyDeltaMerge01() throws Exception { PropertyDelta delta2 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); delta2.addValueToAdd(new PrismPropertyValue("add2")); - + // WHEN delta1.merge(delta2); - + // THEN System.out.println("Merged delta:"); System.out.println(delta1.debugDump()); @@ -140,9 +140,9 @@ public void testPropertyDeltaMerge01() throws Exception { @Test public void testPropertyDeltaMerge02() throws Exception { System.out.println("\n\n===[ testPropertyDeltaMerge02 ]===\n"); - + // GIVEN - PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, + PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); PropertyDelta delta1 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); @@ -150,10 +150,10 @@ public void testPropertyDeltaMerge02() throws Exception { PropertyDelta delta2 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); delta2.addValueToDelete(new PrismPropertyValue("del2")); - + // WHEN delta1.merge(delta2); - + // THEN System.out.println("Merged delta:"); System.out.println(delta1.debugDump()); @@ -166,9 +166,9 @@ public void testPropertyDeltaMerge02() throws Exception { @Test public void testPropertyDeltaMerge03() throws Exception { System.out.println("\n\n===[ testPropertyDeltaMerge03 ]===\n"); - + // GIVEN - PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, + PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); PropertyDelta delta1 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); @@ -178,10 +178,10 @@ public void testPropertyDeltaMerge03() throws Exception { PropertyDelta delta2 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); delta2.addValueToAdd(new PrismPropertyValue("add2")); delta2.addValueToDelete(new PrismPropertyValue("del2")); - + // WHEN delta1.merge(delta2); - + // THEN System.out.println("Merged delta:"); System.out.println(delta1.debugDump()); @@ -194,9 +194,9 @@ public void testPropertyDeltaMerge03() throws Exception { @Test public void testPropertyDeltaMerge04() throws Exception { System.out.println("\n\n===[ testPropertyDeltaMerge04 ]===\n"); - + // GIVEN - PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, + PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); PropertyDelta delta1 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); @@ -206,10 +206,10 @@ public void testPropertyDeltaMerge04() throws Exception { PropertyDelta delta2 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); delta2.addValueToAdd(new PrismPropertyValue("add2")); delta2.addValueToDelete(new PrismPropertyValue("add1")); - + // WHEN delta1.merge(delta2); - + // THEN System.out.println("Merged delta:"); System.out.println(delta1.debugDump()); @@ -218,13 +218,13 @@ public void testPropertyDeltaMerge04() throws Exception { PrismAsserts.assertAdd(delta1, "add2"); PrismAsserts.assertDelete(delta1, "del1"); } - + @Test public void testPropertyDeltaMerge05() throws Exception { System.out.println("\n\n===[ testPropertyDeltaMerge05 ]===\n"); - + // GIVEN - PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, + PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); PropertyDelta delta1 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); @@ -233,10 +233,10 @@ public void testPropertyDeltaMerge05() throws Exception { PropertyDelta delta2 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); delta2.addValueToAdd(new PrismPropertyValue("add2")); delta2.addValueToDelete(new PrismPropertyValue("add1")); - + // WHEN delta1.merge(delta2); - + // THEN System.out.println("Merged delta:"); System.out.println(delta1.debugDump()); @@ -245,13 +245,13 @@ public void testPropertyDeltaMerge05() throws Exception { PrismAsserts.assertAdd(delta1, "add2"); PrismAsserts.assertNoDelete(delta1); } - + @Test public void testPropertyDeltaMerge06() throws Exception { System.out.println("\n\n===[ testPropertyDeltaMerge06 ]===\n"); - + // GIVEN - PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, + PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); PropertyDelta delta1 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); @@ -260,10 +260,10 @@ public void testPropertyDeltaMerge06() throws Exception { PropertyDelta delta2 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); delta2.addValueToAdd(new PrismPropertyValue("del1")); - + // WHEN delta1.merge(delta2); - + // THEN System.out.println("Merged delta:"); System.out.println(delta1.debugDump()); @@ -272,13 +272,13 @@ public void testPropertyDeltaMerge06() throws Exception { PrismAsserts.assertAdd(delta1, "add1"); PrismAsserts.assertNoDelete(delta1); } - + @Test public void testPropertyDeltaMerge10() throws Exception { System.out.println("\n\n===[ testPropertyDeltaMerge10 ]===\n"); - + // GIVEN - PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, + PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); PropertyDelta delta1 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); @@ -286,10 +286,10 @@ public void testPropertyDeltaMerge10() throws Exception { PropertyDelta delta2 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); delta2.addValueToAdd(new PrismPropertyValue("add2")); - + // WHEN delta1.merge(delta2); - + // THEN System.out.println("Merged delta:"); System.out.println(delta1.debugDump()); @@ -298,13 +298,13 @@ public void testPropertyDeltaMerge10() throws Exception { PrismAsserts.assertNoAdd(delta1); PrismAsserts.assertNoDelete(delta1); } - + @Test public void testPropertyDeltaMerge11() throws Exception { System.out.println("\n\n===[ testPropertyDeltaMerge11 ]===\n"); - + // GIVEN - PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, + PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); PropertyDelta delta1 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); @@ -313,10 +313,10 @@ public void testPropertyDeltaMerge11() throws Exception { PropertyDelta delta2 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); delta2.addValueToAdd(new PrismPropertyValue("add2")); delta2.addValueToDelete(new PrismPropertyValue("r1y")); - + // WHEN delta1.merge(delta2); - + // THEN System.out.println("Merged delta:"); System.out.println(delta1.debugDump()); @@ -329,9 +329,9 @@ public void testPropertyDeltaMerge11() throws Exception { @Test public void testPropertyDeltaMerge12() throws Exception { System.out.println("\n\n===[ testPropertyDeltaMerge12 ]===\n"); - + // GIVEN - PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, + PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); PropertyDelta delta1 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); @@ -340,10 +340,10 @@ public void testPropertyDeltaMerge12() throws Exception { PropertyDelta delta2 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); delta2.addValueToAdd(new PrismPropertyValue("add2")); delta2.addValueToDelete(new PrismPropertyValue("del2")); - + // WHEN delta1.merge(delta2); - + // THEN System.out.println("Merged delta:"); System.out.println(delta1.debugDump()); @@ -352,13 +352,13 @@ public void testPropertyDeltaMerge12() throws Exception { PrismAsserts.assertNoAdd(delta1); PrismAsserts.assertNoDelete(delta1); } - + @Test public void testPropertyDeltaMerge13() throws Exception { System.out.println("\n\n===[ testPropertyDeltaMerge13 ]===\n"); - + // GIVEN - PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, + PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); PropertyDelta delta1 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); @@ -366,10 +366,10 @@ public void testPropertyDeltaMerge13() throws Exception { PropertyDelta delta2 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); delta2.addValueToDelete(new PrismPropertyValue("r1x")); - + // WHEN delta1.merge(delta2); - + // THEN System.out.println("Merged delta:"); System.out.println(delta1.debugDump()); @@ -382,9 +382,9 @@ public void testPropertyDeltaMerge13() throws Exception { @Test public void testPropertyDeltaMerge20() throws Exception { System.out.println("\n\n===[ testPropertyDeltaMerge20 ]===\n"); - + // GIVEN - PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, + PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); PropertyDelta delta1 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); @@ -393,10 +393,10 @@ public void testPropertyDeltaMerge20() throws Exception { PropertyDelta delta2 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); delta2.setValuesToReplace(new PrismPropertyValue("r2x"), new PrismPropertyValue("r2y")); - + // WHEN delta1.merge(delta2); - + // THEN System.out.println("Merged delta:"); System.out.println(delta1.debugDump()); @@ -405,27 +405,27 @@ public void testPropertyDeltaMerge20() throws Exception { PrismAsserts.assertNoAdd(delta1); PrismAsserts.assertNoDelete(delta1); } - + @Test public void testPropertyDeltaSwallow01() throws Exception { System.out.println("\n\n===[ testPropertyDeltaSwallow01 ]===\n"); - + // GIVEN - PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, + PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); PropertyDelta delta1 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); delta1.addValueToAdd(new PrismPropertyValue("add1")); - ObjectDelta objectDelta = new ObjectDelta(UserType.class, ChangeType.MODIFY, + ObjectDelta objectDelta = new ObjectDelta(UserType.class, ChangeType.MODIFY, PrismTestUtil.getPrismContext()); objectDelta.addModification(delta1); PropertyDelta delta2 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); delta2.addValueToAdd(new PrismPropertyValue("add2")); - + // WHEN objectDelta.swallow(delta2); - + // THEN System.out.println("Swallowed delta:"); System.out.println(objectDelta.debugDump()); @@ -436,30 +436,30 @@ public void testPropertyDeltaSwallow01() throws Exception { PrismAsserts.assertAdd(modification, "add1", "add2"); PrismAsserts.assertNoDelete(modification); } - + @Test public void testSummarize01() throws Exception { System.out.println("\n\n===[ testSummarize01 ]===\n"); - + // GIVEN - PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, + PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); PropertyDelta delta1 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); delta1.addValueToAdd(new PrismPropertyValue("add1")); - ObjectDelta objectDelta1 = new ObjectDelta(UserType.class, ChangeType.MODIFY, + ObjectDelta objectDelta1 = new ObjectDelta(UserType.class, ChangeType.MODIFY, PrismTestUtil.getPrismContext()); objectDelta1.addModification(delta1); PropertyDelta delta2 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); delta2.addValueToAdd(new PrismPropertyValue("add2")); - ObjectDelta objectDelta2 = new ObjectDelta(UserType.class, ChangeType.MODIFY, + ObjectDelta objectDelta2 = new ObjectDelta(UserType.class, ChangeType.MODIFY, PrismTestUtil.getPrismContext()); objectDelta2.addModification(delta2); - + // WHEN ObjectDelta sumDelta = ObjectDelta.summarize(objectDelta1, objectDelta2); - + // THEN System.out.println("Summarized delta:"); System.out.println(sumDelta.debugDump()); @@ -474,26 +474,26 @@ public void testSummarize01() throws Exception { @Test public void testSummarize02() throws Exception { System.out.println("\n\n===[ testSummarize02 ]===\n"); - + // GIVEN - PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, + PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); PropertyDelta delta1 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); delta1.addValueToDelete(new PrismPropertyValue("del1")); - ObjectDelta objectDelta1 = new ObjectDelta(UserType.class, ChangeType.MODIFY, + ObjectDelta objectDelta1 = new ObjectDelta(UserType.class, ChangeType.MODIFY, PrismTestUtil.getPrismContext()); objectDelta1.addModification(delta1); PropertyDelta delta2 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); delta2.addValueToDelete(new PrismPropertyValue("del2")); - ObjectDelta objectDelta2 = new ObjectDelta(UserType.class, ChangeType.MODIFY, + ObjectDelta objectDelta2 = new ObjectDelta(UserType.class, ChangeType.MODIFY, PrismTestUtil.getPrismContext()); objectDelta2.addModification(delta2); - + // WHEN ObjectDelta sumDelta = ObjectDelta.summarize(objectDelta1, objectDelta2); - + // THEN System.out.println("Summarized delta:"); System.out.println(sumDelta.debugDump()); @@ -504,32 +504,32 @@ public void testSummarize02() throws Exception { PrismAsserts.assertNoAdd(modification); PrismAsserts.assertDelete(modification, "del1", "del2"); } - + @Test public void testSummarize05() throws Exception { System.out.println("\n\n===[ testSummarize05 ]===\n"); - + // GIVEN - PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, + PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); PropertyDelta delta1 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); // Let's complicate the things a bit with origin. This should work even though origins do not match. delta1.addValueToAdd(new PrismPropertyValue("add1", OriginType.OUTBOUND, null)); - ObjectDelta objectDelta1 = new ObjectDelta(UserType.class, ChangeType.MODIFY, + ObjectDelta objectDelta1 = new ObjectDelta(UserType.class, ChangeType.MODIFY, PrismTestUtil.getPrismContext()); objectDelta1.addModification(delta1); PropertyDelta delta2 = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); delta2.addValueToAdd(new PrismPropertyValue("add2")); delta2.addValueToDelete(new PrismPropertyValue("add1")); - ObjectDelta objectDelta2 = new ObjectDelta(UserType.class, ChangeType.MODIFY, + ObjectDelta objectDelta2 = new ObjectDelta(UserType.class, ChangeType.MODIFY, PrismTestUtil.getPrismContext()); objectDelta2.addModification(delta2); - + // WHEN ObjectDelta sumDelta = ObjectDelta.summarize(objectDelta1, objectDelta2); - + // THEN System.out.println("Summarized delta:"); System.out.println(sumDelta.debugDump()); @@ -579,17 +579,17 @@ public void testSummarize06() throws Exception { public void testAddPropertyMulti() throws Exception { System.out.println("\n\n===[ testAddPropertyMulti ]===\n"); // GIVEN - + // User PrismObject user = createUser(); //Delta - ObjectDelta userDelta = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, UserType.F_ADDITIONAL_NAMES, + ObjectDelta userDelta = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, UserType.F_ADDITIONAL_NAMES, PrismTestUtil.getPrismContext(), PrismTestUtil.createPolyString("baz")); - + // WHEN userDelta.applyTo(user); - + // THEN assertEquals("Wrong OID", USER_FOO_OID, user.getOid()); PrismAsserts.assertPropertyValue(user, UserType.F_ADDITIONAL_NAMES, PrismTestUtil.createPolyString("baz"), PrismTestUtil.createPolyString("foobar")); @@ -597,12 +597,12 @@ public void testAddPropertyMulti() throws Exception { assertNotNull("No assignment", assignment); assertEquals("Unexpected number of assignment values", 1, assignment.size()); } - + @Test public void testAddAssignmentSameNullIdApplyToObject() throws Exception { System.out.println("\n\n===[ testAddAssignmentSameNullIdApplyToObject ]===\n"); // GIVEN - + // User PrismObject user = createUser(); @@ -610,13 +610,13 @@ public void testAddAssignmentSameNullIdApplyToObject() throws Exception { PrismContainerValue assignmentValue = new PrismContainerValue(PrismTestUtil.getPrismContext()); // The value id is null assignmentValue.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "jamalalicha patlama paprtala", PrismTestUtil.getPrismContext()); - - ObjectDelta userDelta = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, + + ObjectDelta userDelta = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, UserType.F_ASSIGNMENT, PrismTestUtil.getPrismContext(), assignmentValue); - + // WHEN userDelta.applyTo(user); - + // THEN System.out.println("User after delta application:"); System.out.println(user.debugDump()); @@ -626,18 +626,18 @@ public void testAddAssignmentSameNullIdApplyToObject() throws Exception { assertNotNull("No assignment", assignment); assertEquals("Unexpected number of assignment values", 1, assignment.size()); } - + @Test public void testAddAssignmentSameNullIdSwallow() throws Exception { System.out.println("\n\n===[ testAddAssignmentSameNullIdSwallow ]===\n"); // GIVEN - + //Delta 1 PrismContainerValue assignmentValue1 = new PrismContainerValue(PrismTestUtil.getPrismContext()); // The value id is null assignmentValue1.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "jamalalicha patlama paprtala", PrismTestUtil.getPrismContext()); - - ObjectDelta userDelta1 = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, + + ObjectDelta userDelta1 = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, UserType.F_ASSIGNMENT, PrismTestUtil.getPrismContext(), assignmentValue1); //Delta 2 @@ -646,10 +646,10 @@ public void testAddAssignmentSameNullIdSwallow() throws Exception { assignmentValue2.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "jamalalicha patlama paprtala", PrismTestUtil.getPrismContext()); ContainerDelta containerDelta2 = ContainerDelta.createDelta(UserType.F_ASSIGNMENT,getUserTypeDefinition()); containerDelta2.addValueToAdd(assignmentValue2); - + // WHEN userDelta1.swallow(containerDelta2); - + // THEN System.out.println("Delta after swallow:"); System.out.println(userDelta1.debugDump()); @@ -662,18 +662,18 @@ public void testAddAssignmentSameNullIdSwallow() throws Exception { assertEquals("Unexpected number of values to add", 1, valuesToAdd.size()); assertEquals("Wrong value to add", assignmentValue1, valuesToAdd.iterator().next()); } - + @Test public void testAddAssignmentDifferentNullIdSwallow() throws Exception { System.out.println("\n\n===[ testAddAssignmentDifferentNullIdSwallow ]===\n"); // GIVEN - + //Delta 1 PrismContainerValue assignmentValue1 = new PrismContainerValue(PrismTestUtil.getPrismContext()); // The value id is null assignmentValue1.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "jamalalicha patlama paprtala", PrismTestUtil.getPrismContext()); - - ObjectDelta userDelta1 = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, + + ObjectDelta userDelta1 = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, UserType.F_ASSIGNMENT, PrismTestUtil.getPrismContext(), assignmentValue1); //Delta 2 @@ -682,10 +682,10 @@ public void testAddAssignmentDifferentNullIdSwallow() throws Exception { assignmentValue2.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "abra kadabra", PrismTestUtil.getPrismContext()); ContainerDelta containerDelta2 = ContainerDelta.createDelta(UserType.F_ASSIGNMENT,getUserTypeDefinition()); containerDelta2.addValueToAdd(assignmentValue2); - + // WHEN userDelta1.swallow(containerDelta2); - + // THEN System.out.println("Delta after swallow:"); System.out.println(userDelta1.debugDump()); @@ -699,30 +699,30 @@ public void testAddAssignmentDifferentNullIdSwallow() throws Exception { assertTrue("Value "+assignmentValue1+" missing ", valuesToAdd.contains(assignmentValue1)); assertTrue("Value "+assignmentValue2+" missing ", valuesToAdd.contains(assignmentValue2)); } - + @Test public void testAddAssignmentDifferentFirstIdSwallow() throws Exception { System.out.println("\n\n===[ testAddAssignmentDifferentFirstIdSwallow ]===\n"); // GIVEN - + //Delta 1 PrismContainerValue assignmentValue1 = new PrismContainerValue(PrismTestUtil.getPrismContext()); assignmentValue1.setId(USER_ASSIGNMENT_1_ID); assignmentValue1.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "jamalalicha patlama paprtala", PrismTestUtil.getPrismContext()); - - ObjectDelta userDelta1 = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, + + ObjectDelta userDelta1 = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, UserType.F_ASSIGNMENT, PrismTestUtil.getPrismContext(), assignmentValue1); //Delta 2 PrismContainerValue assignmentValue2 = new PrismContainerValue(PrismTestUtil.getPrismContext()); - // The value id is null + // The value id is null assignmentValue2.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "abra kadabra", PrismTestUtil.getPrismContext()); ContainerDelta containerDelta2 = ContainerDelta.createDelta(UserType.F_ASSIGNMENT, getUserTypeDefinition()); containerDelta2.addValueToAdd(assignmentValue2); - + // WHEN userDelta1.swallow(containerDelta2); - + // THEN System.out.println("Delta after swallow:"); System.out.println(userDelta1.debugDump()); @@ -736,18 +736,18 @@ public void testAddAssignmentDifferentFirstIdSwallow() throws Exception { assertTrue("Value "+assignmentValue1+" missing ", valuesToAdd.contains(assignmentValue1)); assertTrue("Value "+assignmentValue2+" missing ", valuesToAdd.contains(assignmentValue2)); } - + @Test public void testAddAssignmentDifferentSecondIdSwallow() throws Exception { System.out.println("\n\n===[ testAddAssignmentDifferentSecondIdSwallow ]===\n"); // GIVEN - + //Delta 1 PrismContainerValue assignmentValue1 = new PrismContainerValue(PrismTestUtil.getPrismContext()); // The value id is null assignmentValue1.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "jamalalicha patlama paprtala", PrismTestUtil.getPrismContext()); - - ObjectDelta userDelta1 = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, + + ObjectDelta userDelta1 = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, UserType.F_ASSIGNMENT, PrismTestUtil.getPrismContext(), assignmentValue1); //Delta 2 @@ -756,10 +756,10 @@ public void testAddAssignmentDifferentSecondIdSwallow() throws Exception { assignmentValue2.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "abra kadabra", PrismTestUtil.getPrismContext()); ContainerDelta containerDelta2 = ContainerDelta.createDelta(UserType.F_ASSIGNMENT,getUserTypeDefinition()); containerDelta2.addValueToAdd(assignmentValue2); - + // WHEN userDelta1.swallow(containerDelta2); - + // THEN System.out.println("Delta after swallow:"); System.out.println(userDelta1.debugDump()); @@ -773,18 +773,18 @@ public void testAddAssignmentDifferentSecondIdSwallow() throws Exception { assertTrue("Value "+assignmentValue1+" missing ", valuesToAdd.contains(assignmentValue1)); assertTrue("Value "+assignmentValue2+" missing ", valuesToAdd.contains(assignmentValue2)); } - + @Test public void testAddAssignmentDifferentTwoIdsSwallow() throws Exception { System.out.println("\n\n===[ testAddAssignmentDifferentTwoIdsSwallow ]===\n"); // GIVEN - + //Delta 1 PrismContainerValue assignmentValue1 = new PrismContainerValue(PrismTestUtil.getPrismContext()); assignmentValue1.setId(USER_ASSIGNMENT_1_ID); assignmentValue1.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "jamalalicha patlama paprtala", PrismTestUtil.getPrismContext()); - - ObjectDelta userDelta1 = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, + + ObjectDelta userDelta1 = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, UserType.F_ASSIGNMENT, PrismTestUtil.getPrismContext(), assignmentValue1); //Delta 2 @@ -793,10 +793,10 @@ public void testAddAssignmentDifferentTwoIdsSwallow() throws Exception { assignmentValue2.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "abra kadabra", PrismTestUtil.getPrismContext()); ContainerDelta containerDelta2 = ContainerDelta.createDelta(UserType.F_ASSIGNMENT,getUserTypeDefinition()); containerDelta2.addValueToAdd(assignmentValue2); - + // WHEN userDelta1.swallow(containerDelta2); - + // THEN System.out.println("Delta after swallow:"); System.out.println(userDelta1.debugDump()); @@ -810,18 +810,18 @@ public void testAddAssignmentDifferentTwoIdsSwallow() throws Exception { assertTrue("Value "+assignmentValue1+" missing ", valuesToAdd.contains(assignmentValue1)); assertTrue("Value "+assignmentValue2+" missing ", valuesToAdd.contains(assignmentValue2)); } - + @Test public void testAddAssignmentDifferentIdSameSwallow() throws Exception { System.out.println("\n\n===[ testAddAssignmentDifferentIdConflictSwallow ]===\n"); // GIVEN - + //Delta 1 PrismContainerValue assignmentValue1 = new PrismContainerValue(PrismTestUtil.getPrismContext()); assignmentValue1.setId(USER_ASSIGNMENT_1_ID); assignmentValue1.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "jamalalicha patlama paprtala", PrismTestUtil.getPrismContext()); - - ObjectDelta userDelta1 = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, + + ObjectDelta userDelta1 = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, UserType.F_ASSIGNMENT, PrismTestUtil.getPrismContext(), assignmentValue1); //Delta 2 @@ -830,10 +830,10 @@ public void testAddAssignmentDifferentIdSameSwallow() throws Exception { assignmentValue2.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "jamalalicha patlama paprtala", PrismTestUtil.getPrismContext()); ContainerDelta containerDelta2 = ContainerDelta.createDelta(UserType.F_ASSIGNMENT,getUserTypeDefinition()); containerDelta2.addValueToAdd(assignmentValue2); - + // WHEN userDelta1.swallow(containerDelta2); - + // THEN System.out.println("Delta after swallow:"); System.out.println(userDelta1.debugDump()); @@ -846,19 +846,19 @@ public void testAddAssignmentDifferentIdSameSwallow() throws Exception { assertEquals("Unexpected number of values to add", 1, valuesToAdd.size()); assertTrue("Value "+assignmentValue1+" missing ", valuesToAdd.contains(assignmentValue1)); } - + // MID-1296 @Test(enabled=false) public void testAddAssignmentDifferentIdConflictSwallow() throws Exception { System.out.println("\n\n===[ testAddAssignmentDifferentIdConflictSwallow ]===\n"); // GIVEN - + //Delta 1 PrismContainerValue assignmentValue1 = new PrismContainerValue(PrismTestUtil.getPrismContext()); assignmentValue1.setId(USER_ASSIGNMENT_1_ID); assignmentValue1.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "jamalalicha patlama paprtala", PrismTestUtil.getPrismContext()); - - ObjectDelta userDelta1 = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, + + ObjectDelta userDelta1 = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, UserType.F_ASSIGNMENT, PrismTestUtil.getPrismContext(), assignmentValue1); //Delta 2 @@ -867,32 +867,32 @@ public void testAddAssignmentDifferentIdConflictSwallow() throws Exception { assignmentValue2.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "abra kadabra", PrismTestUtil.getPrismContext()); ContainerDelta containerDelta2 = ContainerDelta.createDelta(UserType.F_ASSIGNMENT, getUserTypeDefinition()); containerDelta2.addValueToAdd(assignmentValue2); - + // WHEN userDelta1.swallow(containerDelta2); - + AssertJUnit.fail("Unexpected success"); } - + @Test public void testAddDeltaAddAssignmentDifferentNoIdSwallow() throws Exception { System.out.println("\n\n===[ testAddDeltaAddAssignmentDifferentNoIdSwallow ]===\n"); // GIVEN - + //Delta 1 PrismObject user = createUser(); ObjectDelta userDelta1 = ObjectDelta.createAddDelta(user); - + //Delta 2 PrismContainerValue assignmentValue2 = new PrismContainerValue(PrismTestUtil.getPrismContext()); // null container ID assignmentValue2.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "abra kadabra", PrismTestUtil.getPrismContext()); ContainerDelta containerDelta2 = ContainerDelta.createDelta(UserType.F_ASSIGNMENT,getUserTypeDefinition()); containerDelta2.addValueToAdd(assignmentValue2); - + // WHEN userDelta1.swallow(containerDelta2); - + // THEN System.out.println("Delta after swallow:"); System.out.println(userDelta1.debugDump()); @@ -909,26 +909,26 @@ public void testAddDeltaAddAssignmentDifferentNoIdSwallow() throws Exception { } assertTrue("Value "+assignmentValue2+" missing ", valuesToAdd.contains(assignmentValue2)); } - + @Test public void testAddDeltaNoAssignmentAddAssignmentDifferentNoIdSwallow() throws Exception { System.out.println("\n\n===[ testAddDeltaNoAssignmentAddAssignmentDifferentNoIdSwallow ]===\n"); // GIVEN - + //Delta 1 PrismObject user = createUserNoAssignment(); ObjectDelta userDelta1 = ObjectDelta.createAddDelta(user); - + //Delta 2 PrismContainerValue assignmentValue2 = new PrismContainerValue(PrismTestUtil.getPrismContext()); // null container ID assignmentValue2.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "abra kadabra", PrismTestUtil.getPrismContext()); ContainerDelta containerDelta2 = ContainerDelta.createDelta(UserType.F_ASSIGNMENT,getUserTypeDefinition()); containerDelta2.addValueToAdd(assignmentValue2); - + // WHEN userDelta1.swallow(containerDelta2); - + // THEN System.out.println("Delta after swallow:"); System.out.println(userDelta1.debugDump()); @@ -941,26 +941,26 @@ public void testAddDeltaNoAssignmentAddAssignmentDifferentNoIdSwallow() throws E assertEquals("Unexpected number of values to add", 1, valuesToAdd.size()); assertTrue("Value "+assignmentValue2+" missing ", valuesToAdd.contains(assignmentValue2)); } - + @Test public void testAddDeltaNoAssignmentAddAssignmentDifferentIdSwallow() throws Exception { System.out.println("\n\n===[ testAddDeltaNoAssignmentAddAssignmentDifferentIdSwallow ]===\n"); // GIVEN - + //Delta 1 PrismObject user = createUserNoAssignment(); ObjectDelta userDelta1 = ObjectDelta.createAddDelta(user); - + //Delta 2 PrismContainerValue assignmentValue2 = new PrismContainerValue(PrismTestUtil.getPrismContext()); assignmentValue2.setId(USER_ASSIGNMENT_2_ID); assignmentValue2.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "abra kadabra", PrismTestUtil.getPrismContext()); ContainerDelta containerDelta2 = ContainerDelta.createDelta(UserType.F_ASSIGNMENT,getUserTypeDefinition()); containerDelta2.addValueToAdd(assignmentValue2); - + // WHEN userDelta1.swallow(containerDelta2); - + // THEN System.out.println("Delta after swallow:"); System.out.println(userDelta1.debugDump()); @@ -973,12 +973,12 @@ public void testAddDeltaNoAssignmentAddAssignmentDifferentIdSwallow() throws Exc assertEquals("Unexpected number of values to add", 1, valuesToAdd.size()); assertTrue("Value "+assignmentValue2+" missing ", valuesToAdd.contains(assignmentValue2)); } - + @Test public void testAddAssignmentActivationDifferentNullIdApplyToObject() throws Exception { System.out.println("\n\n===[ testAddAssignmentActivationDifferentNullIdApplyToObject ]===\n"); // GIVEN - + // User PrismObject user = createUser(); @@ -986,18 +986,18 @@ public void testAddAssignmentActivationDifferentNullIdApplyToObject() throws Exc PrismContainerValue activationValue = new PrismContainerValue(PrismTestUtil.getPrismContext()); // The value id is null activationValue.setPropertyRealValue(ActivationType.F_ENABLED, true, PrismTestUtil.getPrismContext()); - - ObjectDelta userDelta = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, + + ObjectDelta userDelta = ObjectDelta.createModificationAddContainer(UserType.class, USER_FOO_OID, new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), // We really need ID here. Otherwise it would not be clear to which assignment to add new IdItemPathSegment(123L), new NameItemPathSegment(AssignmentType.F_ACTIVATION)), PrismTestUtil.getPrismContext(), activationValue); - + // WHEN userDelta.applyTo(user); - + // THEN System.out.println("User after delta application:"); System.out.println(user.debugDump()); @@ -1006,24 +1006,24 @@ public void testAddAssignmentActivationDifferentNullIdApplyToObject() throws Exc PrismContainer assignment = user.findContainer(UserType.F_ASSIGNMENT); assertNotNull("No assignment", assignment); assertEquals("Unexpected number of assignment values", 1, assignment.size()); - + // TODO } - + @Test public void testObjectDeltaApplyToAdd() throws Exception { System.out.println("\n\n===[ testObjectDeltaApplyToAdd ]===\n"); // GIVEN PrismObject user = PrismTestUtil.parseObject(USER_JACK_FILE_XML); //Delta - ObjectDelta userDelta = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, + ObjectDelta userDelta = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, UserType.F_LOCALITY, PrismTestUtil.getPrismContext(), "Caribbean"); - + // WHEN userDelta.applyTo(user); - + // THEN - + PrismAsserts.assertPropertyValue(user, UserType.F_LOCALITY, "Caribbean"); user.checkConsistence(); } @@ -1034,112 +1034,112 @@ public void testObjectDeltaApplyToDelete() throws Exception { // GIVEN PrismObject user = PrismTestUtil.parseObject(USER_JACK_FILE_XML); //Delta - ObjectDelta userDelta = ObjectDelta.createModificationDeleteProperty(UserType.class, USER_FOO_OID, + ObjectDelta userDelta = ObjectDelta.createModificationDeleteProperty(UserType.class, USER_FOO_OID, UserType.F_ADDITIONAL_NAMES, PrismTestUtil.getPrismContext(), "Jackie"); - + // WHEN userDelta.applyTo(user); - + // THEN - + PrismAsserts.assertPropertyValue(user, UserType.F_ADDITIONAL_NAMES, "Captain"); user.checkConsistence(); } - + @Test public void testObjectDeltaApplyToReplace() throws Exception { System.out.println("\n\n===[ testObjectDeltaApplyToReplace ]===\n"); // GIVEN PrismObject user = PrismTestUtil.parseObject(USER_JACK_FILE_XML); //Delta - ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_FOO_OID, + ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_FOO_OID, UserType.F_ADDITIONAL_NAMES, PrismTestUtil.getPrismContext(), "Cpt"); - + // WHEN userDelta.applyTo(user); - + // THEN - + PrismAsserts.assertPropertyValue(user, UserType.F_ADDITIONAL_NAMES, "Cpt"); user.checkConsistence(); } - + @Test public void testObjectDeltaApplyToReplaceEmpty() throws Exception { System.out.println("\n\n===[ testObjectDeltaApplyToReplaceEmpty ]===\n"); // GIVEN PrismObject user = PrismTestUtil.parseObject(USER_JACK_FILE_XML); //Delta - ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_FOO_OID, + ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_FOO_OID, UserType.F_ADDITIONAL_NAMES, PrismTestUtil.getPrismContext()); - + // WHEN userDelta.applyTo(user); - + // THEN - + PrismAsserts.assertNoItem(user, UserType.F_ADDITIONAL_NAMES); user.checkConsistence(); } - + @Test public void testObjectDeltaFindItemDeltaModifyProperty() throws Exception { System.out.println("\n\n===[ testObjectDeltaFindItemDeltaModifyProperty ]===\n"); // GIVEN - + ObjectDelta userDelta = createDeltaForFindItem(); ItemPath itemDeltaPath = new ItemPath(UserType.F_GIVEN_NAME); - + // WHEN ItemDelta itemDelta = userDelta.findItemDelta(itemDeltaPath); - + // THEN PrismAsserts.assertInstanceOf(PropertyDelta.class, itemDelta); assertEquals(itemDeltaPath, itemDelta.getPath()); - PrismAsserts.assertPropertyValues("Wrong replace values in "+itemDelta, + PrismAsserts.assertPropertyValues("Wrong replace values in "+itemDelta, ((PropertyDelta)itemDelta).getValuesToReplace(), "Guybrush"); } - + @Test public void testObjectDeltaFindItemDeltaModifyPropertyInContainer() throws Exception { System.out.println("\n\n===[ testObjectDeltaFindItemDeltaModifyPropertyInContainer ]===\n"); // GIVEN ObjectDelta userDelta = createDeltaForFindItem(); System.out.println("Object delta:\n"+userDelta.debugDump()); - + ItemPath itemDeltaPath = new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ENABLED); - + // WHEN ItemDelta itemDelta = userDelta.findItemDelta(itemDeltaPath); - + // THEN System.out.println("Item delta:\n"+(itemDelta==null?"null":itemDelta.debugDump())); PrismAsserts.assertInstanceOf(PropertyDelta.class, itemDelta); assertEquals(itemDeltaPath, itemDelta.getPath()); - PrismAsserts.assertPropertyValues("Wrong add values in "+itemDelta, + PrismAsserts.assertPropertyValues("Wrong add values in "+itemDelta, ((PropertyDelta)itemDelta).getValuesToAdd(), Boolean.TRUE); } private ObjectDelta createDeltaForFindItem() throws SchemaException { - ObjectDelta userDelta = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, + ObjectDelta userDelta = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, UserType.F_LOCALITY, PrismTestUtil.getPrismContext(), "Caribbean"); userDelta.addModificationReplaceProperty(UserType.F_GIVEN_NAME, "Guybrush"); - + ContainerDelta activationDelta = userDelta.createContainerModification(new ItemPath(UserType.F_ACTIVATION)); PrismContainerValue activationCVal = new PrismContainerValue(); activationDelta.addValueToAdd(activationCVal); - + PrismProperty enabledProperty = activationCVal.createProperty(ActivationType.F_ENABLED); enabledProperty.setRealValue(Boolean.TRUE); - + PrismProperty validFromProperty = activationCVal.createProperty(ActivationType.F_VALID_FROM); validFromProperty.setRealValue(XmlTypeConverter.createXMLGregorianCalendar(20016, 5, 16, 19, 8, 33)); userDelta.addModification(activationDelta); - + return userDelta; } - + /** * MODIFY/add + MODIFY/add */ @@ -1147,58 +1147,58 @@ private ObjectDelta createDeltaForFindItem() throws SchemaException { public void testObjectDeltaUnion01Simple() throws Exception { System.out.println("\n\n===[ testObjectDeltaUnion01Simple ]===\n"); // GIVEN - + //Delta - ObjectDelta userDelta1 = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, + ObjectDelta userDelta1 = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, UserType.F_FULL_NAME, PrismTestUtil.getPrismContext(), PrismTestUtil.createPolyString("baz")); - ObjectDelta userDelta2 = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, + ObjectDelta userDelta2 = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, UserType.F_FULL_NAME, PrismTestUtil.getPrismContext(), PrismTestUtil.createPolyString("baz")); - + // WHEN ObjectDelta userDeltaUnion = ObjectDelta.union(userDelta1, userDelta2); - + // THEN assertUnion01Delta(userDeltaUnion); } - + /** * MODIFY/add + MODIFY/add - */ + */ @Test public void testObjectDeltaUnion01Metadata() throws Exception { System.out.println("\n\n===[ testObjectDeltaUnion01Metadata ]===\n"); // GIVEN - - ObjectDelta userDelta1 = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, + + ObjectDelta userDelta1 = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, UserType.F_FULL_NAME, PrismTestUtil.getPrismContext(), PrismTestUtil.createPolyString("baz")); - - - PropertyDelta fullNameDelta2 = PropertyDelta.createDelta(UserType.F_FULL_NAME, UserType.class, + + + PropertyDelta fullNameDelta2 = PropertyDelta.createDelta(UserType.F_FULL_NAME, UserType.class, PrismTestUtil.getPrismContext()); PrismPropertyValue fullNameValue2 = new PrismPropertyValue(PrismTestUtil.createPolyString("baz")); // Set some metadata to spoil usual equals fullNameValue2.setOriginType(OriginType.OUTBOUND); fullNameDelta2.addValueToAdd(fullNameValue2); - ObjectDelta userDelta2 = ObjectDelta.createModifyDelta(USER_FOO_OID, fullNameDelta2, UserType.class, + ObjectDelta userDelta2 = ObjectDelta.createModifyDelta(USER_FOO_OID, fullNameDelta2, UserType.class, PrismTestUtil.getPrismContext()); - + // WHEN ObjectDelta userDeltaUnion = ObjectDelta.union(userDelta1, userDelta2); - + // THEN assertUnion01Delta(userDeltaUnion); } - + private void assertUnion01Delta(ObjectDelta userDeltaUnion) { PropertyDelta fullNameDeltaUnion = getCheckedPropertyDeltaFromUnion(userDeltaUnion); Collection> valuesToAdd = fullNameDeltaUnion.getValuesToAdd(); assertNotNull("No valuesToAdd in fullName delta after union", valuesToAdd); assertEquals("Unexpected size of valuesToAdd in fullName delta after union", 1, valuesToAdd.size()); PrismPropertyValue valueToAdd = valuesToAdd.iterator().next(); - assertEquals("Unexcted value in valuesToAdd in fullName delta after union", + assertEquals("Unexcted value in valuesToAdd in fullName delta after union", PrismTestUtil.createPolyString("baz"), valueToAdd.getValue()); } - + /** * MODIFY/replace + MODIFY/replace */ @@ -1206,26 +1206,26 @@ private void assertUnion01Delta(ObjectDelta userDeltaUnion) { public void testObjectDeltaUnion02() throws Exception { System.out.println("\n\n===[ testObjectDeltaUnion02 ]===\n"); // GIVEN - + //Delta - ObjectDelta userDelta1 = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_FOO_OID, + ObjectDelta userDelta1 = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_FOO_OID, UserType.F_FULL_NAME, PrismTestUtil.getPrismContext()); - ObjectDelta userDelta2 = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_FOO_OID, + ObjectDelta userDelta2 = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_FOO_OID, UserType.F_FULL_NAME, PrismTestUtil.getPrismContext(), PrismTestUtil.createPolyString("baz")); - + // WHEN ObjectDelta userDeltaUnion = ObjectDelta.union(userDelta1, userDelta2); - + // THEN PropertyDelta fullNameDeltaUnion = getCheckedPropertyDeltaFromUnion(userDeltaUnion); Collection> valuesToReplace = fullNameDeltaUnion.getValuesToReplace(); assertNotNull("No valuesToReplace in fullName delta after union", valuesToReplace); assertEquals("Unexpected size of valuesToReplace in fullName delta after union", 1, valuesToReplace.size()); PrismPropertyValue valueToReplace = valuesToReplace.iterator().next(); - assertEquals("Unexcted value in valueToReplace in fullName delta after union", + assertEquals("Unexcted value in valueToReplace in fullName delta after union", PrismTestUtil.createPolyString("baz"), valueToReplace.getValue()); } - + /** * MODIFY/replace + MODIFY/add */ @@ -1233,26 +1233,26 @@ public void testObjectDeltaUnion02() throws Exception { public void testObjectDeltaUnion03() throws Exception { System.out.println("\n\n===[ testObjectDeltaUnion03 ]===\n"); // GIVEN - + //Delta - ObjectDelta userDelta1 = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_FOO_OID, + ObjectDelta userDelta1 = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_FOO_OID, UserType.F_FULL_NAME, PrismTestUtil.getPrismContext()); - ObjectDelta userDelta2 = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, + ObjectDelta userDelta2 = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, UserType.F_FULL_NAME, PrismTestUtil.getPrismContext(), PrismTestUtil.createPolyString("baz")); - + // WHEN ObjectDelta userDeltaUnion = ObjectDelta.union(userDelta1, userDelta2); - + // THEN PropertyDelta fullNameDeltaUnion = getCheckedPropertyDeltaFromUnion(userDeltaUnion); Collection> valuesToReplace = fullNameDeltaUnion.getValuesToReplace(); assertNotNull("No valuesToReplace in fullName delta after union", valuesToReplace); assertEquals("Unexpected size of valuesToReplace in fullName delta after union", 1, valuesToReplace.size()); PrismPropertyValue valueToReplace = valuesToReplace.iterator().next(); - assertEquals("Unexcted value in valueToReplace in fullName delta after union", + assertEquals("Unexcted value in valueToReplace in fullName delta after union", PrismTestUtil.createPolyString("baz"), valueToReplace.getValue()); } - + private PropertyDelta getCheckedPropertyDeltaFromUnion(ObjectDelta userDeltaUnion) { userDeltaUnion.checkConsistence(); assertEquals("Wrong OID", USER_FOO_OID, userDeltaUnion.getOid()); @@ -1267,15 +1267,15 @@ private PropertyDelta getCheckedPropertyDeltaFromUnion(ObjectDelta userDelta1 = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, + + ObjectDelta userDelta1 = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, UserType.F_ADDITIONAL_NAMES, PrismTestUtil.getPrismContext(), PrismTestUtil.createPolyString("foo")); - ObjectDelta userDelta2 = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, + ObjectDelta userDelta2 = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, UserType.F_ADDITIONAL_NAMES, PrismTestUtil.getPrismContext(), PrismTestUtil.createPolyString("bar")); - + // WHEN ObjectDelta userDeltaSum = ObjectDelta.summarize(userDelta1, userDelta2); - + // THEN assertEquals("Wrong OID", USER_FOO_OID, userDeltaSum.getOid()); PrismAsserts.assertIsModify(userDeltaSum); @@ -1284,20 +1284,20 @@ public void testObjectDeltaSummarizeModifyAdd() throws Exception { assertNotNull("No additionalNames delta after summarize", namesDeltaUnion); PrismAsserts.assertAdd(namesDeltaUnion, PrismTestUtil.createPolyString("foo"), PrismTestUtil.createPolyString("bar")); } - + @Test public void testObjectDeltaSummarizeModifyReplace() throws Exception { System.out.println("\n\n===[ testObjectDeltaSummarizeModifyReplace ]===\n"); // GIVEN - - ObjectDelta userDelta1 = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_FOO_OID, + + ObjectDelta userDelta1 = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_FOO_OID, UserType.F_FULL_NAME, PrismTestUtil.getPrismContext(), PrismTestUtil.createPolyString("foo")); - ObjectDelta userDelta2 = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_FOO_OID, + ObjectDelta userDelta2 = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_FOO_OID, UserType.F_FULL_NAME, PrismTestUtil.getPrismContext(), PrismTestUtil.createPolyString("bar")); - + // WHEN ObjectDelta userDeltaSum = ObjectDelta.summarize(userDelta1, userDelta2); - + // THEN assertEquals("Wrong OID", USER_FOO_OID, userDeltaSum.getOid()); PrismAsserts.assertIsModify(userDeltaSum); @@ -1306,22 +1306,22 @@ public void testObjectDeltaSummarizeModifyReplace() throws Exception { assertNotNull("No fullName delta after summarize", fullNameDeltaUnion); PrismAsserts.assertReplace(fullNameDeltaUnion, PrismTestUtil.createPolyString("bar")); } - + @Test public void testObjectDeltaSummarizeModifyMix() throws Exception { System.out.println("\n\n===[ testObjectDeltaSummarizeModifyMix ]===\n"); // GIVEN - - ObjectDelta userDelta1 = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, + + ObjectDelta userDelta1 = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, UserType.F_ADDITIONAL_NAMES, PrismTestUtil.getPrismContext(), PrismTestUtil.createPolyString("baz")); - ObjectDelta userDelta2 = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_FOO_OID, + ObjectDelta userDelta2 = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_FOO_OID, UserType.F_ADDITIONAL_NAMES, PrismTestUtil.getPrismContext(), PrismTestUtil.createPolyString("foo")); - ObjectDelta userDelta3 = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, + ObjectDelta userDelta3 = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, UserType.F_ADDITIONAL_NAMES, PrismTestUtil.getPrismContext(), PrismTestUtil.createPolyString("bar")); - + // WHEN ObjectDelta userDeltaSum = ObjectDelta.summarize(userDelta1, userDelta2, userDelta3); - + // THEN assertEquals("Wrong OID", USER_FOO_OID, userDeltaSum.getOid()); PrismAsserts.assertIsModify(userDeltaSum); @@ -1330,30 +1330,30 @@ public void testObjectDeltaSummarizeModifyMix() throws Exception { assertNotNull("No additionalNames delta after summarize", namesDeltaUnion); PrismAsserts.assertReplace(namesDeltaUnion, PrismTestUtil.createPolyString("foo"), PrismTestUtil.createPolyString("bar")); } - + @Test public void testObjectDeltaSummarizeAddModifyMix() throws Exception { System.out.println("\n\n===[ testObjectDeltaSummarizeAddModifyMix ]===\n"); // GIVEN - + PrismObject user = createUser(); ObjectDelta userDelta0 = ObjectDelta.createAddDelta(user); - ObjectDelta userDelta1 = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, + ObjectDelta userDelta1 = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, UserType.F_ADDITIONAL_NAMES, PrismTestUtil.getPrismContext(), PrismTestUtil.createPolyString("baz")); - ObjectDelta userDelta2 = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_FOO_OID, + ObjectDelta userDelta2 = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_FOO_OID, UserType.F_ADDITIONAL_NAMES, PrismTestUtil.getPrismContext(), PrismTestUtil.createPolyString("foo")); - ObjectDelta userDelta3 = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, + ObjectDelta userDelta3 = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, UserType.F_ADDITIONAL_NAMES, PrismTestUtil.getPrismContext(), PrismTestUtil.createPolyString("bar")); - + // WHEN ObjectDelta userDeltaSum = ObjectDelta.summarize(userDelta0, userDelta1, userDelta2, userDelta3); - + // THEN assertEquals("Wrong OID", USER_FOO_OID, userDeltaSum.getOid()); PrismAsserts.assertIsAdd(userDeltaSum); PrismObject userSum = userDeltaSum.getObjectToAdd(); assert user != userSum : "User was not clonned"; - PrismAsserts.assertPropertyValue(userSum, UserType.F_ADDITIONAL_NAMES, + PrismAsserts.assertPropertyValue(userSum, UserType.F_ADDITIONAL_NAMES, PrismTestUtil.createPolyString("foo"), PrismTestUtil.createPolyString("bar")); // TODO } @@ -1394,12 +1394,12 @@ public void testObjectDeltaSummarizeAddModifySameRefValues() throws Exception { public void testDeltaComplex() throws Exception { System.out.println("\n\n===[ testDeltaComplex ]===\n"); // GIVEN - - ObjectDelta delta = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, + + ObjectDelta delta = ObjectDelta.createModificationAddProperty(UserType.class, USER_FOO_OID, UserType.F_FULL_NAME, PrismTestUtil.getPrismContext(), PrismTestUtil.createPolyString("Foo Bar")); - + PrismObjectDefinition userTypeDefinition = getUserTypeDefinition(); - + PrismContainerDefinition activationDefinition = userTypeDefinition.findContainerDefinition(UserType.F_ACTIVATION); PrismContainer activationContainer = activationDefinition.instantiate(); PrismPropertyDefinition enabledDef = activationDefinition.findPropertyDefinition(ActivationType.F_ENABLED); @@ -1407,10 +1407,10 @@ public void testDeltaComplex() throws Exception { enabledProperty.setRealValue(true); activationContainer.add(enabledProperty); delta.addModificationDeleteContainer(UserType.F_ACTIVATION, activationContainer.getValue().clone()); - + PrismContainerDefinition assDef = userTypeDefinition.findContainerDefinition(UserType.F_ASSIGNMENT); PrismPropertyDefinition descDef = assDef.findPropertyDefinition(AssignmentType.F_DESCRIPTION); - + PrismContainerValue assVal1 = new PrismContainerValue(PrismTestUtil.getPrismContext()); assVal1.setId(111L); PrismProperty descProp1 = descDef.instantiate(); @@ -1422,15 +1422,15 @@ public void testDeltaComplex() throws Exception { PrismProperty descProp2 = descDef.instantiate(); descProp2.setRealValue("desc 2"); assVal2.add(descProp2); - + delta.addModificationAddContainer(UserType.F_ASSIGNMENT, assVal1, assVal2); - + System.out.println("Delta:"); System.out.println(delta.debugDump()); - + // WHEN, THEN PrismInternalTestUtil.assertVisitor(delta, 14); - + PrismInternalTestUtil.assertPathVisitor(delta, new ItemPath(UserType.F_FULL_NAME), true, 2); PrismInternalTestUtil.assertPathVisitor(delta, new ItemPath(UserType.F_ACTIVATION), true, 4); PrismInternalTestUtil.assertPathVisitor(delta, new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ENABLED), true, 2); @@ -1438,7 +1438,7 @@ public void testDeltaComplex() throws Exception { PrismInternalTestUtil.assertPathVisitor(delta, new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), IdItemPathSegment.WILDCARD), true, 6); - + PrismInternalTestUtil.assertPathVisitor(delta, new ItemPath(UserType.F_FULL_NAME), false, 1); PrismInternalTestUtil.assertPathVisitor(delta, new ItemPath(UserType.F_ACTIVATION), false, 1); PrismInternalTestUtil.assertPathVisitor(delta, new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ENABLED), false, 1); @@ -1447,25 +1447,25 @@ public void testDeltaComplex() throws Exception { new NameItemPathSegment(UserType.F_ASSIGNMENT), IdItemPathSegment.WILDCARD), false, 2); } - - + + @Test public void testPropertyDeltaNarrow01() throws Exception { System.out.println("\n\n===[ testPropertyDeltaNarrow01 ]===\n"); - + // GIVEN - PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, + PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); PropertyDelta delta = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); delta.addValueToAdd(new PrismPropertyValue("blabla")); delta.addValueToAdd(new PrismPropertyValue("bubu")); - + PrismObject user = createUserNoAssignment(); - + // WHEN PropertyDelta narrowedDelta = delta.narrow(user); - + // THEN System.out.println("Narrowed delta:"); System.out.println(narrowedDelta.debugDump()); @@ -1474,25 +1474,25 @@ public void testPropertyDeltaNarrow01() throws Exception { PrismAsserts.assertAdd(narrowedDelta, "blabla", "bubu"); PrismAsserts.assertNoDelete(narrowedDelta); } - + @Test public void testPropertyDeltaNarrow02() throws Exception { System.out.println("\n\n===[ testPropertyDeltaNarrow02 ]===\n"); - + // GIVEN - PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, + PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); PropertyDelta delta = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); delta.addValueToAdd(new PrismPropertyValue("blabla")); delta.addValueToAdd(new PrismPropertyValue("bubu")); - + PrismObject user = createUserNoAssignment(); user.setPropertyRealValue(UserType.F_DESCRIPTION, "bubu"); - + // WHEN PropertyDelta narrowedDelta = delta.narrow(user); - + // THEN System.out.println("Narrowed delta:"); System.out.println(narrowedDelta.debugDump()); @@ -1505,20 +1505,20 @@ public void testPropertyDeltaNarrow02() throws Exception { @Test public void testPropertyDeltaNarrow03() throws Exception { System.out.println("\n\n===[ testPropertyDeltaNarrow03 ]===\n"); - + // GIVEN - PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, + PrismPropertyDefinition propertyDefinition = new PrismPropertyDefinitionImpl(UserType.F_DESCRIPTION, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); PropertyDelta delta = new PropertyDelta(propertyDefinition, PrismTestUtil.getPrismContext()); delta.addValueToAdd(new PrismPropertyValue("bubu")); - + PrismObject user = createUserNoAssignment(); user.setPropertyRealValue(UserType.F_DESCRIPTION, "bubu"); - + // WHEN PropertyDelta narrowedDelta = delta.narrow(user); - + // THEN System.out.println("Narrowed delta:"); System.out.println(narrowedDelta.debugDump()); @@ -1529,19 +1529,19 @@ public void testPropertyDeltaNarrow03() throws Exception { assertTrue("Delta not empty", narrowedDelta.isEmpty()); } - + private PrismObject createUser() throws SchemaException { PrismObject user = createUserNoAssignment(); - + PrismContainer assignment = user.findOrCreateContainer(UserType.F_ASSIGNMENT); PrismContainerValue assignmentValue = assignment.createNewValue(); assignmentValue.setId(123L); assignmentValue.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "jamalalicha patlama paprtala", PrismTestUtil.getPrismContext()); - + return user; } - + private PrismObject createUserNoAssignment() throws SchemaException { PrismObjectDefinition userDef = getUserTypeDefinition(); @@ -1550,7 +1550,7 @@ private PrismObject createUserNoAssignment() throws SchemaException { user.setPropertyRealValue(UserType.F_NAME, PrismTestUtil.createPolyString("foo")); PrismProperty anamesProp = user.findOrCreateProperty(UserType.F_ADDITIONAL_NAMES); anamesProp.addRealValue(PrismTestUtil.createPolyString("foobar")); - + return user; } diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestDiff.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestDiff.java index b781be23eae..b843bb8a212 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestDiff.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestDiff.java @@ -47,79 +47,79 @@ * */ public class TestDiff { - + @BeforeSuite public void setupDebug() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(DEFAULT_NAMESPACE_PREFIX); PrismTestUtil.resetPrismContext(new PrismInternalTestUtil()); } - + @Test public void testUserSimplePropertyDiffNoChange() throws Exception { System.out.println("\n\n===[ testUserSimplePropertyDiffNoChange ]===\n"); // GIVEN PrismObjectDefinition userDef = getUserTypeDefinition(); - + PrismObject user1 = userDef.instantiate(); user1.setOid(USER_JACK_OID); user1.setPropertyRealValue(UserType.F_NAME, PrismTestUtil.createPolyString("test name")); - + PrismObject user2 = userDef.instantiate(); user2.setOid(USER_JACK_OID); user2.setPropertyRealValue(UserType.F_NAME, PrismTestUtil.createPolyString("test name")); - + // WHEN ObjectDelta delta = user1.diff(user2); - + // THEN assertNotNull(delta); assertEquals("Unexpected number of midifications", 0, delta.getModifications().size()); assertEquals("Wrong OID", USER_JACK_OID, delta.getOid()); delta.checkConsistence(); } - + @Test public void testPropertySimplePropertyDiffNoChange() throws Exception { System.out.println("\n\n===[ testPropertySimplePropertyDiffNoChange ]===\n"); // GIVEN PrismObjectDefinition userDef = getUserTypeDefinition(); - + PrismObject user1 = userDef.instantiate(); user1.setOid(USER_JACK_OID); user1.setPropertyRealValue(UserType.F_NAME, PrismTestUtil.createPolyString("test name")); PrismProperty user1NameProp = user1.findProperty(UserType.F_NAME); - + PrismObject user2 = userDef.instantiate(); user2.setOid(USER_JACK_OID); user2.setPropertyRealValue(UserType.F_NAME, PrismTestUtil.createPolyString("test name")); PrismProperty user2NameProp = user2.findProperty(UserType.F_NAME); - + // WHEN PropertyDelta delta = user1NameProp.diff(user2NameProp); - + // THEN assertNull(delta); } - + @Test public void testPropertySimplePropertyDiffNoChangeStatic() throws Exception { System.out.println("\n\n===[ testPropertySimplePropertyDiffNoChangeStatic ]===\n"); // GIVEN PrismObjectDefinition userDef = getUserTypeDefinition(); - + PrismObject user1 = userDef.instantiate(); user1.setOid(USER_JACK_OID); user1.setPropertyRealValue(UserType.F_NAME, PrismTestUtil.createPolyString("test name")); PrismProperty user1NameProp = user1.findProperty(UserType.F_NAME); - + PrismObject user2 = userDef.instantiate(); user2.setOid(USER_JACK_OID); user2.setPropertyRealValue(UserType.F_NAME, PrismTestUtil.createPolyString("test name")); PrismProperty user2NameProp = user2.findProperty(UserType.F_NAME); - + // WHEN PropertyDelta delta = PrismProperty.diff(user1NameProp, user2NameProp); - + // THEN assertNull(delta); } @@ -129,18 +129,18 @@ public void testUserSimplePropertyDiffReplace() throws Exception { System.out.println("\n\n===[ testUserSimplePropertyDiffReplace ]===\n"); // GIVEN PrismObjectDefinition userDef = getUserTypeDefinition(); - + PrismObject user1 = userDef.instantiate(); user1.setOid(USER_JACK_OID); user1.setPropertyRealValue(UserType.F_NAME, PrismTestUtil.createPolyString("test name")); - + PrismObject user2 = userDef.instantiate(); user2.setOid(USER_JACK_OID); user2.setPropertyRealValue(UserType.F_NAME, PrismTestUtil.createPolyString("other name")); - + // WHEN ObjectDelta delta = user1.diff(user2); - + // THEN assertNotNull(delta); System.out.println(delta.debugDump()); @@ -155,46 +155,46 @@ public void testPropertyUserSimplePropertyDiffReplace() throws Exception { System.out.println("\n\n===[ testPropertyUserSimplePropertyDiffReplace ]===\n"); // GIVEN PrismObjectDefinition userDef = getUserTypeDefinition(); - + PrismObject user1 = userDef.instantiate(); user1.setOid(USER_JACK_OID); user1.setPropertyRealValue(UserType.F_NAME, PrismTestUtil.createPolyString("test name")); PrismProperty user1NameProp = user1.findProperty(UserType.F_NAME); - + PrismObject user2 = userDef.instantiate(); user2.setOid(USER_JACK_OID); user2.setPropertyRealValue(UserType.F_NAME, PrismTestUtil.createPolyString("other name")); PrismProperty user2NameProp = user2.findProperty(UserType.F_NAME); - + // WHEN PropertyDelta delta = user1NameProp.diff(user2NameProp); - + // THEN assertNotNull(delta); System.out.println(delta.debugDump()); PrismAsserts.assertReplace(delta, PrismTestUtil.createPolyString("other name")); delta.checkConsistence(); } - + @Test public void testPropertyUserSimplePropertyDiffReplaceStatic() throws Exception { System.out.println("\n\n===[ testPropertyUserSimplePropertyDiffReplaceStatic ]===\n"); // GIVEN PrismObjectDefinition userDef = getUserTypeDefinition(); - + PrismObject user1 = userDef.instantiate(); user1.setOid(USER_JACK_OID); user1.setPropertyRealValue(UserType.F_NAME, PrismTestUtil.createPolyString("test name")); PrismProperty user1NameProp = user1.findProperty(UserType.F_NAME); - + PrismObject user2 = userDef.instantiate(); user2.setOid(USER_JACK_OID); user2.setPropertyRealValue(UserType.F_NAME, PrismTestUtil.createPolyString("other name")); PrismProperty user2NameProp = user2.findProperty(UserType.F_NAME); - + // WHEN PropertyDelta delta = PrismProperty.diff(user1NameProp, user2NameProp); - + // THEN assertNotNull(delta); System.out.println(delta.debugDump()); @@ -205,80 +205,80 @@ public void testPropertyUserSimplePropertyDiffReplaceStatic() throws Exception { @Test public void testUserSimpleDiffMultiNoChange() throws Exception { System.out.println("\n\n===[ testUserSimpleDiffMultiNoChange ]===\n"); - + // GIVEN PrismObjectDefinition userDef = getUserTypeDefinition(); - + PrismObject user1 = userDef.instantiate(); user1.setOid(USER_JACK_OID); PrismProperty anamesProp1 = user1.findOrCreateProperty(UserType.F_ADDITIONAL_NAMES); anamesProp1.addRealValue("foo"); anamesProp1.addRealValue("bar"); - + PrismObject user2 = userDef.instantiate(); user2.setOid(USER_JACK_OID); PrismProperty anamesProp2 = user2.findOrCreateProperty(UserType.F_ADDITIONAL_NAMES); anamesProp2.addRealValue("foo"); anamesProp2.addRealValue("bar"); - + // WHEN ObjectDelta delta = user1.diff(user2); - + // THEN assertNotNull(delta); assertEquals("Unexpected number of midifications", 0, delta.getModifications().size()); assertEquals("Wrong OID", USER_JACK_OID, delta.getOid()); delta.checkConsistence(); } - + @Test public void testPropertyUserSimpleDiffMultiNoChange() throws Exception { System.out.println("\n\n===[ testPropertyUserSimpleDiffMultiNoChange ]===\n"); - + // GIVEN PrismObjectDefinition userDef = getUserTypeDefinition(); - + PrismObject user1 = userDef.instantiate(); user1.setOid(USER_JACK_OID); PrismProperty additionalNamesProp1 = user1.findOrCreateProperty(UserType.F_ADDITIONAL_NAMES); additionalNamesProp1.addRealValue("foo"); additionalNamesProp1.addRealValue("bar"); - + PrismObject user2 = userDef.instantiate(); user2.setOid(USER_JACK_OID); PrismProperty additionalNamesProp2 = user2.findOrCreateProperty(UserType.F_ADDITIONAL_NAMES); additionalNamesProp2.addRealValue("foo"); additionalNamesProp2.addRealValue("bar"); - + // WHEN PropertyDelta delta = additionalNamesProp1.diff(additionalNamesProp2); - + // THEN assertNull(delta); } - + @Test public void testPropertyUserSimpleDiffMultiNoChangeStatic() throws Exception { System.out.println("\n\n===[ testPropertyUserSimpleDiffMultiNoChangeStatic ]===\n"); - + // GIVEN PrismObjectDefinition userDef = getUserTypeDefinition(); - + PrismObject user1 = userDef.instantiate(); user1.setOid(USER_JACK_OID); PrismProperty additionalNamesProp1 = user1.findOrCreateProperty(UserType.F_ADDITIONAL_NAMES); additionalNamesProp1.addRealValue("foo"); additionalNamesProp1.addRealValue("bar"); - + PrismObject user2 = userDef.instantiate(); user2.setOid(USER_JACK_OID); PrismProperty additionalNamesProp2 = user2.findOrCreateProperty(UserType.F_ADDITIONAL_NAMES); additionalNamesProp2.addRealValue("foo"); additionalNamesProp2.addRealValue("bar"); - + // WHEN PropertyDelta delta = PrismProperty.diff(additionalNamesProp1, additionalNamesProp2); - + // THEN assertNull(delta); } @@ -286,26 +286,26 @@ public void testPropertyUserSimpleDiffMultiNoChangeStatic() throws Exception { @Test public void testUserSimpleDiffMultiAdd() throws Exception { System.out.println("\n\n===[ testUserSimpleDiffMulti ]===\n"); - + // GIVEN PrismObjectDefinition userDef = getUserTypeDefinition(); - + PrismObject user1 = userDef.instantiate(); user1.setOid(USER_JACK_OID); PrismProperty anamesProp1 = user1.findOrCreateProperty(UserType.F_ADDITIONAL_NAMES); anamesProp1.addRealValue("foo"); anamesProp1.addRealValue("bar"); - + PrismObject user2 = userDef.instantiate(); user2.setOid(USER_JACK_OID); PrismProperty anamesProp2 = user2.findOrCreateProperty(UserType.F_ADDITIONAL_NAMES); anamesProp2.addRealValue("foo"); anamesProp2.addRealValue("bar"); anamesProp2.addRealValue("baz"); - + // WHEN ObjectDelta delta = user1.diff(user2); - + // THEN assertNotNull(delta); System.out.println(delta.debugDump()); @@ -314,106 +314,106 @@ public void testUserSimpleDiffMultiAdd() throws Exception { assertEquals("Wrong OID", USER_JACK_OID, delta.getOid()); delta.checkConsistence(); } - + @Test public void testPropertyUserSimpleDiffMultiAdd() throws Exception { System.out.println("\n\n===[ testPropertyUserSimpleDiffMultiAdd ]===\n"); - + // GIVEN PrismObjectDefinition userDef = getUserTypeDefinition(); - + PrismObject user1 = userDef.instantiate(); user1.setOid(USER_JACK_OID); PrismProperty additionalNamesProp1 = user1.findOrCreateProperty(UserType.F_ADDITIONAL_NAMES); additionalNamesProp1.addRealValue("foo"); additionalNamesProp1.addRealValue("bar"); - + PrismObject user2 = userDef.instantiate(); user2.setOid(USER_JACK_OID); PrismProperty additionalNamesProp2 = user2.findOrCreateProperty(UserType.F_ADDITIONAL_NAMES); additionalNamesProp2.addRealValue("foo"); additionalNamesProp2.addRealValue("bar"); additionalNamesProp2.addRealValue("baz"); - + // WHEN PropertyDelta delta = additionalNamesProp1.diff(additionalNamesProp2); - + // THEN assertNotNull(delta); System.out.println(delta.debugDump()); PrismAsserts.assertAdd(delta, "baz"); delta.checkConsistence(); } - + @Test public void testPropertyUserSimpleDiffMultiAddStatic() throws Exception { System.out.println("\n\n===[ testPropertyUserSimpleDiffMultiAddStatic ]===\n"); - + // GIVEN PrismObjectDefinition userDef = getUserTypeDefinition(); - + PrismObject user1 = userDef.instantiate(); user1.setOid(USER_JACK_OID); PrismProperty additionalNamesProp1 = user1.findOrCreateProperty(UserType.F_ADDITIONAL_NAMES); additionalNamesProp1.addRealValue("foo"); additionalNamesProp1.addRealValue("bar"); - + PrismObject user2 = userDef.instantiate(); user2.setOid(USER_JACK_OID); PrismProperty additionalNamesProp2 = user2.findOrCreateProperty(UserType.F_ADDITIONAL_NAMES); additionalNamesProp2.addRealValue("foo"); additionalNamesProp2.addRealValue("bar"); additionalNamesProp2.addRealValue("baz"); - + // WHEN PropertyDelta delta = PrismProperty.diff(additionalNamesProp1, additionalNamesProp2); - + // THEN assertNotNull(delta); System.out.println(delta.debugDump()); PrismAsserts.assertAdd(delta, "baz"); delta.checkConsistence(); } - + @Test public void testPropertyUserSimpleDiffMultiAddStaticNull1() throws Exception { System.out.println("\n\n===[ testPropertyUserSimpleDiffMultiAddStaticNull1 ]===\n"); - + // GIVEN PrismObjectDefinition userDef = getUserTypeDefinition(); - + PrismObject user2 = userDef.instantiate(); user2.setOid(USER_JACK_OID); PrismProperty additionalNamesProp2 = user2.findOrCreateProperty(UserType.F_ADDITIONAL_NAMES); additionalNamesProp2.addRealValue("foo"); additionalNamesProp2.addRealValue("bar"); - + // WHEN PropertyDelta delta = PrismProperty.diff(null, additionalNamesProp2); - + // THEN assertNotNull(delta); System.out.println(delta.debugDump()); PrismAsserts.assertAdd(delta, "foo", "bar"); delta.checkConsistence(); } - + @Test public void testPropertyUserSimpleDiffMultiAddStaticNull2() throws Exception { System.out.println("\n\n===[ testPropertyUserSimpleDiffMultiAddStaticNull2 ]===\n"); - + // GIVEN PrismObjectDefinition userDef = getUserTypeDefinition(); - + PrismObject user2 = userDef.instantiate(); user2.setOid(USER_JACK_OID); PrismProperty additionalNamesProp1 = user2.findOrCreateProperty(UserType.F_ADDITIONAL_NAMES); additionalNamesProp1.addRealValue("bar"); additionalNamesProp1.addRealValue("baz"); - + // WHEN PropertyDelta delta = PrismProperty.diff(additionalNamesProp1, null); - + // THEN assertNotNull(delta); System.out.println(delta.debugDump()); @@ -424,22 +424,22 @@ public void testPropertyUserSimpleDiffMultiAddStaticNull2() throws Exception { @Test public void testContainerSimpleDiffModificationsNoChange() throws Exception { System.out.println("\n\n===[ testContainerSimpleDiffModificationsNoChange ]===\n"); - + // GIVEN PrismObjectDefinition userDef = getUserTypeDefinition(); PrismContainerDefinition assignmentContDef = userDef.findContainerDefinition(UserType.F_ASSIGNMENT); - + PrismContainer ass1 = assignmentContDef.instantiate(); PrismContainerValue ass1cval = ass1.createNewValue(); ass1cval.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "blah blah", PrismTestUtil.getPrismContext()); - + PrismContainer ass2 = assignmentContDef.instantiate(); PrismContainerValue ass2cval = ass2.createNewValue(); ass2cval.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "blah blah", PrismTestUtil.getPrismContext()); - + // WHEN Collection modifications = ass1.diffModifications(ass2); - + // THEN assertNotNull(modifications); System.out.println(DebugUtil.debugDump(modifications)); @@ -450,30 +450,30 @@ public void testContainerSimpleDiffModificationsNoChange() throws Exception { @Test public void testContainerDiffModificationsDesciption() throws Exception { System.out.println("\n\n===[ testContainerDiffModificationsDesciption ]===\n"); - + // GIVEN PrismObjectDefinition userDef = getUserTypeDefinition(); PrismContainerDefinition assignmentContDef = userDef.findContainerDefinition(UserType.F_ASSIGNMENT); - + PrismContainer ass1 = assignmentContDef.instantiate(); PrismContainerValue ass1cval = ass1.createNewValue(); ass1cval.setId(1L); ass1cval.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "blah blah", PrismTestUtil.getPrismContext()); - + PrismContainer ass2 = assignmentContDef.instantiate(); PrismContainerValue ass2cval = ass2.createNewValue(); ass2cval.setId(1L); ass2cval.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "chamalalia patlama paprtala", PrismTestUtil.getPrismContext()); - + // WHEN Collection modifications = ass1.diffModifications(ass2); - + // THEN assertNotNull(modifications); System.out.println(DebugUtil.debugDump(modifications)); assertEquals("Unexpected number of midifications", 1, modifications.size()); PrismAsserts.assertPropertyReplace( - modifications, + modifications, new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(1L), @@ -481,32 +481,32 @@ public void testContainerDiffModificationsDesciption() throws Exception { "chamalalia patlama paprtala"); ItemDelta.checkConsistence(modifications); } - + @Test public void testContainerValueDiffDesciptionNoPath() throws Exception { System.out.println("\n\n===[ testContainerValueDiffDesciptionNoPath ]===\n"); - + // GIVEN PrismObjectDefinition userDef = getUserTypeDefinition(); PrismContainerDefinition assignmentContDef = userDef.findContainerDefinition(UserType.F_ASSIGNMENT); - + PrismContainer ass1 = assignmentContDef.instantiate(); PrismContainerValue ass1cval = ass1.createNewValue(); ass1cval.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "blah blah", PrismTestUtil.getPrismContext()); - + PrismContainer ass2 = assignmentContDef.instantiate(); PrismContainerValue ass2cval = ass2.createNewValue(); ass2cval.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "chamalalia patlama paprtala", PrismTestUtil.getPrismContext()); - + // WHEN Collection modifications = ass1cval.diff(ass2cval); - + // THEN assertNotNull(modifications); System.out.println(DebugUtil.debugDump(modifications)); assertEquals("Unexpected number of midifications", 1, modifications.size()); PrismAsserts.assertPropertyReplace( - modifications, + modifications, new ItemPath(UserType.F_ASSIGNMENT, AssignmentType.F_DESCRIPTION), "chamalalia patlama paprtala"); ItemDelta.checkConsistence(modifications); @@ -515,32 +515,32 @@ public void testContainerValueDiffDesciptionNoPath() throws Exception { // @Test // public void testContainerValueDiffDesciptionPath() throws Exception { // System.out.println("\n\n===[ testContainerValueDiffDesciptionPath ]===\n"); -// +// // // GIVEN // PrismObjectDefinition userDef = getUserTypeDefinition(); // PrismContainerDefinition assignmentContDef = userDef.findContainerDefinition(UserType.F_ASSIGNMENT); -// +// // PrismContainer ass1 = assignmentContDef.instantiate(); // PrismContainerValue ass1cval = ass1.createNewValue(); // ass1cval.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "blah blah"); -// +// // PrismContainer ass2 = assignmentContDef.instantiate(); // PrismContainerValue ass2cval = ass2.createNewValue(); // ass2cval.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "chamalalia patlama paprtala"); -// +// // ItemPath pathPrefix = new ItemPath( // new NameItemPathSegment(UserType.F_ASSIGNMENT), // new IdItemPathSegment("1")); -// +// // // WHEN // Collection modifications = ass1cval.diff(ass2cval, pathPrefix, true, false); -// +// // // THEN // assertNotNull(modifications); // System.out.println(DebugUtil.debugDump(modifications)); // assertEquals("Unexpected number of midifications", 1, modifications.size()); // PrismAsserts.assertPropertyReplace( -// modifications, +// modifications, // new ItemPath( // new NameItemPathSegment(UserType.F_ASSIGNMENT), // new IdItemPathSegment("1"), diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestExtraSchema.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestExtraSchema.java index 5fd402e1a1f..df26a2134c6 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestExtraSchema.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestExtraSchema.java @@ -48,14 +48,14 @@ import com.evolveum.midpoint.util.exception.SchemaException; public class TestExtraSchema { - + public static final String NS_USER_2_EXT = "http://example.com/xml/ns/user-2-extension"; - + private static final QName USER_EXTENSION_TYPE_QNAME = new QName(NS_USER_EXT,"UserExtensionType"); private static final QName USER_2_EXTENSION_TYPE_QNAME = new QName(NS_USER_2_EXT,"User2ExtensionType"); private static final QName USER_EXT_2_ELEMENT = new QName(NS_USER_2_EXT, "ext2"); - + /** * Test is extra schema can be loaded to the schema registry and whether the file compliant to that * schema can be validated. @@ -63,7 +63,7 @@ public class TestExtraSchema { @Test public void testExtraSchema() throws SAXException, IOException, SchemaException { System.out.println("===[ testExtraSchema ]==="); - + Document dataDoc = DOMUtil.parseFile(new File(COMMON_DIR_PATH, "root-foo.xml")); PrismContext context = constructPrismContext(); @@ -73,7 +73,7 @@ public void testExtraSchema() throws SAXException, IOException, SchemaException reg.initialize(); Schema javaxSchema = reg.getJavaxSchema(); assertNotNull(javaxSchema); - + Validator validator = javaxSchema.newValidator(); DOMResult validationResult = new DOMResult(); validator.validate(new DOMSource(dataDoc),validationResult); @@ -83,49 +83,49 @@ public void testExtraSchema() throws SAXException, IOException, SchemaException /** * Test if a schema directory can be loaded to the schema registry. This contains definition of - * user extension, therefore check if it is applied to the user definition. + * user extension, therefore check if it is applied to the user definition. */ @Test public void testUserExtensionSchemaLoad() throws SAXException, IOException, SchemaException { System.out.println("===[ testUserExtensionSchemaLoad ]==="); - + PrismContext context = constructPrismContext(); SchemaRegistryImpl reg = (SchemaRegistryImpl) context.getSchemaRegistry(); reg.registerPrismSchemasFromDirectory(EXTRA_SCHEMA_DIR); context.initialize(); System.out.println("Initialized registry"); System.out.println(reg.debugDump()); - + // Try midpoint schemas by parsing a XML file PrismSchema schema = reg.getSchema(NS_FOO); System.out.println("Parsed foo schema:"); System.out.println(schema.debugDump()); - + // TODO: assert user schema = reg.getSchema(NS_USER_EXT); System.out.println("Parsed user ext schema:"); System.out.println(schema.debugDump()); - + ComplexTypeDefinition userExtComplexType = schema.findComplexTypeDefinition(USER_EXTENSION_TYPE_QNAME); assertEquals("Extension type ref does not match", USER_TYPE_QNAME, userExtComplexType.getExtensionForType()); - + } - + @Test public void testUserExtensionSchemaParseUser() throws SAXException, IOException, SchemaException { System.out.println("===[ testUserExtensionSchemaParseUser ]==="); Document dataDoc = DOMUtil.parseFile(USER_JACK_FILE_XML); - + PrismContext context = constructPrismContext(); SchemaRegistryImpl reg = (SchemaRegistryImpl) context.getSchemaRegistry(); reg.registerPrismSchemasFromDirectory(EXTRA_SCHEMA_DIR); context.initialize(); - + // Parsing user PrismObject user = context.parserFor(DOMUtil.getFirstChildElement(dataDoc)).compat().parse(); // items from user extension are not correctly defined in the schema assertNotNull("No definition for user", user.getDefinition()); - + System.out.println("Parsed root object:"); System.out.println(user.debugDump()); @@ -139,7 +139,7 @@ public void testUserExtensionSchemaParseUser() throws SAXException, IOException, validator.validate(new DOMSource(dataDoc),validationResult); // System.out.println("Validation result:"); // System.out.println(DOMUtil.serializeDOMToString(validationResult.getNode())); - + } @Test @@ -150,29 +150,29 @@ public void testUserExtensionSchemaSchemaRegistry() throws SAXException, IOExcep SchemaRegistryImpl reg = (SchemaRegistryImpl) context.getSchemaRegistry(); reg.registerPrismSchemasFromDirectory(EXTRA_SCHEMA_DIR); context.initialize(); - + PrismObjectDefinition userDef = reg.findObjectDefinitionByType(USER_TYPE_QNAME); - + System.out.println("User definition:"); System.out.println(userDef.debugDump()); - + assertUserDefinition(userDef); - + PrismObjectDefinition usedDefByClass = reg.findObjectDefinitionByCompileTimeClass(UserType.class); assertUserDefinition(usedDefByClass); - + PrismObjectDefinition userDefByElement = reg.findObjectDefinitionByElementName(USER_QNAME); assertUserDefinition(userDefByElement); } - + private void assertUserDefinition(PrismObjectDefinition userDef) { PrismContainerDefinition extDef = userDef.findContainerDefinition(USER_EXTENSION_QNAME); - + System.out.println("User extension"); System.out.println(extDef.debugDump()); - + assertTrue("Extension is not dynamic", extDef.isRuntimeSchema()); - assertTrue("Wrong extension type "+extDef.getTypeName(), + assertTrue("Wrong extension type "+extDef.getTypeName(), USER_EXTENSION_TYPE_QNAME.equals(extDef.getTypeName()) || USER_2_EXTENSION_TYPE_QNAME.equals(extDef.getTypeName())); assertEquals("Wrong extension displayOrder", (Integer)1000, extDef.getDisplayOrder()); @@ -180,7 +180,7 @@ private void assertUserDefinition(PrismObjectDefinition userDef) { assertNotNull("No 'bar' definition in user extension", barPropDef); PrismAsserts.assertDefinition(barPropDef, USER_EXT_BAR_ELEMENT, DOMUtil.XSD_STRING, 1, 1); assertTrue("'bar' not indexed", barPropDef.isIndexed()); - + PrismPropertyDefinition foobarPropDef = extDef.findPropertyDefinition(USER_EXT_FOOBAR_ELEMENT); assertNotNull("No 'foobar' definition in user extension", foobarPropDef); PrismAsserts.assertDefinition(foobarPropDef, USER_EXT_FOOBAR_ELEMENT, DOMUtil.XSD_STRING, 0, 1); @@ -190,11 +190,11 @@ private void assertUserDefinition(PrismObjectDefinition userDef) { assertNotNull("No 'multi' definition in user extension", multiPropDef); PrismAsserts.assertDefinition(multiPropDef, USER_EXT_MULTI_ELEMENT, DOMUtil.XSD_STRING, 0, -1); assertFalse("'multi' not indexed", multiPropDef.isIndexed()); - + PrismPropertyDefinition ext2Def = extDef.findPropertyDefinition(USER_EXT_2_ELEMENT); assertNotNull("No 'ext2' definition in user extension", ext2Def); PrismAsserts.assertDefinition(ext2Def, USER_EXT_2_ELEMENT, DOMUtil.XSD_STRING, 1, 1); - + // Make sure that the ordering is OK. If it is not then a serialization will produce XML that // does not comply to schema List definitions = userDef.getDefinitions(); @@ -212,27 +212,27 @@ private void assertDefinitionOrder(List definitions, Q /** * Test if a schema directory can be loaded to the schema registry. This contains definition of - * user extension, therefore check if it is applied to the user definition. + * user extension, therefore check if it is applied to the user definition. */ @Test public void testTypeOverride() throws SAXException, IOException, SchemaException { System.out.println("===[ testTypeOverride ]==="); - + PrismContext context = constructPrismContext(); SchemaRegistryImpl reg = (SchemaRegistryImpl) context.getSchemaRegistry(); reg.registerPrismSchemasFromDirectory(EXTRA_SCHEMA_DIR); context.initialize(); - + PrismSchema schema = reg.getSchema(NS_ROOT); System.out.println("Parsed root schema:"); System.out.println(schema.debugDump()); - + PrismContainerDefinition rootContDef = schema.findContainerDefinitionByElementName(new QName(NS_ROOT,"root")); assertNotNull("Not definition", rootContDef); PrismContainerDefinition extensionContDef = rootContDef.findContainerDefinition(new QName(NS_FOO, "extension")); assertNotNull("Not definition", extensionContDef); assertEquals("Wrong type", new QName(NS_ROOT, "MyExtensionType"), extensionContDef.getTypeName()); - + } } diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestFind.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestFind.java index e1210e32078..60f318a1b13 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestFind.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestFind.java @@ -41,25 +41,25 @@ * */ public class TestFind { - + @BeforeSuite public void setupDebug() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(DEFAULT_NAMESPACE_PREFIX); PrismTestUtil.resetPrismContext(new PrismInternalTestUtil()); } - + @Test public void testFindString() throws SchemaException, SAXException, IOException { final String TEST_NAME = "testFindString"; System.out.println("===[ "+TEST_NAME+" ]==="); - + // GIVEN PrismObject user = createUser(); ItemPath path = new ItemPath(UserType.F_DESCRIPTION); - + // WHEN PrismProperty nameProperty = findProperty(user, path); - + // THEN assertEquals("Wrong property value (path="+path+")", USER_JACK_DESCRIPTION, nameProperty.getRealValue()); assertTrue("QName found something other", nameProperty == (PrismProperty) user.findProperty(UserType.F_DESCRIPTION)); @@ -69,147 +69,147 @@ public void testFindString() throws SchemaException, SAXException, IOException { public void testFindPolyString() throws SchemaException, SAXException, IOException { final String TEST_NAME = "testFindPolyString"; System.out.println("===[ "+TEST_NAME+" ]==="); - + // GIVEN PrismObject user = createUser(); ItemPath path = new ItemPath(UserType.F_POLY_NAME); - + // WHEN PrismProperty nameProperty = findProperty(user, path); - + // THEN assertEquals("Wrong property value (path="+path+")", PrismTestUtil.createPolyString(USER_JACK_POLYNAME_ORIG), nameProperty.getRealValue()); assertTrue("QName found something other", nameProperty == (PrismProperty) user.findProperty(UserType.F_POLY_NAME)); } - + @Test public void testFindPolyStringOrig() throws SchemaException, SAXException, IOException { final String TEST_NAME = "testFindPolyStringOrig"; System.out.println("===[ "+TEST_NAME+" ]==="); - + // GIVEN ItemPath path = new ItemPath(UserType.F_POLY_NAME, PolyString.F_ORIG); - + // WHEN Object found = findUser(path); - + // THEN assertEquals("Wrong property value (path="+path+")", USER_JACK_POLYNAME_ORIG, found); } - + @Test public void testFindPolyStringNorm() throws SchemaException, SAXException, IOException { final String TEST_NAME = "testFindPolyStringNorm"; System.out.println("===[ "+TEST_NAME+" ]==="); - + // GIVEN ItemPath path = new ItemPath(UserType.F_POLY_NAME, PolyString.F_NORM); - + // WHEN Object found = findUser(path); - + // THEN assertEquals("Wrong property value (path="+path+")", USER_JACK_POLYNAME_NORM, found); } - + @Test public void testFindExtensionBar() throws SchemaException, SAXException, IOException { final String TEST_NAME = "testFindExtensionBar"; System.out.println("===[ "+TEST_NAME+" ]==="); - + // GIVEN ItemPath path = new ItemPath(UserType.F_EXTENSION, EXTENSION_BAR_ELEMENT); - + // WHEN PrismProperty property = findUserProperty(path); - + // THEN assertEquals("Wrong property value (path="+path+")", "BAR", property.getAnyRealValue()); } - + @Test public void testFindAssignment1Description() throws SchemaException, SAXException, IOException { final String TEST_NAME = "testFindAssignment1Description"; System.out.println("===[ "+TEST_NAME+" ]==="); - + // GIVEN ItemPath path = new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(USER_ASSIGNMENT_1_ID), new NameItemPathSegment(AssignmentType.F_DESCRIPTION)); - + // WHEN PrismProperty property = findUserProperty(path); - + // THEN assertEquals("Wrong property value (path="+path+")", "Assignment 1", property.getRealValue()); } - + @Test public void testFindAssignment2Construction() throws SchemaException, SAXException, IOException { final String TEST_NAME = "testFindAssignment2ConstructionHowto"; System.out.println("===[ "+TEST_NAME+" ]==="); - + // GIVEN ItemPath path = new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(USER_ASSIGNMENT_2_ID), new NameItemPathSegment(AssignmentType.F_ACCOUNT_CONSTRUCTION)); - + // WHEN PrismProperty property = findUserProperty(path); - + // THEN assertEquals("Wrong property value (path="+path+")", "Just do it", property.getRealValue().getHowto()); } - + @Test public void testFindAssignment() throws SchemaException, SAXException, IOException { final String TEST_NAME = "testFindAssignment"; System.out.println("===[ "+TEST_NAME+" ]==="); - + // GIVEN ItemPath path = new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT)); - + // WHEN PrismContainer container = findUserContainer(path); - + // THEN PrismContainerValue value2 = container.getValue(USER_ASSIGNMENT_2_ID); assertEquals("Wrong value2 description (path="+path+")", "Assignment 2", value2.findProperty(AssignmentType.F_DESCRIPTION).getRealValue()); } - + private T findUser(ItemPath path) throws SchemaException, SAXException, IOException { PrismObject user = createUser(); return find(user, path); } - + private T find(PrismObject user, ItemPath path) { System.out.println("Path:"); System.out.println(path); - + // WHEN Object found = user.find(path); - + // THEN System.out.println("Found:"); System.out.println(found); return (T) found; } - + private PrismProperty findUserProperty(ItemPath path) throws SchemaException, SAXException, IOException { PrismObject user = createUser(); return findProperty(user, path); } - + private PrismProperty findProperty(PrismObject user, ItemPath path) { System.out.println("Path:"); System.out.println(path); - + // WHEN PrismProperty property = user.findProperty(path); - + // THEN System.out.println("Found:"); System.out.println(property); @@ -220,25 +220,25 @@ private PrismContainer findUserContainer(ItemPath p PrismObject user = createUser(); return findContainer(user, path); } - + private PrismContainer findContainer(PrismObject user, ItemPath path) { System.out.println("Path:"); System.out.println(path); - + // WHEN PrismContainer container = user.findContainer(path); - + // THEN System.out.println("Found:"); System.out.println(container); return container; } - + public PrismObject createUser() throws SchemaException, SAXException, IOException { PrismObject user = PrismTestUtil.parseObject(USER_JACK_FILE_XML); return user; } - + } diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestFundamentals.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestFundamentals.java index 7cd00586098..a70804e5ac4 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestFundamentals.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestFundamentals.java @@ -39,13 +39,13 @@ * */ public class TestFundamentals { - + @BeforeSuite public void setupDebug() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(DEFAULT_NAMESPACE_PREFIX); PrismTestUtil.resetPrismContext(new PrismInternalTestUtil()); } - + @Test public void testPrismValueContainsRealValue() throws Exception { System.out.println("\n\n===[ testPrismValueContainsRealValue ]===\n"); @@ -56,17 +56,17 @@ public void testPrismValueContainsRealValue() throws Exception { Collection collection = new ArrayList(); collection.add(valFoo1); collection.add(valBar1); - + PrismPropertyValue valFoo2 = new PrismPropertyValue("foo"); PrismPropertyValue valFoo3 = new PrismPropertyValue("foo"); valFoo3.setOriginType(OriginType.OUTBOUND); - + PrismPropertyValue valBar2 = new PrismPropertyValue("bar"); valBar2.setOriginType(OriginType.OUTBOUND); PrismPropertyValue valBar3 = new PrismPropertyValue("bar"); - + PrismPropertyValue valBaz = new PrismPropertyValue("baz"); - + // WHEN - THEN assert PrismValue.containsRealValue(collection, valFoo1); assert PrismValue.containsRealValue(collection, valBar1); diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPath.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPath.java index bedd258fcf8..bd4a97867ee 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPath.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPath.java @@ -43,7 +43,7 @@ * */ public class TestPath { - + private static final String NS = "http://example.com/"; @BeforeSuite @@ -51,11 +51,11 @@ public void setupDebug() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(DEFAULT_NAMESPACE_PREFIX); PrismTestUtil.resetPrismContext(new PrismInternalTestUtil()); } - + @Test public void testPathNormalize() throws Exception { System.out.println("\n\n===[ testPathNormalize ]===\n"); - + // GIVEN ItemPath path1 = new ItemPath(new QName(NS, "foo"), new QName(NS, "bar")); ItemPath path2 = new ItemPath(new NameItemPathSegment(new QName(NS, "foo")), new IdItemPathSegment(123L), @@ -67,7 +67,7 @@ public void testPathNormalize() throws Exception { ItemPath path4 = new ItemPath(new QName(NS, "x")); ItemPath path5 = new ItemPath(new NameItemPathSegment(new QName(NS, "foo")), new IdItemPathSegment(123L)); ItemPath pathE = ItemPath.EMPTY_PATH; - + // WHEN ItemPath normalized1 = path1.normalize(); ItemPath normalized2 = path2.normalize(); @@ -76,7 +76,7 @@ public void testPathNormalize() throws Exception { ItemPath normalized4 = path4.normalize(); ItemPath normalized5 = path5.normalize(); ItemPath normalizedE = pathE.normalize(); - + // THEN System.out.println("Normalized path 1:" + normalized1); System.out.println("Normalized path 2:" + normalized2); @@ -94,11 +94,11 @@ public void testPathNormalize() throws Exception { assertNormalizedPath(normalized5, "foo", 123L); assert normalizedE.isEmpty() : "normalizedE is not empty"; } - + @Test public void testPathCompare() throws Exception { System.out.println("\n\n===[ testPathCompare ]===\n"); - + // GIVEN ItemPath pathFoo = new ItemPath(new QName(NS, "foo")); ItemPath pathFooNull = new ItemPath(new NameItemPathSegment(new QName(NS, "foo")), new IdItemPathSegment()); @@ -158,23 +158,23 @@ public void testPathCompare() throws Exception { assertFalse(ItemPath.containsSuperpathOrEquivalent(onlyFooBar, pathFooBarBaz)); assertFalse(ItemPath.containsSuperpath(onlyFooBar, pathFooBarBaz)); } - + @Test public void testPathRemainder() throws Exception { System.out.println("\n\n===[ testPathRemainder ]===\n"); - + // GIVEN ItemPath pathFoo = new ItemPath(new QName(NS, "foo")); ItemPath pathBar = new ItemPath(new QName(NS, "bar")); ItemPath pathFooNull = new ItemPath(new NameItemPathSegment(new QName(NS, "foo")), new IdItemPathSegment()); ItemPath pathFoo123 = new ItemPath(new NameItemPathSegment(new QName(NS, "foo")), new IdItemPathSegment(123L)); ItemPath pathFooBar = new ItemPath(new QName(NS, "foo"), new QName(NS, "bar")); - ItemPath pathFooNullBar = new ItemPath(new NameItemPathSegment(new QName(NS, "foo")), new IdItemPathSegment(), + ItemPath pathFooNullBar = new ItemPath(new NameItemPathSegment(new QName(NS, "foo")), new IdItemPathSegment(), new NameItemPathSegment(new QName(NS, "bar"))); - + // WHEN ItemPath remainder1 = pathFooBar.remainder(pathFooNull); - + // THEN assertEquals("Remainder fooBar, fooNull", pathBar, remainder1); } @@ -188,7 +188,7 @@ private void assertNormalizedPath(ItemPath normalized, Object... expected) { assert name != null : "name is null"; assert name.getNamespaceURI().equals(NS) : "wrong namespace: "+name.getNamespaceURI(); assert name.getLocalPart().equals(expected[i]) : "wrong local name, expected "+expected[i]+", was "+name.getLocalPart(); - + if (i + 1 < expected.length) { ItemPathSegment idSegment = normalized.getSegments().get(i+1); assert idSegment instanceof IdItemPathSegment : "Expected is segment but it was "+nameSegment.getClass(); diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPerformance.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPerformance.java index 1e929c8ae5a..0f97c0baf3b 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPerformance.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPerformance.java @@ -31,10 +31,10 @@ * */ public class TestPerformance { - + private static final int ITERATIONS = 10000; - - + + @BeforeSuite public void setupDebug() { PrettyPrinter.setDefaultNamespacePrefix(DEFAULT_NAMESPACE_PREFIX); @@ -48,7 +48,7 @@ public void setupDebug() { public void testPerfContainerNewValue() throws Exception { final String TEST_NAME = "testPerfContainerNewValue"; PrismInternalTestUtil.displayTestTitle(TEST_NAME); - + // GIVEN PrismContext ctx = constructInitializedPrismContext(); PrismObjectDefinition userDefinition = getFooSchema(ctx).findObjectDefinitionByElementName(new QName(NS_FOO,"user")); @@ -57,30 +57,30 @@ public void testPerfContainerNewValue() throws Exception { PerfRecorder recorderCreateNewValue = new PerfRecorder("createNewValue"); PerfRecorder recorderFindOrCreateProperty = new PerfRecorder("findOrCreateProperty"); PerfRecorder recorderSetRealValue = new PerfRecorder("setRealValue"); - + // WHEN for (int i=0; i < ITERATIONS; i++) { long tsStart = System.nanoTime(); - + PrismContainerValue newValue = assignmentContainer.createNewValue(); - + long ts1 = System.nanoTime(); - + PrismProperty descriptionProperty = newValue.findOrCreateProperty(AssignmentType.F_DESCRIPTION); - + long ts2 = System.nanoTime(); - + descriptionProperty.setRealValue("ass "+i); - + long tsEnd = System.nanoTime(); - + recorderCreateNewValue.record(i, ((double)(ts1 - tsStart))/1000000); recorderFindOrCreateProperty.record(i, ((double)(ts2 - ts1))/1000000); recorderSetRealValue.record(i, ((double)(tsEnd - ts2))/1000000); - + System.out.println("Run "+i+": total "+(((double)(tsEnd - tsStart))/1000000)+"ms"); } - + // THEN System.out.println(recorderCreateNewValue.dump()); System.out.println(recorderFindOrCreateProperty.dump()); @@ -93,9 +93,9 @@ public void testPerfContainerNewValue() throws Exception { recorderFindOrCreateProperty.assertAverageBelow(0.1D); recorderCreateNewValue.assertAverageBelow(0.05D); - + System.out.println("User:"); System.out.println(user.debugDump()); - } + } } diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPolyString.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPolyString.java index 84328d13f1d..a627d5b22ff 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPolyString.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPolyString.java @@ -40,13 +40,13 @@ * */ public class TestPolyString { - + @BeforeSuite public void setupDebug() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(DEFAULT_NAMESPACE_PREFIX); PrismTestUtil.resetPrismContext(new PrismInternalTestUtil()); } - + @Test public void testSimpleNormalization() { testNormalization("testSimpleNormalization", @@ -60,7 +60,7 @@ public void testNormalizationNonLatinAll() { "\u0421\u043E\u044E\u0301\u0437 \u0421\u043E\u0432\u0435\u0301\u0442\u0441\u043A\u0438\u0445 \u0421\u043E\u0446\u0438\u0430\u043B\u0438\u0441\u0442\u0438\u0301\u0447\u0435\u0441\u043A\u0438\u0445 \u0420\u0435\u0441\u043F\u0443\u0301\u0431\u043B\u0438\u043A", ""); } - + @Test public void testNormalizationNonLatinSome() { testNormalization("testSimpleNormalization", @@ -71,22 +71,22 @@ public void testNormalizationNonLatinSome() { private void testNormalization(final String TEST_NAME, String orig, String expectedNorm) { System.out.println("===[ "+TEST_NAME+" ]==="); PolyString polyString = new PolyString(orig); - + PolyStringNormalizer normalizer = new PrismDefaultPolyStringNormalizer(); - + // WHEN polyString.recompute(normalizer); - + // THEN assertEquals("orig have changed", orig, polyString.getOrig()); assertEquals("wrong norm", expectedNorm, polyString.getNorm()); assertEquals("wrong toString", orig, polyString.toString()); } - + @Test public void testRecompute() throws Exception { System.out.println("===[ testRecompute ]==="); - + // GIVEN PrismContext ctx = constructInitializedPrismContext(); PrismObjectDefinition userDefinition = getFooSchema(ctx).findObjectDefinitionByElementName(new QName(NS_FOO,"user")); @@ -94,26 +94,26 @@ public void testRecompute() throws Exception { String orig = "Ľala ho papľuha"; PolyString polyName = new PolyString(orig); - + PrismProperty polyNameProperty = user.findOrCreateProperty(USER_POLYNAME_QNAME); - + // WHEN polyNameProperty.setRealValue(polyName); - + // THEN assertEquals("Changed orig", orig, polyName.getOrig()); assertEquals("Wrong norm", "lala ho papluha", polyName.getNorm()); - + } - + @Test public void testCompareTo() throws Exception { System.out.println("===[ testCompareTo ]==="); - + // GIVEN String orig = "Ľala ho papľuha"; PolyString polyName = new PolyString(orig); - + // WHEN, THEN assertTrue(polyName.compareTo("Ľala ho papľuha") == 0); assertTrue(polyName.compareTo(new PolyString("Ľala ho papľuha")) == 0); @@ -121,7 +121,7 @@ public void testCompareTo() throws Exception { assertTrue(polyName.compareTo(new PolyString("something different")) != 0); assertTrue(polyName.compareTo("") != 0); assertTrue(polyName.compareTo(null) != 0); - + } - + } diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismContext.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismContext.java index 2d8a38a19d9..2936d4a28d0 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismContext.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismContext.java @@ -53,9 +53,9 @@ * */ public class TestPrismContext { - + private static final String NS_FOO = "http://midpoint.evolveum.com/xml/ns/test/foo-1.xsd"; - + @BeforeSuite public void setupDebug() { PrettyPrinter.setDefaultNamespacePrefix("http://midpoint.evolveum.com/xml/ns"); @@ -64,38 +64,38 @@ public void setupDebug() { @Test public void testPrefixMapper() throws SchemaException, SAXException, IOException { System.out.println("===[ testPrefixMapper ]==="); - + // WHEN PrismContextImpl prismContext = constructInitializedPrismContext(); - + // THEN assertNotNull("No prism context", prismContext); - + SchemaRegistry schemaRegistry = prismContext.getSchemaRegistry(); assertNotNull("No schema registry in context", schemaRegistry); - + DynamicNamespacePrefixMapper prefixMapper = schemaRegistry.getNamespacePrefixMapper(); System.out.println("Prefix mapper:"); System.out.println(DebugUtil.dump(prefixMapper)); - + assertEquals("Wrong foo prefix", "", prefixMapper.getPrefix(NS_FOO)); assertEquals("Wrong xsd prefix", DOMUtil.NS_W3C_XML_SCHEMA_PREFIX, prefixMapper.getPrefix(XMLConstants.W3C_XML_SCHEMA_NS_URI)); - + } - + @Test public void testCompileTimeClassmap() throws SchemaException, SAXException, IOException { System.out.println("===[ testCompileTimeClassmap ]==="); - + // WHEN PrismContext prismContext = constructInitializedPrismContext(); - + // THEN assertNotNull("No prism context", prismContext); - + SchemaRegistry schemaRegistry = prismContext.getSchemaRegistry(); assertNotNull("No schema registry in context", schemaRegistry); - + SchemaDescription fooDesc = schemaRegistry.findSchemaDescriptionByNamespace(NS_FOO); Map> map = fooDesc.getXsdTypeTocompileTimeClassMap(); assertNotNull("No XsdTypeTocompileTimeClassMap", map); @@ -107,7 +107,7 @@ public void testCompileTimeClassmap() throws SchemaException, SAXException, IOEx // This is not a container, but it should be in the map anyway assertMapping(map, AccountConstructionType.class, ACCOUNT_CONSTRUCTION_TYPE_QNAME); } - + private void assertMapping(Map> map, Class clazz, QName typeName) { assertEquals("Wrong xsdType->class mapping for "+typeName, clazz, map.get(typeName)); } @@ -115,46 +115,46 @@ private void assertMapping(Map> map, Class clazz, QName typeN @Test public void testBasicSchemas() throws SchemaException, SAXException, IOException { System.out.println("===[ testBasicSchemas ]==="); - + // WHEN PrismContext prismContext = constructInitializedPrismContext(); - + // THEN assertNotNull("No prism context", prismContext); - + SchemaRegistry schemaRegistry = prismContext.getSchemaRegistry(); assertNotNull("No schema registry in context", schemaRegistry); - + System.out.println("Schema registry:"); System.out.println(schemaRegistry.debugDump()); PrismSchema fooSchema = schemaRegistry.findSchemaByNamespace(NS_FOO); System.out.println("Foo schema:"); System.out.println(fooSchema.debugDump()); - + // Assert USER definition PrismObjectDefinition userDefinition = fooSchema.findObjectDefinitionByElementName(new QName(NS_FOO,"user")); assertNotNull("No user definition", userDefinition); System.out.println("User definition:"); System.out.println(userDefinition.debugDump()); - + PrismObjectDefinition userDefinitionByClass = schemaRegistry.findObjectDefinitionByCompileTimeClass(UserType.class); assertTrue("Different user def", userDefinition == userDefinitionByClass); - + assertUserDefinition(userDefinition); - + // Assert ACCOUNT definition PrismObjectDefinition accountDefinition = fooSchema.findObjectDefinitionByElementName(new QName(NS_FOO,"account")); assertNotNull("No account definition", accountDefinition); System.out.println("Account definition:"); System.out.println(accountDefinition.debugDump()); - + PrismObjectDefinition accountDefinitionByClass = schemaRegistry.findObjectDefinitionByCompileTimeClass(AccountType.class); assertTrue("Different user def", accountDefinition == accountDefinitionByClass); assertAccountDefinition(accountDefinition); } - + private void assertUserDefinition(PrismObjectDefinition userDefinition) { assertEquals("Wrong compile-time class in user definition", UserType.class, userDefinition.getCompileTimeClass()); @@ -172,7 +172,7 @@ private void assertUserDefinition(PrismObjectDefinition userDefinition PrismAsserts.assertPropertyDefinition(userDefinition, USER_FAMILYNAME_QNAME, DOMUtil.XSD_STRING, 0, 1); PrismAsserts.assertPropertyDefinition(userDefinition, USER_ADDITIONALNAMES_QNAME, DOMUtil.XSD_STRING, 0, -1); assertFalse("User definition is marked as runtime", userDefinition.isRuntimeSchema()); - + PrismContainerDefinition extensionContainer = userDefinition.findContainerDefinition(USER_EXTENSION_QNAME); PrismAsserts.assertDefinition(extensionContainer, USER_EXTENSION_QNAME, DOMUtil.XSD_ANY, 0, 1); assertTrue("Extension is not runtime", extensionContainer.isRuntimeSchema()); @@ -180,7 +180,7 @@ private void assertUserDefinition(PrismObjectDefinition userDefinition PrismAsserts.assertItemDefinitionDisplayName(userDefinition, USER_EXTENSION_QNAME, "ObjectType.extension"); PrismAsserts.assertItemDefinitionDisplayOrder(userDefinition, USER_EXTENSION_QNAME, 1000); PrismAsserts.assertItemDefinitionHelp(userDefinition, USER_EXTENSION_QNAME, "Object extension contains extra properties"); - + PrismContainerDefinition activationContainer = userDefinition.findContainerDefinition(USER_ACTIVATION_QNAME); PrismAsserts.assertDefinition(activationContainer, USER_ACTIVATION_QNAME, ACTIVATION_TYPE_QNAME, 0, 1); assertFalse("Activation is runtime", activationContainer.isRuntimeSchema()); @@ -189,7 +189,7 @@ private void assertUserDefinition(PrismObjectDefinition userDefinition PrismAsserts.assertPropertyDefinition(activationContainer, USER_ENABLED_QNAME, DOMUtil.XSD_BOOLEAN, 0, 1); PrismAsserts.assertPropertyDefinition(activationContainer, USER_VALID_FROM_QNAME, DOMUtil.XSD_DATETIME, 0, 1); PrismAsserts.assertPropertyDefinition(activationContainer, USER_VALID_TO_QNAME, DOMUtil.XSD_DATETIME, 0, 1); - + PrismContainerDefinition assignmentContainer = userDefinition.findContainerDefinition(USER_ASSIGNMENT_QNAME); PrismAsserts.assertDefinition(assignmentContainer, USER_ASSIGNMENT_QNAME, ASSIGNMENT_TYPE_QNAME, 0, -1); assertFalse("Assignment is runtime", assignmentContainer.isRuntimeSchema()); @@ -197,70 +197,70 @@ private void assertUserDefinition(PrismObjectDefinition userDefinition assertEquals("Assignment size", 4, assignmentContainer.getDefinitions().size()); PrismAsserts.assertPropertyDefinition(assignmentContainer, USER_DESCRIPTION_QNAME, DOMUtil.XSD_STRING, 0, 1); PrismAsserts.assertPropertyDefinition(assignmentContainer, USER_ACCOUNT_CONSTRUCTION_QNAME, ACCOUNT_CONSTRUCTION_TYPE_QNAME, 0, 1); - + PrismReferenceDefinition accountRefDef = userDefinition.findItemDefinition(USER_ACCOUNTREF_QNAME, PrismReferenceDefinition.class); PrismAsserts.assertDefinition(accountRefDef, USER_ACCOUNTREF_QNAME, OBJECT_REFERENCE_TYPE_QNAME, 0, -1); assertEquals("Wrong target type in accountRef", ACCOUNT_TYPE_QNAME, accountRefDef.getTargetTypeName()); assertEquals("Wrong composite object element name in accountRef", USER_ACCOUNT_QNAME, accountRefDef.getCompositeObjectElementName()); - + } - + private void assertAccountDefinition(PrismObjectDefinition accountDefinition) { - + assertEquals("Wrong compile-time class in account definition", AccountType.class, accountDefinition.getCompileTimeClass()); PrismAsserts.assertPropertyDefinition(accountDefinition, ACCOUNT_NAME_QNAME, PolyStringType.COMPLEX_TYPE, 0, 1); PrismAsserts.assertPropertyDefinition(accountDefinition, ACCOUNT_DESCRIPTION_QNAME, DOMUtil.XSD_STRING, 0, 1); assertFalse("Account definition is marked as runtime", accountDefinition.isRuntimeSchema()); - + PrismContainerDefinition attributesContainer = accountDefinition.findContainerDefinition(ACCOUNT_ATTRIBUTES_QNAME); PrismAsserts.assertDefinition(attributesContainer, ACCOUNT_ATTRIBUTES_QNAME, ATTRIBUTES_TYPE_QNAME, 0, 1); assertTrue("Attributes is NOT runtime", attributesContainer.isRuntimeSchema()); } - + @Test public void testExtensionSchema() throws SchemaException, SAXException, IOException { System.out.println("===[ testExtensionSchema ]==="); - + // GIVEN PrismContext prismContext = constructInitializedPrismContext(); assertNotNull("No prism context", prismContext); SchemaRegistry schemaRegistry = prismContext.getSchemaRegistry(); assertNotNull("No schema registry in context", schemaRegistry); - + PrismPropertyDefinition ignoredTypeDef = schemaRegistry.findPropertyDefinitionByElementName(EXTENSION_IGNORED_TYPE_ELEMENT); PrismAsserts.assertDefinition(ignoredTypeDef, EXTENSION_IGNORED_TYPE_ELEMENT, DOMUtil.XSD_STRING, 0, -1); assertTrue("Element "+EXTENSION_IGNORED_TYPE_ELEMENT+" is NOT ignored", ignoredTypeDef.isIgnored()); - + PrismPropertyDefinition stringTypeDef = schemaRegistry.findPropertyDefinitionByElementName(EXTENSION_STRING_TYPE_ELEMENT); PrismAsserts.assertDefinition(stringTypeDef, EXTENSION_STRING_TYPE_ELEMENT, DOMUtil.XSD_STRING, 0, -1); assertFalse("Element "+EXTENSION_STRING_TYPE_ELEMENT+" is ignored", stringTypeDef.isIgnored()); - + PrismPropertyDefinition singleStringTypeDef = schemaRegistry.findPropertyDefinitionByElementName(EXTENSION_SINGLE_STRING_TYPE_ELEMENT); PrismAsserts.assertDefinition(singleStringTypeDef, EXTENSION_SINGLE_STRING_TYPE_ELEMENT, DOMUtil.XSD_STRING, 0, 1); assertFalse("Element "+EXTENSION_SINGLE_STRING_TYPE_ELEMENT+" is ignored", singleStringTypeDef.isIgnored()); - + PrismPropertyDefinition intTypeDef = schemaRegistry.findPropertyDefinitionByElementName(EXTENSION_INT_TYPE_ELEMENT); PrismAsserts.assertDefinition(intTypeDef, EXTENSION_INT_TYPE_ELEMENT, DOMUtil.XSD_INT, 0, -1); assertFalse("Element "+EXTENSION_INT_TYPE_ELEMENT+" is ignored", intTypeDef.isIgnored()); - + PrismContainerDefinition meleeContextDefinition = schemaRegistry.findContainerDefinitionByElementName(EXTENSION_MELEE_CONTEXT_ELEMENT); PrismAsserts.assertDefinition(meleeContextDefinition, EXTENSION_MELEE_CONTEXT_ELEMENT, EXTENSION_MELEE_CONTEXT_TYPE_QNAME, 0, 1); assertTrue("Melee context container is NOT marked as runtime", meleeContextDefinition.isRuntimeSchema()); PrismReferenceDefinition opponentRefDef = meleeContextDefinition.findReferenceDefinition(EXTENSION_MELEE_CONTEXT_OPPONENT_REF_ELEMENT); assertTrue("opponentRef definition is NOT composite", opponentRefDef.isComposite()); } - + @Test public void testSchemaToDom() throws SchemaException, SAXException, IOException { System.out.println("===[ testSchemaToDom ]==="); - + // GIVEN PrismContext prismContext = constructInitializedPrismContext(); PrismSchema fooSchema = prismContext.getSchemaRegistry().findSchemaByNamespace(NS_FOO); - + // WHEN Document fooXsd = fooSchema.serializeToXsd(); - + // THEN assertNotNull("No foo XSD DOM", fooXsd); } @@ -270,41 +270,41 @@ public void testSchemaToDom() throws SchemaException, SAXException, IOException // @Test // public void testSchemaParsingRoundTrip() throws SchemaException, SAXException, IOException { // System.out.println("===[ testSchemaParsingRoundTrip ]==="); -// +// // // GIVEN // PrismContext prismContext = constructInitializedPrismContext(); // PrismSchema fooSchema = prismContext.getSchemaRegistry().findSchemaByNamespace(NS_FOO); -// +// // // WHEN // Document fooXsd = fooSchema.serializeToXsd(); -// +// // // THEN // assertNotNull("No foo XSD DOM", fooXsd); // System.out.println("Serialized schema"); // System.out.println(DOMUtil.serializeDOMToString(fooXsd)); -// +// // // WHEN // PrismSchema parsedSchema = PrismSchema.parse(DOMUtil.getFirstChildElement(fooXsd), prismContext); -// +// // // THEN // assertNotNull("No parsed schema", parsedSchema); // System.out.println("Parsed schema"); // System.out.println(parsedSchema.dump()); -// +// // // Assert USER definition // PrismObjectDefinition userDefinition = parsedSchema.findObjectDefinitionByElementName(new QName(NS_FOO,"user")); // assertNotNull("No user definition", userDefinition); // System.out.println("User definition:"); // System.out.println(userDefinition.dump()); -// +// // assertUserDefinition(userDefinition); -// +// // // Assert ACCOUNT definition // PrismObjectDefinition accountDefinition = parsedSchema.findObjectDefinitionByElementName(new QName(NS_FOO,"account")); // assertNotNull("No account definition", accountDefinition); // System.out.println("Account definition:"); // System.out.println(accountDefinition.dump()); -// +// // assertAccountDefinition(accountDefinition); // } diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismObjectConstruction.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismObjectConstruction.java index 349c8eb4e35..56c1a2fa2f5 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismObjectConstruction.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismObjectConstruction.java @@ -45,12 +45,12 @@ * */ public class TestPrismObjectConstruction { - + private static final String USER_OID = "1234567890"; private static final String ACCOUNT1_OID = "11100000111"; private static final String ACCOUNT2_OID = "11100000222"; - - + + @BeforeSuite public void setupDebug() { PrettyPrinter.setDefaultNamespacePrefix(DEFAULT_NAMESPACE_PREFIX); @@ -64,26 +64,26 @@ public void setupDebug() { public void testConstructionWithSchema() throws Exception { final String TEST_NAME = "testConstructionWithSchema"; PrismInternalTestUtil.displayTestTitle(TEST_NAME); - + // GIVEN PrismContext ctx = constructInitializedPrismContext(); PrismObjectDefinition userDefinition = getFooSchema(ctx).findObjectDefinitionByElementName(new QName(NS_FOO,"user")); - + // WHEN PrismObject user = userDefinition.instantiate(); // Fill-in object values, checking presence of definition while doing so fillInUserDrake(user, true); - + // THEN System.out.println("User:"); System.out.println(user.debugDump()); // Check if the values are correct, also checking definitions assertUserDrake(user, true, ctx); } - + /** * Construct object without schema. Starts by creating object "out of the blue" and - * the working downwards. + * the working downwards. */ @Test(enabled = false) // definition-less containers are no longer supported public void testDefinitionlessConstruction() throws Exception { @@ -92,12 +92,12 @@ public void testDefinitionlessConstruction() throws Exception { // GIVEN // No context needed - + // WHEN PrismObject user = new PrismObject(USER_QNAME, UserType.class); // Fill-in object values, no schema checking fillInUserDrake(user, false); - + // THEN System.out.println("User:"); System.out.println(user.debugDump()); @@ -105,7 +105,7 @@ public void testDefinitionlessConstruction() throws Exception { PrismContext ctx = constructInitializedPrismContext(); assertUserDrake(user, false, ctx); } - + /** * Construct object without schema. Starts by creating object "out of the blue" and * the working downwards. Then apply the schema. Check definitions. @@ -123,28 +123,28 @@ public void testDefinitionlessConstructionAndSchemaApplication() throws Exceptio // Make sure the object is OK PrismContext ctx = constructInitializedPrismContext(); assertUserDrake(user, false, ctx); - - + + PrismObjectDefinition userDefinition = getFooSchema(ctx).findObjectDefinitionByElementName(new QName(NS_FOO,"user")); - + // WHEN user.applyDefinition(userDefinition); - + // THEN System.out.println("User:"); System.out.println(user.debugDump()); - - // Check schema now + + // Check schema now assertUserDrake(user, true, ctx); } - + @Test public void testClone() throws Exception { final String TEST_NAME = "testClone"; PrismInternalTestUtil.displayTestTitle(TEST_NAME); - + // GIVEN PrismContext ctx = constructInitializedPrismContext(); PrismObjectDefinition userDefinition = getFooSchema(ctx).findObjectDefinitionByElementName(new QName(NS_FOO,"user")); @@ -155,7 +155,7 @@ public void testClone() throws Exception { // WHEN PrismObject clone = user.clone(); - + // THEN System.out.println("Cloned user:"); System.out.println(clone.debugDump()); @@ -167,23 +167,23 @@ public void testClone() throws Exception { public void testCloneEquals() throws Exception { final String TEST_NAME = "testCloneEquals"; PrismInternalTestUtil.displayTestTitle(TEST_NAME); - + // GIVEN PrismContext ctx = constructInitializedPrismContext(); PrismObjectDefinition userDefinition = getFooSchema(ctx).findObjectDefinitionByElementName(new QName(NS_FOO,"user")); PrismObject user = userDefinition.instantiate(); fillInUserDrake(user, true); PrismObject clone = user.clone(); - + // WHEN, THEN assertTrue("Clone not equal", clone.equals(user)); assertTrue("Clone not equivalent", clone.equivalent(user)); } - + private void fillInUserDrake(PrismObject user, boolean assertDefinitions) throws SchemaException { user.setOid(USER_OID); - + // fullName PrismProperty fullNameProperty = user.findOrCreateProperty(USER_FULLNAME_QNAME); assertEquals(USER_FULLNAME_QNAME, fullNameProperty.getElementName()); @@ -193,7 +193,7 @@ private void fillInUserDrake(PrismObject user, boolean assertDefinitio PrismProperty fullNamePropertyAgain = user.findOrCreateProperty(USER_FULLNAME_QNAME); // The "==" is there by purpose. We really want to make sure that is the same *instance*, that is was not created again assertTrue("Property not the same", fullNameProperty == fullNamePropertyAgain); - + // activation PrismContainer activationContainer = user.findOrCreateContainer(USER_ACTIVATION_QNAME); assertEquals(USER_ACTIVATION_QNAME, activationContainer.getElementName()); @@ -202,7 +202,7 @@ private void fillInUserDrake(PrismObject user, boolean assertDefinitio PrismContainer activationContainerAgain = user.findOrCreateContainer(USER_ACTIVATION_QNAME); // The "==" is there by purpose. We really want to make sure that is the same *instance*, that is was not created again assertTrue("Property not the same", activationContainer == activationContainerAgain); - + // activation/enabled PrismProperty enabledProperty = user.findOrCreateProperty(USER_ENABLED_PATH); assertEquals(USER_ENABLED_QNAME, enabledProperty.getElementName()); @@ -212,7 +212,7 @@ private void fillInUserDrake(PrismObject user, boolean assertDefinitio PrismProperty enabledPropertyAgain = activationContainer.findOrCreateProperty(USER_ENABLED_QNAME); // The "==" is there by purpose. We really want to make sure that is the same *instance*, that is was not created again assertTrue("Property not the same", enabledProperty == enabledPropertyAgain); - + // assignment // Try to create this one from the value. It should work the same, but let's test a different code path PrismContainer assignmentContainer = user.getValue().findOrCreateContainer(USER_ASSIGNMENT_QNAME); @@ -223,7 +223,7 @@ private void fillInUserDrake(PrismObject user, boolean assertDefinitio // The "==" is there by purpose. We really want to make sure that is the same *instance*, that is was not created again assertTrue("Property not the same", assignmentContainer == assignmentContainerAgain); assertEquals("Wrong number of assignment values (empty)", 0, assignmentContainer.getValues().size()); - + // assignment values: construct assignment value as a new container "out of the blue" and then add it. PrismContainer assBlueContainer = new PrismContainer(USER_ASSIGNMENT_QNAME); PrismProperty assBlueDescriptionProperty = assBlueContainer.findOrCreateProperty(USER_DESCRIPTION_QNAME); @@ -232,7 +232,7 @@ private void fillInUserDrake(PrismObject user, boolean assertDefinitio assignmentContainer.mergeValues(assBlueContainer); assertEquals("Wrong number of assignment values (after blue)", 1, assignmentContainer.getValues().size()); PrismAsserts.assertParentConsistency(user); - + // assignment values: construct assignment value as a new container value "out of the blue" and then add it. PrismContainerValue assCyanContainerValue = new PrismContainerValue(); PrismProperty assCyanDescriptionProperty = assCyanContainerValue.findOrCreateProperty(USER_DESCRIPTION_QNAME); @@ -240,14 +240,14 @@ private void fillInUserDrake(PrismObject user, boolean assertDefinitio assignmentContainer.mergeValue(assCyanContainerValue); assertEquals("Wrong number of assignment values (after cyan)", 2, assignmentContainer.getValues().size()); PrismAsserts.assertParentConsistency(user); - + // assignment values: construct assignment value from existing container PrismContainerValue assRedContainerValue = assignmentContainer.createNewValue(); PrismProperty assRedDescriptionProperty = assRedContainerValue.findOrCreateProperty(USER_DESCRIPTION_QNAME); assRedDescriptionProperty.addValue(new PrismPropertyValue("Assignment created out of the red")); assertEquals("Wrong number of assignment values (after red)", 3, assignmentContainer.getValues().size()); PrismAsserts.assertParentConsistency(user); - + // accountRef PrismReference accountRef = user.findOrCreateReference(USER_ACCOUNTREF_QNAME); assertEquals(USER_ACCOUNTREF_QNAME, accountRef.getElementName()); @@ -259,7 +259,7 @@ private void fillInUserDrake(PrismObject user, boolean assertDefinitio assertTrue("Property not the same", accountRef == accountRefAgain); assertEquals("accountRef size", 2, accountRef.getValues().size()); PrismAsserts.assertParentConsistency(user); - + // extension PrismContainer extensionContainer = user.findOrCreateContainer(USER_EXTENSION_QNAME); assertEquals(USER_EXTENSION_QNAME, extensionContainer.getElementName()); @@ -269,28 +269,28 @@ private void fillInUserDrake(PrismObject user, boolean assertDefinitio // The "==" is there by purpose. We really want to make sure that is the same *instance*, that is was not created again assertTrue("Extension not the same", extensionContainer == extensionContainerAgain); assertEquals("Wrong number of extension values (empty)", 0, extensionContainer.getValues().size()); - + // extension / stringType PrismProperty stringTypeProperty = extensionContainer.findOrCreateProperty(EXTENSION_STRING_TYPE_ELEMENT); assertEquals(EXTENSION_STRING_TYPE_ELEMENT, stringTypeProperty.getElementName()); PrismAsserts.assertParentConsistency(user); if (assertDefinitions) PrismAsserts.assertDefinition(stringTypeProperty, DOMUtil.XSD_STRING, 0, -1); - + // TODO - + } private void assertUserDrake(PrismObject user, boolean assertDefinitions, PrismContext prismContext) throws SchemaException, SAXException, IOException { assertEquals("Wrong OID", USER_OID, user.getOid()); assertEquals("Wrong compileTimeClass", UserType.class, user.getCompileTimeClass()); - + user.checkConsistence(); assertUserDrakeContent(user, assertDefinitions); if (assertDefinitions) { serializeAndValidate(user, prismContext); } } - + private void assertUserDrakeContent(PrismObject user, boolean assertDefinitions) { // fullName PrismProperty fullNameProperty = user.findProperty(USER_FULLNAME_QNAME); @@ -335,7 +335,7 @@ private void assertUserDrakeContent(PrismObject user, boolean assertDe assertEquals("accountRef size", 2, accountRef.getValues().size()); PrismAsserts.assertParentConsistency(user); } - + private void serializeAndValidate(PrismObject user, PrismContext prismContext) throws SchemaException, SAXException, IOException { String xmlString = prismContext.serializeObjectToString(user, PrismContext.LANG_XML); System.out.println("Serialized XML"); diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismParsing.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismParsing.java index bea95d56be3..09acb5966c2 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismParsing.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismParsing.java @@ -51,42 +51,42 @@ public abstract class TestPrismParsing { protected abstract String getSubdirName(); - + protected abstract String getFilenameSuffix(); - + protected File getCommonSubdir() { return new File(COMMON_DIR_PATH, getSubdirName()); } - + protected File getFile(String baseName) { return new File(getCommonSubdir(), baseName+"."+getFilenameSuffix()); } - + @BeforeSuite public void setupDebug() { PrettyPrinter.setDefaultNamespacePrefix(DEFAULT_NAMESPACE_PREFIX); } - + protected abstract String getOutputFormat(); - + @Test public void test100PrismParseFile() throws Exception { final String TEST_NAME = "test100PrismParseFile"; PrismInternalTestUtil.displayTestTitle(TEST_NAME); // GIVEN PrismContext prismContext = constructInitializedPrismContext(); - + // WHEN PrismObject user = prismContext.parseObject(getFile(USER_JACK_FILE_BASENAME)); - + // THEN System.out.println("User:"); System.out.println(user.debugDump()); assertNotNull(user); - + assertUserJack(user, true); } - + @Test public void test110PrismParseFileNoNs() throws Exception { final String TEST_NAME = "test110PrismParseFileNoNs"; @@ -109,18 +109,18 @@ public void test110PrismParseFileNoNs() throws Exception { public void test120PrismParseFileObject() throws Exception { final String TEST_NAME = "test120PrismParseFileObject"; PrismInternalTestUtil.displayTestTitle(TEST_NAME); - + // GIVEN PrismContext prismContext = constructInitializedPrismContext(); - + // WHEN PrismObject user = prismContext.parseObject(getFile(USER_JACK_OBJECT_BASENAME)); - + // THEN System.out.println("User:"); System.out.println(user.debugDump()); assertNotNull(user); - + assertUserJack(user, true); } @@ -147,7 +147,7 @@ public void test130PrismParseFileAdhoc() throws Exception { public void test200RoundTrip() throws Exception { final String TEST_NAME = "test200RoundTrip"; PrismInternalTestUtil.displayTestTitle(TEST_NAME); - + roundTrip(getFile(USER_JACK_FILE_BASENAME)); } @@ -163,35 +163,35 @@ public void test210RoundTripNoNs() throws Exception { public void test220RoundTripObject() throws Exception { final String TEST_NAME = "test220RoundTripObject"; PrismInternalTestUtil.displayTestTitle(TEST_NAME); - + roundTrip(getFile(USER_JACK_OBJECT_BASENAME)); } private void roundTrip(File file) throws SchemaException, SAXException, IOException { - + // GIVEN PrismContext prismContext = constructInitializedPrismContext(); PrismObject originalUser = prismContext.parseObject(file); - + System.out.println("Input parsed user:"); System.out.println(originalUser.debugDump()); assertNotNull(originalUser); - + // precondition assertUserJack(originalUser, true); - + // WHEN // We need to serialize with composite objects during roundtrip, otherwise the result will not be equal String userXml = prismContext.serializerFor(getOutputFormat()).serialize(originalUser); - + // THEN System.out.println("Serialized user:"); System.out.println(userXml); assertNotNull(userXml); - + validateXml(userXml, prismContext); - + // WHEN PrismObject parsedUser = prismContext.parseObject(userXml); System.out.println("Re-parsed user:"); @@ -199,22 +199,22 @@ private void roundTrip(File file) throws SchemaException, SAXException, IOExcept assertNotNull(parsedUser); assertUserJack(parsedUser, true); - + ObjectDelta diff = DiffUtil.diff(originalUser, parsedUser); System.out.println("Diff:"); System.out.println(diff.debugDump()); - + assertTrue("Diff: "+diff, diff.isEmpty()); - + assertTrue("Users not equal", originalUser.equals(parsedUser)); } - + @Test public void test230RoundTripAdhoc() throws Exception { final String TEST_NAME = "test230RoundTripAdhoc"; PrismInternalTestUtil.displayTestTitle(TEST_NAME); - + roundTripAdhoc(getFile(USER_JACK_ADHOC_BASENAME)); } @@ -222,25 +222,25 @@ private void roundTripAdhoc(File file) throws SchemaException, SAXException, IOE // GIVEN PrismContext prismContext = constructInitializedPrismContext(); PrismObject originalUser = prismContext.parseObject(file); - + System.out.println("Input parsed user:"); System.out.println(originalUser.debugDump()); assertNotNull(originalUser); - + // precondition assertUserAdhoc(originalUser, true); - + // WHEN // We need to serialize with composite objects during roundtrip, otherwise the result will not be equal String userXml = prismContext.serializeObjectToString(originalUser, getOutputFormat()); - + // THEN System.out.println("Serialized user:"); System.out.println(userXml); assertNotNull(userXml); - + validateXml(userXml, prismContext); - + // WHEN PrismObject parsedUser = prismContext.parseObject(userXml); System.out.println("Re-parsed user:"); @@ -248,19 +248,19 @@ private void roundTripAdhoc(File file) throws SchemaException, SAXException, IOE assertNotNull(parsedUser); assertUserAdhoc(parsedUser, true); - + assertTrue("Users not equal", originalUser.equals(parsedUser)); } - + @Test public void test300MeleeContext() throws Exception { final String TEST_NAME = "test300MeleeContext"; PrismInternalTestUtil.displayTestTitle(TEST_NAME); - + // GIVEN PrismContext prismContext = constructInitializedPrismContext(); - + PrismObject userJack = prismContext.parseObject(getFile(USER_JACK_FILE_BASENAME)); PrismContainer meleeContextContainer = userJack.findOrCreateContainer(new ItemPath(UserType.F_EXTENSION, EXTENSION_MELEE_CONTEXT_ELEMENT)); PrismReference opponentRef = meleeContextContainer.findOrCreateReference(EXTENSION_MELEE_CONTEXT_OPPONENT_REF_ELEMENT); @@ -270,35 +270,35 @@ public void test300MeleeContext() throws Exception { PrismReferenceValue opponentRefValue = new PrismReferenceValue(); opponentRefValue.setObject(userBarbossa); opponentRef.add(opponentRefValue); - + System.out.println("User jack:"); System.out.println(userJack.debugDump()); - + // WHEN String elementJack = prismContext.serializeObjectToString(userJack, getOutputFormat()); - + // THEN System.out.println("Serialized user jack:"); System.out.println(elementJack); - + // TODO: see that there is really the serialized barbossa - + // WHEN PrismObject reparsedUserJack = prismContext.parseObject(elementJack); - + // THEN System.out.println("Re-parsed user jack:"); System.out.println(reparsedUserJack.debugDump()); - + PrismReference reparsedOpponentRef = reparsedUserJack.findReference(new ItemPath(UserType.F_EXTENSION, EXTENSION_MELEE_CONTEXT_ELEMENT, EXTENSION_MELEE_CONTEXT_OPPONENT_REF_ELEMENT)); assertNotNull("No opponent ref (reparsed)", reparsedOpponentRef); PrismReferenceValue reparsedOpponentRefValue = reparsedOpponentRef.getValue(); assertNotNull("No opponent ref value (reparsed)", reparsedOpponentRefValue); PrismObject reparsedUserBarbossa = reparsedOpponentRefValue.getObject(); assertNotNull("No object in opponent ref value (reparsed)", reparsedUserBarbossa); - + PrismAsserts.assertEquivalent("User barbossa", userBarbossa, reparsedUserBarbossa); - + // Make the original user jack suitable for comparison. // Some of the accountRef information is (intentionally) lost in re-parsing therefore erase it before comparing PrismReference jackAccountRef = userJack.findReference(UserType.F_ACCOUNT_REF); @@ -309,68 +309,68 @@ public void test300MeleeContext() throws Exception { accRefVal.setOid(oid); accRefVal.setTargetType(targetType); } - + PrismAsserts.assertEquivalent("User jack", userJack, reparsedUserJack); - + } - + @Test public void test400UserWill() throws Exception { final String TEST_NAME = "test400UserWill"; PrismInternalTestUtil.displayTestTitle(TEST_NAME); - + // GIVEN PrismContext prismContext = constructInitializedPrismContext(); - + // WHEN PrismObject user = prismContext.parseObject(getFile(USER_WILL_FILE_BASENAME)); - + // THEN System.out.println("User:"); System.out.println(user.debugDump()); assertNotNull(user); - + assertUserWill(user); } - + @Test public void test410UserWillRoundTrip() throws Exception { final String TEST_NAME = "test410UserWillRoundTrip"; PrismInternalTestUtil.displayTestTitle(TEST_NAME); - + // GIVEN PrismContext prismContext = constructInitializedPrismContext(); - + // WHEN PrismObject user = prismContext.parseObject(getFile(USER_WILL_FILE_BASENAME)); - + // THEN System.out.println("User:"); System.out.println(user.debugDump()); assertNotNull(user); - + assertUserWill(user); - + // WHEN String serialized = prismContext.serializerFor(getOutputFormat()).serialize(user); - + // THEN assertNotNull(serialized); System.out.println("Serialized user:"); System.out.println(serialized); - + // WHEN PrismObject reparsedUser = prismContext.parseObject(serialized); - + // THEN System.out.println("Re-parsed user:"); System.out.println(reparsedUser.debugDump()); assertNotNull(reparsedUser); - + assertUserWill(reparsedUser); - + } - + @Test public void test500UserElisabethRoundTrip() throws Exception { final String TEST_NAME = "test500UserElisabethRoundTrip"; @@ -415,17 +415,17 @@ protected void assertUserAdhoc(PrismObject user, boolean expectRawInCo assertUserExtensionAdhoc(user); assertVisitor(user, 58); } - + private void assertUserExtensionAdhoc(PrismObject user) { - + PrismContainer extension = user.getExtension(); assertContainerDefinition(extension, "extension", DOMUtil.XSD_ANY, 0, 1); PrismContainerValue extensionValue = extension.getValue(); assertTrue("Extension parent", extensionValue.getParent() == extension); assertNull("Extension ID", extensionValue.getId()); PrismAsserts.assertPropertyValue(extension, USER_ADHOC_BOTTLES_ELEMENT, 20); - + ItemPath bottlesPath = new ItemPath(new QName(NS_FOO,"extension"), USER_ADHOC_BOTTLES_ELEMENT); PrismProperty bottlesProperty = user.findProperty(bottlesPath); assertNotNull("Property "+bottlesPath+" not found", bottlesProperty); @@ -434,76 +434,76 @@ private void assertUserExtensionAdhoc(PrismObject user) { assertNotNull("No definition for bottles", bottlesPropertyDef); PrismAsserts.assertDefinition(bottlesPropertyDef, USER_ADHOC_BOTTLES_ELEMENT, DOMUtil.XSD_INT, 1, -1); assertTrue("Bottles definition is NOT dynamic", bottlesPropertyDef.isDynamic()); - + } - + private void assertUserWill(PrismObject user) throws SchemaException { user.checkConsistence(); user.assertDefinitions("test"); assertUserWillExtension(user); assertVisitor(user,55); } - + private void assertUserWillExtension(PrismObject user) { - + PrismContainer extension = user.getExtension(); assertContainerDefinition(extension, "extension", DOMUtil.XSD_ANY, 0, 1); PrismContainerValue extensionValue = extension.getValue(); assertTrue("Extension parent", extensionValue.getParent() == extension); assertNull("Extension ID", extensionValue.getId()); - + PrismProperty stringType = extension.findProperty(EXTENSION_STRING_TYPE_ELEMENT); PrismAsserts.assertPropertyValue(stringType, "BARbar", "FOObar"); PrismPropertyDefinition stringTypePropertyDef = stringType.getDefinition(); PrismAsserts.assertDefinition(stringTypePropertyDef, EXTENSION_STRING_TYPE_ELEMENT, DOMUtil.XSD_STRING, 0, -1); assertNull("'Indexed' attribute on 'stringType' property is not null", stringTypePropertyDef.isIndexed()); - + PrismProperty singleStringType = extension.findProperty(EXTENSION_SINGLE_STRING_TYPE_ELEMENT); PrismAsserts.assertPropertyValue(singleStringType, "foobar"); PrismPropertyDefinition singleStringTypePropertyDef = singleStringType.getDefinition(); PrismAsserts.assertDefinition(singleStringTypePropertyDef, EXTENSION_SINGLE_STRING_TYPE_ELEMENT, DOMUtil.XSD_STRING, 0, 1); assertNull("'Indexed' attribute on 'singleStringType' property is not null", singleStringTypePropertyDef.isIndexed()); - + PrismProperty doubleType = extension.findProperty(EXTENSION_DOUBLE_TYPE_ELEMENT); PrismAsserts.assertPropertyValue(doubleType, 3.1415926535); PrismPropertyDefinition doubleTypePropertyDef = doubleType.getDefinition(); PrismAsserts.assertDefinition(doubleTypePropertyDef, EXTENSION_DOUBLE_TYPE_ELEMENT, DOMUtil.XSD_DOUBLE, 0, -1); assertNull("'Indexed' attribute on 'doubleType' property is not null", doubleTypePropertyDef.isIndexed()); - + PrismProperty intType = extension.findProperty(EXTENSION_INT_TYPE_ELEMENT); PrismAsserts.assertPropertyValue(intType, 42); PrismPropertyDefinition intTypePropertyDef = intType.getDefinition(); PrismAsserts.assertDefinition(intTypePropertyDef, EXTENSION_INT_TYPE_ELEMENT, DOMUtil.XSD_INT, 0, -1); assertNull("'Indexed' attribute on 'intType' property is not null", intTypePropertyDef.isIndexed()); - + PrismProperty integerType = extension.findProperty(EXTENSION_INTEGER_TYPE_ELEMENT); PrismAsserts.assertPropertyValue(integerType, new BigInteger("19134702400093278081449423917")); PrismPropertyDefinition integerTypePropertyDef = integerType.getDefinition(); PrismAsserts.assertDefinition(integerTypePropertyDef, EXTENSION_INTEGER_TYPE_ELEMENT, DOMUtil.XSD_INTEGER, 0, -1); assertNull("'Indexed' attribute on 'integerType' property is not null", integerTypePropertyDef.isIndexed()); - + PrismProperty longType = extension.findProperty(EXTENSION_LONG_TYPE_ELEMENT); PrismAsserts.assertPropertyValue(longType, 299792458L); PrismPropertyDefinition longTypePropertyDef = longType.getDefinition(); PrismAsserts.assertDefinition(longTypePropertyDef, EXTENSION_LONG_TYPE_ELEMENT, DOMUtil.XSD_LONG, 0, -1); assertNull("'Indexed' attribute on 'longType' property is not null", longTypePropertyDef.isIndexed()); - + PrismProperty dateType = extension.findProperty(EXTENSION_DATE_TYPE_ELEMENT); PrismAsserts.assertPropertyValue(dateType, XmlTypeConverter.createXMLGregorianCalendar(1975, 5, 30, 22, 30, 0)); PrismPropertyDefinition dateTypePropertyDef = dateType.getDefinition(); PrismAsserts.assertDefinition(dateTypePropertyDef, EXTENSION_DATE_TYPE_ELEMENT, DOMUtil.XSD_DATETIME, 0, -1); assertNull("'Indexed' attribute on 'longType' property is not null", dateTypePropertyDef.isIndexed()); - + PrismProperty durationType = extension.findProperty(EXTENSION_DURATION_TYPE_ELEMENT); PrismAsserts.assertPropertyValue(durationType, XmlTypeConverter.createDuration(true, 17, 3, 2, 0, 0, 0)); PrismPropertyDefinition durationTypePropertyDef = durationType.getDefinition(); PrismAsserts.assertDefinition(durationTypePropertyDef, EXTENSION_DURATION_TYPE_ELEMENT, DOMUtil.XSD_DURATION, 0, -1); assertNull("'Indexed' attribute on 'longType' property is not null", durationTypePropertyDef.isIndexed()); - + PrismContainer locationsType = extension.findContainer(EXTENSION_LOCATIONS_ELEMENT); PrismContainerDefinition localtionsDef = locationsType.getDefinition(); PrismAsserts.assertDefinition(localtionsDef, EXTENSION_LOCATIONS_ELEMENT, EXTENSION_LOCATIONS_TYPE_QNAME, 0, -1); - + PrismProperty ignoredType = extension.findProperty(EXTENSION_IGNORED_TYPE_ELEMENT); PrismAsserts.assertPropertyValue(ignoredType, "this is just a fiction"); PrismPropertyDefinition ignoredTypePropertyDef = ignoredType.getDefinition(); @@ -515,7 +515,7 @@ private void assertUserWillExtension(PrismObject user) { PrismPropertyDefinition indexedStringPropertyDef = indexedString.getDefinition(); PrismAsserts.assertDefinition(indexedStringPropertyDef, EXTENSION_SINGLE_STRING_TYPE_ELEMENT, DOMUtil.XSD_STRING, 0, -1); assertEquals("'Indexed' attribute on 'singleStringType' property is wrong", Boolean.FALSE, indexedStringPropertyDef.isIndexed()); - + ItemPath barPath = new ItemPath(new QName(NS_FOO,"extension"), EXTENSION_BAR_ELEMENT); PrismProperty barProperty = user.findProperty(barPath); assertNotNull("Property "+barPath+" not found", barProperty); @@ -530,7 +530,7 @@ private void assertUserWillExtension(PrismObject user) { PrismAsserts.assertDefinition(multiPropertyDef, EXTENSION_MULTI_ELEMENT, DOMUtil.XSD_STRING, 1, -1); assertNull("'Indexed' attribute on 'multi' property is not null", multiPropertyDef.isIndexed()); - + PrismAsserts.assertPropertyValue(extension, EXTENSION_BAR_ELEMENT, "BAR"); PrismAsserts.assertPropertyValue(extension, EXTENSION_NUM_ELEMENT, 42); Collection> multiPVals = extension.findProperty(EXTENSION_MULTI_ELEMENT).getValues(); @@ -568,5 +568,5 @@ private void assertUserElisabethExtension(PrismObject user) { protected void validateXml(String xmlString, PrismContext prismContext) throws SAXException, IOException { } - + } diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismParsingJson.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismParsingJson.java index 5f51f39342c..0f5815ea78f 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismParsingJson.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismParsingJson.java @@ -5,7 +5,7 @@ import com.evolveum.midpoint.prism.PrismContext; public class TestPrismParsingJson extends TestPrismParsing { - + @Override protected String getSubdirName() { return "json"; @@ -15,7 +15,7 @@ protected String getSubdirName() { protected String getFilenameSuffix() { return "json"; } - + @Test public void f() { } diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismParsingXml.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismParsingXml.java index 1dff0bc2414..29c806a4a71 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismParsingXml.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismParsingXml.java @@ -29,51 +29,51 @@ protected String getFilenameSuffix() { protected String getOutputFormat() { return PrismContext.LANG_XML; } - + @Test public void testPrismParseDom() throws Exception { final String TEST_NAME = "testPrismParseDom"; PrismInternalTestUtil.displayTestTitle(TEST_NAME); - + // GIVEN Document document = DOMUtil.parseFile(getFile(USER_JACK_FILE_BASENAME)); Element userElement = DOMUtil.getFirstChildElement(document); - + PrismContext prismContext = constructInitializedPrismContext(); - + // WHEN PrismObject user = prismContext.parserFor(userElement).parse(); - + // THEN System.out.println("User:"); System.out.println(user.debugDump()); assertNotNull(user); - + assertUserJack(user, true); } - + @Test public void testPrismParseDomAdhoc() throws Exception { final String TEST_NAME = "testPrismParseDomAdhoc"; PrismInternalTestUtil.displayTestTitle(TEST_NAME); - + // GIVEN Document document = DOMUtil.parseFile(getFile(USER_JACK_ADHOC_BASENAME)); Element userElement = DOMUtil.getFirstChildElement(document); - + PrismContext prismContext = constructInitializedPrismContext(); - + // WHEN PrismObject user = prismContext.parserFor(userElement).parse(); - + // THEN System.out.println("User:"); System.out.println(user.debugDump()); assertNotNull(user); - + assertUserAdhoc(user, true); } - + @Override protected void validateXml(String xmlString, PrismContext prismContext) throws SAXException, IOException { // Document xmlDocument = DOMUtil.parseDocument(xmlString); diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismSchemaConstruction.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismSchemaConstruction.java index 37cb6da4350..51bdb857510 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismSchemaConstruction.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestPrismSchemaConstruction.java @@ -45,7 +45,7 @@ * */ public class TestPrismSchemaConstruction { - + private static final String NS_MY_SCHEMA = "http://midpoint.evolveum.com/xml/ns/test/my-1"; private static final String WEAPON_TYPE_LOCAL_NAME = "WeaponType"; private static final QName WEAPON_TYPE_QNAME = new QName(NS_MY_SCHEMA, WEAPON_TYPE_LOCAL_NAME); @@ -56,8 +56,8 @@ public class TestPrismSchemaConstruction { private static final int SCHEMA_ROUNDTRIP_LOOP_ATTEMPTS = 10; private static final String WEAPON_PASSWORD_LOCAL_NAME = "password"; private static final String WEAPON_BLADE_LOCAL_NAME = "blade"; - - + + @BeforeSuite public void setupDebug() { PrettyPrinter.setDefaultNamespacePrefix(DEFAULT_NAMESPACE_PREFIX); @@ -66,33 +66,33 @@ public void setupDebug() { @Test public void testConstructSchema() throws SchemaException, SAXException, IOException { System.out.println("===[ testConstructSchema ]==="); - + // GIVEN PrismContext ctx = constructInitializedPrismContext(); - + // WHEN PrismSchema schema = constructSchema(ctx); - + // THEN System.out.println("Constructed schema"); System.out.println(schema.debugDump()); assertSchema(schema); } - + @Test public void testSchemaRoundtrip() throws Exception { System.out.println("===[ testSchemaRoundtrip ]==="); - + // GIVEN PrismContext ctx = constructInitializedPrismContext(); - + schemaRoundtrip(ctx); } - + @Test public void testSchemaRoundtripLoopShareContext() throws Exception { System.out.println("===[ testSchemaRoundtripLoopShareContext ]==="); - + PrismContext ctx = constructInitializedPrismContext(); for(int i=0; i < SCHEMA_ROUNDTRIP_LOOP_ATTEMPTS; i++) { System.out.println("\n--- attempt "+i+"---"); @@ -103,7 +103,7 @@ public void testSchemaRoundtripLoopShareContext() throws Exception { @Test public void testSchemaRoundtripLoopNewContext() throws Exception { System.out.println("===[ testSchemaRoundtripLoopNewContext ]==="); - + for(int i=0; i < SCHEMA_ROUNDTRIP_LOOP_ATTEMPTS; i++) { System.out.println("\n--- attempt "+i+"---"); PrismContext ctx = constructInitializedPrismContext(); @@ -111,24 +111,24 @@ public void testSchemaRoundtripLoopNewContext() throws Exception { } } - + private void schemaRoundtrip(PrismContext ctx) throws SchemaException, SAXException, IOException { - + PrismSchema schema = constructSchema(ctx); assertSchema(schema); - + // WHEN Document xsdDocument = schema.serializeToXsd(); - + // THEN Element xsdElement = DOMUtil.getFirstChildElement(xsdDocument); System.out.println("Serialized schema"); System.out.println(DOMUtil.serializeDOMToString(xsdElement)); - + assertPrefix("xsd", xsdElement); Element displayNameElement = DOMUtil.findElementRecursive(xsdElement, PrismConstants.A_DISPLAY_NAME); assertPrefix(PrismConstants.PREFIX_NS_ANNOTATION, displayNameElement); - + // re-parse PrismSchema reparsedSchema = PrismSchemaImpl.parse(xsdElement, true, "serialized schema", ctx); System.out.println("Re-parsed schema"); @@ -138,7 +138,7 @@ private void schemaRoundtrip(PrismContext ctx) throws SchemaException, SAXExcept private PrismSchema constructSchema(PrismContext prismContext) { PrismSchemaImpl schema = new PrismSchemaImpl(NS_MY_SCHEMA, prismContext); - + ComplexTypeDefinitionImpl weaponTypeDef = (ComplexTypeDefinitionImpl) schema.createComplexTypeDefinition(WEAPON_TYPE_QNAME); PrismPropertyDefinitionImpl kindPropertyDef = weaponTypeDef.createPropertyDefinition(WEAPON_KIND_QNAME, DOMUtil.XSD_STRING); kindPropertyDef.setDisplayName("Weapon kind"); @@ -148,20 +148,20 @@ private PrismSchema constructSchema(PrismContext prismContext) { PrismPropertyDefinitionImpl createTimestampPropertyDef = weaponTypeDef.createPropertyDefinition(WEAPON_CREATE_TIMESTAMP_QNAME, DOMUtil.XSD_DATETIME); createTimestampPropertyDef.setDisplayName("Create timestamp"); createTimestampPropertyDef.setOperational(true); - + schema.createPropertyContainerDefinition(WEAPON_LOCAL_NAME, WEAPON_TYPE_LOCAL_NAME); - + return schema; } - + private void assertSchema(PrismSchema schema) { - assertNotNull("Schema is null", schema); + assertNotNull("Schema is null", schema); assertEquals("Wrong schema namespace", NS_MY_SCHEMA, schema.getNamespace()); Collection definitions = schema.getDefinitions(); assertNotNull("Null definitions", definitions); assertFalse("Empty definitions", definitions.isEmpty()); assertEquals("Unexpected number of definitions in schema", 2, definitions.size()); - + Iterator schemaDefIter = definitions.iterator(); ComplexTypeDefinition weaponTypeDef = (ComplexTypeDefinition)schemaDefIter.next(); assertEquals("Unexpected number of definitions in weaponTypeDef", 5, weaponTypeDef.getDefinitions().size()); @@ -170,30 +170,30 @@ private void assertSchema(PrismSchema schema) { PrismAsserts.assertDefinition(kindPropertyDef, WEAPON_KIND_QNAME, DOMUtil.XSD_STRING, 1, 1); assertEquals("Wrong kindPropertyDef displayName", "Weapon kind", kindPropertyDef.getDisplayName()); assertFalse("kindPropertyDef IS operational", kindPropertyDef.isOperational()); - + PrismPropertyDefinition brandPropertyDef = (PrismPropertyDefinition) weaponTypeDefIter.next(); - PrismAsserts.assertDefinition(brandPropertyDef, new QName(NS_MY_SCHEMA, WEAPON_BRAND_LOCAL_NAME), + PrismAsserts.assertDefinition(brandPropertyDef, new QName(NS_MY_SCHEMA, WEAPON_BRAND_LOCAL_NAME), PrismInternalTestUtil.WEAPONS_WEAPON_BRAND_TYPE_QNAME, 1, 1); - + PrismPropertyDefinition passwordPropertyDef = (PrismPropertyDefinition) weaponTypeDefIter.next(); - PrismAsserts.assertDefinition(passwordPropertyDef, new QName(NS_MY_SCHEMA, WEAPON_PASSWORD_LOCAL_NAME), + PrismAsserts.assertDefinition(passwordPropertyDef, new QName(NS_MY_SCHEMA, WEAPON_PASSWORD_LOCAL_NAME), PrismInternalTestUtil.DUMMY_PROTECTED_STRING_TYPE, 1, 1); - + PrismPropertyDefinition bladePropertyDef = (PrismPropertyDefinition) weaponTypeDefIter.next(); - PrismAsserts.assertDefinition(bladePropertyDef, new QName(NS_MY_SCHEMA, WEAPON_BLADE_LOCAL_NAME), + PrismAsserts.assertDefinition(bladePropertyDef, new QName(NS_MY_SCHEMA, WEAPON_BLADE_LOCAL_NAME), PrismInternalTestUtil.EXTENSION_BLADE_TYPE_QNAME, 1, 1); - + PrismPropertyDefinition createTimestampPropertyDef = (PrismPropertyDefinition) weaponTypeDefIter.next(); PrismAsserts.assertDefinition(createTimestampPropertyDef, WEAPON_CREATE_TIMESTAMP_QNAME, DOMUtil.XSD_DATETIME, 1, 1); assertEquals("Wrong createTimestampPropertyDef displayName", "Create timestamp", createTimestampPropertyDef.getDisplayName()); assertTrue("createTimestampPropertyDef not operational", createTimestampPropertyDef.isOperational()); - + PrismContainerDefinition weaponContDef = (PrismContainerDefinition)schemaDefIter.next(); assertEquals("Wrong complex type def in weaponContDef", weaponTypeDef, weaponContDef.getComplexTypeDefinition()); } - + private void assertPrefix(String expectedPrefix, Element element) { assertEquals("Wrong prefix on element "+DOMUtil.getQName(element), expectedPrefix, element.getPrefix()); - } - + } + } diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestTypeConversion.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestTypeConversion.java index 0f8c1accc0a..5c1c925d33b 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestTypeConversion.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestTypeConversion.java @@ -40,7 +40,7 @@ * */ public class TestTypeConversion { - + private static final String MY_NS = "http://midpoint.evolveum.com/xml/ns/testing/xmlconversion"; private static final String MY_ELEMENT_NAME = "foo"; private static final QName MY_ELEMENT_QNAME = new QName(MY_NS, MY_ELEMENT_NAME); @@ -49,13 +49,13 @@ public class TestTypeConversion { public void setupDebug() { PrettyPrinter.setDefaultNamespacePrefix(DEFAULT_NAMESPACE_PREFIX); } - + @Test public void testXmlDateTimeType() throws Exception { assertEquals("Wrong datetime class", XMLGregorianCalendar.class, XsdTypeMapper.toJavaType(DOMUtil.XSD_DATETIME)); assertEquals("Wrong datetime class", DOMUtil.XSD_DATETIME, XsdTypeMapper.toXsdType(XMLGregorianCalendar.class)); } - + @Test public void testXmlDateTimeValue() throws Exception { String stringDate = "1975-05-30T21:30:00.000Z"; @@ -70,23 +70,23 @@ public void testXmlDateTimeValue() throws Exception { @Test public void testJavaStringToXMLGregorianCalendar() throws Exception { String stringDate = "1975-05-30T21:30:00.000Z"; - + // WHEN XMLGregorianCalendar xmlGregorianCalendar = JavaTypeConverter.convert(XMLGregorianCalendar.class, stringDate); - + // THEN XMLGregorianCalendar expectedCal = XmlTypeConverter.createXMLGregorianCalendar(1975, 5, 30, 21, 30, 0); PrismAsserts.assertEquals("Wrong java value", expectedCal, xmlGregorianCalendar); } - + @Test public void testJavaStringToXMLGregorianCalendarWrongFormat() throws Exception { String stringDate = "blah blah blah"; - + try { // WHEN XMLGregorianCalendar xmlGregorianCalendar = JavaTypeConverter.convert(XMLGregorianCalendar.class, stringDate); - + AssertJUnit.fail("Unexpected success"); } catch (IllegalArgumentException e) { // This is expected @@ -98,21 +98,21 @@ public void testJavaStringToXMLGregorianCalendarWrongFormat() throws Exception { @Test public void testJavaXMLGregorianCalendarToString() throws Exception { XMLGregorianCalendar cal = XmlTypeConverter.createXMLGregorianCalendar(1975, 5, 30, 21, 30, 0); - + // WHEN String string = JavaTypeConverter.convert(String.class, cal); - + // THEN PrismAsserts.assertEquals("Wrong java value", "1975-05-30T21:30:00.000Z", string); } - + @Test public void testJavaXMLGregorianCalendarToLong() throws Exception { XMLGregorianCalendar cal = XmlTypeConverter.createXMLGregorianCalendar(1975, 5, 30, 21, 30, 0); - + // WHEN Long val = JavaTypeConverter.convert(Long.class, cal); - + // THEN PrismAsserts.assertEquals("Wrong java value", 170717400000L, val); } @@ -123,5 +123,5 @@ private Element createElement(String string) { element.setTextContent(string); return element; } - + } diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestUnknownItems.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestUnknownItems.java index a74377caa0e..b14ee2be393 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestUnknownItems.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestUnknownItems.java @@ -44,14 +44,14 @@ public class TestUnknownItems { public void setupDebug() { PrettyPrinter.setDefaultNamespacePrefix(DEFAULT_NAMESPACE_PREFIX); } - + @Test(expectedExceptions = SchemaException.class) public void test010ParseWrongItemStrict() throws Exception { final String TEST_NAME = "testParseWrongItemStrict"; PrismInternalTestUtil.displayTestTitle(TEST_NAME); // GIVEN PrismContext prismContext = constructInitializedPrismContext(); - + // WHEN+THEN try { prismContext.parseObject(WRONG_ITEM_FILE); @@ -60,7 +60,7 @@ public void test010ParseWrongItemStrict() throws Exception { throw e; } } - + @Test public void test020ParseWrongItemCompat() throws Exception { final String TEST_NAME = "testParseWrongItemCompat"; diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestXmlSerialization.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestXmlSerialization.java index de549d92689..9278bbb7d8b 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestXmlSerialization.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/TestXmlSerialization.java @@ -38,18 +38,18 @@ * */ public class TestXmlSerialization { - + @BeforeSuite public void setupDebug() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(DEFAULT_NAMESPACE_PREFIX); PrismTestUtil.resetPrismContext(new PrismInternalTestUtil()); } - + @Test public void testHandlingInvalidChars() throws Exception { final String TEST_NAME = "testHandlingInvalidChars"; displayTestTitle(TEST_NAME); - + // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/crypto/TestProtector.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/crypto/TestProtector.java index 174c766a31a..a8c8f41af80 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/crypto/TestProtector.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/crypto/TestProtector.java @@ -30,83 +30,83 @@ import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; public class TestProtector { - - private static transient Trace LOGGER = TraceManager.getTrace(TestProtector.class); - + + private static transient Trace LOGGER = TraceManager.getTrace(TestProtector.class); + @Test public void testProtectorEncryptionRoundTrip() throws Exception { String value = "someValue"; - + Protector protector256 = PrismInternalTestUtil.createProtector(XMLCipher.AES_256); Protector protector128 = PrismInternalTestUtil.createProtector(XMLCipher.AES_128); - + ProtectedStringType pdt = new ProtectedStringType(); pdt.setClearValue(value); assertFalse(pdt.isEmpty()); assertFalse(pdt.isHashed()); assertFalse(pdt.isEncrypted()); - + // WHEN protector256.encrypt(pdt); - + // THEN assertFalse(pdt.isEmpty()); assertTrue(pdt.isEncrypted()); assertFalse(pdt.isHashed()); assertNull(pdt.getClearValue()); - + // WHEN protector128.decrypt(pdt); - + // THEN assertFalse(pdt.isEmpty()); assertFalse(pdt.isEncrypted()); assertFalse(pdt.isHashed()); AssertJUnit.assertEquals(value, pdt.getClearValue()); - + // WHEN ProtectedStringType pstEnc = protector256.encryptString(value); - + // THEN assertFalse(pstEnc.isEmpty()); assertTrue(pstEnc.isEncrypted()); assertFalse(pstEnc.isHashed()); - + // WHEN String clear = protector256.decryptString(pstEnc); assertNotNull(clear); - + // THEN AssertJUnit.assertEquals(value, clear); - + // WHEN boolean compare1 = protector256.compare(pdt, pstEnc); - + // THEN assertTrue("compare1 failed", compare1); - + // WHEN boolean compare2 = protector256.compare(pstEnc, pdt); - + // THEN assertTrue("compare2 failed", compare2); - + ProtectedStringType wrongPst = new ProtectedStringType(); wrongPst.setClearValue("nonono This is not it"); - + // WHEN boolean compare5 = protector256.compare(pdt, wrongPst); - + // THEN assertFalse("compare5 unexpected success", compare5); - + // WHEN boolean compare6 = protector256.compare(wrongPst, pdt); - + // THEN assertFalse("compare6 unexpected success", compare6); } - + @Test public void testProtectorHashRoundTrip() throws Exception { String value = "someValue"; @@ -201,15 +201,15 @@ public void testProtectorHashRoundTrip() throws Exception { // THEN assertFalse("compare10 unexpected success", compare10); - + ProtectedStringType pstEncHash = new ProtectedStringType(); pstEncHash.setClearValue(value); assertFalse(pstEncHash.isEmpty()); protector256.encrypt(pstEncHash); - + // WHEN protector256.hash(pstEncHash); - + // THEN assertFalse(pstEncHash.isEmpty()); assertTrue(pstEncHash.isHashed()); diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/AccountConstructionType.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/AccountConstructionType.java index 442a7eccfe8..b9c9d484a94 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/AccountConstructionType.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/AccountConstructionType.java @@ -15,10 +15,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.24 at 02:46:19 PM CET +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.02.24 at 02:46:19 PM CET // @@ -39,16 +39,16 @@ /** - * + * * Account construction type is NOT a container. It is a complex-type property. * This tests the ability to deal with complex type properties and also with * dateTime fields in them. - * - * + * + * *

Java class for AccountConstructionType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

  * <complexType name="AccountConstructionType">
  *   <complexContent>
@@ -62,8 +62,8 @@
  *   </complexContent>
  * </complexType>
  * 
- * - * + * + * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "AccountConstructionType", propOrder = { @@ -91,11 +91,11 @@ public List getValue() { /** * Gets the value of the howto property. - * + * * @return * possible object is * {@link String } - * + * */ public String getHowto() { return howto; @@ -103,11 +103,11 @@ public String getHowto() { /** * Sets the value of the howto property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setHowto(String value) { this.howto = value; @@ -115,11 +115,11 @@ public void setHowto(String value) { /** * Gets the value of the when property. - * + * * @return * possible object is * {@link javax.xml.datatype.XMLGregorianCalendar } - * + * */ public XMLGregorianCalendar getWhen() { return when; @@ -127,11 +127,11 @@ public XMLGregorianCalendar getWhen() { /** * Sets the value of the when property. - * + * * @param value * allowed object is * {@link javax.xml.datatype.XMLGregorianCalendar } - * + * */ public void setWhen(XMLGregorianCalendar value) { this.when = value; diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/AccountType.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/AccountType.java index e61aa7abc55..0c25838609a 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/AccountType.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/AccountType.java @@ -15,10 +15,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.22 at 05:53:26 PM CET +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.02.22 at 05:53:26 PM CET // @@ -32,9 +32,9 @@ /** *

Java class for AccountType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

  * <complexType name="AccountType">
  *   <complexContent>
@@ -46,8 +46,8 @@
  *   </complexContent>
  * </complexType>
  * 
- * - * + * + * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "AccountType", propOrder = { @@ -63,11 +63,11 @@ public class AccountType /** * Gets the value of the attributes property. - * + * * @return * possible object is * {@link AttributesType } - * + * */ public AttributesType getAttributes() { return attributes; @@ -75,11 +75,11 @@ public AttributesType getAttributes() { /** * Sets the value of the attributes property. - * + * * @param value * allowed object is * {@link AttributesType } - * + * */ public void setAttributes(AttributesType value) { this.attributes = value; diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/ActivationType.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/ActivationType.java index 0a5c2640b45..80ff9b3f14a 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/ActivationType.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/ActivationType.java @@ -15,10 +15,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.24 at 02:46:19 PM CET +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.02.24 at 02:46:19 PM CET // @@ -37,15 +37,15 @@ /** - * + * * ActivationTyps is a container, therefore the following elements are properties. * This tests the ability to deal with boolean and dateTime properties. - * - * + * + * *

Java class for ActivationType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

  * <complexType name="ActivationType">
  *   <complexContent>
@@ -59,8 +59,8 @@
  *   </complexContent>
  * </complexType>
  * 
- * - * + * + * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ActivationType", propOrder = { @@ -83,10 +83,10 @@ public class ActivationType public final static QName F_ENABLED = new QName(ObjectType.NS_FOO, "enabled"); public final static QName F_VALID_FROM = new QName(ObjectType.NS_FOO, "validFrom"); public final static QName F_VALID_TO = new QName(ObjectType.NS_FOO, "validTo"); - + /** * Gets the value of the enabled property. - * + * */ public boolean isEnabled() { return enabled; @@ -94,7 +94,7 @@ public boolean isEnabled() { /** * Sets the value of the enabled property. - * + * */ public void setEnabled(boolean value) { this.enabled = value; @@ -102,11 +102,11 @@ public void setEnabled(boolean value) { /** * Gets the value of the validFrom property. - * + * * @return * possible object is * {@link XMLGregorianCalendar } - * + * */ public XMLGregorianCalendar getValidFrom() { return validFrom; @@ -114,11 +114,11 @@ public XMLGregorianCalendar getValidFrom() { /** * Sets the value of the validFrom property. - * + * * @param value * allowed object is * {@link XMLGregorianCalendar } - * + * */ public void setValidFrom(XMLGregorianCalendar value) { this.validFrom = value; @@ -126,11 +126,11 @@ public void setValidFrom(XMLGregorianCalendar value) { /** * Gets the value of the validTo property. - * + * * @return * possible object is * {@link XMLGregorianCalendar } - * + * */ public XMLGregorianCalendar getValidTo() { return validTo; @@ -138,11 +138,11 @@ public XMLGregorianCalendar getValidTo() { /** * Sets the value of the validTo property. - * + * * @param value * allowed object is * {@link XMLGregorianCalendar } - * + * */ public void setValidTo(XMLGregorianCalendar value) { this.validTo = value; diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/AssignmentType.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/AssignmentType.java index 6eabcaf2d20..23efba3b71e 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/AssignmentType.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/AssignmentType.java @@ -15,10 +15,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.24 at 02:46:19 PM CET +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.02.24 at 02:46:19 PM CET // @@ -37,9 +37,9 @@ /** *

Java class for AssignmentType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

  * <complexType name="AssignmentType">
  *   <complexContent>
@@ -53,8 +53,8 @@
  *   </complexContent>
  * </complexType>
  * 
- * - * + * + * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "AssignmentType", propOrder = { @@ -71,7 +71,7 @@ public class AssignmentType public final static QName F_NOTE = new QName(ObjectType.NS_FOO, "note"); public final static QName F_ACCOUNT_CONSTRUCTION = new QName(ObjectType.NS_FOO, "accountConstruction"); public final static QName F_ACTIVATION = new QName(ObjectType.NS_FOO, "activation"); - + private final static long serialVersionUID = 201202081233L; protected String description; protected String note; @@ -81,11 +81,11 @@ public class AssignmentType /** * Gets the value of the description property. - * + * * @return * possible object is * {@link String } - * + * */ public String getDescription() { return description; @@ -93,11 +93,11 @@ public String getDescription() { /** * Sets the value of the description property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setDescription(String value) { this.description = value; @@ -113,11 +113,11 @@ public void setNote(String note) { /** * Gets the value of the accountConstruction property. - * + * * @return * possible object is * {@link AccountConstructionType } - * + * */ public AccountConstructionType getAccountConstruction() { return accountConstruction; @@ -125,11 +125,11 @@ public AccountConstructionType getAccountConstruction() { /** * Sets the value of the accountConstruction property. - * + * * @param value * allowed object is * {@link AccountConstructionType } - * + * */ public void setAccountConstruction(AccountConstructionType value) { this.accountConstruction = value; @@ -137,11 +137,11 @@ public void setAccountConstruction(AccountConstructionType value) { /** * Gets the value of the id property. - * + * * @return * possible object is * {@link String } - * + * */ public String getId() { return id; @@ -149,11 +149,11 @@ public String getId() { /** * Sets the value of the id property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setId(String value) { this.id = value; diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/AttributesType.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/AttributesType.java index ef70bec846b..fb2f8ac83f4 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/AttributesType.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/AttributesType.java @@ -15,10 +15,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.22 at 05:53:26 PM CET +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.02.22 at 05:53:26 PM CET // @@ -36,9 +36,9 @@ /** *

Java class for AttributesType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

  * <complexType name="AttributesType">
  *   <complexContent>
@@ -50,8 +50,8 @@
  *   </complexContent>
  * </complexType>
  * 
- * - * + * + * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "AttributesType", propOrder = { @@ -67,26 +67,26 @@ public class AttributesType /** * Gets the value of the any property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the any property. - * + * *

* For example, to add a new item, do as follows: *

      *    getAny().add(newItem);
      * 
- * - * + * + * *

* Objects of the following type(s) are allowed in the list * {@link Object } * {@link Element } - * - * + * + * */ public List getAny() { if (any == null) { diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/DummyProtectedStringType.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/DummyProtectedStringType.java index ccd23d48e06..579bbbe2c5f 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/DummyProtectedStringType.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/DummyProtectedStringType.java @@ -1,8 +1,8 @@ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2014.02.07 at 10:53:52 AM CET +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.02.07 at 10:53:52 AM CET // @@ -16,14 +16,14 @@ /** - * + * * This type mimmicks a complex type that may be used in properties. - * - * + * + * *

Java class for DummyProtectedStringType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

  * <complexType name="DummyProtectedStringType">
  *   <complexContent>
@@ -35,8 +35,8 @@
  *   </complexContent>
  * </complexType>
  * 
- * - * + * + * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DummyProtectedStringType", propOrder = { @@ -52,11 +52,11 @@ public class DummyProtectedStringType /** * Gets the value of the value property. - * + * * @return * possible object is * {@link String } - * + * */ public String getValue() { return value; @@ -64,11 +64,11 @@ public String getValue() { /** * Sets the value of the value property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setValue(String value) { this.value = value; diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/EventCategoryFilterType.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/EventCategoryFilterType.java index fc87e477034..41702df1c25 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/EventCategoryFilterType.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/EventCategoryFilterType.java @@ -48,7 +48,7 @@ public class EventCategoryFilterType /** * Creates a new {@code EventCategoryFilterType} instance. - * + * */ public EventCategoryFilterType() { // CC-XJC Version 2.0 Build 2011-09-16T18:27:24+0000 @@ -57,8 +57,8 @@ public EventCategoryFilterType() { /** * Creates a new {@code EventCategoryFilterType} instance by deeply copying a given {@code EventCategoryFilterType} instance. - * - * + * + * * @param o * The instance to copy. * @throws NullPointerException @@ -78,25 +78,25 @@ public EventCategoryFilterType(final EventCategoryFilterType o) { /** * Gets the value of the category property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the category property. - * + * *

* For example, to add a new item, do as follows: *

      *    getCategory().add(newItem);
      * 
- * - * + * + * *

* Objects of the following type(s) are allowed in the list * {@link String } - * - * + * + * */ public List getCategory() { if (category == null) { @@ -108,7 +108,7 @@ public List getCategory() { /** * Generates a String representation of the contents of this type. * This is an extension method, produced by the 'ts' xjc plugin - * + * */ public int hashCode(ObjectLocator locator, HashCodeStrategy strategy) { @@ -156,7 +156,7 @@ public boolean equals(Object object) { /** * Copies all values of property {@code Category} deeply. - * + * * @param source * The source to copy from. * @param target @@ -183,8 +183,8 @@ private static void copyCategory(final List source, final List t /** * Creates and returns a deep copy of this object. - * - * + * + * * @return * A deep copy of this object. */ diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/EventHandlerChainType.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/EventHandlerChainType.java index 0f6d87db3f9..10bc3327bc4 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/EventHandlerChainType.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/EventHandlerChainType.java @@ -53,7 +53,7 @@ public class EventHandlerChainType /** * Creates a new {@code EventHandlerChainType} instance. - * + * */ public EventHandlerChainType() { // CC-XJC Version 2.0 Build 2011-09-16T18:27:24+0000 @@ -62,8 +62,8 @@ public EventHandlerChainType() { /** * Creates a new {@code EventHandlerChainType} instance by deeply copying a given {@code EventHandlerChainType} instance. - * - * + * + * * @param o * The instance to copy. * @throws NullPointerException @@ -83,20 +83,20 @@ public EventHandlerChainType(final EventHandlerChainType o) { /** * Gets the value of the handler property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the handler property. - * + * *

* For example, to add a new item, do as follows: *

      *    getHandler().add(newItem);
      * 
- * - * + * + * *

* Objects of the following type(s) are allowed in the list * {@link javax.xml.bind.JAXBElement }{@code <}{@link SimpleWorkflowNotifierType }{@code >} @@ -112,8 +112,8 @@ public EventHandlerChainType(final EventHandlerChainType o) { * {@link javax.xml.bind.JAXBElement }{@code <}{@link EventHandlerForkType }{@code >} * {@link javax.xml.bind.JAXBElement }{@code <}{@link EventOperationFilterType }{@code >} * {@link javax.xml.bind.JAXBElement }{@code <}{@link SimpleUserNotifierType }{@code >} - * - * + * + * */ public List> getHandler() { if (handler == null) { @@ -125,7 +125,7 @@ public List> getHandler() { /** * Generates a String representation of the contents of this type. * This is an extension method, produced by the 'ts' xjc plugin - * + * */ public int hashCode(ObjectLocator locator, HashCodeStrategy strategy) { int currentHashCode = super.hashCode(locator, strategy); @@ -172,7 +172,7 @@ public boolean equals(Object object) { /** * Copies all values of property {@code Handler} deeply. - * + * * @param source * The source to copy from. * @param target @@ -222,7 +222,7 @@ private static void copyHandler(final List} instance. - * + * * @param e * The instance to copy or {@code null}. * @return @@ -244,7 +244,7 @@ private static JAXBElement copyOfEventOperationFilterT /** * Creates and returns a deep copy of a given {@code javax.xml.bind.JAXBElement} instance. - * + * * @param e * The instance to copy or {@code null}. * @return @@ -265,7 +265,7 @@ private static JAXBElement copyOfEventStatusFilterTypeEle /** * Creates and returns a deep copy of a given {@code javax.xml.bind.JAXBElement} instance. - * + * * @param e * The instance to copy or {@code null}. * @return @@ -287,7 +287,7 @@ private static JAXBElement copyOfEventCategoryFilterTyp /** * Creates and returns a deep copy of a given {@code javax.xml.bind.JAXBElement} instance. - * + * * @param e * The instance to copy or {@code null}. * @return @@ -309,7 +309,7 @@ private static JAXBElement copyOfEventHandlerChainTypeEle /** * Creates and returns a deep copy of a given {@code javax.xml.bind.JAXBElement} instance. - * + * * @param e * The instance to copy or {@code null}. * @return @@ -330,8 +330,8 @@ private static JAXBElement copyOfEventHandlerTypeElement(final /** * Creates and returns a deep copy of this object. - * - * + * + * * @return * A deep copy of this object. */ diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/EventHandlerType.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/EventHandlerType.java index cb49d355ff3..dbbe67f4155 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/EventHandlerType.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/EventHandlerType.java @@ -35,14 +35,14 @@ /** - * + * * An event handler - typically either a filter, a notifier, a fork (fan-out), or a chain of handlers. - * - * + * + * *

Java class for EventHandlerType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

  * <complexType name="EventHandlerType">
  *   <complexContent>
@@ -55,8 +55,8 @@
  *   </complexContent>
  * </complexType>
  * 
- * - * + * + * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EventHandlerType", propOrder = { @@ -77,7 +77,7 @@ public class EventHandlerType implements Serializable, Cloneable, Equals, HashCo /** * Creates a new {@code EventHandlerType} instance. - * + * */ public EventHandlerType() { // CC-XJC Version 2.0 Build 2011-09-16T18:27:24+0000 @@ -86,8 +86,8 @@ public EventHandlerType() { /** * Creates a new {@code EventHandlerType} instance by deeply copying a given {@code EventHandlerType} instance. - * - * + * + * * @param o * The instance to copy. * @throws NullPointerException @@ -105,29 +105,29 @@ public EventHandlerType(final EventHandlerType o) { /** * Gets the value of the description property. - * + * * @return * possible object is * {@link String } - * + * */ /** * Sets the value of the description property. - * + * * @param value * allowed object is * {@link String } - * + * */ /** * Gets the value of the name property. - * + * * @return * possible object is * {@link String } - * + * */ public String getName() { return name; @@ -135,11 +135,11 @@ public String getName() { /** * Sets the value of the name property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setName(String value) { this.name = value; @@ -148,7 +148,7 @@ public void setName(String value) { /** * Generates a String representation of the contents of this type. * This is an extension method, produced by the 'ts' xjc plugin - * + * */ public int hashCode(ObjectLocator locator, HashCodeStrategy strategy) { @@ -193,8 +193,8 @@ public boolean equals(Object object) { /** * Creates and returns a deep copy of this object. - * - * + * + * * @return * A deep copy of this object. */ diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/EventOperationFilterType.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/EventOperationFilterType.java index 923fa4bdc47..6a3d3c5d3a3 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/EventOperationFilterType.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/EventOperationFilterType.java @@ -37,9 +37,9 @@ /** *

Java class for EventOperationFilterType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

  * <complexType name="EventOperationFilterType">
  *   <complexContent>
@@ -51,8 +51,8 @@
  *   </complexContent>
  * </complexType>
  * 
- * - * + * + * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EventOperationFilterType", propOrder = { @@ -68,7 +68,7 @@ public class EventOperationFilterType /** * Creates a new {@code EventOperationFilterType} instance. - * + * */ public EventOperationFilterType() { // CC-XJC Version 2.0 Build 2011-09-16T18:27:24+0000 @@ -77,8 +77,8 @@ public EventOperationFilterType() { /** * Creates a new {@code EventOperationFilterType} instance by deeply copying a given {@code EventOperationFilterType} instance. - * - * + * + * * @param o * The instance to copy. * @throws NullPointerException @@ -98,25 +98,25 @@ public EventOperationFilterType(final EventOperationFilterType o) { /** * Gets the value of the operation property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the operation property. - * + * *

* For example, to add a new item, do as follows: *

      *    getOperation().add(newItem);
      * 
- * - * + * + * *

* Objects of the following type(s) are allowed in the list * {@link EventOperationType } - * - * + * + * */ public List getOperation() { if (operation == null) { @@ -128,7 +128,7 @@ public List getOperation() { /** * Generates a String representation of the contents of this type. * This is an extension method, produced by the 'ts' xjc plugin - * + * */ public int hashCode(ObjectLocator locator, HashCodeStrategy strategy) { @@ -176,7 +176,7 @@ public boolean equals(Object object) { /** * Copies all values of property {@code Operation} deeply. - * + * * @param source * The source to copy from. * @param target @@ -203,8 +203,8 @@ private static void copyOperation(final List source, final List /** * Creates and returns a deep copy of this object. - * - * + * + * * @return * A deep copy of this object. */ diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/EventStatusFilterType.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/EventStatusFilterType.java index a3ed945d48e..0a3d62e464b 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/EventStatusFilterType.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/EventStatusFilterType.java @@ -37,9 +37,9 @@ /** *

Java class for EventStatusFilterType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

  * <complexType name="EventStatusFilterType">
  *   <complexContent>
@@ -51,8 +51,8 @@
  *   </complexContent>
  * </complexType>
  * 
- * - * + * + * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EventStatusFilterType", propOrder = { @@ -68,7 +68,7 @@ public class EventStatusFilterType /** * Creates a new {@code EventStatusFilterType} instance. - * + * */ public EventStatusFilterType() { // CC-XJC Version 2.0 Build 2011-09-16T18:27:24+0000 @@ -77,8 +77,8 @@ public EventStatusFilterType() { /** * Creates a new {@code EventStatusFilterType} instance by deeply copying a given {@code EventStatusFilterType} instance. - * - * + * + * * @param o * The instance to copy. * @throws NullPointerException @@ -98,25 +98,25 @@ public EventStatusFilterType(final EventStatusFilterType o) { /** * Gets the value of the status property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the status property. - * + * *

* For example, to add a new item, do as follows: *

      *    getStatus().add(newItem);
      * 
- * - * + * + * *

* Objects of the following type(s) are allowed in the list * {@link String } - * - * + * + * */ public List getStatus() { if (status == null) { @@ -128,7 +128,7 @@ public List getStatus() { /** * Generates a String representation of the contents of this type. * This is an extension method, produced by the 'ts' xjc plugin - * + * */ public int hashCode(ObjectLocator locator, HashCodeStrategy strategy) { @@ -176,7 +176,7 @@ public boolean equals(Object object) { /** * Copies all values of property {@code Status} deeply. - * + * * @param source * The source to copy from. * @param target @@ -203,8 +203,8 @@ private static void copyStatus(final List source, final List tar /** * Creates and returns a deep copy of this object. - * - * + * + * * @return * A deep copy of this object. */ diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/Extension.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/Extension.java index 506391cb7f8..7aa5fe6235b 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/Extension.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/Extension.java @@ -30,9 +30,9 @@ /** *

Java class for anonymous complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

  * <complexType>
  *   <complexContent>
@@ -44,8 +44,8 @@
  *   </complexContent>
  * </complexType>
  * 
- * - * + * + * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { @@ -62,26 +62,26 @@ public class Extension /** * Gets the value of the any property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the any property. - * + * *

* For example, to add a new item, do as follows: *

      *    getAny().add(newItem);
      * 
- * - * + * + * *

* Objects of the following type(s) are allowed in the list * {@link Element } * {@link Object } - * - * + * + * */ public List getAny() { if (any == null) { diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/FooObjectClass.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/FooObjectClass.java index de1d953d898..e52e2ee5463 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/FooObjectClass.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/FooObjectClass.java @@ -1,8 +1,8 @@ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2014.02.07 at 10:53:52 AM CET +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.02.07 at 10:53:52 AM CET // @@ -19,9 +19,9 @@ /** *

Java class for FooObjectClass complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

  * <complexType name="FooObjectClass">
  *   <complexContent>
@@ -35,8 +35,8 @@
  *   </complexContent>
  * </complexType>
  * 
- * - * + * + * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "FooObjectClass", propOrder = { @@ -57,11 +57,11 @@ public class FooObjectClass /** * Gets the value of the uid property. - * + * * @return * possible object is * {@link String } - * + * */ public String getUid() { return uid; @@ -69,11 +69,11 @@ public String getUid() { /** * Sets the value of the uid property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setUid(String value) { this.uid = value; @@ -81,11 +81,11 @@ public void setUid(String value) { /** * Gets the value of the name property. - * + * * @return * possible object is * {@link String } - * + * */ public String getName() { return name; @@ -93,11 +93,11 @@ public String getName() { /** * Sets the value of the name property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setName(String value) { this.name = value; @@ -105,25 +105,25 @@ public void setName(String value) { /** * Gets the value of the foo property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the foo property. - * + * *

* For example, to add a new item, do as follows: *

      *    getFoo().add(newItem);
      * 
- * - * + * + * *

* Objects of the following type(s) are allowed in the list * {@link String } - * - * + * + * */ public List getFoo() { if (foo == null) { diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/ObjectFactory.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/ObjectFactory.java index fa6a852ae78..b47404692f7 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/ObjectFactory.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/ObjectFactory.java @@ -26,18 +26,18 @@ /** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the com.evolveum.midpoint.xml.ns.test.foo_1 package. - *

An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are + * This object contains factory methods for each + * Java content interface and Java element interface + * generated in the com.evolveum.midpoint.xml.ns.test.foo_1 package. + *

An ObjectFactory allows you to programatically + * construct new instances of the Java representation + * for XML content. The Java representation of XML + * content can consist of schema derived interfaces + * and classes representing the binding of schema + * type definitions, element declarations and model + * groups. Factory methods for each of these are * provided in this class. - * + * */ @XmlRegistry public class ObjectFactory { @@ -58,14 +58,14 @@ public class ObjectFactory { /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.evolveum.midpoint.xml.ns.test.foo_1 - * + * */ public ObjectFactory() { } /** * Create an instance of {@link ObjectReferenceType } - * + * */ public ObjectReferenceType createObjectReferenceType() { return new ObjectReferenceType(); @@ -73,7 +73,7 @@ public ObjectReferenceType createObjectReferenceType() { /** * Create an instance of {@link Extension } - * + * */ public Extension createExtension() { return new Extension(); @@ -81,7 +81,7 @@ public Extension createExtension() { /** * Create an instance of {@link ResourceType } - * + * */ public ResourceType createResourceType() { return new ResourceType(); @@ -89,7 +89,7 @@ public ResourceType createResourceType() { /** * Create an instance of {@link AccountType } - * + * */ public AccountType createAccountType() { return new AccountType(); @@ -97,7 +97,7 @@ public AccountType createAccountType() { /** * Create an instance of {@link UserType } - * + * */ public UserType createUserType() { return new UserType(); @@ -105,7 +105,7 @@ public UserType createUserType() { /** * Create an instance of {@link FooObjectClass } - * + * */ public FooObjectClass createFooObjectClass() { return new FooObjectClass(); @@ -113,7 +113,7 @@ public FooObjectClass createFooObjectClass() { /** * Create an instance of {@link ActivationType } - * + * */ public ActivationType createActivationType() { return new ActivationType(); @@ -121,7 +121,7 @@ public ActivationType createActivationType() { /** * Create an instance of {@link AttributesType } - * + * */ public AttributesType createAttributesType() { return new AttributesType(); @@ -129,7 +129,7 @@ public AttributesType createAttributesType() { /** * Create an instance of {@link AccountConstructionType } - * + * */ public AccountConstructionType createAccountConstructionType() { return new AccountConstructionType(); @@ -137,7 +137,7 @@ public AccountConstructionType createAccountConstructionType() { /** * Create an instance of {@link DummyProtectedStringType } - * + * */ public DummyProtectedStringType createDummyProtectedStringType() { return new DummyProtectedStringType(); @@ -145,7 +145,7 @@ public DummyProtectedStringType createDummyProtectedStringType() { /** * Create an instance of {@link AssignmentType } - * + * */ public AssignmentType createAssignmentType() { return new AssignmentType(); @@ -153,7 +153,7 @@ public AssignmentType createAssignmentType() { /** * Create an instance of {@link ObjectReferenceType.Filter } - * + * */ public ObjectReferenceType.Filter createObjectReferenceTypeFilter() { return new ObjectReferenceType.Filter(); @@ -161,7 +161,7 @@ public ObjectReferenceType.Filter createObjectReferenceTypeFilter() { /** * Create an instance of {@link ObjectReferenceType.Object } - * + * */ public ObjectReferenceType.Object createObjectReferenceTypeObject() { return new ObjectReferenceType.Object(); @@ -169,7 +169,7 @@ public ObjectReferenceType.Object createObjectReferenceTypeObject() { /** * Create an instance of {@link JAXBElement }{@code <}{@link ObjectType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://midpoint.evolveum.com/xml/ns/test/foo-1.xsd", name = "object") public JAXBElement createObject(ObjectType value) { @@ -178,7 +178,7 @@ public JAXBElement createObject(ObjectType value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link PolyStringType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://midpoint.evolveum.com/xml/ns/test/foo-1.xsd", name = "name") public JAXBElement createName(PolyStringType value) { @@ -187,7 +187,7 @@ public JAXBElement createName(PolyStringType value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link ResourceType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://midpoint.evolveum.com/xml/ns/test/foo-1.xsd", name = "resource") public JAXBElement createResource(ResourceType value) { @@ -196,7 +196,7 @@ public JAXBElement createResource(ResourceType value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link UserType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://midpoint.evolveum.com/xml/ns/test/foo-1.xsd", name = "user") public JAXBElement createUser(UserType value) { @@ -205,7 +205,7 @@ public JAXBElement createUser(UserType value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://midpoint.evolveum.com/xml/ns/test/foo-1.xsd", name = "displayName") public JAXBElement createDisplayName(String value) { @@ -214,7 +214,7 @@ public JAXBElement createDisplayName(String value) { /** * Create an instance of {@link JAXBElement }{@code <}{@link AccountType }{@code >}} - * + * */ @XmlElementDecl(namespace = "http://midpoint.evolveum.com/xml/ns/test/foo-1.xsd", name = "account") public JAXBElement createAccount(AccountType value) { diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/ObjectReferenceType.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/ObjectReferenceType.java index 1416d80dbb5..05adcf05cf5 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/ObjectReferenceType.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/ObjectReferenceType.java @@ -1,8 +1,8 @@ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2014.02.07 at 10:53:52 AM CET +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.02.07 at 10:53:52 AM CET // @@ -24,14 +24,14 @@ /** - * + * * Reference to an object. It contains OID of the object that it refers to. - * - * + * + * *

Java class for ObjectReferenceType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

  * <complexType name="ObjectReferenceType">
  *   <complexContent>
@@ -68,8 +68,8 @@
  *   </complexContent>
  * </complexType>
  * 
- * - * + * + * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ObjectReferenceType", propOrder = { @@ -92,11 +92,11 @@ public class ObjectReferenceType /** * Gets the value of the description property. - * + * * @return * possible object is * {@link String } - * + * */ public String getDescription() { return description; @@ -104,11 +104,11 @@ public String getDescription() { /** * Sets the value of the description property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setDescription(String value) { this.description = value; @@ -116,11 +116,11 @@ public void setDescription(String value) { /** * Gets the value of the filter property. - * + * * @return * possible object is * {@link ObjectReferenceType.Filter } - * + * */ public ObjectReferenceType.Filter getFilter() { return filter; @@ -128,11 +128,11 @@ public ObjectReferenceType.Filter getFilter() { /** * Sets the value of the filter property. - * + * * @param value * allowed object is * {@link ObjectReferenceType.Filter } - * + * */ public void setFilter(ObjectReferenceType.Filter value) { this.filter = value; @@ -140,11 +140,11 @@ public void setFilter(ObjectReferenceType.Filter value) { /** * Gets the value of the object property. - * + * * @return * possible object is * {@link ObjectReferenceType.Object } - * + * */ public ObjectReferenceType.Object getObject() { return object; @@ -152,11 +152,11 @@ public ObjectReferenceType.Object getObject() { /** * Sets the value of the object property. - * + * * @param value * allowed object is * {@link ObjectReferenceType.Object } - * + * */ public void setObject(ObjectReferenceType.Object value) { this.object = value; @@ -164,11 +164,11 @@ public void setObject(ObjectReferenceType.Object value) { /** * Gets the value of the oid property. - * + * * @return * possible object is * {@link String } - * + * */ public String getOid() { return oid; @@ -176,11 +176,11 @@ public String getOid() { /** * Sets the value of the oid property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setOid(String value) { this.oid = value; @@ -188,11 +188,11 @@ public void setOid(String value) { /** * Gets the value of the type property. - * + * * @return * possible object is * {@link QName } - * + * */ public QName getType() { return type; @@ -200,11 +200,11 @@ public QName getType() { /** * Sets the value of the type property. - * + * * @param value * allowed object is * {@link QName } - * + * */ public void setType(QName value) { this.type = value; @@ -213,9 +213,9 @@ public void setType(QName value) { /** *

Java class for anonymous complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

      * <complexType>
      *   <complexContent>
@@ -227,8 +227,8 @@ public void setType(QName value) {
      *   </complexContent>
      * </complexType>
      * 
- * - * + * + * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { @@ -244,26 +244,26 @@ public static class Filter /** * Gets the value of the any property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the any property. - * + * *

* For example, to add a new item, do as follows: *

          *    getAny().add(newItem);
          * 
- * - * + * + * *

* Objects of the following type(s) are allowed in the list * {@link Element } * {@link java.lang.Object } - * - * + * + * */ public List getAny() { if (any == null) { @@ -277,9 +277,9 @@ public List getAny() { /** *

Java class for anonymous complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

      * <complexType>
      *   <complexContent>
@@ -292,8 +292,8 @@ public List getAny() {
      *   </complexContent>
      * </complexType>
      * 
- * - * + * + * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { @@ -311,26 +311,26 @@ public static class Object /** * Gets the value of the any property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the any property. - * + * *

* For example, to add a new item, do as follows: *

          *    getAny().add(newItem);
          * 
- * - * + * + * *

* Objects of the following type(s) are allowed in the list * {@link Element } * {@link java.lang.Object } - * - * + * + * */ public List getAny() { if (any == null) { @@ -341,15 +341,15 @@ public List getAny() { /** * Gets a map that contains attributes that aren't bound to any typed property on this class. - * + * *

- * the map is keyed by the name of the attribute and + * the map is keyed by the name of the attribute and * the value is the string value of the attribute. - * + * * the map returned by this method is live, and you can add new attribute * by updating the map directly. Because of this design, there's no setter. - * - * + * + * * @return * always non-null */ diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/ObjectType.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/ObjectType.java index 13c933790b4..56be56dda1f 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/ObjectType.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/ObjectType.java @@ -33,9 +33,9 @@ /** *

Java class for ObjectType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

  * <complexType name="ObjectType">
  *   <complexContent>
@@ -51,8 +51,8 @@
  *   </complexContent>
  * </complexType>
  * 
- * - * + * + * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ObjectType", propOrder = { @@ -76,7 +76,7 @@ public abstract class ObjectType public final static QName F_DESCRIPTION = new QName(NS_FOO, "description"); public final static QName F_EXTENSION = new QName(NS_FOO, "extension"); public final static QName F_PARENT_ORG_REF = new QName(NS_FOO, "parentOrgRef"); - + private final static long serialVersionUID = 201202081233L; protected PolyStringType name; protected String description; @@ -89,11 +89,11 @@ public abstract class ObjectType /** * Gets the value of the name property. - * + * * @return * possible object is * {@link String } - * + * */ public PolyStringType getName() { return name; @@ -101,11 +101,11 @@ public PolyStringType getName() { /** * Sets the value of the name property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setName(PolyStringType value) { this.name = value; @@ -113,11 +113,11 @@ public void setName(PolyStringType value) { /** * Gets the value of the description property. - * + * * @return * possible object is * {@link String } - * + * */ public String getDescription() { return description; @@ -125,11 +125,11 @@ public String getDescription() { /** * Sets the value of the description property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setDescription(String value) { this.description = value; @@ -137,11 +137,11 @@ public void setDescription(String value) { /** * Gets the value of the extension property. - * + * * @return * possible object is * {@link Extension } - * + * */ public Extension getExtension() { return extension; @@ -149,11 +149,11 @@ public Extension getExtension() { /** * Sets the value of the extension property. - * + * * @param value * allowed object is * {@link Extension } - * + * */ public void setExtension(Extension value) { this.extension = value; @@ -161,11 +161,11 @@ public void setExtension(Extension value) { /** * Gets the value of the oid property. - * + * * @return * possible object is * {@link String } - * + * */ public String getOid() { return oid; @@ -173,11 +173,11 @@ public String getOid() { /** * Sets the value of the oid property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setOid(String value) { this.oid = value; @@ -185,11 +185,11 @@ public void setOid(String value) { /** * Gets the value of the version property. - * + * * @return * possible object is * {@link String } - * + * */ public String getVersion() { return version; @@ -197,11 +197,11 @@ public String getVersion() { /** * Sets the value of the version property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setVersion(String value) { this.version = value; @@ -216,7 +216,7 @@ public String toDebugName() { public String toDebugType() { return "object"; } - + @Override public PrismObject asPrismObject() { throw new UnsupportedOperationException("not implemented yet"); diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/ResourceType.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/ResourceType.java index 66ca65be043..add71ec154b 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/ResourceType.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/ResourceType.java @@ -1,8 +1,8 @@ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2014.02.07 at 10:53:52 AM CET +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2014.02.07 at 10:53:52 AM CET // @@ -20,9 +20,9 @@ /** *

Java class for ResourceType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

  * <complexType name="ResourceType">
  *   <complexContent>
@@ -34,8 +34,8 @@
  *   </complexContent>
  * </complexType>
  * 
- * - * + * + * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ResourceType", propOrder = { @@ -43,18 +43,18 @@ }) public class ResourceType extends ObjectType implements Serializable { private final static long serialVersionUID = 201202081233L; - + public final static QName F_SCHEMA = new QName(NS_FOO, "schema"); - + protected SchemaDefinitionType schema; /** * Gets the value of the schema property. - * + * * @return * possible object is * {@link SchemaDefinitionType } - * + * */ public SchemaDefinitionType getSchema() { return schema; @@ -62,11 +62,11 @@ public SchemaDefinitionType getSchema() { /** * Sets the value of the schema property. - * + * * @param value * allowed object is * {@link SchemaDefinitionType } - * + * */ public void setSchema(SchemaDefinitionType value) { this.schema = value; diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/UserType.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/UserType.java index 6349a944dab..6532f23ffe1 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/UserType.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/foo/UserType.java @@ -15,10 +15,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 -// See http://java.sun.com/xml/jaxb -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2012.02.11 at 12:54:37 PM CET +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.02.11 at 12:54:37 PM CET // @@ -36,9 +36,9 @@ /** *

Java class for UserType complex type. - * + * *

The following schema fragment specifies the expected content contained within this class. - * + * *

  * <complexType name="UserType">
  *   <complexContent>
@@ -55,8 +55,8 @@
  *   </complexContent>
  * </complexType>
  * 
- * - * + * + * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "UserType", propOrder = { @@ -68,7 +68,7 @@ "assignment", "activation", "specialWithInternalizedName", - "singleActivation", + "singleActivation", "multiActivation", "multiActivationCopy", "singleConstruction", @@ -115,17 +115,17 @@ public class UserType protected AccountConstructionType singleConstruction; protected List multiConstruction; protected List multiConstructionCopy; - + @XmlElement(name = "special") protected String specialWithInternalizedName; // internal name here differs from the one in serialized form /** * Gets the value of the fullName property. - * + * * @return * possible object is * {@link String } - * + * */ public String getFullName() { return fullName; @@ -133,11 +133,11 @@ public String getFullName() { /** * Sets the value of the fullName property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setFullName(String value) { this.fullName = value; @@ -145,11 +145,11 @@ public void setFullName(String value) { /** * Gets the value of the givenName property. - * + * * @return * possible object is * {@link String } - * + * */ public String getGivenName() { return givenName; @@ -157,11 +157,11 @@ public String getGivenName() { /** * Sets the value of the givenName property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setGivenName(String value) { this.givenName = value; @@ -169,11 +169,11 @@ public void setGivenName(String value) { /** * Gets the value of the familyName property. - * + * * @return * possible object is * {@link String } - * + * */ public String getFamilyName() { return familyName; @@ -181,11 +181,11 @@ public String getFamilyName() { /** * Sets the value of the familyName property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setFamilyName(String value) { this.familyName = value; @@ -193,25 +193,25 @@ public void setFamilyName(String value) { /** * Gets the value of the additionalNames property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the additionalNames property. - * + * *

* For example, to add a new item, do as follows: *

      *    getAdditionalNames().add(newItem);
      * 
- * - * + * + * *

* Objects of the following type(s) are allowed in the list * {@link String } - * - * + * + * */ public List getAdditionalNames() { if (additionalNames == null) { @@ -219,14 +219,14 @@ public List getAdditionalNames() { } return this.additionalNames; } - + /** * Gets the value of the locality property. - * + * * @return * possible object is * {@link String } - * + * */ public String getLocality() { return locality; @@ -234,11 +234,11 @@ public String getLocality() { /** * Sets the value of the locality property. - * + * * @param value * allowed object is * {@link String } - * + * */ public void setLocality(String value) { this.locality = value; @@ -246,25 +246,25 @@ public void setLocality(String value) { /** * Gets the value of the assignment property. - * + * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the assignment property. - * + * *

* For example, to add a new item, do as follows: *

      *    getAssignment().add(newItem);
      * 
- * - * + * + * *

* Objects of the following type(s) are allowed in the list * {@link AssignmentType } - * - * + * + * */ public List getAssignment() { if (assignment == null) { @@ -275,11 +275,11 @@ public List getAssignment() { /** * Gets the value of the activation property. - * + * * @return * possible object is * {@link ActivationType } - * + * */ public ActivationType getActivation() { return activation; @@ -287,11 +287,11 @@ public ActivationType getActivation() { /** * Sets the value of the activation property. - * + * * @param value * allowed object is * {@link ActivationType } - * + * */ public void setActivation(ActivationType value) { this.activation = value; diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/lex/AbstractLexicalProcessorTest.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/lex/AbstractLexicalProcessorTest.java index febcaa152e8..03c6b3dc272 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/lex/AbstractLexicalProcessorTest.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/lex/AbstractLexicalProcessorTest.java @@ -58,8 +58,8 @@ * */ public abstract class AbstractLexicalProcessorTest { - - private static final QName XSD_COMPLEX_TYPE_ELEMENT_NAME + + private static final QName XSD_COMPLEX_TYPE_ELEMENT_NAME = new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "complexType"); public static final String EVENT_HANDLER_FILE_BASENAME = "event-handler"; @@ -75,26 +75,26 @@ public void setupDebug() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(DEFAULT_NAMESPACE_PREFIX); PrismTestUtil.resetPrismContext(new PrismInternalTestUtil()); } - + protected abstract String getSubdirName(); - + protected abstract String getFilenameSuffix(); - + protected File getCommonSubdir() { return new File(COMMON_DIR_PATH, getSubdirName()); } - + protected File getFile(String baseName) { return new File(getCommonSubdir(), baseName+"."+getFilenameSuffix()); } - + protected abstract LexicalProcessor createParser(); @Test public void testParseUserToPrism() throws Exception { final String TEST_NAME = "testParseUserToPrism"; displayTestTitle(TEST_NAME); - + // GIVEN LexicalProcessor lexicalProcessor = createParser(); PrismContext prismContext = PrismTestUtil.getPrismContext(); @@ -103,18 +103,18 @@ public void testParseUserToPrism() throws Exception { RootXNode xnode = lexicalProcessor.read(getFileSource(USER_JACK_FILE_BASENAME), ParsingContext.createDefault()); System.out.println("XNode after parsing:"); System.out.println(xnode.debugDump()); - + // WHEN (parse to prism) PrismObject user = prismContext.parserFor(xnode).parse(); - + // THEN System.out.println("Parsed user:"); System.out.println(user.debugDump()); assertUserJackXNodeOrdering("serialized xnode", xnode); - + assertUserJack(user, true); - + } ParserSource getFileSource(String basename) { @@ -125,7 +125,7 @@ ParserSource getFileSource(String basename) { public void testParseUserRoundTrip() throws Exception { final String TEST_NAME = "testParseUserRoundTrip"; displayTestTitle(TEST_NAME); - + // GIVEN LexicalProcessor lexicalProcessor = createParser(); PrismContext prismContext = PrismTestUtil.getPrismContext(); @@ -135,19 +135,19 @@ public void testParseUserRoundTrip() throws Exception { System.out.println("\nParsed xnode:"); System.out.println(xnode.debugDump()); PrismObject user = prismContext.parserFor(xnode).parse(); - + // THEN System.out.println("\nParsed user:"); System.out.println(user.debugDump()); - + assertUserJack(user, true); - + // WHEN (re-serialize to XNode) RootXNode serializedXNode = prismContext.xnodeSerializer() .options(SerializationOptions.createSerializeCompositeObjects()) .serialize(user); String serializedString = lexicalProcessor.write(serializedXNode, new QName(NS_FOO, "user"), null); - + // THEN System.out.println("\nXNode after re-serialization:"); System.out.println(serializedXNode.debugDump()); @@ -156,15 +156,15 @@ public void testParseUserRoundTrip() throws Exception { String whenSerialized = getWhenItemSerialized(); assertTrue("Serialized form does not contain " + whenSerialized, serializedString.contains(whenSerialized)); - + assertUserJackXNodeOrdering("serialized xnode", serializedXNode); - + validateUserSchema(serializedString, prismContext); - + // WHEN (re-parse) RootXNode reparsedXnode = lexicalProcessor.read(new ParserStringSource(serializedString), ParsingContext.createDefault()); PrismObject reparsedUser = prismContext.parserFor(reparsedXnode).parse(); - + // THEN System.out.println("\nXNode after re-parsing:"); System.out.println(reparsedXnode.debugDump()); @@ -172,20 +172,20 @@ public void testParseUserRoundTrip() throws Exception { System.out.println(reparsedUser.debugDump()); assertUserJackXNodeOrdering("serialized xnode", reparsedXnode); - + ObjectDelta diff = DiffUtil.diff(user, reparsedUser); System.out.println("\nDiff:"); System.out.println(diff.debugDump()); - + PrismObject accountRefObjOrig = findObjectFromAccountRef(user); PrismObject accountRefObjRe = findObjectFromAccountRef(reparsedUser); - + ObjectDelta accountRefObjDiff = DiffUtil.diff(accountRefObjOrig, accountRefObjRe); System.out.println("\naccountRef object diff:"); System.out.println(accountRefObjDiff.debugDump()); - + assertTrue("Re-parsed object in accountRef does not match: "+accountRefObjDiff, accountRefObjDiff.isEmpty()); - + assertTrue("Re-parsed user does not match: "+diff, diff.isEmpty()); } @@ -196,7 +196,7 @@ public void testParseUserRoundTrip() throws Exception { public void testParseResourceRumToPrism() throws Exception { final String TEST_NAME = "testParseResourceRumToPrism"; displayTestTitle(TEST_NAME); - + // GIVEN LexicalProcessor lexicalProcessor = createParser(); PrismContext prismContext = PrismTestUtil.getPrismContext(); @@ -205,23 +205,23 @@ public void testParseResourceRumToPrism() throws Exception { RootXNode xnode = lexicalProcessor.read(getFileSource(RESOURCE_RUM_FILE_BASENAME), ParsingContext.createDefault()); System.out.println("XNode after parsing:"); System.out.println(xnode.debugDump()); - + // WHEN (parse to prism) PrismObject resource = prismContext.parserFor(xnode).parse(); - + // THEN System.out.println("Parsed resource:"); System.out.println(resource.debugDump()); - - assertResourceRum(resource); - + + assertResourceRum(resource); + } @Test public void testParseResourceRoundTrip() throws Exception { final String TEST_NAME = "testParseResourceRoundTrip"; displayTestTitle(TEST_NAME); - + // GIVEN LexicalProcessor lexicalProcessor = createParser(); PrismContext prismContext = PrismTestUtil.getPrismContext(); @@ -229,63 +229,63 @@ public void testParseResourceRoundTrip() throws Exception { // WHEN (parse) RootXNode xnode = lexicalProcessor.read(getFileSource(RESOURCE_RUM_FILE_BASENAME), ParsingContext.createDefault()); PrismObject resource = prismContext.parserFor(xnode).parse(); - + // THEN System.out.println("\nParsed resource:"); System.out.println(resource.debugDump()); - + assertResourceRum(resource); - + // WHEN (re-serialize to XNode) XNode serializedXNode = prismContext.xnodeSerializer() .options(SerializationOptions.createSerializeCompositeObjects()) .serialize(resource); String serializedString = lexicalProcessor.write(serializedXNode, new QName(NS_FOO, "resource"), null); - + // THEN System.out.println("\nXNode after re-serialization:"); System.out.println(serializedXNode.debugDump()); System.out.println("\nRe-serialized string:"); System.out.println(serializedString); - + validateResourceSchema(serializedString, prismContext); - + // WHEN (re-parse) RootXNode reparsedXnode = lexicalProcessor.read(new ParserStringSource(serializedString), ParsingContext.createDefault()); PrismObject reparsedResource = prismContext.parserFor(reparsedXnode).parse(); - + // THEN System.out.println("\nXNode after re-parsing:"); System.out.println(reparsedXnode.debugDump()); System.out.println("\nRe-parsed resource:"); System.out.println(reparsedResource.debugDump()); - + ObjectDelta diff = DiffUtil.diff(resource, reparsedResource); System.out.println("\nDiff:"); System.out.println(diff.debugDump()); - + assertTrue("Re-parsed user does not match: "+diff, diff.isEmpty()); - } + } private void assertResourceRum(PrismObject resource) throws SchemaException { resource.checkConsistence(); resource.assertDefinitions("test"); - + assertEquals("Wrong oid", RESOURCE_RUM_OID, resource.getOid()); PrismAsserts.assertObjectDefinition(resource.getDefinition(), RESOURCE_QNAME, RESOURCE_TYPE_QNAME, ResourceType.class); PrismAsserts.assertParentConsistency(resource); - + assertPropertyValue(resource, "name", new PolyString("Rum Delivery System", "rum delivery system")); assertPropertyDefinition(resource, "name", PolyStringType.COMPLEX_TYPE, 0, 1); - + PrismProperty propSchema = resource.findProperty(ResourceType.F_SCHEMA); assertNotNull("No schema property in resource", propSchema); PrismPropertyDefinition propSchemaDef = propSchema.getDefinition(); assertNotNull("No definition of schema property in resource", propSchemaDef); SchemaDefinitionType schemaDefinitionType = propSchema.getRealValue(); assertNotNull("No value of schema property in resource", schemaDefinitionType); - + Element schemaElement = schemaDefinitionType.getSchema(); assertNotNull("No schema element in schema property in resource", schemaElement); System.out.println("Resource schema:"); @@ -312,13 +312,13 @@ protected X getAssertXNode(String message, XNode xnode, Class< expectedClass.isAssignableFrom(xnode.getClass())); return (X) xnode; } - + protected X getAssertXMapSubnode(String message, MapXNode xmap, QName key, Class expectedClass) { XNode xsubnode = xmap.get(key); assertNotNull(message+" no key "+key, xsubnode); return getAssertXNode(message+" key "+key, xsubnode, expectedClass); } - + protected void assertUserJackXNodeOrdering(String message, XNode xnode) { if (xnode instanceof RootXNode) { xnode = ((RootXNode)xnode).getSubnode(); @@ -336,11 +336,11 @@ protected void assertUserJackXNodeOrdering(String message, XNode xnode) { assertEquals(message+": Wrong entry 3, the xnodes were shuffled", UserType.F_DESCRIPTION, reTopMapEntry3.getKey()); } - + protected void validateUserSchema(String dataString, PrismContext prismContext) throws SAXException, IOException { // Nothing to do by default } - + protected void validateResourceSchema(String dataString, PrismContext prismContext) throws SAXException, IOException { // Nothing to do by default } diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/lex/TestDomParser.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/lex/TestDomParser.java index 6cf3f6d6d9f..ffc768d0a78 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/lex/TestDomParser.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/lex/TestDomParser.java @@ -40,7 +40,7 @@ * */ public class TestDomParser extends AbstractLexicalProcessorTest { - + @Override protected String getSubdirName() { return "xml"; @@ -60,31 +60,31 @@ protected DomLexicalProcessor createParser() { public void testParseUserToXNode() throws Exception { final String TEST_NAME = "testParseUserToXNode"; displayTestTitle(TEST_NAME); - + // GIVEN DomLexicalProcessor parser = createParser(); - + // WHEN XNode xnode = parser.read(getFile(USER_JACK_FILE_BASENAME), ParsingContext.createDefault()); - + // THEN System.out.println("Parsed XNode:"); System.out.println(xnode.debugDump()); RootXNode root = getAssertXNode("root node", xnode, RootXNode.class); - + MapXNode rootMap = getAssertXNode("root subnode", root.getSubnode(), MapXNode.class); PrimitiveXNode xname = getAssertXMapSubnode("root map", rootMap, UserType.F_NAME, PrimitiveXNode.class); // TODO: assert value - + ListXNode xass = getAssertXMapSubnode("root map", rootMap, UserType.F_ASSIGNMENT, ListXNode.class); assertEquals("assignment size", 2, xass.size()); // TODO: asserts - + MapXNode xextension = getAssertXMapSubnode("root map", rootMap, UserType.F_EXTENSION, MapXNode.class); - + } - + private void validateSchemaCompliance(String xmlString, PrismContext prismContext) throws SAXException, IOException { // Document xmlDocument = DOMUtil.parseDocument(xmlString); // Schema javaxSchema = prismContext.getSchemaRegistry().getJavaxSchema(); @@ -92,7 +92,7 @@ private void validateSchemaCompliance(String xmlString, PrismContext prismContex // validator.setResourceResolver(prismContext.getEntityResolver()); // validator.validate(new DOMSource(xmlDocument)); } - + @Override protected void validateUserSchema(String xmlString, PrismContext prismContext) throws SAXException, IOException { validateSchemaCompliance(xmlString, prismContext); diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/lex/TestJsonParser.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/lex/TestJsonParser.java index 0feecc9ee7e..32a041c1153 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/lex/TestJsonParser.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/lex/TestJsonParser.java @@ -4,7 +4,7 @@ import com.evolveum.midpoint.prism.util.PrismTestUtil; public class TestJsonParser extends AbstractJsonLexicalProcessorTest { - + @Override protected String getSubdirName() { return "json"; diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/lex/TestProtectedString.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/lex/TestProtectedString.java index 5feec07e764..a0adb167092 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/lex/TestProtectedString.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/lex/TestProtectedString.java @@ -44,18 +44,18 @@ * */ public class TestProtectedString { - + @BeforeSuite public void setupDebug() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(DEFAULT_NAMESPACE_PREFIX); PrismTestUtil.resetPrismContext(new PrismInternalTestUtil()); } - + @Test public void testParseProtectedStringEncrypted() throws Exception { final String TEST_NAME = "testParseProtectedStringEncrypted"; displayTestTitle(TEST_NAME); - + // GIVEN Protector protector = PrismInternalTestUtil.createProtector(XMLCipher.AES_128); ProtectedStringType protectedStringType = protector.encryptString("salalala"); @@ -73,12 +73,12 @@ public void testParseProtectedStringEncrypted() throws Exception { System.out.println("Unmarshalled value: " + unmarshalled); assertEquals("Unmarshalled value differs from the original", protectedStringType, unmarshalled); } - + @Test public void testParseProtectedStringHashed() throws Exception { final String TEST_NAME = "testParseProtectedStringHashed"; displayTestTitle(TEST_NAME); - + // GIVEN ProtectedStringType protectedStringType = new ProtectedStringType(); protectedStringType.setClearValue("blabla"); diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/match/TestMatchingRule.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/match/TestMatchingRule.java index b07712a70e9..fb80def0334 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/match/TestMatchingRule.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/match/TestMatchingRule.java @@ -43,20 +43,20 @@ public class TestMatchingRule { private static MatchingRuleRegistry matchingRuleRegistry; - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(DEFAULT_NAMESPACE_PREFIX); PrismTestUtil.resetPrismContext(new PrismInternalTestUtil()); - + matchingRuleRegistry = MatchingRuleRegistryFactory.createRegistry(); } - + @Test public void testStringDefault() throws Exception { // GIVEN MatchingRule rule = matchingRuleRegistry.getMatchingRule(null, DOMUtil.XSD_STRING); - // WHEN, THEN + // WHEN, THEN assertMatch(rule, "foo", "foo"); assertNoMatch(rule, "foo", "bar"); assertNoMatch(rule, "foo", "Foo"); @@ -64,13 +64,13 @@ public void testStringDefault() throws Exception { assertNormalized(rule, "Foo", "Foo"); assertNormalized(rule, "baR", "baR"); } - + @Test public void testStringCaseInsensitive() throws Exception { // GIVEN - MatchingRule rule = matchingRuleRegistry.getMatchingRule(StringIgnoreCaseMatchingRule.NAME, + MatchingRule rule = matchingRuleRegistry.getMatchingRule(StringIgnoreCaseMatchingRule.NAME, DOMUtil.XSD_STRING); - // WHEN, THEN + // WHEN, THEN assertMatch(rule, "foo", "foo"); assertNoMatch(rule, "foo", "bar"); assertMatch(rule, "foo", "Foo"); @@ -79,54 +79,54 @@ public void testStringCaseInsensitive() throws Exception { assertNormalized(rule, "foo", "FoO"); assertNormalized(rule, "foobar", "foobar"); } - + @Test public void testPolyStringStrict() throws Exception { // GIVEN - MatchingRule rule = matchingRuleRegistry.getMatchingRule(PolyStringStrictMatchingRule.NAME, + MatchingRule rule = matchingRuleRegistry.getMatchingRule(PolyStringStrictMatchingRule.NAME, PolyStringType.COMPLEX_TYPE); - // WHEN, THEN + // WHEN, THEN assertMatch(rule, new PolyString("Bar", "bar"), new PolyString("Bar", "bar")); assertNoMatch(rule, new PolyString("BAR", "bar"), new PolyString("Foo", "bar")); assertNoMatch(rule, new PolyString("Bar", "bar"), new PolyString("bAR", "bar")); assertNoMatch(rule, new PolyString("Bar", "bar"), new PolyString("Bar", "barbar")); } - + @Test public void testPolyStringOrig() throws Exception { // GIVEN - MatchingRule rule = matchingRuleRegistry.getMatchingRule(PolyStringOrigMatchingRule.NAME, + MatchingRule rule = matchingRuleRegistry.getMatchingRule(PolyStringOrigMatchingRule.NAME, PolyStringType.COMPLEX_TYPE); - // WHEN, THEN + // WHEN, THEN assertMatch(rule, new PolyString("Bar", "bar"), new PolyString("Bar", "bar")); assertNoMatch(rule, new PolyString("BAR", "bar"), new PolyString("Foo", "bar")); assertNoMatch(rule, new PolyString("Bar", "bar"), new PolyString("bAR", "bar")); assertMatch(rule, new PolyString("Bar", "bar"), new PolyString("Bar", "barbar")); } - + @Test public void testPolyStringNorm() throws Exception { // GIVEN - MatchingRule rule = matchingRuleRegistry.getMatchingRule(PolyStringNormMatchingRule.NAME, + MatchingRule rule = matchingRuleRegistry.getMatchingRule(PolyStringNormMatchingRule.NAME, PolyStringType.COMPLEX_TYPE); - // WHEN, THEN + // WHEN, THEN assertMatch(rule, new PolyString("Bar", "bar"), new PolyString("Bar", "bar")); assertMatch(rule, new PolyString("BAR", "bar"), new PolyString("Foo", "bar")); assertMatch(rule, new PolyString("Bar", "bar"), new PolyString("bAR", "bar")); assertNoMatch(rule, new PolyString("Bar", "bar"), new PolyString("Bar", "barbar")); } - + @Test public void testXml() throws Exception { // GIVEN - MatchingRule rule = matchingRuleRegistry.getMatchingRule(XmlMatchingRule.NAME, + MatchingRule rule = matchingRuleRegistry.getMatchingRule(XmlMatchingRule.NAME, DOMUtil.XSD_STRING); - // WHEN, THEN + // WHEN, THEN assertMatch(rule, "BAR", "BAR"); assertNoMatch(rule, "BAR", "BARbar"); assertMatch(rule, "BAR", " BAR "); assertMatch(rule, "\n BAR\n", " BAR "); - + assertMatch(rule, "FOOBAR", "FOOBAR"); assertNoMatch(rule, "FOOBAR", "FOOBAR"); assertNoMatch(rule, "FOOBAR", "BAR"); @@ -137,28 +137,28 @@ public void testXml() throws Exception { assertMatch(rule, "FOOBAR", "\n\n\n FOO\n BAR\n\n"); assertMatch(rule, " \n FOO \n ", " FOO "); assertMatch(rule, "FOO \n ", "\n\n FOO "); - + // Invalid XML assertMatch(rule, "FOOBAR", "FOOBAR"); assertNoMatch(rule, "FOOBAR", "FOOBAR"); - + // normalization assertNormalized(rule, "BAR", "BAR"); assertNormalized(rule, "BAR", " BAR "); assertNormalized(rule, "BAR", "\n BAR\n"); - assertNormalized(rule, "FOO", "\n\n \n FOO \n "); + assertNormalized(rule, "FOO", "\n\n \n FOO \n "); assertNormalized(rule, "FOOfoo", " FOOfoo "); assertNormalized(rule, "FOO", "\n\n \n FOO \n "); assertNormalized(rule, "FOO", " FOO "); assertNormalized(rule, "FOO", " FOO "); assertNormalized(rule, "FOO", " " + " FOO "); - + // Invalid XML assertNormalized(rule, "FOO BAR ", "FOO BAR "); } - + private void assertMatch(MatchingRule rule, T a, T b) throws SchemaException { assertTrue("Values '"+a+"' and '"+b+"' does not match; rule: "+rule, rule.match(a, b)); } diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/query/TestObjectQuery.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/query/TestObjectQuery.java index 4fe75c89647..c12e4759c8e 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/query/TestObjectQuery.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/query/TestObjectQuery.java @@ -40,17 +40,17 @@ import static com.evolveum.midpoint.prism.PrismInternalTestUtil.DEFAULT_NAMESPACE_PREFIX; public class TestObjectQuery { - + private static MatchingRuleRegistry matchingRuleRegistry; - + @BeforeSuite public void setupDebug() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(DEFAULT_NAMESPACE_PREFIX); PrismTestUtil.resetPrismContext(new PrismInternalTestUtil()); - + matchingRuleRegistry = MatchingRuleRegistryFactory.createRegistry(); } - + @Test public void testMatchAndFilter() throws Exception{ PrismObject user = PrismTestUtil.parseObject(PrismInternalTestUtil.USER_JACK_FILE_XML); @@ -62,8 +62,8 @@ public void testMatchAndFilter() throws Exception{ boolean match = ObjectQuery.match(user, filter, matchingRuleRegistry); AssertJUnit.assertTrue("filter does not match object", match); } - - + + @Test public void testMatchOrFilter() throws Exception{ PrismObject user = PrismTestUtil.parseObject(PrismInternalTestUtil.USER_JACK_FILE_XML); @@ -74,7 +74,7 @@ public void testMatchOrFilter() throws Exception{ boolean match = ObjectQuery.match(user, filter, matchingRuleRegistry); AssertJUnit.assertTrue("filter does not match object", match); } - + @Test public void testDontMatchEqualFilter() throws Exception{ PrismObject user = PrismTestUtil.parseObject(PrismInternalTestUtil.USER_JACK_FILE_XML); @@ -84,7 +84,7 @@ public void testDontMatchEqualFilter() throws Exception{ boolean match = ObjectQuery.match(user, filter, matchingRuleRegistry); AssertJUnit.assertFalse("filter matches object, but it should not", match); } - + @Test public void testMatchEqualMultivalue() throws Exception{ PrismObject user = PrismTestUtil.parseObject(PrismInternalTestUtil.USER_JACK_FILE_XML); @@ -147,7 +147,7 @@ public void testComplexMatch() throws Exception{ boolean match = ObjectQuery.match(user, filter, matchingRuleRegistry); AssertJUnit.assertTrue("filter does not match object", match); } - + @Test public void testPolystringMatchEqualFilter() throws Exception{ PrismObject user = PrismTestUtil.parseObject(PrismInternalTestUtil.USER_JACK_FILE_XML); diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/query/TestQueryBuilder.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/query/TestQueryBuilder.java index 26043954d29..d1c8f80b680 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/query/TestQueryBuilder.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/query/TestQueryBuilder.java @@ -56,12 +56,12 @@ public class TestQueryBuilder { public static final QName USER_TYPE_QNAME = new QName(NS_FOO, "UserType"); public static final QName ASSIGNMENT_TYPE_QNAME = new QName(NS_FOO, "AssignmentType"); private static MatchingRuleRegistry matchingRuleRegistry; - + @BeforeSuite public void setupDebug() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(DEFAULT_NAMESPACE_PREFIX); PrismTestUtil.resetPrismContext(new PrismInternalTestUtil()); - + matchingRuleRegistry = MatchingRuleRegistryFactory.createRegistry(); } @@ -69,7 +69,7 @@ public void setupDebug() throws SchemaException, SAXException, IOException { public void beforeMethod(Method method) throws Exception { System.out.println(">>>>>>>>>>>>>>>>>>>>>>>> START TEST" + getClass().getName() + "." + method.getName() + "<<<<<<<<<<<<<<<<<<<<<<<<"); } - + @Test public void test100EmptyFilter() throws Exception{ ObjectQuery actual = QueryBuilder.queryFor(UserType.class, getPrismContext()).build(); diff --git a/infra/prism/src/test/java/com/evolveum/midpoint/prism/query/TestQueryConvertors.java b/infra/prism/src/test/java/com/evolveum/midpoint/prism/query/TestQueryConvertors.java index 76a5ca1aefe..eca56f67729 100644 --- a/infra/prism/src/test/java/com/evolveum/midpoint/prism/query/TestQueryConvertors.java +++ b/infra/prism/src/test/java/com/evolveum/midpoint/prism/query/TestQueryConvertors.java @@ -71,7 +71,7 @@ public void setupDebug() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(DEFAULT_NAMESPACE_PREFIX); PrismTestUtil.resetPrismContext(new PrismInternalTestUtil()); } - + @Test public void testFilterUserNameJaxb() throws Exception { displayTestTitle("testFilterUserNameJaxb"); @@ -95,16 +95,16 @@ public void testFilterUserNameJaxb() throws Exception { System.out.println("Serialized filter (JAXB->DOM)"); System.out.println(DOMUtil.serializeDOMToString(filterClauseElement)); - + DomAsserts.assertElementQName(filterClauseElement, EqualFilter.ELEMENT_NAME); DomAsserts.assertSubElements(filterClauseElement, 2); - + DomAsserts.assertSubElement(filterClauseElement, PrismConstants.Q_VALUE); Element valueElement = DOMUtil.getChildElement(filterClauseElement, PrismConstants.Q_VALUE); DomAsserts.assertTextContent(valueElement, "jack"); - + } - + @Test public void testFilterUserAndJaxb() throws Exception { displayTestTitle("testFilterUserAndJaxb"); @@ -117,12 +117,12 @@ public void testFilterUserAndJaxb() throws Exception { ObjectFilter filter = query.getFilter(); PrismAsserts.assertAndFilter(filter, 2); - + ObjectFilter first = getFilterCondition(filter, 0); PrismAsserts.assertEqualsFilter(first, UserType.F_GIVEN_NAME, DOMUtil.XSD_STRING, new ItemPath(new QName(null,UserType.F_GIVEN_NAME.getLocalPart()))); PrismAsserts.assertEqualsFilterValue((EqualFilter) first, "Jack"); - + ObjectFilter second = getFilterCondition(filter, 1); PrismAsserts.assertEqualsFilter(second, UserType.F_LOCALITY, DOMUtil.XSD_STRING, new ItemPath(new QName(null,UserType.F_LOCALITY.getLocalPart()))); @@ -131,7 +131,7 @@ public void testFilterUserAndJaxb() throws Exception { QueryType convertedQueryType = toQueryType(query); System.out.println("Re-converted query type"); System.out.println(convertedQueryType.debugDump()); - + SearchFilterType convertedFilterType = convertedQueryType.getFilter(); MapXNode xFilter = convertedFilterType.serializeToXNode(); PrismAsserts.assertSize(xFilter, 1); @@ -141,19 +141,19 @@ public void testFilterUserAndJaxb() throws Exception { PrismAsserts.assertSubnode(xandmap, EqualFilter.ELEMENT_NAME, ListXNode.class); ListXNode xequalsList = (ListXNode) xandmap.get(EqualFilter.ELEMENT_NAME); PrismAsserts.assertSize(xequalsList, 2); - + Element filterClauseElement = convertedFilterType.getFilterClauseAsElement(getPrismContext()); System.out.println("Serialized filter (JAXB->DOM)"); System.out.println(DOMUtil.serializeDOMToString(filterClauseElement)); - + DomAsserts.assertElementQName(filterClauseElement, AndFilter.ELEMENT_NAME); DomAsserts.assertSubElements(filterClauseElement, 2); - + Element firstSubelement = DOMUtil.getChildElement(filterClauseElement, 0); DomAsserts.assertElementQName(firstSubelement, EqualFilter.ELEMENT_NAME); Element firstValueElement = DOMUtil.getChildElement(firstSubelement, PrismConstants.Q_VALUE); DomAsserts.assertTextContent(firstValueElement, "Jack"); - + Element secondSubelement = DOMUtil.getChildElement(filterClauseElement, 1); DomAsserts.assertElementQName(secondSubelement, EqualFilter.ELEMENT_NAME); Element secondValueElement = DOMUtil.getChildElement(secondSubelement, PrismConstants.Q_VALUE); @@ -164,9 +164,9 @@ public void testFilterUserAndJaxb() throws Exception { public void testFilterTypeUserNone() throws Exception { displayTestTitle("testFilterTypeUserNone"); - + SearchFilterType filterType = PrismTestUtil.parseAnyValue(FILTER_TYPE_USER_NONE); - + ObjectQuery query = toObjectQuery(UserType.class, filterType); displayQuery(query); @@ -174,10 +174,10 @@ public void testFilterTypeUserNone() throws Exception { ObjectFilter filter = query.getFilter(); assertTrue("Filter is not of TYPE type", filter instanceof TypeFilter); - + ObjectFilter subFilter = ((TypeFilter) filter).getFilter(); assertTrue("Filter is not of NONE type", subFilter instanceof NoneFilter); - + QueryType convertedQueryType = toQueryType(query); System.out.println("Re-converted query type"); System.out.println(convertedQueryType.debugDump()); @@ -185,16 +185,16 @@ public void testFilterTypeUserNone() throws Exception { Element filterClauseElement = convertedQueryType.getFilter().getFilterClauseAsElement(getPrismContext()); LOGGER.info(convertedQueryType.getFilter().getFilterClauseXNode().debugDump()); - + System.out.println("Serialized filter (JAXB->DOM)"); String filterAsString = DOMUtil.serializeDOMToString(filterClauseElement); System.out.println(filterAsString); LOGGER.info(filterAsString); - + DomAsserts.assertElementQName(filterClauseElement, new QName(PrismConstants.NS_QUERY, "type")); - - - + + + } @Test @@ -270,7 +270,7 @@ private ObjectQuery toObjectQuery(Class type, QueryType queryType) throws Except getPrismContext()); return query; } - + private ObjectQuery toObjectQuery(Class type, SearchFilterType filterType) throws Exception { ObjectQuery query = QueryJaxbConvertor.createObjectQuery(type, filterType, getPrismContext()); diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/AbstractOptions.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/AbstractOptions.java index 1a3eed15b0b..8f44353643d 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/AbstractOptions.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/AbstractOptions.java @@ -32,7 +32,7 @@ protected void appendFlag(StringBuilder sb, String name, Boolean val) { sb.append("=false,"); } } - + protected void appendVal(StringBuilder sb, String name, Object val) { if (val != null) { sb.append(name); @@ -41,7 +41,7 @@ protected void appendVal(StringBuilder sb, String name, Object val) { sb.append(","); } } - + protected void removeLastComma(StringBuilder sb) { if (sb.charAt(sb.length() - 1) == ',') { sb.deleteCharAt(sb.length() - 1); diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/CapabilityUtil.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/CapabilityUtil.java index a29d12611ff..dc9a5f62113 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/CapabilityUtil.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/CapabilityUtil.java @@ -63,7 +63,7 @@ public static boolean isCapabilityEnabled(Object capability) throws SchemaExcept if (capability instanceof JAXBElement) { capability = ((JAXBElement)capability).getValue(); } - + if (capability instanceof CapabilityType) { return CapabilityUtil.isCapabilityEnabled((CapabilityType)capability); } else if (capability instanceof Element) { @@ -127,7 +127,7 @@ public static String getCapabilityDisplayName(Object capability) { } return className; } - + public static boolean isPasswordReturnedByDefault(CredentialsCapabilityType capability) { if (capability == null) { return false; @@ -141,7 +141,7 @@ public static boolean isPasswordReturnedByDefault(CredentialsCapabilityType capa } return password.isReturnedByDefault(); } - + public static boolean isActivationStatusReturnedByDefault(ActivationCapabilityType capability) { if (capability == null) { return false; @@ -155,7 +155,7 @@ public static boolean isActivationStatusReturnedByDefault(ActivationCapabilityTy } return statusCap.isReturnedByDefault(); } - + public static boolean isActivationLockoutStatusReturnedByDefault(ActivationCapabilityType capability) { if (capability == null) { return false; @@ -169,7 +169,7 @@ public static boolean isActivationLockoutStatusReturnedByDefault(ActivationCapab } return statusCap.isReturnedByDefault(); } - + public static boolean isActivationValidFromReturnedByDefault(ActivationCapabilityType capability) { if (capability == null) { return false; @@ -183,7 +183,7 @@ public static boolean isActivationValidFromReturnedByDefault(ActivationCapabilit } return valCap.isReturnedByDefault(); } - + public static boolean isActivationValidToReturnedByDefault(ActivationCapabilityType capability) { if (capability == null) { return false; @@ -273,7 +273,7 @@ public static void fillDefaults(@NotNull CapabilityType capability) { private static Boolean def(Boolean originalValue, boolean defaultValue) { return originalValue != null ? originalValue : defaultValue; } - + public static T getEffectiveCapability(CapabilitiesType capabilitiesType, Class capabilityClass) { if (capabilitiesType == null) { return null; diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/DefinitionProcessingOption.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/DefinitionProcessingOption.java index 89c7e408988..970f7f5e559 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/DefinitionProcessingOption.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/DefinitionProcessingOption.java @@ -22,13 +22,13 @@ */ public enum DefinitionProcessingOption { - + /** * Full definition processing for the specified item(s) is to be done. * This applies recursively also to sub-items. */ FULL, - + /** * Full definition processing for the specified item(s) is to be done, but only if the item(s) exist. * This applies recursively also to sub-items. @@ -36,7 +36,7 @@ public enum DefinitionProcessingOption { * Currently supported on root level only. */ ONLY_IF_EXISTS, - + /** * Definition for the specified item(s) is to be excluded from the resulting object, even if the item(s) do exist. * diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/DeltaConvertor.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/DeltaConvertor.java index ceeb6e22f09..87c2730daba 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/DeltaConvertor.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/DeltaConvertor.java @@ -54,7 +54,7 @@ * */ public class DeltaConvertor { - + public static final QName PATH_ELEMENT_NAME = new QName(PrismConstants.NS_TYPES, "path"); public static ObjectDelta createObjectDelta(ObjectModificationType objectModification, @@ -120,11 +120,11 @@ public static ObjectDelta createObjectDelta(ObjectDelt } - + public static ObjectDelta createObjectDelta(ObjectDeltaType objectDeltaType, PrismContext prismContext) throws SchemaException { return createObjectDelta(objectDeltaType, prismContext, false); - + } public static ObjectDeltaOperation createObjectDeltaOperation(ObjectDeltaOperationType objectDeltaOperationType, @@ -152,13 +152,13 @@ public static Collection toModificat } return toModifications(objectModification, objectDefinition); } - - public static Collection toModifications(ObjectModificationType objectModification, + + public static Collection toModifications(ObjectModificationType objectModification, PrismObjectDefinition objDef) throws SchemaException { return toModifications(objectModification.getItemDelta(), objDef); } - - public static Collection toModifications(Collection itemDeltaTypes, + + public static Collection toModifications(Collection itemDeltaTypes, PrismObjectDefinition objDef) throws SchemaException { Collection modifications = new ArrayList(); for (ItemDeltaType propMod : itemDeltaTypes) { @@ -167,7 +167,7 @@ public static Collection toModificat } return modifications; } - + /** * Converts this delta to ObjectModificationType (XML). */ @@ -205,7 +205,7 @@ public static ObjectDeltaType toObjectDeltaType(ObjectDelta prismObject = objectDelta.getObjectToAdd(); if (prismObject != null) { @@ -305,7 +305,7 @@ public static ItemDelta if (propMod.getValue() == null) { throw new IllegalArgumentException("No value in item delta (path: " + parentPath + ") while creating a property delta"); } - + ItemDefinition containingPcd = pcDef.findItemDefinition(parentPath); PrismContainerDefinition containerDef = null; if (containingPcd == null) { @@ -315,7 +315,7 @@ public static ItemDelta return null; } throw new SchemaException("No definition for " + parentPath.allUpToLastNamed().lastNamed().getName() + " (while creating delta for " + pcDef + ")"); - } + } } QName elementName = parentPath.lastNamed().getName(); Item item = RawTypeUtil.getParsedItem(containingPcd, propMod.getValue(), elementName, containerDef);//propMod.getValue().getParsedValue(containingPcd); @@ -327,7 +327,7 @@ public static ItemDelta } else if (propMod.getModificationType() == ModificationTypeType.REPLACE) { itemDelta.setValuesToReplace(PrismValue.resetParentCollection(PrismValue.cloneCollection(item.getValues()))); } - + if (!propMod.getEstimatedOldValue().isEmpty()) { Item oldItem = RawTypeUtil.getParsedItem(containingPcd, propMod.getEstimatedOldValue(), elementName, containerDef); itemDelta.addEstimatedOldValues(PrismValue.resetParentCollection(PrismValue.cloneCollection(oldItem.getValues()))); @@ -336,7 +336,7 @@ public static ItemDelta return itemDelta; } - + public static ItemDelta createItemDelta(ItemDeltaType propMod, PrismContainerDefinition pcDef) throws SchemaException { return createItemDelta(propMod, pcDef, false); @@ -410,7 +410,7 @@ private static void addModValues(ItemDelta delta, ItemDeltaType mod, Collection< } } } - + private static void addOldValues(ItemDelta delta, ItemDeltaType mod, Collection values, DeltaConversionOptions options) throws SchemaException { if (values == null || values.isEmpty()) { // RawType modValue = new RawType(delta.getPrismContext()); @@ -423,7 +423,7 @@ private static void addOldValues(ItemDelta delta, ItemDeltaType mod, Collection< } } } - + private static XNode toXNode(ItemDelta delta, @NotNull PrismValue value, DeltaConversionOptions options) throws SchemaException{ return delta.getPrismContext().xnodeSerializer() .definition(delta.getDefinition()) 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 e6c7441acfc..d97ccbce549 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 @@ -49,7 +49,7 @@ public class GetOperationOptions extends AbstractOptions implements Serializable *

  • Items marked as INCLUDE will be returned.
  • *
  • Any item marked as EXCLUDE may not be returned. (Note: Excluded items may still be returned if their retrieval is cheap.)
  • *
  • Items marked as DEFAULT will be returned if they would also be returned without any options (by default).
  • - *
  • Items that are not marked (have no option or have null retrieve option) but their superitem is marked (have retrieve option) + *
  • Items that are not marked (have no option or have null retrieve option) but their superitem is marked (have retrieve option) * behave in the same way as superitem. E.g. if a superitem is marked as * INCLUDE they will also be included in the result. This also applies transitively (e.g. superitem of superitem). *
  • If a superitem is marked as EXCLUDE and subitem is marked as INCLUDE then the behavior is undefined. Do not do this. Strange things may happen.
  • @@ -59,7 +59,7 @@ public class GetOperationOptions extends AbstractOptions implements Serializable * */ private RetrieveOption retrieve; - + /** * Resolve the object reference. This only makes sense with a (path-based) selector. */ @@ -76,13 +76,13 @@ public class GetOperationOptions extends AbstractOptions implements Serializable * Such operation returns only the data stored in midPoint repository. */ private Boolean noFetch; - + /** * Avoid any smart processing of the data except for schema application. Do not synchronize the data, do not apply * any expressions, etc. */ private Boolean raw; - + /** * Tolerate "raw" data in returned object. In some cases, raw data are tolerated by default (e.g. if raw=true * and the object is ResourceType or ShadowType). But generally, toleration of raw data can be explicitly requested @@ -96,9 +96,9 @@ public class GetOperationOptions extends AbstractOptions implements Serializable * from the gui, for example */ private Boolean doNotDiscovery; - + private RelationalValueSearchQuery relationalValueSearchQuery; - + /** * This flag indicated if the "object not found" error is critical for * processing the original request. If it is not, we just ignore it and @@ -106,7 +106,7 @@ public class GetOperationOptions extends AbstractOptions implements Serializable * information.. */ private Boolean allowNotFound; - + /** * Return read-only object. The returned object will be only read by the client. The client will not modify it. * Immutable object is returned if it is possible. @@ -114,7 +114,7 @@ public class GetOperationOptions extends AbstractOptions implements Serializable * at all times when the client do not plan to modify the returned object. */ private Boolean readOnly; - + /** * Specifies the point in time for the returned data. This option controls whether fresh or cached data will * be returned or whether future data projection will be returned. MidPoint usually deals with fresh data @@ -126,9 +126,9 @@ public class GetOperationOptions extends AbstractOptions implements Serializable * data. */ private PointInTimeType pointInTimeType; - + /** - * Requirement how stale or fresh the retrieved data should be. It specifies maximum age of the value in millisecods. + * Requirement how stale or fresh the retrieved data should be. It specifies maximum age of the value in millisecods. * 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. @@ -161,14 +161,14 @@ public RetrieveOption getRetrieve() { public void setRetrieve(RetrieveOption retrieve) { this.retrieve = retrieve; } - + public static RetrieveOption getRetrieve(GetOperationOptions options) { if (options == null) { return null; } return options.retrieve; } - + public static GetOperationOptions createRetrieve(RetrieveOption retrieve) { GetOperationOptions options = new GetOperationOptions(); options.retrieve = retrieve; @@ -189,7 +189,7 @@ public static GetOperationOptions createRetrieve(RetrieveOption retrieve) { *
  • Items marked as INCLUDE will be returned.
  • *
  • Any item marked as EXCLUDE may not be returned. (Note: Excluded items may still be returned if their retrieval is cheap.)
  • *
  • Items marked as DEFAULT will be returned if they would also be returned without any options (by default).
  • - *
  • Items that are not marked (have no option or have null retrieve option) but their superitem is marked (have retrieve option) + *
  • Items that are not marked (have no option or have null retrieve option) but their superitem is marked (have retrieve option) * behave in the same way as superitem. E.g. if a superitem is marked as * INCLUDE they will also be included in the result. This also applies transitively (e.g. superitem of superitem). *
  • If a superitem is marked as EXCLUDE and subitem is marked as INCLUDE then the behavior is undefined. Do not do this. Strange things may happen.
  • @@ -216,7 +216,7 @@ public static GetOperationOptions createRetrieve() { *
  • Items marked as INCLUDE will be returned.
  • *
  • Any item marked as EXCLUDE may not be returned. (Note: Excluded items may still be returned if their retrieval is cheap.)
  • *
  • Items marked as DEFAULT will be returned if they would also be returned without any options (by default).
  • - *
  • Items that are not marked (have no option or have null retrieve option) but their superitem is marked (have retrieve option) + *
  • Items that are not marked (have no option or have null retrieve option) but their superitem is marked (have retrieve option) * behave in the same way as superitem. E.g. if a superitem is marked as * INCLUDE they will also be included in the result. This also applies transitively (e.g. superitem of superitem). *
  • If a superitem is marked as EXCLUDE and subitem is marked as INCLUDE then the behavior is undefined. Do not do this. Strange things may happen.
  • @@ -243,7 +243,7 @@ public static GetOperationOptions createDontRetrieve() { *
  • Items marked as INCLUDE will be returned.
  • *
  • Any item marked as EXCLUDE may not be returned. (Note: Excluded items may still be returned if their retrieval is cheap.)
  • *
  • Items marked as DEFAULT will be returned if they would also be returned without any options (by default).
  • - *
  • Items that are not marked (have no option or have null retrieve option) but their superitem is marked (have retrieve option) + *
  • Items that are not marked (have no option or have null retrieve option) but their superitem is marked (have retrieve option) * behave in the same way as superitem. E.g. if a superitem is marked as * INCLUDE they will also be included in the result. This also applies transitively (e.g. superitem of superitem). *
  • If a superitem is marked as EXCLUDE and subitem is marked as INCLUDE then the behavior is undefined. Do not do this. Strange things may happen.
  • @@ -266,7 +266,7 @@ public Boolean getResolve() { public void setResolve(Boolean resolve) { this.resolve = resolve; } - + public static boolean isResolve(GetOperationOptions options) { if (options == null) { return false; @@ -276,7 +276,7 @@ public static boolean isResolve(GetOperationOptions options) { } return options.resolve; } - + /** * Resolve the object reference. This only makes sense with a (path-based) selector. */ @@ -322,7 +322,7 @@ public Boolean getNoFetch() { public void setNoFetch(Boolean noFetch) { this.noFetch = noFetch; } - + public static boolean isNoFetch(GetOperationOptions options) { if (options == null) { return false; @@ -332,7 +332,7 @@ 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. @@ -364,7 +364,7 @@ public Boolean getResolveNames() { public void setResolveNames(Boolean resolveNames) { this.resolveNames = resolveNames; } - + public static boolean isResolveNames(GetOperationOptions options) { if (options == null) { return false; @@ -374,7 +374,7 @@ public static boolean isResolveNames(GetOperationOptions options) { } return options.resolveNames; } - + /** * Resolve the object reference names. */ @@ -465,7 +465,7 @@ public Boolean getDoNotDiscovery() { public void setDoNotDiscovery(Boolean force) { this.doNotDiscovery = force; } - + public static boolean isDoNotDiscovery(GetOperationOptions options) { if (options == null) { return false; @@ -475,7 +475,7 @@ public static boolean isDoNotDiscovery(GetOperationOptions options) { } return options.doNotDiscovery; } - + /** * Force to get object from the resource even if some of the error occurred. * If the any copy of the shadow is fetched, we can't delete this object @@ -486,7 +486,7 @@ public static GetOperationOptions createDoNotDiscovery() { opts.setDoNotDiscovery(true); return opts; } - + /** * This flag indicated if the "object not found" error is critical for * processing the original request. If it is not, we just ignore it and @@ -498,7 +498,7 @@ public static GetOperationOptions createAllowNotFound() { opts.setAllowNotFound(true); return opts; } - + public Boolean getAllowNotFound() { return allowNotFound; } @@ -506,7 +506,7 @@ public Boolean getAllowNotFound() { public void setAllowNotFound(Boolean allowNotFound) { this.allowNotFound = allowNotFound; } - + public static boolean isAllowNotFound(GetOperationOptions options) { if (options == null) { return false; @@ -516,7 +516,7 @@ public static boolean isAllowNotFound(GetOperationOptions options) { } return options.allowNotFound; } - + /** * Return read-only object. The returned object will be only read by the client. The client will not modify it. * Immutable object is returned if it is possible. @@ -528,7 +528,7 @@ public static GetOperationOptions createReadOnly() { opts.setReadOnly(true); return opts; } - + public Boolean getReadOnly() { return readOnly; } @@ -536,7 +536,7 @@ public Boolean getReadOnly() { public void setReadOnly(Boolean readOnly) { this.readOnly = readOnly; } - + public static boolean isReadOnly(GetOperationOptions options) { if (options == null) { return false; @@ -546,7 +546,7 @@ public static boolean isReadOnly(GetOperationOptions options) { } return options.readOnly; } - + public PointInTimeType getPointInTimeType() { return pointInTimeType; } @@ -554,7 +554,7 @@ public PointInTimeType getPointInTimeType() { public void setPointInTimeType(PointInTimeType pointInTimeType) { this.pointInTimeType = pointInTimeType; } - + /** * Specifies the point in time for the returned data. This option controls whether fresh or cached data will * be returned or whether future data projection will be returned. MidPoint usually deals with fresh data @@ -570,7 +570,7 @@ public static GetOperationOptions createPointInTimeType(PointInTimeType pit) { opts.setPointInTimeType(pit); return opts; } - + public static PointInTimeType getPointInTimeType(GetOperationOptions options) { if (options == null) { return null; @@ -588,9 +588,9 @@ public Long getStaleness() { public void setStaleness(Long staleness) { this.staleness = staleness; } - + /** - * Requirement how stale or fresh the retrieved data should be. It specifies maximum age of the value in millisecods. + * Requirement how stale or fresh the retrieved data should be. It specifies maximum age of the value in millisecods. * 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. @@ -600,13 +600,13 @@ public static GetOperationOptions createStaleness(Long staleness) { opts.setStaleness(staleness); return opts; } - + public static GetOperationOptions createMaxStaleness() { GetOperationOptions opts = new GetOperationOptions(); opts.setStaleness(Long.MAX_VALUE); return opts; } - + public static long getStaleness(GetOperationOptions options) { if (options == null) { return 0L; @@ -616,7 +616,7 @@ public static long getStaleness(GetOperationOptions options) { } return options.getStaleness(); } - + public static boolean isMaxStaleness(GetOperationOptions options) { return GetOperationOptions.getStaleness(options) == Long.MAX_VALUE; } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/LabeledString.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/LabeledString.java index d105fb294f9..81ba26d023e 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/LabeledString.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/LabeledString.java @@ -19,10 +19,10 @@ /** * A free-form string value with a label. Useful for displaying a free-form data in forms and tables that - * require a label. - * + * require a label. + * * IMMUTABLE - * + * * @author Radovan Semancik * */ @@ -80,5 +80,5 @@ public boolean equals(Object obj) { public String toString() { return "LabeledString(" + label + ": " + data + ")"; } - + } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/MidPointPrismContextFactory.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/MidPointPrismContextFactory.java index e1f5d2a1e44..b98c2ceaace 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/MidPointPrismContextFactory.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/MidPointPrismContextFactory.java @@ -50,9 +50,9 @@ public class MidPointPrismContextFactory implements PrismContextFactory { private static final File TEST_EXTRA_SCHEMA_DIR = new File("src/test/resources/schema"); public static final MidPointPrismContextFactory FACTORY = new MidPointPrismContextFactory(TEST_EXTRA_SCHEMA_DIR); - + private File extraSchemaDir; - + public MidPointPrismContextFactory() { this.extraSchemaDir = null; } @@ -73,7 +73,7 @@ public PrismContext createPrismContext() throws SchemaException, FileNotFoundExc } return context; } - + public PrismContext createEmptyPrismContext() throws SchemaException, FileNotFoundException { SchemaRegistryImpl schemaRegistry = createSchemaRegistry(); PrismContextImpl context = PrismContextImpl.createEmptyContext(schemaRegistry); @@ -82,7 +82,7 @@ public PrismContext createEmptyPrismContext() throws SchemaException, FileNotFou context.setObjectsElementName(SchemaConstants.C_OBJECTS); return context; } - + private SchemaDefinitionFactory createDefinitionFactory() { return new MidPointSchemaDefinitionFactory(); } @@ -102,63 +102,63 @@ private SchemaRegistryImpl createSchemaRegistry() throws SchemaException, FileNo registerExtensionSchemas(schemaRegistry); return schemaRegistry; } - + protected void registerExtensionSchemas(SchemaRegistryImpl schemaRegistry) throws SchemaException, FileNotFoundException { if (extraSchemaDir != null && extraSchemaDir.exists()) { schemaRegistry.registerPrismSchemasFromDirectory(extraSchemaDir); } } - + private void registerBuiltinSchemas(SchemaRegistryImpl schemaRegistry) throws SchemaException { // Note: the order of schema registration may affect the way how the schema files are located // (whether are pulled from the registry or by using a catalog file). - + // Standard schemas - + schemaRegistry.getNamespacePrefixMapper().registerPrefix("http://www.w3.org/2001/XMLSchema", DOMUtil.NS_W3C_XML_SCHEMA_PREFIX, false); schemaRegistry.getNamespacePrefixMapper().registerPrefix(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "xsi", false); - + // Prism Schemas schemaRegistry.registerPrismSchemaResource("xml/ns/public/annotation-3.xsd", "a"); - schemaRegistry.registerPrismSchemaResource("xml/ns/public/types-3.xsd", "t", + schemaRegistry.registerPrismSchemaResource("xml/ns/public/types-3.xsd", "t", com.evolveum.prism.xml.ns._public.types_3.ObjectFactory.class.getPackage(), true); // declared by default - schemaRegistry.registerPrismSchemaResource("xml/ns/public/query-3.xsd", "q", + schemaRegistry.registerPrismSchemaResource("xml/ns/public/query-3.xsd", "q", com.evolveum.prism.xml.ns._public.query_3.ObjectFactory.class.getPackage(), true); // declared by default - - + + // midPoint schemas - schemaRegistry.registerPrismDefaultSchemaResource("xml/ns/public/common/common-3.xsd", "c", + schemaRegistry.registerPrismDefaultSchemaResource("xml/ns/public/common/common-3.xsd", "c", com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectFactory.class.getPackage()); // declared by default - - schemaRegistry.registerPrismSchemaResource("xml/ns/public/common/audit-3.xsd", "aud", - com.evolveum.midpoint.xml.ns._public.common.audit_3.ObjectFactory.class.getPackage()); - + + schemaRegistry.registerPrismSchemaResource("xml/ns/public/common/audit-3.xsd", "aud", + com.evolveum.midpoint.xml.ns._public.common.audit_3.ObjectFactory.class.getPackage()); + schemaRegistry.registerPrismSchemaResource("xml/ns/public/common/api-types-3.xsd", "apti", com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectFactory.class.getPackage()); schemaRegistry.registerPrismSchemasFromWsdlResource("xml/ns/public/model/model-3.wsdl", Arrays.asList(com.evolveum.midpoint.xml.ns._public.model.model_3.ObjectFactory.class.getPackage())); - + schemaRegistry.registerPrismSchemasFromWsdlResource("xml/ns/public/report/report-3.wsdl", Arrays.asList(com.evolveum.midpoint.xml.ns._public.report.report_3.ObjectFactory.class.getPackage())); - + // schemaRegistry.registerPrismSchemasFromWsdlResource("xml/ns/public/report/report-3.wsdl", // Arrays.asList(com.evolveum.midpoint.xml.ns._public.report.report_3.ObjectFactory.class.getPackage())); - + schemaRegistry.registerPrismSchemaResource("xml/ns/public/resource/annotation-3.xsd", "ra"); - + schemaRegistry.registerPrismSchemaResource("xml/ns/public/resource/capabilities-3.xsd", "cap", com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.ObjectFactory.class.getPackage()); - + schemaRegistry.registerPrismSchemaResource("xml/ns/public/connector/icf-1/connector-schema-3.xsd", "icfc", com.evolveum.midpoint.xml.ns._public.connector.icf_1.connector_schema_3.ObjectFactory.class.getPackage()); - + schemaRegistry.registerPrismSchemaResource("xml/ns/public/connector/icf-1/resource-schema-3.xsd", "icfs", com.evolveum.midpoint.xml.ns._public.connector.icf_1.resource_schema_3.ObjectFactory.class.getPackage(), true); // declared by default - + schemaRegistry.registerPrismSchemaResource("xml/ns/public/model/extension-3.xsd", "mext"); schemaRegistry.registerPrismSchemaResource("xml/ns/public/report/extension-3.xsd", "rext"); @@ -182,7 +182,7 @@ private void registerBuiltinSchemas(SchemaRegistryImpl schemaRegistry) throws Sc schemaRegistry.getNamespacePrefixMapper().registerPrefix(SchemaConstants.NS_ORG, SchemaConstants.PREFIX_NS_ORG, false); schemaRegistry.getNamespacePrefixMapper().addDeclaredByDefault(SchemaConstants.PREFIX_NS_ORG); // declared by default } - + private void setupDebug() { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/ObjectDeltaOperation.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/ObjectDeltaOperation.java index 78fed4570b1..6dd25e2f670 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/ObjectDeltaOperation.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/ObjectDeltaOperation.java @@ -36,11 +36,11 @@ public class ObjectDeltaOperation implements DebugDumpable private PolyString objectName; private String resourceOid; private PolyString resourceName; - + public ObjectDeltaOperation() { super(); } - + public ObjectDeltaOperation(ObjectDelta objectDelta) { super(); this.objectDelta = objectDelta; @@ -55,15 +55,15 @@ public ObjectDeltaOperation(ObjectDelta objectDelta, OperationResult executio public ObjectDelta getObjectDelta() { return objectDelta; } - + public void setObjectDelta(ObjectDelta objectDelta) { this.objectDelta = objectDelta; } - + public OperationResult getExecutionResult() { return executionResult; } - + public void setExecutionResult(OperationResult executionResult) { this.executionResult = executionResult; } @@ -95,7 +95,7 @@ public void setResourceName(PolyString resourceName) { public boolean containsDelta(ObjectDelta delta) { return objectDelta.equals(delta); } - + public static boolean containsDelta(Collection> deltaOps, ObjectDelta delta) { if (deltaOps == null) { return false; @@ -107,7 +107,7 @@ public static boolean containsDelta(Collection clone() { ObjectDeltaOperation clone = new ObjectDeltaOperation(); copyToClone(clone); @@ -135,7 +135,7 @@ public void checkConsistence() { objectDelta.checkConsistence(); } } - + public static Collection> cloneCollection( Collection> origCollection) { Collection> clonedCollection = new ArrayList>(origCollection.size()); @@ -145,7 +145,7 @@ public static Collection> cloneCollec } return clonedCollection; } - + public static Collection> cloneDeltaCollection( Collection> origCollection) { Collection> clonedCollection = new ArrayList>(origCollection.size()); diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/ObjectOperationOption.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/ObjectOperationOption.java index 629773f4fbb..22d9b48c7b7 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/ObjectOperationOption.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/ObjectOperationOption.java @@ -24,42 +24,42 @@ * */ public enum ObjectOperationOption { - + /** * Resolve the object reference. This only makes sense with a (path-based) selector. */ RESOLVE, - + /** * 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_FETCH, - + /** * Force the operation even if it would otherwise fail due to external failure. E.g. attempt to delete an account * that no longer exists on resource may fail without a FORCE option. If FORCE option is used then the operation is * finished even if the account does not exist (e.g. at least shadow is removed from midPoint repository). */ FORCE, - + /** * Avoid any smart processing of the data except for schema application. Do not synchronize the data, do not apply * any expressions, etc. */ RAW, - + /** * Encrypt any cleartext data on write, decrypt any encrypted data on read. Applies only to the encrypted * data formats (ProtectedString, ProtectedByteArray). */ CRYPT; - + // TODO: // SYNC option: always perform synchronous operation. If it would go to async or delayed then throw an error // (e.g. if approvals are started, async provisioning, queueing the operation because resource is offline, etc.) - + public static boolean hasOption(Collection options, ObjectOperationOption option) { if (options == null) { return false; diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/ObjectSelector.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/ObjectSelector.java index 02180e545bd..cf4479aa86a 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/ObjectSelector.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/ObjectSelector.java @@ -24,7 +24,7 @@ * */ public class ObjectSelector implements Serializable { - + private ItemPath path; public ObjectSelector(ItemPath path) { @@ -40,5 +40,5 @@ public ItemPath getPath() { public String toString() { return "ObjectSelector(" + path + ")"; } - + } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/PointInTimeType.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/PointInTimeType.java index 5c673b8982a..6639621ad62 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/PointInTimeType.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/PointInTimeType.java @@ -23,26 +23,26 @@ * that describe situation at the current point in time. But the client code may want to get data from the * cache that may be possibly stale. Or the client code may want a projection about the future state of the * data (e.g. taking running asynchronous operation into consideration). - * + * * @author semancik */ public enum PointInTimeType { - + /** * Return cached data (if available). * Avoid fetching the data from external system. */ CACHED, - + /** * Return current data. Fetch from external system if needed. * The "current" has to be understood in Einsteinean sense. * The returned data are as fresh as possible - but that still * may be hours or days old for some resources. - * This is usually the default. + * This is usually the default. */ CURRENT, - + /** * Returns current data and applies all the available projections * about future state of the data. E.g. applies projected state of diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/ProvisioningDiag.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/ProvisioningDiag.java index f6a55d21c53..3ae85db0633 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/ProvisioningDiag.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/ProvisioningDiag.java @@ -21,11 +21,11 @@ /** * DTO that contains provisioning run-time configuration and diagnostic information. - * + * * All information contained in this class are meant for information purposes only. * They are not meant to be used by a machine or algorithm, they are meant to be displayed * to a human user. - * + * * @author Radovan Semancik * @author mederly * @@ -54,6 +54,6 @@ public void setAdditionalDetails(List additionalDetails) { public String toString() { return "ProvisioningDiag(additionalDetails=" + additionalDetails + ")"; } - - + + } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/RelationalValueSearchQuery.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/RelationalValueSearchQuery.java index 0dd672e960d..89e991311bb 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/RelationalValueSearchQuery.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/RelationalValueSearchQuery.java @@ -88,7 +88,7 @@ public RelationalValueSearchQuery clone() { } return clone; } - + @Override public int hashCode() { final int prime = 31; diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/RepositoryDiag.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/RepositoryDiag.java index a8098e7ac1f..90a5126dac7 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/RepositoryDiag.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/RepositoryDiag.java @@ -20,46 +20,46 @@ /** * DTO that contains repository run-time configuration and diagnostic information. - * + * * All information contained in this class are meant for information purposes only. * They are not meant to be used by a machine or algorithm, they are meant to be displayed * to a human user. - * + * * @author Radovan Semancik * */ public class RepositoryDiag implements Serializable { - + /** * Short description of the implementation type, e.g. "SQL", "BaseX", "LDAP" */ private String implementationShortName; - + /** * Longer (possible multi-line) description of the implementation; */ private String implementationDescription; - + private boolean isEmbedded; - + /** * Short description of a driver or a library used to access the repository. * It is usually a named of the JDBC driver (e.g. "org.postgresql.Driver") or * something equivalent for other implementations (e.g. "Mozilla SDK" for LDAP). */ private String driverShortName; - + /** * Version of the driver (if known) */ private String driverVersion; - + /** - * URL-formatted location of the repository, usually JDBC connection string, + * URL-formatted location of the repository, usually JDBC connection string, * LDAP server URL or a similar construction. */ private String repositoryUrl; - + /** * Additional repository information that do not fit the structured data above. * May be anything that the implementations thinks is important. @@ -74,7 +74,7 @@ public String getImplementationShortName() { public void setImplementationShortName(String implementationShortName) { this.implementationShortName = implementationShortName; } - + public String getImplementationDescription() { return implementationDescription; } @@ -187,6 +187,6 @@ public String toString() { + ", driverShortName=" + driverShortName + ", driverVersion=" + driverVersion + ", repositoryUrl=" + repositoryUrl + ", additionalDetails=" + additionalDetails + ")"; } - - + + } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/ResourceShadowDiscriminator.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/ResourceShadowDiscriminator.java index 4ed834cb1be..0352ea69f1c 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/ResourceShadowDiscriminator.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/ResourceShadowDiscriminator.java @@ -33,41 +33,41 @@ * Aggregate bean containing resource OID, intent and thombstone flag. * It uniquely identifies an shadow projection (usually account) for a specific user regardless whether it has OID, does not have * OID yet, it exists of was deleted. - * + * * This is used mostly as a key in hashes and for searches. - * + * * TODO: split to two objects: * 1: ResourceShadowCoordinates which will stay in common * 2: ResourceShadowDiscriminator (subclass) which will go to model. This will contains thombstone and order. - * + * * @author Radovan Semancik */ public class ResourceShadowDiscriminator implements Serializable, DebugDumpable, HumanReadableDescribable { private static final long serialVersionUID = 346600684011645741L; - + private String resourceOid; private ShadowKindType kind = ShadowKindType.ACCOUNT; private String intent; private QName objectClass; private boolean thombstone; private int order = 0; - + public ResourceShadowDiscriminator(String resourceOid, ShadowKindType kind, String intent, boolean thombstone) { this.resourceOid = resourceOid; this.thombstone = thombstone; setIntent(intent); setKind(kind); } - + public ResourceShadowDiscriminator(String resourceOid, ShadowKindType kind, String intent) { this(resourceOid, kind, intent, false); } - + public ResourceShadowDiscriminator(ShadowDiscriminatorType accRefType) { this(accRefType.getResourceRef().getOid(), accRefType.getKind(), accRefType.getIntent()); } - + public ResourceShadowDiscriminator(ShadowDiscriminatorType accRefType, String defaultResourceOid, ShadowKindType defaultKind) { ShadowKindType kind = accRefType.getKind(); if (kind == null) { @@ -82,7 +82,7 @@ public ResourceShadowDiscriminator(ShadowDiscriminatorType accRefType, String de setIntent(accRefType.getIntent()); setKind(kind); } - + public ResourceShadowDiscriminator(String resourceOid, QName objectClass) { this.resourceOid = resourceOid; this.objectClass = objectClass; @@ -92,11 +92,11 @@ public ResourceShadowDiscriminator(String resourceOid, QName objectClass) { public String getResourceOid() { return resourceOid; } - + public void setResourceOid(String resourceOid) { this.resourceOid = resourceOid; } - + public ShadowKindType getKind() { return kind; } @@ -108,14 +108,14 @@ public void setKind(ShadowKindType kind) { public String getIntent() { return intent; } - + public void setIntent(String intent) { if (intent == null) { intent = SchemaConstants.INTENT_DEFAULT; } this.intent = intent; } - + public QName getObjectClass() { return objectClass; } @@ -146,12 +146,12 @@ public boolean isThombstone() { public void setThombstone(boolean thombstone) { this.thombstone = thombstone; } - + public boolean isWildcard() { return kind == null && objectClass == null; } - + public ShadowDiscriminatorType toResourceShadowDiscriminatorType() { ShadowDiscriminatorType rsdt = new ShadowDiscriminatorType(); rsdt.setIntent(intent); @@ -167,13 +167,13 @@ public static ResourceShadowDiscriminator fromResourceShadowDiscriminatorType(Sh if (resourceShadowDiscriminatorType == null) { return null; } - + // For compatibility. Otherwise the kind should be explicitly serialized. ShadowKindType kind = resourceShadowDiscriminatorType.getKind(); if (kind == null) { kind = ShadowKindType.ACCOUNT; } - + return new ResourceShadowDiscriminator( resourceShadowDiscriminatorType.getResourceRef() != null ? resourceShadowDiscriminatorType.getResourceRef().getOid() : null, kind, @@ -222,7 +222,7 @@ public boolean equals(Object obj) { } /** - * Similar to equals but ignores the order. + * Similar to equals but ignores the order. */ public boolean equivalent(Object obj) { if (this == obj) @@ -246,19 +246,19 @@ public boolean equivalent(Object obj) { return false; return true; } - + public static boolean equalsIntent(String a, String b) { if (a == null || b == null) { return false; } return a.equals(b); } - + @Override public String toString() { return toHumanReadableDescription(); } - + public String toHumanReadableDescription() { StringBuilder sb = new StringBuilder("RSD("); sb.append(kind==null?"null":kind.value()); diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/ResultHandler.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/ResultHandler.java index a0e0d4a0435..e306ea99ed0 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/ResultHandler.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/ResultHandler.java @@ -24,7 +24,7 @@ * * It is only used to handle iterative search results now. It may be reused for * other purposes as well. - * + * * @author Radovan Semancik */ @FunctionalInterface @@ -36,5 +36,5 @@ public interface ResultHandler { * @return true if the operation should proceed, false if it should stop */ boolean handle(PrismObject object, OperationResult parentResult); - + } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/RetrieveOption.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/RetrieveOption.java index aa471d863f0..738498e8b0d 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/RetrieveOption.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/RetrieveOption.java @@ -3,18 +3,18 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.RetrieveOptionType; public enum RetrieveOption { - + /** * Return the item "as ususal". If the item would be returned by default then return it. * If the item would not be returned by default then it may not be returned. */ DEFAULT, - + /** * Include the item in the result. The item will be returned (even if it would not be returned by default). */ INCLUDE, - + /** * Exclude the item from the result. */ @@ -31,7 +31,7 @@ public static RetrieveOption fromRetrieveOptionType(RetrieveOptionType retrieveO default: throw new IllegalStateException("Unsupported RetrieveOptionType: " + retrieveOptionType); } } - + public static RetrieveOptionType toRetrieveOptionType(RetrieveOption retrieveOption) { if (retrieveOption == null) { return RetrieveOptionType.DEFAULT; diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/SearchResultList.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/SearchResultList.java index c5ea73d74d7..add951ae75f 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/SearchResultList.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/SearchResultList.java @@ -29,17 +29,17 @@ * */ public class SearchResultList implements List, Cloneable, Serializable { - + private List list = null; private SearchResultMetadata metadata = null; - + public SearchResultList() { }; - + public SearchResultList(List list) { super(); this.list = list; } - + public SearchResultList(List list, SearchResultMetadata metadata) { super(); this.list = list; @@ -201,7 +201,7 @@ public String toString() { return "SearchResultList("+metadata+")"; } else { return "SearchResultList("+list+", "+metadata+")"; - } + } } } @@ -216,7 +216,7 @@ public SearchResultList clone() { } return clone; } - + private List getInitializedList() { if (list == null) { list = new ArrayList<>(); diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/SearchResultMetadata.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/SearchResultMetadata.java index 0523cd8b4e9..d01fc41996b 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/SearchResultMetadata.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/SearchResultMetadata.java @@ -23,11 +23,11 @@ * @author semancik */ public class SearchResultMetadata implements Serializable { - + private String pagingCookie; private Integer approxNumberOfAllResults; private boolean partialResults = false; - + /** * Returns the paging cookie. The paging cookie is used for optimization of paged searches. * The presence of the cookie may allow the data store to correlate queries and associate @@ -39,7 +39,7 @@ public class SearchResultMetadata implements Serializable { public String getPagingCookie() { return pagingCookie; } - + /** * Sets paging cookie. The paging cookie is used for optimization of paged searches. * The presence of the cookie may allow the data store to correlate queries and associate @@ -51,7 +51,7 @@ public String getPagingCookie() { public void setPagingCookie(String pagingCookie) { this.pagingCookie = pagingCookie; } - + /** * Returns the approximate number of all results that would be returned for the * filter if there was no paging limitation. This property is optional and it is @@ -63,11 +63,11 @@ public void setPagingCookie(String pagingCookie) { public Integer getApproxNumberOfAllResults() { return approxNumberOfAllResults; } - + public void setApproxNumberOfAllResults(Integer approxNumberOfAllResults) { this.approxNumberOfAllResults = approxNumberOfAllResults; } - + /** * Flag indicating whether the search returned partial results. * If set to false then all the results requested by the query were returned. 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 a9975487fc6..89a5e314e36 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 @@ -36,7 +36,7 @@ * */ public class SelectorOptions implements Serializable, DebugDumpable { - + private ObjectSelector selector; private T options; @@ -46,7 +46,7 @@ public SelectorOptions(ObjectSelector selector, T options) { this.selector = selector; this.options = options; } - + public SelectorOptions(T options) { super(); this.selector = null; diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/constants/ConnectorTestOperation.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/constants/ConnectorTestOperation.java index ba584ee5878..adfa89e2573 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/constants/ConnectorTestOperation.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/constants/ConnectorTestOperation.java @@ -17,13 +17,13 @@ /** * Enumeration of standardized test connection opration codes as they are presented in the OperationResult. - * + * * @author lazyman * @author Radovan Semancik - * + * */ public enum ConnectorTestOperation { - + TEST_CONNECTION(ConnectorTestOperation.class.getName() + ".testConnection"), /** @@ -46,7 +46,7 @@ public enum ConnectorTestOperation { * Check whether a connection to the resource can be established. */ CONNECTOR_CONNECTION(ConnectorTestOperation.class.getName() + ".connector.connection"), - + /** * Check whether a connection to the resource can be established. */ diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/constants/ExpressionConstants.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/constants/ExpressionConstants.java index 4e7b4f16aaa..89847b801b8 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/constants/ExpressionConstants.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/constants/ExpressionConstants.java @@ -26,9 +26,9 @@ public class ExpressionConstants { // Generic variables public static final QName VAR_INPUT = new QName(SchemaConstants.NS_C, "input"); public static final QName VAR_OBJECT = new QName(SchemaConstants.NS_C, "object"); - + // Variables used in various mappings - public static final QName VAR_FOCUS = new QName(SchemaConstants.NS_C, "focus"); + public static final QName VAR_FOCUS = new QName(SchemaConstants.NS_C, "focus"); public static final QName VAR_PROJECTION = new QName(SchemaConstants.NS_C, "projection"); public static final QName VAR_SOURCE = new QName(SchemaConstants.NS_C, "source"); public static final QName VAR_ASSIGNMENT = new QName(SchemaConstants.NS_C, "assignment"); @@ -60,27 +60,27 @@ public class ExpressionConstants { public static final QName VAR_ASSIGNED = new QName(SchemaConstants.NS_C, "assigned"); public static final QName VAR_FOCUS_EXISTS = new QName(SchemaConstants.NS_C, "focusExists"); public static final QName VAR_ADMINISTRATIVE_STATUS = new QName(SchemaConstants.NS_C, "administrativeStatus"); - + public static final QName VAR_ASSOCIATION_TARGET_OBJECT_CLASS_DEFINITION = new QName(SchemaConstants.NS_C, "associationTargetObjectClassDefinition"); - + /** * Numeric value describing the current iteration. It starts with 0 and increments on every iteration. * Iterations are used to find unique values for an account, to resolve naming conflicts, etc. */ public static final QName VAR_ITERATION = new QName(SchemaConstants.NS_C, "iteration"); - + /** * String value describing the current iteration. It is usually suffix that is appended to the username * or a similar "extension" of the value. It should have different value for every iteration. The actual * value is determined by the iteration settings. */ public static final QName VAR_ITERATION_TOKEN = new QName(SchemaConstants.NS_C, "iterationToken"); - + // Variables used in object merging expressions public static final QName VAR_SIDE = new QName(SchemaConstants.NS_C, "side"); public static final QName VAR_OBJECT_LEFT = new QName(SchemaConstants.NS_C, "objectLeft"); public static final QName VAR_OBJECT_RIGHT = new QName(SchemaConstants.NS_C, "objectRight"); - + public static final QName OUTPUT_ELEMENT_NAME = new QName(SchemaConstants.NS_C, "output"); // "case" would collide with java keyword diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/constants/MidPointConstants.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/constants/MidPointConstants.java index 3a403655380..fab1e3d73da 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/constants/MidPointConstants.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/constants/MidPointConstants.java @@ -25,7 +25,7 @@ public class MidPointConstants { public static final String NS_MIDPOINT_PUBLIC_PREFIX = "http://midpoint.evolveum.com/xml/ns/public"; public static final String NS_MIDPOINT_TEST_PREFIX = "http://midpoint.evolveum.com/xml/ns/test"; - + public static final String NS_RA = NS_MIDPOINT_PUBLIC_PREFIX+"/resource/annotation-3"; public static final String PREFIX_NS_RA = "ra"; public static final QName RA_RESOURCE_OBJECT = new QName(NS_RA, "resourceObject"); @@ -47,16 +47,16 @@ public class MidPointConstants { public static final QName RA_ACCOUNT = new QName(NS_RA, "account"); @Deprecated public static final QName RA_ACCOUNT_TYPE = new QName(NS_RA, "accountType"); - + public static final String NS_RI = NS_MIDPOINT_PUBLIC_PREFIX+"/resource/instance-3"; public static final String PREFIX_NS_RI = "ri"; - + public static final String FUNCTION_LIBRARY_BASIC_VARIABLE_NAME = "basic"; public static final String NS_FUNC_BASIC = NS_MIDPOINT_PUBLIC_PREFIX+"/function/basic-3"; - + public static final String FUNCTION_LIBRARY_MIDPOINT_VARIABLE_NAME = "midpoint"; public static final String NS_FUNC_MIDPOINT = NS_MIDPOINT_PUBLIC_PREFIX+"/function/midpoint-3"; - + public static final String FUNCTION_LIBRARY_LOG_VARIABLE_NAME = "log"; public static final String NS_FUNC_LOG = NS_MIDPOINT_PUBLIC_PREFIX+"/function/log-3"; diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/constants/ObjectTypes.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/constants/ObjectTypes.java index dcbd8448ac7..f23c7aae553 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/constants/ObjectTypes.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/constants/ObjectTypes.java @@ -76,7 +76,7 @@ public enum ObjectTypes { REPORT_OUTPUT(ReportOutputType.COMPLEX_TYPE, SchemaConstants.C_REPORT_OUTPUT, ReportOutputType.class, ObjectManager.MODEL, "reportOutputs"), - + SECURITY_POLICY(SecurityPolicyType.COMPLEX_TYPE, SchemaConstants.C_SECURITY_POLICY, SecurityPolicyType.class, ObjectManager.MODEL, "securityPolicies"), diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/constants/SchemaConstants.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/constants/SchemaConstants.java index 5782d064ae3..bf2a34d9b7b 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/constants/SchemaConstants.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/constants/SchemaConstants.java @@ -57,7 +57,7 @@ public abstract class SchemaConstants { public static final String NS_FAULT = "http://midpoint.evolveum.com/xml/ns/public/common/fault-3"; public static final String NS_SAMPLES_EXTENSION = "http://midpoint.evolveum.com/xml/ns/samples/extension-3"; public static final String NS_CASE = "http://midpoint.evolveum.com/xml/ns/public/common/case-3"; - + /** * Namespace for default (bult-in) object collections, such as "all objects", "all roles", ... */ @@ -165,35 +165,35 @@ public abstract class SchemaConstants { * Specifies that the subject is a deputy of another user. */ public static final QName ORG_DEPUTY = new QName(NS_ORG, "deputy"); - + /** * Relation "is approver of". Used as a relation value in object references. * Specifies that the subject is a (general) approver of specified (abstract) role. * The approver will be asked for decision if the role is assigned, if there is * a rule conflict during assignment (e.g. SoD conflict) or if there is any similar * situation. - * + * * This is a generic approver used for all the situation. The system may be customized * with more specific approver roles, e.g. technicalApprover, securityApprover, etc. - * + * * This approver is responsible for the use of the role, which mostly means * that he decides about role assignment. It is NOT meant to approve role changes. * Role owner is meant for that purpose. */ public static final QName ORG_APPROVER = new QName(NS_ORG, "approver"); - + /** * Relation "is owner of". Used as a relation value in object references. * Specifies that the subject is a (business) owner of specified (abstract) role. * The owner will be asked for decision if the role is modified, when the associated * policy changes and so on. - * + * * This owner is responsible for maintaining role definition and policies. It is * NPT necessarily concerned with role use (e.g. assignment). The approver relation - * is meant for that purpose. + * is meant for that purpose. */ public static final QName ORG_OWNER = new QName(NS_ORG, "owner"); - + /** * Relation "is consent for". Used as a relation value in object references. * Specifies that the subject gave a consent for using personnel information related to this role. @@ -208,7 +208,7 @@ public abstract class SchemaConstants { public static final ItemPath PATH_NONCE = new ItemPath(C_CREDENTIALS, CredentialsType.F_NONCE); public static final ItemPath PATH_NONCE_VALUE = new ItemPath(C_CREDENTIALS, CredentialsType.F_NONCE, NonceType.F_VALUE); - + public static final ItemPath PATH_SECURITY_QUESTIONS = new ItemPath(C_CREDENTIALS, CredentialsType.F_SECURITY_QUESTIONS); public static final ItemPath PATH_SECURITY_QUESTIONS_QUESTION_ANSWER = new ItemPath(C_CREDENTIALS, CredentialsType.F_SECURITY_QUESTIONS, SecurityQuestionsCredentialsType.F_QUESTION_ANSWER); @@ -247,7 +247,7 @@ public abstract class SchemaConstants { public static final String NS_PROVISIONING = NS_MIDPOINT_PUBLIC + "/provisioning"; public static final String NS_PROVISIONING_LIVE_SYNC = NS_PROVISIONING + "/liveSync-3"; public static final QName SYNC_TOKEN = new QName(NS_PROVISIONING_LIVE_SYNC, "token"); - + // Synchronization constants public static final String NS_PROVISIONING_CHANNEL = NS_PROVISIONING + "/channels-3"; public static final QName CHANGE_CHANNEL_LIVE_SYNC = new QName(NS_PROVISIONING_CHANNEL, "liveSync"); @@ -293,24 +293,24 @@ public abstract class SchemaConstants { NS_MODEL_EXTENSION, "lastScanTimestamp"); public static final String NS_MODEL_DISABLE_REASON = NS_MODEL + "/disableReason"; - public static final String MODEL_DISABLE_REASON_EXPLICIT = + public static final String MODEL_DISABLE_REASON_EXPLICIT = QNameUtil.qNameToUri(new QName(NS_MODEL_DISABLE_REASON, "explicit")); - public static final String MODEL_DISABLE_REASON_DEPROVISION = + public static final String MODEL_DISABLE_REASON_DEPROVISION = QNameUtil.qNameToUri(new QName(NS_MODEL_DISABLE_REASON, "deprovision")); - public static final String MODEL_DISABLE_REASON_MAPPED = + public static final String MODEL_DISABLE_REASON_MAPPED = QNameUtil.qNameToUri(new QName(NS_MODEL_DISABLE_REASON, "mapped")); public static final String NS_MODEL_POLICY = NS_MODEL + "/policy"; public static final String NS_MODEL_POLICY_SITUATION = NS_MODEL_POLICY + "/situation"; - public static final String MODEL_POLICY_SITUATION_EXCLUSION_VIOLATION = + public static final String MODEL_POLICY_SITUATION_EXCLUSION_VIOLATION = QNameUtil.qNameToUri(new QName(NS_MODEL_POLICY_SITUATION, "exclusionViolation")); - public static final String MODEL_POLICY_SITUATION_UNDERASSIGNED = + public static final String MODEL_POLICY_SITUATION_UNDERASSIGNED = QNameUtil.qNameToUri(new QName(NS_MODEL_POLICY_SITUATION, "underassigned")); - public static final String MODEL_POLICY_SITUATION_OVERASSIGNED = + public static final String MODEL_POLICY_SITUATION_OVERASSIGNED = QNameUtil.qNameToUri(new QName(NS_MODEL_POLICY_SITUATION, "overassigned")); - public static final String MODEL_POLICY_SITUATION_MODIFIED = + public static final String MODEL_POLICY_SITUATION_MODIFIED = QNameUtil.qNameToUri(new QName(NS_MODEL_POLICY_SITUATION, "modified")); - public static final String MODEL_POLICY_SITUATION_ASSIGNED = + public static final String MODEL_POLICY_SITUATION_ASSIGNED = QNameUtil.qNameToUri(new QName(NS_MODEL_POLICY_SITUATION, "assigned")); public static final String MODEL_POLICY_SITUATION_TIME_VALIDITY = QNameUtil.qNameToUri(new QName(NS_MODEL_POLICY_SITUATION, "timeValidity")); // currently unused, planned for 3.7+ @@ -388,11 +388,11 @@ public abstract class SchemaConstants { public static final String REGISTRATION_CONFIRAMTION_PREFIX = "/confirm/registration"; public static final String PASSWORD_RESET_CONFIRMATION_PREFIX = "/confirm/reset"; public static final String ACCOUNT_ACTIVATION_PREFIX = "/activate/accounts"; - + public static final String INTENT_DEFAULT = "default"; public static final String CONNECTOR_SCHEMA_CONFIGURATION_TYPE_LOCAL_NAME = "ConfigurationType"; - + // This constant should not be here. It is used by schema processor to // supply correct import. But the dependency should // be inverted, eventually (MID-356) @@ -412,13 +412,13 @@ public abstract class SchemaConstants { public static final QName ICFS_NAME = new QName(NS_ICF_SCHEMA, "name"); public static final QName ICFS_UID = new QName(NS_ICF_SCHEMA, "uid"); public static final String CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_LOCAL_NAME = "configurationProperties"; - public static final QName CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_QNAME = new QName(NS_ICF_CONFIGURATION, + public static final QName CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_QNAME = new QName(NS_ICF_CONFIGURATION, CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_LOCAL_NAME); public static final String ACCOUNT_OBJECT_CLASS_LOCAL_NAME = "AccountObjectClass"; public static final String GROUP_OBJECT_CLASS_LOCAL_NAME = "GroupObjectClass"; public static final String UCF_FRAMEWORK_URI_BUILTIN = "http://midpoint.evolveum.com/xml/ns/public/connector/builtin-1"; - + // OTHER (temporary? [mederly]) public static final String ICF_CONNECTOR_EXTENSION = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/connector-extension-3"; @@ -457,9 +457,9 @@ public abstract class SchemaConstants { public static final QName C_MODEL_CONTEXT = new QName(NS_C, "modelContext"); public static final QName C_ITEM_TO_APPROVE = new QName(NS_C, "itemToApprove"); public static final QName C_SHADOW_DISCRIMINATOR = new QName(NS_C, "shadowDiscriminator"); - + // Lifecycle - + public static final String LIFECYCLE_DRAFT = "draft"; public static final String LIFECYCLE_PROPOSED = "proposed"; public static final String LIFECYCLE_ACTIVE = "active"; @@ -468,14 +468,14 @@ public abstract class SchemaConstants { public static final String LIFECYCLE_FAILED = "failed"; // Case: generic reusable case states - + public static final String CASE_STATE_OPEN = "open"; public static final QName CASE_STATE_OPEN_QNAME = new QName(NS_CASE, CASE_STATE_OPEN); public static final String CASE_STATE_CLOSED = "closed"; public static final QName CASE_STATE_CLOSED_QNAME = new QName(NS_CASE, CASE_STATE_CLOSED); - + // Object collections - + /** * All objects in role catalog. It means all the objects in all the categories that are placed under the * primary role catalog defined in the system. If used in a context where the role catalog can be displayed @@ -483,25 +483,25 @@ public abstract class SchemaConstants { */ public static final QName OBJECT_COLLECTION_ROLE_CATALOG_QNAME = new QName(NS_OBJECT_COLLECTIONS, "roleCatalog"); public static final String OBJECT_COLLECTION_ROLE_CATALOG_URI = QNameUtil.qNameToUri(OBJECT_COLLECTION_ROLE_CATALOG_QNAME); - + /** * Collection that contains all roles. */ public static final QName OBJECT_COLLECTION_ALL_ROLES_QNAME = new QName(NS_OBJECT_COLLECTIONS, "allRoles"); public static final String OBJECT_COLLECTION_ALL_ROLES_URI = QNameUtil.qNameToUri(OBJECT_COLLECTION_ALL_ROLES_QNAME); - + /** * Collection that contains all orgs. */ public static final QName OBJECT_COLLECTION_ALL_ORGS_QNAME = new QName(NS_OBJECT_COLLECTIONS, "allOrgs"); public static final String OBJECT_COLLECTION_ALL_ORGS_URI = QNameUtil.qNameToUri(OBJECT_COLLECTION_ALL_ORGS_QNAME); - + /** * Collection that contains all services. */ public static final QName OBJECT_COLLECTION_ALL_SERVICES_QNAME = new QName(NS_OBJECT_COLLECTIONS, "allServices"); public static final String OBJECT_COLLECTION_ALL_SERVICES_URI = QNameUtil.qNameToUri(OBJECT_COLLECTION_ALL_SERVICES_QNAME); - + /** * Collection that contains user's assignments. */ @@ -514,14 +514,15 @@ public abstract class SchemaConstants { public static final QName SAMPLES_DOMAIN = new QName(SchemaConstants.NS_SAMPLES_EXTENSION, "domain"); // Misc - - public static String SCHEMA_LOCALIZATION_PROPERTIES_RESOURCE_BASE_PATH = "localization/schema"; + + public static String BUNDLE_NAME = "schema"; + public static String SCHEMA_LOCALIZATION_PROPERTIES_RESOURCE_BASE_PATH = "localization/" + BUNDLE_NAME; public static final QName APPROVAL_LEVEL_OUTCOME_TYPE_COMPLEX_TYPE = new QName(SchemaConstants.NS_C, ApprovalLevelOutcomeType.class.getSimpleName()); // registration public static final String USER_ID = "user"; public static final String TOKEN = "token"; - + // // resetPassword // public static final String RESET_PASSWORD_ID = "user"; // public static final String RESET_PASSWORD_TOKEN = "token"; diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/CachingStatistics.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/CachingStatistics.java index 570ec145f36..0a2f328a9bd 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/CachingStatistics.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/CachingStatistics.java @@ -20,47 +20,47 @@ * */ public class CachingStatistics { - + private long requests = 0; private long hits = 0; private long misses = 0; - + public long getRequests() { return requests; } - + public synchronized void setRequests(long requests) { this.requests = requests; } - + public synchronized void recordRequest() { this.requests++; } - + public long getHits() { return hits; } - + public synchronized void setHits(long hits) { this.hits = hits; } - + public synchronized void recordHit() { this.hits++; } - + public long getMisses() { return misses; } - + public synchronized void setMisses(long misses) { this.misses = misses; } - + public synchronized void recordMiss() { this.misses++; } - + public CachingStatistics clone() { CachingStatistics clone = new CachingStatistics(); clone.requests = this.requests; diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/InternalCounters.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/InternalCounters.java index 2a0e8cbb32f..e244fff5fa2 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/InternalCounters.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/InternalCounters.java @@ -21,52 +21,52 @@ */ public enum InternalCounters { RESOURCE_SCHEMA_PARSE_COUNT("resourceSchemaParseCount", "resource schema parse count", InternalOperationClasses.RESOURCE_SCHEMA_OPERATIONS), - + RESOURCE_SCHEMA_FETCH_COUNT("resourceSchemaFetchCount", "resource schema fetch count", InternalOperationClasses.REPOSITORY_OPERATIONS), - + CONNECTOR_INSTANCE_INITIALIZATION_COUNT("connectorInstanceInitializationCount", "connector instance initialization count", InternalOperationClasses.CONNECTOR_OPERATIONS), - + CONNECTOR_SCHEMA_PARSE_COUNT("connectorSchemaParseCount", "connector schema parse count", InternalOperationClasses.CONNECTOR_OPERATIONS), - + CONNECTOR_CAPABILITIES_FETCH_COUNT("connectorCapabilitiesFetchCount", "connector capabilities fetchCount", InternalOperationClasses.CONNECTOR_OPERATIONS), - + SCRIPT_COMPILE_COUNT("scriptCompileCount", "script compile count", null), - + SCRIPT_EXECUTION_COUNT("scriptExecutionCount", "script execution count", null), - + CONNECTOR_OPERATION_COUNT("connectorOperationCount", "connector operation count", InternalOperationClasses.CONNECTOR_OPERATIONS), - + CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT("connectorSimulatedPagingSearchCount", "connector simulated paging search count", InternalOperationClasses.CONNECTOR_OPERATIONS), - + SHADOW_FETCH_OPERATION_COUNT("shadowFetchOperationCount", "shadow fetch operation count", InternalOperationClasses.SHADOW_FETCH_OPERATIONS), - + SHADOW_CHANGE_OPERATION_COUNT("shadowChangeOperationCount", "shadow change operation count", null), - + /** * All provisioning operations that reach out to the resources. */ PROVISIONING_ALL_EXT_OPERATION_COUNT("provisioningAllExtOperationCount", "provisioning all ext operation count", null), - + REPOSITORY_READ_COUNT("repositoryReadCount", "repository read count", null), - + PRISM_OBJECT_COMPARE_COUNT("prismObjectCompareCount", "prism object compare count", null), - + PRISM_OBJECT_CLONE_COUNT("prismObjectCloneCount", "prism object clone count", null), - + ROLE_EVALUATION_COUNT("roleEvaluationCount", "role evaluation count", InternalOperationClasses.ROLE_EVALUATIONS), - + ROLE_EVALUATION_SKIP_COUNT("roleEvaluationSkipCount", "role evaluation skip count", null), - + PROJECTOR_RUN_COUNT("projectorRunCount", "projector run count", null); - + // Used as localization key private String key; - + // Used in logfiles, etc. private String label; - + private InternalOperationClasses operationClass; - + private InternalCounters(String key, String label, InternalOperationClasses operationClass) { this.key = key; this.label = label; diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/InternalInspector.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/InternalInspector.java index 4f0bae4b7c6..726bfed2616 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/InternalInspector.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/InternalInspector.java @@ -25,6 +25,6 @@ public interface InternalInspector { void inspectRepositoryRead(Class type, String oid); - + void inspectRoleEvaluation(F target, boolean fullEvaluation); } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/InternalMonitor.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/InternalMonitor.java index f6410500d9c..c9a22869dea 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/InternalMonitor.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/InternalMonitor.java @@ -33,26 +33,26 @@ * Simple monitoring object. It records the count of expensive operations * in the system. It is used in the tests to make sure such operations are not * executed more frequently than expected. It may also have some run-time value. - * + * * @author Radovan Semancik * */ public class InternalMonitor implements PrismMonitor, DebugDumpable { - + private static final Trace LOGGER = TraceManager.getTrace(InternalMonitor.class); private static final String CLONE_START_TIMESTAMP_KEY = InternalMonitor.class.getName()+".cloneStartTimestamp"; - + private static Map counterMap = new HashMap<>(); private static Map traceMap = new HashMap<>(); - + private static CachingStatistics resourceCacheStats = new CachingStatistics(); private static CachingStatistics connectorCacheStats = new CachingStatistics(); - + private static long prismObjectCloneDurationMillis = 0; - + private static InternalInspector inspector; - + public static long getCount(InternalCounters counter) { Long count = counterMap.get(counter); if (count == null) { @@ -60,7 +60,7 @@ public static long getCount(InternalCounters counter) { } return count; } - + public static void recordCount(InternalCounters counter) { long count = recordCountInternal(counter); InternalOperationClasses operationClass = counter.getOperationClass(); @@ -68,7 +68,7 @@ public static void recordCount(InternalCounters counter) { traceOperation(operationClass, count); } } - + private static synchronized long recordCountInternal(InternalCounters counter) { Long count = counterMap.get(counter); if (count == null) { @@ -78,7 +78,7 @@ private static synchronized long recordCountInternal(InternalCounters counter) { counterMap.put(counter, count); return count; } - + public static boolean isTrace(InternalOperationClasses operationClass) { Boolean b = traceMap.get(operationClass); if (b == null) { @@ -87,7 +87,7 @@ public static boolean isTrace(InternalOperationClasses operationClass) { return b; } } - + private static boolean isTrace(InternalCounters counter) { InternalOperationClasses operationClass = counter.getOperationClass(); if (operationClass == null) { @@ -95,11 +95,11 @@ private static boolean isTrace(InternalCounters counter) { } return isTrace(operationClass); } - + public static void setTrace(InternalOperationClasses operationClass, boolean val) { traceMap.put(operationClass, val); } - + private static void traceOperation(InternalOperationClasses operationClass, long counter) { traceOperation(operationClass.getKey(), null, counter, false); } @@ -135,7 +135,7 @@ private static void traceOperation(String opName, Supplier paramsSupplie } } - + public static CachingStatistics getResourceCacheStats() { return resourceCacheStats; } @@ -143,14 +143,14 @@ public static CachingStatistics getResourceCacheStats() { public static CachingStatistics getConnectorCacheStats() { return connectorCacheStats; } - + public static void recordConnectorOperation(String name) { long count = recordCountInternal(InternalCounters.CONNECTOR_OPERATION_COUNT); if (isTrace(InternalCounters.CONNECTOR_OPERATION_COUNT)) { traceOperation("connector", () -> name, count, true); } } - + public static void recordRepositoryRead(Class type, String oid) { long count = recordCountInternal(InternalCounters.REPOSITORY_READ_COUNT); if (isTrace(InternalCounters.REPOSITORY_READ_COUNT)) { @@ -172,7 +172,7 @@ public static long getPrismObjectCloneDurationMillis() { public static void setPrismObjectCloneDurationMillis(long prismObjectCloneDurationMillis) { InternalMonitor.prismObjectCloneDurationMillis = prismObjectCloneDurationMillis; } - + @Override public void beforeObjectClone(PrismObject orig) { LOGGER.trace("MONITOR prism object clone start: {}", orig); @@ -180,7 +180,7 @@ public void beforeObjectClone(PrismObject orig) { orig.setUserData(CLONE_START_TIMESTAMP_KEY, System.currentTimeMillis()); } } - + @Override public synchronized void afterObjectClone(PrismObject orig, PrismObject clone) { long count = recordCountInternal(InternalCounters.PRISM_OBJECT_CLONE_COUNT); @@ -196,7 +196,7 @@ public synchronized void afterObjectClone(PrismObject traceOperation("prism object clone", null, count, false); } } - + public static void recordRoleEvaluation(F target, boolean fullEvaluation) { long count = recordCountInternal(InternalCounters.ROLE_EVALUATION_COUNT); if (isTrace(InternalCounters.ROLE_EVALUATION_COUNT)) { @@ -206,14 +206,14 @@ public static void recordRoleEvaluation(F target, boolean inspector.inspectRoleEvaluation(target, fullEvaluation); } } - + public static void recordRoleEvaluationSkip(F target, boolean fullEvaluation) { long count = recordCountInternal(InternalCounters.ROLE_EVALUATION_SKIP_COUNT); if (isTrace(InternalCounters.ROLE_EVALUATION_SKIP_COUNT)) { traceOperation("roleEvaluationSkip", () -> target.toString() , count, true); } } - + public static InternalInspector getInspector() { return inspector; } @@ -221,7 +221,7 @@ public static InternalInspector getInspector() { public static void setInspector(InternalInspector inspector) { InternalMonitor.inspector = inspector; } - + public static void reset() { LOGGER.info("MONITOR reset"); counterMap.clear(); diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/InternalOperationClasses.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/InternalOperationClasses.java index 054d817b490..0274cc6e575 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/InternalOperationClasses.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/InternalOperationClasses.java @@ -21,23 +21,23 @@ */ public enum InternalOperationClasses { RESOURCE_SCHEMA_OPERATIONS("resourceSchemaOperations", "resource schema operations"), - + CONNECTOR_OPERATIONS("connectorOperations", "connector operations"), - + SHADOW_FETCH_OPERATIONS("shadowFetchOperations", "shadow fetch operations"), - + REPOSITORY_OPERATIONS("repositoryOperations", "repository operations"), - + PRISM_OBJECT_CLONES("prismObjectClone", "prism object clones"), - + ROLE_EVALUATIONS("roleEvaluations", "role evaluations"); - + // Used as localization key private String key; - + // Used in logfiles, etc. private String label; - + private InternalOperationClasses(String key, String label) { this.key = key; this.label = label; diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/InternalsConfig.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/InternalsConfig.java index 53e0346cc1d..677b7df3b8b 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/InternalsConfig.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/InternalsConfig.java @@ -20,39 +20,39 @@ * */ public class InternalsConfig { - + /** * Checks for consistency of data structures (e.g. prism objects, containers, contexts). */ public static boolean consistencyChecks = true; - + /** * Additional checks that method arguments make sense (e.g. deltas are not duplicated) */ private static boolean sanityChecks = true; - + public static boolean encryptionChecks = true; - + // We don't want this to be on by default. It will ruin the ability to explicitly import // non-encrypted value to repo. public static boolean readEncryptionChecks = false; - + // Used by testing code. If set to true then any change to a logging configuration from // inside midpoint (e.g. change of SystemConfiguration object) will be ignored. // DO NOT USE IN PRODUCTION CODE private static boolean avoidLoggingChange = false; - + private static boolean prismMonitoring = false; - + private static boolean allowClearDataLogging = false; - + /** * Non-null value enables alternative code paths used in testing. This adds * special pieces of code that alter normal behavior of the system. These * may reverse the normal evaluation ordering, randomize evaluations or * operation ordering and so on. It is used to make tests more thorough, * so they have a chance to catch more bugs with the same test code. - * + * * These alternative testing paths may be quite inefficient. * This is NOT supposed to be used in production. This is only for * use in testing. @@ -114,19 +114,19 @@ public static TestingPaths getTestingPaths() { public static void setTestingPaths(TestingPaths testingPaths) { InternalsConfig.testingPaths = testingPaths; } - + public static boolean isAllowClearDataLogging() { return allowClearDataLogging; } - + public static void setAllowClearDataLogging(boolean allowClearDataLogging) { InternalsConfig.allowClearDataLogging = allowClearDataLogging; } - + public static void resetTestingPaths() { testingPaths = null; } - + public static void reset() { consistencyChecks = true; sanityChecks = false; @@ -144,7 +144,7 @@ public static void setDevelopmentMode() { prismMonitoring = true; allowClearDataLogging = true; } - + public static void turnOffAllChecks() { consistencyChecks = false; sanityChecks = false; diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/TestingPaths.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/TestingPaths.java index 0983f0cdf3a..e8c40dbbb52 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/TestingPaths.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/internals/TestingPaths.java @@ -22,5 +22,5 @@ public enum TestingPaths { REVERSED, RANDOMIZED; - + } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ConnectorSchemaImpl.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ConnectorSchemaImpl.java index c42eeac767f..9ecb51953c1 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ConnectorSchemaImpl.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ConnectorSchemaImpl.java @@ -51,7 +51,7 @@ protected ConnectorSchemaImpl(PrismContext prismContext) { public ConnectorSchemaImpl(String namespace, PrismContext prismContext) { super(namespace, prismContext); } - + public static ConnectorSchemaImpl parse(Element element, String shortDesc, PrismContext prismContext) throws SchemaException { // TODO: make sure correct parser plugins are used return (ConnectorSchemaImpl) PrismSchemaImpl.parse(element, new ConnectorSchemaImpl(prismContext), true, shortDesc, prismContext); @@ -101,7 +101,7 @@ public Collection getObjectClassDefinitions() // add(cTypeDef); // return cTypeDef; // } - + @Override public ObjectClassComplexTypeDefinition findObjectClassDefinition(QName qName) { diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/MidPointSchemaDefinitionFactory.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/MidPointSchemaDefinitionFactory.java index f898ea74908..5aa62e006c4 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/MidPointSchemaDefinitionFactory.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/MidPointSchemaDefinitionFactory.java @@ -44,7 +44,7 @@ * */ public class MidPointSchemaDefinitionFactory extends SchemaDefinitionFactory { - + @Override public ComplexTypeDefinition createComplexTypeDefinition(XSComplexType complexType, PrismContext prismContext, XSAnnotation annotation) throws SchemaException { @@ -57,14 +57,14 @@ public ComplexTypeDefinition createComplexTypeDefinition(XSComplexType complexTy private ComplexTypeDefinition createObjectClassDefinition(XSComplexType complexType, PrismContext prismContext, XSAnnotation annotation) throws SchemaException { QName typeName = new QName(complexType.getTargetNamespace(),complexType.getName()); - + ObjectClassComplexTypeDefinitionImpl ocDef = new ObjectClassComplexTypeDefinitionImpl(typeName, prismContext); - + // nativeObjectClass Element nativeAttrElement = SchemaProcessorUtil.getAnnotationElement(annotation, MidPointConstants.RA_NATIVE_OBJECT_CLASS); String nativeObjectClass = nativeAttrElement == null ? null : nativeAttrElement.getTextContent(); ocDef.setNativeObjectClass(nativeObjectClass); - + ShadowKindType kind = null; Element kindElement = SchemaProcessorUtil.getAnnotationElement(annotation, MidPointConstants.RA_KIND); if (kindElement != null) { @@ -79,21 +79,21 @@ private ComplexTypeDefinition createObjectClassDefinition(XSComplexType complexT } ocDef.setKind(kind); } - + Boolean defaultInAKind = SchemaProcessorUtil.getAnnotationBooleanMarker(annotation, MidPointConstants.RA_DEFAULT); if (defaultInAKind == null) { ocDef.setDefaultInAKind(false); } else { ocDef.setDefaultInAKind(defaultInAKind); } - + Boolean auxiliary = SchemaProcessorUtil.getAnnotationBooleanMarker(annotation, MidPointConstants.RA_AUXILIARY); if (auxiliary == null) { ocDef.setAuxiliary(false); } else { ocDef.setAuxiliary(auxiliary); } - + String intent = null; Element intentElement = SchemaProcessorUtil.getAnnotationElement(annotation, MidPointConstants.RA_INTENT); if (intentElement != null) { @@ -103,7 +103,7 @@ private ComplexTypeDefinition createObjectClassDefinition(XSComplexType complexT } ocDef.setIntent(intent); } - + // accountType: DEPRECATED if (isAccountObject(annotation)) { if (kind != null && kind != ShadowKindType.ACCOUNT) { @@ -127,11 +127,11 @@ private ComplexTypeDefinition createObjectClassDefinition(XSComplexType complexT ocDef.setIntent(accountType); } } - + return ocDef; } - + @Override public void finishComplexTypeDefinition(ComplexTypeDefinition complexTypeDefinition, XSComplexType complexType, PrismContext prismContext, XSAnnotation annotation) throws SchemaException { @@ -144,7 +144,7 @@ public void finishComplexTypeDefinition(ComplexTypeDefinition complexTypeDefinit private void finishObjectClassDefinition(ObjectClassComplexTypeDefinitionImpl ocDef, XSComplexType complexType, PrismContext prismContext, XSAnnotation annotation) throws SchemaException { - + // displayNameAttribute ResourceAttributeDefinition attrDefinition = getAnnotationReference(annotation, MidPointConstants.RA_DISPLAY_NAME_ATTRIBUTE, ocDef); if (attrDefinition != null) { @@ -171,7 +171,7 @@ private void finishObjectClassDefinition(ObjectClassComplexTypeDefinitionImpl oc ((Collection)ocDef.getSecondaryIdentifiers()).add(attrDefinition); } } - + @Override public void addExtraComplexTypeAnnotations(ComplexTypeDefinition definition, Element appinfo, SchemaToDomProcessor schemaToDomProcessor) { super.addExtraComplexTypeAnnotations(definition, appinfo, schemaToDomProcessor); @@ -182,7 +182,7 @@ public void addExtraComplexTypeAnnotations(ComplexTypeDefinition definition, Ele private void addExtraObjectClassAnnotations(ObjectClassComplexTypeDefinition definition, Element appinfo, SchemaToDomProcessor processor) { processor.addAnnotation(MidPointConstants.RA_RESOURCE_OBJECT, appinfo); - + // displayName, identifier, secondaryIdentifier for (ResourceAttributeDefinition identifier : definition.getPrimaryIdentifiers()) { processor.addRefAnnotation(MidPointConstants.RA_IDENTIFIER, identifier.getName(), appinfo); @@ -204,7 +204,7 @@ private void addExtraObjectClassAnnotations(ObjectClassComplexTypeDefinition def if (!StringUtils.isEmpty(definition.getNativeObjectClass())) { processor.addAnnotation(MidPointConstants.RA_NATIVE_OBJECT_CLASS, definition.getNativeObjectClass(), appinfo); } - + // kind if (definition.getKind() != null) { processor.addAnnotation(MidPointConstants.RA_KIND, definition.getKind().value(), appinfo); @@ -222,20 +222,20 @@ private void addExtraObjectClassAnnotations(ObjectClassComplexTypeDefinition def @Override public PrismContainerDefinition createExtraDefinitionFromComplexType(XSComplexType complexType, - ComplexTypeDefinition complexTypeDefinition, PrismContext prismContext, XSAnnotation annotation) throws SchemaException { + ComplexTypeDefinition complexTypeDefinition, PrismContext prismContext, XSAnnotation annotation) throws SchemaException { // if (complexTypeDefinition instanceof ObjectClassComplexTypeDefinition) { -// return createResourceAttributeContainerDefinition(complexType, (ObjectClassComplexTypeDefinition)complexTypeDefinition, +// return createResourceAttributeContainerDefinition(complexType, (ObjectClassComplexTypeDefinition)complexTypeDefinition, // prismContext, annotation); // } - + return super.createExtraDefinitionFromComplexType(complexType, complexTypeDefinition, prismContext, annotation); } private PrismContainerDefinition createResourceAttributeContainerDefinition(XSComplexType complexType, ObjectClassComplexTypeDefinition complexTypeDefinition, PrismContext prismContext, XSAnnotation annotation) { - + ResourceAttributeContainerDefinition attrContDef = new ResourceAttributeContainerDefinitionImpl(null, complexTypeDefinition, prismContext); - + return attrContDef; } @@ -250,7 +250,7 @@ public PrismPropertyDefinition createPropertyDefinition(QName elementName return super.createPropertyDefinition(elementName, typeName, complexTypeDefinition, prismContext, annotation, elementParticle); } - + @Override public PrismPropertyDefinition createPropertyDefinition(QName elementName, QName typeName, ComplexTypeDefinition complexTypeDefinition, PrismContext prismContext, XSAnnotation annotation, @@ -261,28 +261,28 @@ public PrismPropertyDefinition createPropertyDefinition(QName elementName return super.createPropertyDefinition(elementName, typeName, complexTypeDefinition, prismContext, annotation, elementParticle, allowedValues, defaultValue); } - + private PrismPropertyDefinition createResourceAttributeDefinition(QName elementName, QName typeName, PrismContext prismContext, XSAnnotation annotation) throws SchemaException { ResourceAttributeDefinitionImpl attrDef = new ResourceAttributeDefinitionImpl(elementName, typeName, prismContext); - + // nativeAttributeName Element nativeAttrElement = SchemaProcessorUtil.getAnnotationElement(annotation, MidPointConstants.RA_NATIVE_ATTRIBUTE_NAME); String nativeAttributeName = nativeAttrElement == null ? null : nativeAttrElement.getTextContent(); if (!StringUtils.isEmpty(nativeAttributeName)) { attrDef.setNativeAttributeName(nativeAttributeName); } - + // frameworkAttributeName Element frameworkAttrElement = SchemaProcessorUtil.getAnnotationElement(annotation, MidPointConstants.RA_FRAMEWORK_ATTRIBUTE_NAME); String frameworkAttributeName = frameworkAttrElement == null ? null : frameworkAttrElement.getTextContent(); if (!StringUtils.isEmpty(frameworkAttributeName)) { attrDef.setFrameworkAttributeName(frameworkAttributeName); } - + // returnedByDefault attrDef.setReturnedByDefault(SchemaProcessorUtil.getAnnotationBoolean(annotation, MidPointConstants.RA_RETURNED_BY_DEFAULT_NAME)); - + return attrDef; } @@ -290,7 +290,7 @@ private PrismPropertyDefinition createResourceAttributeDefinition(QName elementN public void addExtraPropertyAnnotations(PrismPropertyDefinition definition, Element appinfo, SchemaToDomProcessor schemaToDomProcessor) { super.addExtraPropertyAnnotations(definition, appinfo, schemaToDomProcessor); - + if (definition instanceof ResourceAttributeDefinition) { ResourceAttributeDefinition rad = (ResourceAttributeDefinition)definition; if (rad.getNativeAttributeName() != null) { @@ -317,20 +317,20 @@ private boolean isResourceObject(XSAnnotation annotation) { } return false; } - + private boolean isAccountObject(XSAnnotation annotation) { if (annotation == null || annotation.getAnnotation() == null) { return false; } - + Element accountType = SchemaProcessorUtil.getAnnotationElement(annotation, MidPointConstants.RA_ACCOUNT); if (accountType != null) { return true; } - + return false; } - + private ResourceAttributeDefinition getAnnotationReference(XSAnnotation annotation, QName qname, ObjectClassComplexTypeDefinition objectClass) throws SchemaException { Element element = SchemaProcessorUtil.getAnnotationElement(annotation, qname); if (element != null) { diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ObjectClassComplexTypeDefinitionImpl.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ObjectClassComplexTypeDefinitionImpl.java index 7305a27330a..72b9be6a074 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ObjectClassComplexTypeDefinitionImpl.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ObjectClassComplexTypeDefinitionImpl.java @@ -102,7 +102,7 @@ public ResourceAttributeDefinition getDescriptionAttribute() { void setDescriptionAttribute(ResourceAttributeDefinition descriptionAttribute) { this.descriptionAttribute = descriptionAttribute; } - + @Override public ResourceAttributeDefinition getNamingAttribute() { return namingAttribute; @@ -111,11 +111,11 @@ public ResourceAttributeDefinition getNamingAttribute() { public void setNamingAttribute(ResourceAttributeDefinition namingAttribute) { this.namingAttribute = namingAttribute; } - + public void setNamingAttribute(QName namingAttribute) { setNamingAttribute(findAttributeDefinition(namingAttribute)); } - + @Override public String getNativeObjectClass() { return nativeObjectClass; @@ -124,7 +124,7 @@ public String getNativeObjectClass() { public void setNativeObjectClass(String nativeObjectClass) { this.nativeObjectClass = nativeObjectClass; } - + @Override public boolean isAuxiliary() { return auxiliary; @@ -147,20 +147,20 @@ public void setKind(ShadowKindType kind) { public boolean isDefaultInAKind() { return defaultInAKind; } - + public void setDefaultInAKind(boolean defaultAccountType) { this.defaultInAKind = defaultAccountType; } - + @Override public String getIntent() { return intent; } - + public void setIntent(String intent) { this.intent = intent; } - + @Override public ResourceAttributeDefinition getDisplayNameAttribute() { return displayNameAttribute; @@ -169,10 +169,10 @@ public ResourceAttributeDefinition getDisplayNameAttribute() { public void setDisplayNameAttribute(ResourceAttributeDefinition displayName) { this.displayNameAttribute = displayName; } - + /** * TODO - * + * * Convenience method. It will internally look up the correct definition. */ public void setDisplayNameAttribute(QName displayName) { @@ -184,18 +184,18 @@ public ResourceAttributeDefinitionImpl createAttributeDefinition(QName na add(propDef); return propDef; } - + public ResourceAttributeDefinitionImpl createAttributeDefinition(String localName, QName typeName) { QName name = new QName(getSchemaNamespace(),localName); return createAttributeDefinition(name,typeName); } - + public ResourceAttributeDefinition createAttributeDefinition(String localName, String localTypeName) { QName name = new QName(getSchemaNamespace(),localName); QName typeName = new QName(getSchemaNamespace(),localTypeName); return createAttributeDefinition(name,typeName); } - + @Override public boolean matches(ShadowType shadowType) { if (shadowType == null) { @@ -214,7 +214,7 @@ public boolean matches(ShadowType shadowType) { public ResourceAttributeContainer instantiate(QName elementName) { return instantiate(elementName, this); } - + public static ResourceAttributeContainer instantiate(QName elementName, ObjectClassComplexTypeDefinition ocdef) { ResourceAttributeContainerDefinition racDef = ocdef.toResourceAttributeContainerDefinition(elementName); return new ResourceAttributeContainer(elementName, racDef, ocdef.getPrismContext()); @@ -249,7 +249,7 @@ protected void copyDefinitionData(ObjectClassComplexTypeDefinitionImpl clone) { clone.secondaryIdentifiers.addAll(this.secondaryIdentifiers); clone.auxiliary = this.auxiliary; } - + @Override public int hashCode() { final int prime = 31; diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceAttribute.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceAttribute.java index 6593897c425..b857f142b1c 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceAttribute.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceAttribute.java @@ -80,7 +80,7 @@ public String getNativeAttributeName() { return getDefinition() == null ? null : getDefinition() .getNativeAttributeName(); } - + @Override public ResourceAttribute clone() { ResourceAttribute clone = new ResourceAttribute(getElementName(), getDefinition(), getPrismContext()); diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceAttributeContainer.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceAttributeContainer.java index 6fa25702c99..b8c169633fe 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceAttributeContainer.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceAttributeContainer.java @@ -30,15 +30,15 @@ /** * Resource Object. - * + * * Resource Object understands resource-specific annotations, such as * identifiers, native object class, etc. - * + * * Object class can be determined by using the definition (inherited from * PropertyContainer) - * + * * @author Radovan Semancik - * + * */ public final class ResourceAttributeContainer extends PrismContainer { @@ -67,11 +67,11 @@ public ResourceAttributeContainerDefinition getDefinition() { /** * Returns set of resource object attributes. - * + * * The order of attributes is insignificant. - * + * * The returned set is imutable! Any change to it will be ignored. - * + * * @return set of resource object attributes. */ @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -86,18 +86,18 @@ public void add(ResourceAttribute attribute) throws SchemaException { /** * Returns a (single) primary identifier. - * + * * This method returns a property that acts as an (primary) identifier for * the resource object. Primary identifiers are used to access the resource * objects, retrieve them from resource, identify objects for modifications, * etc. - * + * * Returns null if no identifier is defined. - * + * * Resource objects may have multiple (composite) identifiers, but this * method assumes that there is only a single identifier. The method will * throw exception if that assumption is not satisfied. - * + * * @return identifier property * @throws IllegalStateException * if resource object has multiple identifiers @@ -107,29 +107,29 @@ public PrismProperty getPrimaryIdentifier() { if (attrDefs.size() > 1){ throw new IllegalStateException("Resource object has more than one identifier."); } - + for (PrismProperty p : attrDefs){ return p; } - + return null; } /** * Returns primary identifiers. - * + * * This method returns properties that act as (primary) identifiers for the * resource object. Primary identifiers are used to access the resource * objects, retrieve them from resource, identify objects for modifications, * etc. - * + * * Returns empty set if no identifier is defined. Must not return null. - * + * * Resource objects may have multiple (composite) identifiers, all of them * are returned. - * + * * The returned set it immutable! Any modifications will be lost. - * + * * @return set of identifier properties */ public Collection> getPrimaryIdentifiers() { @@ -138,17 +138,17 @@ public Collection> getPrimaryIdentifiers() { /** * Returns a (single) secondary identifier. - * + * * This method returns a property that acts as an secondary identifier for * the resource object. Secondary identifiers are used to confirm primary * identification of resource object. - * + * * Returns null if no secondary identifier is defined. - * + * * Resource objects may have multiple (composite) identifiers, but this * method assumes that there is only a single identifier. The method will * throw exception if that assumption is not satisfied. - * + * * @return secondary identifier property * @throws IllegalStateException * if resource object has multiple secondary identifiers @@ -166,22 +166,22 @@ public PrismProperty getSecondaryIdentifier() { /** * Returns secondary identifiers. - * + * * This method returns properties that act as secondary identifiers for the * resource object. Secondary identifiers are used to confirm primary * identification of resource object. - * + * * Returns empty set if no identifier is defined. Must not return null. - * + * * Resource objects may have multiple (composite) identifiers, all of them * are returned. - * + * * @return set of secondary identifier properties - */ + */ public Collection> getSecondaryIdentifiers() { return extractAttributesByDefinitions(getDefinition().getSecondaryIdentifiers()); } - + public Collection> getAllIdentifiers() { return extractAttributesByDefinitions(getDefinition().getAllIdentifiers()); } @@ -201,14 +201,14 @@ private Collection> extractAttributesByDefinitions(Collecti /** * Returns description attribute of a resource object. - * + * * Returns null if there is no description attribute or the attribute is not * known. - * + * * The exception should be never thrown unless there is some bug in the * code. The validation of model consistency should be done at the time of * schema parsing. - * + * * @return description attribute of a resource object. * @throws IllegalStateException * if there is no definition for the referenced attributed @@ -219,18 +219,18 @@ public ResourceAttribute getDescriptionAttribute() { } return findAttribute(getDefinition().getDisplayNameAttribute()); } - + /** * Specifies which resource attribute should be used as a "technical" name * for the account. This name will appear in log files and other troubleshooting * tools. The name should be a form of unique identifier that can be used to * locate the resource object for diagnostics. It should not contain white chars and * special chars if that can be avoided and it should be reasonable short. - - * It is different from a display name attribute. Display name is intended for a + + * It is different from a display name attribute. Display name is intended for a * common user or non-technical administrator (such as role administrator). The * naming attribute is intended for technical IDM administrators and developers. - * + * * @return attribute that should be used as a "technical" name * for the account. */ @@ -246,14 +246,14 @@ public ResourceAttribute getNamingAttribute() { /** * Returns display name attribute of a resource object. - * + * * Returns null if there is no display name attribute or the attribute is * not known. - * + * * The exception should be never thrown unless there is some bug in the * code. The validation of model consistency should be done at the time of * schema parsing. - * + * * @return display name attribute of a resource object. * @throws IllegalStateException * if there is no definition for the referenced attributed @@ -267,20 +267,20 @@ public ResourceAttribute getDisplayNameAttribute() { /** * Returns the native object class string for the resource object. - * + * * Native object class is the name of the Resource Object Definition (Object * Class) as it is seen by the resource itself. The name of the Resource * Object Definition may be constrained by XSD or other syntax and therefore * may be "mangled" to conform to such syntax. The native object * class value will contain unmangled name (if available). - * + * * Returns null if there is no native object class or the native object * class is not known. - * + * * The exception should be never thrown unless there is some bug in the * code. The validation of model consistency should be done at the time of * schema parsing. - * + * * @return native object class * @throws IllegalStateException * if there is more than one description attribute. @@ -293,24 +293,24 @@ public ShadowKindType getKind() { ResourceAttributeContainerDefinition definition = getDefinition(); return (definition != null ? definition.getKind() : null); } - + /** * Indicates whether definition is should be used as default account type. - * + * * If true value is returned then the definition should be used as a default * account type definition. This is a way how a resource connector may * suggest applicable object classes (resource object definitions) for * accounts. - * + * * If no information about account type is present, false should be * returned. This method must return true only if isAccountType() returns * true. - * + * * The exception should be never thrown unless there is some bug in the * code. The validation of at-most-one value should be done at the time of * schema parsing. The exception may not even be thrown at all if the * implementation is not able to determine duplicity. - * + * * @return true if the definition should be used as account type. * @throws IllegalStateException * if more than one default account is suggested in the schema. @@ -322,9 +322,9 @@ public boolean isDefaultInAKind() { /** * Finds a specific attribute in the resource object by name. - * + * * Returns null if nothing is found. - * + * * @param attributeQName * attribute name to find. * @return found attribute or null @@ -336,9 +336,9 @@ public ResourceAttribute findAttribute(QName attributeQName) { /** * Finds a specific attribute in the resource object by definition. - * + * * Returns null if nothing is found. - * + * * @param attributeDefinition * attribute definition to find. * @return found attribute or null @@ -346,19 +346,19 @@ public ResourceAttribute findAttribute(QName attributeQName) { public ResourceAttribute findAttribute(ResourceAttributeDefinition attributeDefinition) { return (ResourceAttribute) getValue().findProperty(attributeDefinition); } - + public ResourceAttribute findOrCreateAttribute(ResourceAttributeDefinition attributeDefinition) throws SchemaException { return (ResourceAttribute) getValue().findOrCreateProperty(attributeDefinition); } - + public ResourceAttribute findOrCreateAttribute(QName attributeName) throws SchemaException { return (ResourceAttribute) getValue().findOrCreateProperty(attributeName); } - + public boolean contains(ResourceAttribute attr) { return getValue().contains(attr); } - + public static ResourceAttributeContainer convertFromContainer(PrismContainer origAttrContainer, ObjectClassComplexTypeDefinition objectClassDefinition) throws SchemaException { if (origAttrContainer == null || origAttrContainer.getValue() == null) { @@ -386,13 +386,13 @@ public static ResourceAttributeContainer convertFromContainer(PrismContainer } return attributesContainer; } - + public static ResourceAttributeContainer createEmptyContainer(QName elementName, ObjectClassComplexTypeDefinition objectClassDefinition) { ResourceAttributeContainerDefinition attributesContainerDefinition = new ResourceAttributeContainerDefinitionImpl(elementName, - objectClassDefinition, objectClassDefinition.getPrismContext()); + objectClassDefinition, objectClassDefinition.getPrismContext()); return new ResourceAttributeContainer(elementName, attributesContainerDefinition , objectClassDefinition.getPrismContext()); } - + @Override public ResourceAttributeContainer clone() { ResourceAttributeContainer clone = new ResourceAttributeContainer(getElementName(), getDefinition(), getPrismContext()); @@ -405,7 +405,7 @@ protected void copyValues(ResourceAttributeContainer clone) { // Nothing to copy } - + @Override public void checkConsistenceInternal(Itemable rootItem, boolean requireDefinitions, boolean prohibitRaw, ConsistencyCheckScope scope) { diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceAttributeContainerDefinitionImpl.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceAttributeContainerDefinitionImpl.java index 1fda343fc3c..0198d11d79f 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceAttributeContainerDefinitionImpl.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceAttributeContainerDefinitionImpl.java @@ -32,32 +32,32 @@ /** * Resource Object Definition (Object Class). - * + * * Object Class refers to a type of object on the Resource. Unix account, Active * Directory group, inetOrgPerson LDAP objectclass or a schema of USERS database * table are all Object Classes from the midPoint point of view. Object class * defines a set of attribute names, types for each attributes and few * additional properties. - * + * * This class represents schema definition for resource object (object class). * See {@link Definition} for more details. - * + * * Resource Object Definition is immutable. TODO: This will probably need to be * changed to a mutable object. - * + * * @author Radovan Semancik - * + * */ public class ResourceAttributeContainerDefinitionImpl extends PrismContainerDefinitionImpl implements ResourceAttributeContainerDefinition { private static final long serialVersionUID = 3943909626639924429L; - + public ResourceAttributeContainerDefinitionImpl(QName name, ObjectClassComplexTypeDefinition complexTypeDefinition, PrismContext prismContext) { super(name, complexTypeDefinition, prismContext); super.setCompileTimeClass(ShadowAttributesType.class); } - + @Override public ObjectClassComplexTypeDefinition getComplexTypeDefinition() { return (ObjectClassComplexTypeDefinition)super.getComplexTypeDefinition(); @@ -65,14 +65,14 @@ public ObjectClassComplexTypeDefinition getComplexTypeDefinition() { /** * Returns the definition of primary identifier attributes of a resource object. - * + * * May return empty set if there are no identifier attributes. Must not * return null. - * + * * The exception should be never thrown unless there is some bug in the * code. The validation of model consistency should be done at the time of * schema parsing. - * + * * @return definition of identifier attributes * @throws IllegalStateException * if there is no definition for the referenced attributed @@ -86,14 +86,14 @@ public Collection getPrimaryIdentifiers() /** * Returns the definition of secondary identifier attributes of a resource * object. - * + * * May return empty set if there are no secondary identifier attributes. * Must not return null. - * + * * The exception should be never thrown unless there is some bug in the * code. The validation of model consistency should be done at the time of * schema parsing. - * + * * @return definition of secondary identifier attributes * @throws IllegalStateException * if there is no definition for the referenced attributed @@ -102,7 +102,7 @@ public Collection getPrimaryIdentifiers() public Collection getSecondaryIdentifiers() { return getComplexTypeDefinition().getSecondaryIdentifiers(); } - + @Override public Collection getAllIdentifiers() { return getComplexTypeDefinition().getAllIdentifiers(); @@ -110,13 +110,13 @@ public Collection getAllIdentifiers() { /** * Returns the definition of description attribute of a resource object. - * + * * Returns null if there is no description attribute. - * + * * The exception should be never thrown unless there is some bug in the * code. The validation of model consistency should be done at the time of * schema parsing. - * + * * @return definition of secondary identifier attributes * @throws IllegalStateException * if there is more than one description attribute. But this @@ -134,18 +134,18 @@ public void setDescriptionAttribute(ResourceAttributeDefinition descriptionAttri // object class definition and attribute container ((ObjectClassComplexTypeDefinitionImpl) getComplexTypeDefinition()).setDescriptionAttribute(descriptionAttribute); } - + /** * Specifies which resource attribute should be used as a "technical" name * for the account. This name will appear in log files and other troubleshooting * tools. The name should be a form of unique identifier that can be used to * locate the resource object for diagnostics. It should not contain white chars and * special chars if that can be avoided and it should be reasonable short. - - * It is different from a display name attribute. Display name is intended for a + + * It is different from a display name attribute. Display name is intended for a * common user or non-technical administrator (such as role administrator). The * naming attribute is intended for technical IDM administrators and developers. - * + * * @return resource attribute definition that should be used as a "technical" name * for the account. */ @@ -166,19 +166,19 @@ public void setNamingAttribute(QName namingAttribute) { /** * Returns the native object class string for the resource object. - * + * * Native object class is the name of the Resource Object Definition (Object * Class) as it is seen by the resource itself. The name of the Resource * Object Definition may be constrained by XSD or other syntax and therefore * may be "mangled" to conform to such syntax. The native object * class value will contain unmangled name (if available). - * + * * Returns null if there is no native object class. - * + * * The exception should be never thrown unless there is some bug in the * code. The validation of model consistency should be done at the time of * schema parsing. - * + * * @return native object class * @throws IllegalStateException * if there is more than one description attribute. @@ -196,21 +196,21 @@ public void setNativeObjectClass(String nativeObjectClass) { /** * Indicates whether definition is should be used as default account type. - * + * * If true value is returned then the definition should be used as a default * account type definition. This is a way how a resource connector may * suggest applicable object classes (resource object definitions) for * accounts. - * + * * If no information about account type is present, false should be * returned. This method must return true only if isAccountType() returns * true. - * + * * The exception should be never thrown unless there is some bug in the * code. The validation of at-most-one value should be done at the time of * schema parsing. The exception may not even be thrown at all if the * implementation is not able to determine duplicity. - * + * * @return true if the definition should be used as account type. * @throws IllegalStateException * if more than one default account is suggested in the schema. @@ -223,40 +223,40 @@ public boolean isDefaultInAKind() { public void setDefaultInAKind(boolean defaultAccountType) { ((ObjectClassComplexTypeDefinitionImpl) getComplexTypeDefinition()).setDefaultInAKind(defaultAccountType); } - + @Override public String getIntent() { return getComplexTypeDefinition().getIntent(); } - + public void setIntent(String accountTypeName) { ((ObjectClassComplexTypeDefinitionImpl) getComplexTypeDefinition()).setIntent(accountTypeName); } - + @Override public ShadowKindType getKind() { return getComplexTypeDefinition().getKind(); } - + public void setKind(ShadowKindType kind) { ((ObjectClassComplexTypeDefinitionImpl) getComplexTypeDefinition()).setKind(kind); } /** * Returns the definition of display name attribute. - * + * * Display name attribute specifies which resource attribute should be used * as title when displaying objects of a specific resource object class. It * must point to an attribute of String type. If not present, primary * identifier should be used instead (but this method does not handle this * default behavior). - * + * * Returns null if there is no display name attribute. - * + * * The exception should be never thrown unless there is some bug in the * code. The validation of model consistency should be done at the time of * schema parsing. - * + * * @return native object class * @throws IllegalStateException * if there is more than one display name attribute or the @@ -273,9 +273,9 @@ public void setDisplayNameAttribute(ResourceAttributeDefinition displayName) { /** * TODO - * + * * Convenience method. It will internally look up the correct definition. - * + * * @param displayName */ public void setDisplayNameAttribute(QName displayName) { @@ -287,14 +287,14 @@ public void setDisplayNameAttribute(QName displayName) { public ResourceAttributeContainer instantiate() { return instantiate(getName()); } - + @NotNull @Override public ResourceAttributeContainer instantiate(QName name) { name = addNamespaceIfApplicable(name); return new ResourceAttributeContainer(name, this, prismContext); } - + @NotNull @Override public ResourceAttributeContainerDefinitionImpl clone() { @@ -303,7 +303,7 @@ public ResourceAttributeContainerDefinitionImpl clone() { copyDefinitionData(clone); return clone; } - + protected void copyDefinitionData(ResourceAttributeContainerDefinitionImpl clone) { super.copyDefinitionData(clone); } @@ -317,7 +317,7 @@ public ResourceAttributeDefinition findAttributeDefinition(QName elementQName) { public ResourceAttributeDefinition findAttributeDefinition(QName elementQName, boolean caseInsensitive) { return findItemDefinition(elementQName, ResourceAttributeDefinition.class, caseInsensitive); } - + @Override public ResourceAttributeDefinition findAttributeDefinition(ItemPath elementPath) { return findItemDefinition(elementPath, ResourceAttributeDefinition.class); @@ -328,7 +328,7 @@ public ResourceAttributeDefinition findAttributeDefinition(String elementLocalna QName elementQName = new QName(getName().getNamespaceURI(),elementLocalname); return findAttributeDefinition(elementQName); } - + @Override public List getAttributeDefinitions() { List attrs = new ArrayList<>(); @@ -341,7 +341,7 @@ public List getAttributeDefinitions() { } return attrs; } - + // Only attribute definitions should be here. @Override public List getDefinitions() { @@ -352,11 +352,11 @@ public List getDefinitions() { public PrismObjectDefinition toShadowDefinition() { PrismObjectDefinition origShadowDef = (PrismObjectDefinition) prismContext.getSchemaRegistry(). findObjectDefinitionByCompileTimeClass(ShadowType.class); - PrismObjectDefinition shadowDefinition = + PrismObjectDefinition shadowDefinition = origShadowDef.cloneWithReplacedDefinition(ShadowType.F_ATTRIBUTES, this); return shadowDefinition; } - + @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceAttributeDefinitionImpl.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceAttributeDefinitionImpl.java index 25fc4382b39..c941acbfa03 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceAttributeDefinitionImpl.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceAttributeDefinitionImpl.java @@ -25,21 +25,21 @@ /** * Resource Object Attribute Definition. - * + * * Resource Object Attribute is a Property of Resource Object. All that applies * to property applies also to attribute, e.g. only a whole attributes can be * changed, they may be simple or complex types, they should be representable in * XML, etc. In addition, attribute definition may have some annotations that * suggest its purpose and use on the Resource. - * + * * Resource Object Attribute understands resource-specific annotations such as * native attribute name. - * + * * This class represents schema definition for resource object attribute. See * {@link Definition} for more details. - * + * * @author Radovan Semancik - * + * */ public class ResourceAttributeDefinitionImpl extends PrismPropertyDefinitionImpl implements ResourceAttributeDefinition { @@ -69,7 +69,7 @@ public ResourceAttribute instantiate(QName name) { public Boolean getReturnedByDefault() { return returnedByDefault; } - + @Override public boolean isReturnedByDefault() { if (returnedByDefault == null) { @@ -85,16 +85,16 @@ public void setReturnedByDefault(Boolean returnedByDefault) { /** * Returns true if the attribute is a (primary) identifier. - * + * * Convenience method. - * + * * @return true if the attribute is a (primary) identifier. */ @Override public boolean isIdentifier(ResourceAttributeContainerDefinition objectDefinition) { return isIdentifier(objectDefinition.getComplexTypeDefinition()); } - + @Override public boolean isIdentifier(ObjectClassComplexTypeDefinition objectDefinition) { for (ResourceAttributeDefinition identifier : objectDefinition.getPrimaryIdentifiers()) { @@ -104,7 +104,7 @@ public boolean isIdentifier(ObjectClassComplexTypeDefinition objectDefinition) { } return false; } - + @Override public boolean isSecondaryIdentifier(ObjectClassComplexTypeDefinition objectDefinition) { for (ResourceAttributeDefinition secondaryIdentifier : objectDefinition.getSecondaryIdentifiers()) { @@ -117,21 +117,21 @@ public boolean isSecondaryIdentifier(ObjectClassComplexTypeDefinition objectDefi /** * Returns native attribute name. - * + * * Native name of the attribute is a name as it is used on the resource or * as seen by the connector. It is used for diagnostics purposes and may be * used by the connector itself. As the attribute names in XSD have to * comply with XML element name limitations, this may be the only way how to * determine original attribute name. - * + * * Returns null if native attribute name is not set or unknown. - * + * * The name should be the same as the one used by the resource, if the * resource supports naming of attributes. E.g. in case of LDAP this * annotation should contain "cn", "givenName", etc. If the resource is not * that flexible, the native attribute names may be hardcoded (e.g. * "username", "homeDirectory") or may not be present at all. - * + * * @return native attribute name */ @Override @@ -142,11 +142,11 @@ public String getNativeAttributeName() { public void setNativeAttributeName(String nativeAttributeName) { this.nativeAttributeName = nativeAttributeName; } - + /** * Returns name of the attribute as given in the connector framework. * This is not used for any significant logic. It is mostly for diagnostics. - * + * * @return name of the attribute as given in the connector framework. */ @Override @@ -165,14 +165,14 @@ public ResourceAttributeDefinition clone() { copyDefinitionData(clone); return clone; } - + protected void copyDefinitionData(ResourceAttributeDefinitionImpl clone) { super.copyDefinitionData(clone); clone.nativeAttributeName = this.nativeAttributeName; clone.frameworkAttributeName = this.frameworkAttributeName; clone.returnedByDefault = this.returnedByDefault; } - + @Override public int hashCode() { final int prime = 31; @@ -226,7 +226,7 @@ protected void extendToString(StringBuilder sb) { sb.append(returnedByDefault); } } - + /** * Return a human readable name of this class suitable for logs. */ diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceObjectIdentification.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceObjectIdentification.java index ed2c1c5d712..c538c55dd08 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceObjectIdentification.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceObjectIdentification.java @@ -36,9 +36,9 @@ public class ResourceObjectIdentification implements Serializable { private Collection> primaryIdentifiers; private Collection> secondaryIdentifiers; // TODO: identification strategy - - public ResourceObjectIdentification(ObjectClassComplexTypeDefinition objectClassDefinition, - Collection> primaryIdentifiers, + + public ResourceObjectIdentification(ObjectClassComplexTypeDefinition objectClassDefinition, + Collection> primaryIdentifiers, Collection> secondaryIdentifiers) { this.objectClassDefinition = objectClassDefinition; this.primaryIdentifiers = primaryIdentifiers; @@ -48,7 +48,7 @@ public ResourceObjectIdentification(ObjectClassComplexTypeDefinition objectClass public Collection> getPrimaryIdentifiers() { return primaryIdentifiers; } - + public ResourceAttribute getPrimaryIdentifier() throws SchemaException { if (primaryIdentifiers == null || primaryIdentifiers.isEmpty()) { return null; @@ -62,7 +62,7 @@ public ResourceAttribute getPrimaryIdentifier() throws SchemaException { public Collection> getSecondaryIdentifiers() { return secondaryIdentifiers; } - + public ResourceAttribute getSecondaryIdentifier() throws SchemaException { if (secondaryIdentifiers == null || secondaryIdentifiers.isEmpty()) { return null; @@ -77,8 +77,8 @@ public ResourceAttribute getSecondaryIdentifier() throws SchemaException public ObjectClassComplexTypeDefinition getObjectClassDefinition() { return objectClassDefinition; } - - public static ResourceObjectIdentification create(ObjectClassComplexTypeDefinition objectClassDefinition, + + public static ResourceObjectIdentification create(ObjectClassComplexTypeDefinition objectClassDefinition, Collection> allIdentifiers) throws SchemaException { if (allIdentifiers == null) { throw new IllegalArgumentException("Cannot create ResourceObjectIdentification with null identifiers"); @@ -102,8 +102,8 @@ public static ResourceObjectIdentification create(ObjectClassComplexTypeDefiniti } return new ResourceObjectIdentification(objectClassDefinition, primaryIdentifiers, secondaryIdentifiers); } - - public static ResourceObjectIdentification createFromAttributes(ObjectClassComplexTypeDefinition objectClassDefinition, + + public static ResourceObjectIdentification createFromAttributes(ObjectClassComplexTypeDefinition objectClassDefinition, Collection> attributes) throws SchemaException { Collection> primaryIdentifiers = null; Collection> secondaryIdentifiers = null; @@ -122,22 +122,22 @@ public static ResourceObjectIdentification createFromAttributes(ObjectClassCompl } return new ResourceObjectIdentification(objectClassDefinition, primaryIdentifiers, secondaryIdentifiers); } - - public static ResourceObjectIdentification createFromShadow(ObjectClassComplexTypeDefinition objectClassDefinition, + + public static ResourceObjectIdentification createFromShadow(ObjectClassComplexTypeDefinition objectClassDefinition, ShadowType shadowType) throws SchemaException { return createFromAttributes(objectClassDefinition, ShadowUtil.getAttributes(shadowType)); } - + public void validatePrimaryIdenfiers() { if (!hasPrimaryIdentifiers()) { throw new IllegalStateException("No primary identifiers in " + this); } } - + public boolean hasPrimaryIdentifiers() { return primaryIdentifiers != null && !primaryIdentifiers.isEmpty(); } - + @Override public int hashCode() { final int prime = 31; @@ -171,8 +171,8 @@ public boolean equals(Object obj) { @Override public String toString() { - return "ResourceObjectIdentification(" + PrettyPrinter.prettyPrint(objectClassDefinition.getTypeName()) + return "ResourceObjectIdentification(" + PrettyPrinter.prettyPrint(objectClassDefinition.getTypeName()) + ": primary=" + primaryIdentifiers + ", secondary=" + secondaryIdentifiers + ")"; } - + } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceSchemaImpl.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceSchemaImpl.java index ed5697e9427..55826cc45b7 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceSchemaImpl.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/ResourceSchemaImpl.java @@ -44,7 +44,7 @@ protected ResourceSchemaImpl(PrismContext prismContext) { public ResourceSchemaImpl(String namespace, PrismContext prismContext) { super(namespace, prismContext); } - + public static ResourceSchemaImpl parse(Element element, String shortDesc, PrismContext prismContext) throws SchemaException { // TODO: make sure correct parser plugins are used return (ResourceSchemaImpl) PrismSchemaImpl.parse(element, new ResourceSchemaImpl(prismContext), true, shortDesc, prismContext); @@ -90,9 +90,9 @@ public ObjectClassComplexTypeDefinition findDefaultObjectClassDefinition(ShadowK /** * Creates a new resource object definition and adds it to the schema. - * + * * This is a preferred way how to create definition in the schema. - * + * * @param localTypeName * type name "relative" to schema namespace * @return new resource object definition @@ -104,9 +104,9 @@ public ObjectClassComplexTypeDefinition createObjectClassDefinition(String local /** * Creates a new resource object definition and adds it to the schema. - * + * * This is a preferred way how to create definition in the schema. - * + * * @param typeName * type QName * @return new resource object definition @@ -116,6 +116,6 @@ public ObjectClassComplexTypeDefinition createObjectClassDefinition(QName typeNa add(cTypeDef); return cTypeDef; } - + } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/SearchHierarchyConstraints.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/SearchHierarchyConstraints.java index 09bd4eed16d..6ae1fd99e1f 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/SearchHierarchyConstraints.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/processor/SearchHierarchyConstraints.java @@ -23,7 +23,7 @@ public class SearchHierarchyConstraints { ResourceObjectIdentification baseContext; SearchHierarchyScope scope; - + public SearchHierarchyConstraints(ResourceObjectIdentification baseContext, SearchHierarchyScope scope) { super(); this.baseContext = baseContext; @@ -37,6 +37,6 @@ public ResourceObjectIdentification getBaseContext() { public SearchHierarchyScope getScope() { return scope; } - - + + } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/AsynchronousOperationQueryable.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/AsynchronousOperationQueryable.java index e5d76a3bb11..f402d0499e4 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/AsynchronousOperationQueryable.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/AsynchronousOperationQueryable.java @@ -20,12 +20,12 @@ /** * Interface that provide ability to query status of asynchronous operation. - * + * * @author Radovan Semancik */ @FunctionalInterface public interface AsynchronousOperationQueryable { OperationResultStatus queryOperationStatus(String asyncronousOperationReference, OperationResult parentResult) throws ObjectNotFoundException, SchemaException; - + } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/AsynchronousOperationResult.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/AsynchronousOperationResult.java index ea383b453ea..01ae9a3c5be 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/AsynchronousOperationResult.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/AsynchronousOperationResult.java @@ -19,14 +19,14 @@ * Primary goal of this class is to support asynchronous operations. * The call to operation may return even if the resource operation * is still in progress. The IN_PROGRESS status will be indicated in - * this class in the operation result. The result may also include + * this class in the operation result. The result may also include * the asynchronous operation reference in the operational status. * This reference may be later used to check the status of the - * operation. - * + * operation. + * * This may seems too simple and maybe pointless now. But we expect * that it may later evolve to something like future/promise. - * + * * @author semancik * */ @@ -41,13 +41,13 @@ public OperationResult getOperationResult() { public void setOperationResult(OperationResult operationResult) { this.operationResult = operationResult; } - + public static AsynchronousOperationResult wrap(OperationResult result) { AsynchronousOperationResult ret = new AsynchronousOperationResult(); ret.setOperationResult(result); return ret; } - + public boolean isInProgress() { return operationResult.isInProgress(); } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/AsynchronousOperationReturnValue.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/AsynchronousOperationReturnValue.java index 5a24236d8fa..b5af216ba12 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/AsynchronousOperationReturnValue.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/AsynchronousOperationReturnValue.java @@ -18,7 +18,7 @@ /** * This may seems too simple and maybe pointless now. But we expect * that it may later evolve to something like future/promise. - * + * * @author semancik * */ @@ -33,12 +33,12 @@ public T getReturnValue() { public void setReturnValue(T returnValue) { this.returnValue = returnValue; } - + public static AsynchronousOperationReturnValue wrap(T returnValue, OperationResult result) { AsynchronousOperationReturnValue ret = new AsynchronousOperationReturnValue<>(); ret.setOperationResult(result); ret.setReturnValue(returnValue); return ret; } - + } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/OperationConstants.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/OperationConstants.java index 32ae451a4e4..7eba0513736 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/OperationConstants.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/OperationConstants.java @@ -22,7 +22,7 @@ public class OperationConstants { public static final String PREFIX = "com.evolveum.midpoint.common.operation"; - + public static final String LIVE_SYNC = PREFIX + ".liveSync"; public static final String LIVE_SYNC_STATISTICS = PREFIX + ".liveSync.statistics"; public static final String RECONCILIATION = PREFIX + ".reconciliation"; @@ -31,9 +31,9 @@ public class OperationConstants { public static final String RECOMPUTE_USER = PREFIX + ".recompute.user"; public static final String RECOMPUTE_STATISTICS = PREFIX + ".recompute.statistics"; public static final String CLEANUP = PREFIX + ".cleanup"; - + public static final String EXECUTE = PREFIX + ".execute"; - + public static final String IMPORT_ACCOUNTS_FROM_RESOURCE = PREFIX + ".import.accountsFromResource"; public static final String IMPORT_ACCOUNTS_FROM_RESOURCE_STATISTICS = PREFIX + ".import.accountsFromResource.statistics"; public static final String IMPORT_OBJECTS_FROM_FILE = PREFIX + ".import.objectsFromFile"; @@ -43,7 +43,7 @@ public class OperationConstants { public static final String FOCUS_VALIDITY_SCAN = PREFIX + ".focusValidityScan"; public static final String TRIGGER_SCAN = PREFIX + ".triggerScan"; - + public static final String CREATE_REPORT_FILE = PREFIX + ".createReportFile"; public static final String CHECK_SHADOW_INTEGRITY = PREFIX + ".checkShadowIntegrity"; diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/OperationResult.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/OperationResult.java index ca2bf0ad57a..681c00b6721 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/OperationResult.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/OperationResult.java @@ -57,20 +57,20 @@ /** * Nested Operation Result. - * + * * This class provides information for better error handling in complex * operations. It contains a status (success, failure, warning, ...) and an * error message. It also contains a set of sub-results - results on inner * operations. - * + * * This object can be used by GUI to display smart (and interactive) error * information. It can also be used by the client code to detect deeper problems * in the invocations, retry or otherwise compensate for the errors or decide * how severe the error was and it is possible to proceed. - * + * * @author lazyman * @author Radovan Semancik - * + * */ public class OperationResult implements Serializable, DebugDumpable, Cloneable { @@ -95,7 +95,7 @@ public class OperationResult implements Serializable, DebugDumpable, Cloneable { public static final String CONTEXT_ITEM = "item"; public static final String CONTEXT_TASK = "task"; public static final String CONTEXT_RESOURCE = "resource"; - + public static final String PARAM_OID = "oid"; public static final String PARAM_NAME = "name"; public static final String PARAM_TYPE = "type"; @@ -105,21 +105,21 @@ public class OperationResult implements Serializable, DebugDumpable, Cloneable { public static final String PARAM_QUERY = "query"; public static final String PARAM_PROJECTION = "projection"; public static final String PARAM_LANGUAGE = "language"; - + public static final String RETURN_COUNT = "count"; public static final String RETURN_BACKGROUND_TASK_OID = "backgroundTaskOid"; private static long TOKEN_COUNT = 1000000000000000000L; private String operation; private OperationResultStatus status; - + // Values of the following maps should NOT be null. But in reality it does happen. // If there is a null value, it should be stored as a single-item collection, where the item is null. // But the collection should not be null. TODO; fix this private Map> params; private Map> context; private Map> returns; - + private long token; private String messageCode; private String message; @@ -134,7 +134,7 @@ public class OperationResult implements Serializable, DebugDumpable, Cloneable { private boolean summarizePartialErrors; private boolean summarizeSuccesses; private boolean minor = false; - + /** * Reference to an asynchronous operation that can be used to retrieve * the status of the running operation. This may be a task identifier, @@ -143,7 +143,7 @@ public class OperationResult implements Serializable, DebugDumpable, Cloneable { * executed. */ private String asynchronousOperationReference; - + private static final Trace LOGGER = TraceManager.getTrace(OperationResult.class); public OperationResult(String operation) { @@ -192,7 +192,7 @@ public OperationResult(String operation, Map> params, this(operation, params, status, token, messageCode, message, localizationMessage, null, cause, subresults); } - + public OperationResult(String operation, Map> params, OperationResultStatus status, long token, String messageCode, String message, String localizationMessage, List localizationArguments, Throwable cause, List subresults) { @@ -237,13 +237,13 @@ public OperationResult createSubresult(String operation) { addSubresult(subresult); return subresult; } - + public OperationResult createMinorSubresult(String operation) { OperationResult subresult = createSubresult(operation); subresult.minor = true; return subresult; } - + /** * Reference to an asynchronous operation that can be used to retrieve * the status of the running operation. This may be a task identifier, @@ -292,13 +292,13 @@ public String referenceToTaskOid(String ref) { * constant in module interface with description and possible parameters. It * can be used for further processing. It will be used as key for * translation in admin-gui. - * + * * @return always return non null, non empty string */ public String getOperation() { return operation; } - + public int getCount() { return count; } @@ -306,7 +306,7 @@ public int getCount() { public void setCount(int count) { this.count = count; } - + public void incrementCount() { this.count++; } @@ -346,7 +346,7 @@ public boolean isSummarizeSuccesses() { public void setSummarizeSuccesses(boolean summarizeSuccesses) { this.summarizeSuccesses = summarizeSuccesses; } - + public boolean isEmpty() { return (status == null || status == OperationResultStatus.UNKNOWN) && (subresults == null || subresults.isEmpty()); @@ -356,7 +356,7 @@ public boolean isEmpty() { /** * Method returns list of operation subresults @{link * {@link OperationResult}. - * + * * @return never returns null */ public List getSubresults() { @@ -394,7 +394,7 @@ public OperationResultStatus getLastSubresultStatus() { public void addSubresult(OperationResult subresult) { getSubresults().add(subresult); } - + public OperationResult findSubresult(String operation) { if (subresults == null) { return null; @@ -406,7 +406,7 @@ public OperationResult findSubresult(String operation) { } return null; } - + public List findSubresults(String operation) { List found = new ArrayList<>(); if (subresults == null) { @@ -422,7 +422,7 @@ public List findSubresults(String operation) { /** * Contains operation status as defined in {@link OperationResultStatus} - * + * * @return never returns null */ public OperationResultStatus getStatus() { @@ -435,10 +435,10 @@ public void setStatus(OperationResultStatus status) { /** * Returns true if the result is success. - * + * * This returns true if the result is absolute success. Presence of partial * failures or warnings fail this test. - * + * * @return true if the result is success. */ public boolean isSuccess() { @@ -451,11 +451,11 @@ public boolean isWarning() { /** * Returns true if the result is acceptable for further processing. - * + * * In other words: if there were no fatal errors. Warnings and partial * errors are acceptable. Yet, this test also fails if the operation state * is not known. - * + * * @return true if the result is acceptable for further processing. */ public boolean isAcceptable() { @@ -469,7 +469,7 @@ public boolean isUnknown() { public boolean isInProgress() { return (status == OperationResultStatus.IN_PROGRESS); } - + public boolean isError() { return (status == OperationResultStatus.FATAL_ERROR) || (status == OperationResultStatus.PARTIAL_ERROR); @@ -478,15 +478,15 @@ public boolean isError() { public boolean isFatalError() { return (status == OperationResultStatus.FATAL_ERROR); } - + public boolean isPartialError() { return (status == OperationResultStatus.PARTIAL_ERROR); } - + public boolean isHandledError() { return (status == OperationResultStatus.HANDLED_ERROR); } - + public boolean isNotApplicable() { return (status == OperationResultStatus.NOT_APPLICABLE); } @@ -507,7 +507,7 @@ public void setErrorsHandled() { /** * Computes operation result status based on subtask status and sets an * error message if the status is FATAL_ERROR. - * + * * @param errorMessage * error message */ @@ -522,7 +522,7 @@ public void computeStatus(String errorMessage, String warnMessage) { // therefore we need to check before calling computeStatus boolean noMessage = StringUtils.isEmpty(message); computeStatus(); - + switch (status) { case FATAL_ERROR: case PARTIAL_ERROR: @@ -607,7 +607,7 @@ public void computeStatus() { } } } - + if (allNotApplicable && !getSubresults().isEmpty()) { status = OperationResultStatus.NOT_APPLICABLE; } @@ -693,7 +693,7 @@ public void computeStatusComposite() { } } } - + if (allNotApplicable) { status = OperationResultStatus.NOT_APPLICABLE; } else if (allFatalError) { @@ -710,7 +710,7 @@ public void computeStatusComposite() { status = OperationResultStatus.SUCCESS; } } - + public OperationResultStatus getComputeStatus() { OperationResultStatus origStatus = status; String origMessage = message; @@ -734,7 +734,7 @@ public void recomputeStatus() { computeStatus(); } } - + public void recomputeStatus(String message) { // Only recompute if there are subresults, otherwise keep original // status @@ -756,13 +756,13 @@ public void recordSuccessIfUnknown() { recordSuccess(); } } - + public void recordNotApplicableIfUnknown() { if (isUnknown()) { status = OperationResultStatus.NOT_APPLICABLE; } } - + public boolean isMinor() { return minor; } @@ -777,11 +777,11 @@ public Map> getParams() { } return params; } - + public Collection getParam(String name) { return getParams().get(name); } - + public String getParamSingle(String name) { Collection values = getParams().get(name); if (values == null) { @@ -799,11 +799,11 @@ public String getParamSingle(String name) { public void addParam(String name, String value) { getParams().put(name, collectionize(value)); } - + public void addParam(String name, PrismObject value) { getParams().put(name, collectionize(stringify(value))); } - + public void addParam(String name, ObjectType value) { getParams().put(name, collectionize(stringify(value))); } @@ -811,15 +811,15 @@ public void addParam(String name, ObjectType value) { public void addParam(String name, boolean value) { getParams().put(name, collectionize(stringify(value))); } - + public void addParam(String name, long value) { getParams().put(name, collectionize(stringify(value))); } - + public void addParam(String name, int value) { getParams().put(name, collectionize(stringify(value))); } - + @SuppressWarnings("unchecked") public void addParam(String name, Class value) { if (ObjectType.class.isAssignableFrom(value)) { @@ -828,24 +828,24 @@ public void addParam(String name, Class value) { getParams().put(name, collectionize(stringify(value))); } } - + public void addParam(String name, QName value) { getParams().put(name, collectionize(value == null ? null : QNameUtil.qNameToUri(value))); } - + public void addParam(String name, PolyString value) { getParams().put(name, collectionize(value == null ? null : value.getOrig())); } - + public void addParam(String name, ObjectQuery value) { getParams().put(name, collectionize(stringify(value))); } - + public void addParam(String name, ObjectDelta value) { getParams().put(name, collectionize(stringify(value))); } - - + + public void addParam(String name, String... values) { getParams().put(name, collectionize(values)); } @@ -864,31 +864,31 @@ public Map> getContext() { } return context; } - + public void addContext(String name, String value) { getContext().put(name, collectionize(value)); } - + public void addContext(String name, PrismObject value) { getContext().put(name, collectionize(stringify(value))); } - + public void addContext(String name, ObjectType value) { getContext().put(name, collectionize(stringify(value))); } - + public void addContext(String name, boolean value) { getContext().put(name, collectionize(stringify(value))); } - + public void addContext(String name, long value) { getContext().put(name, collectionize(stringify(value))); } - + public void addContext(String name, int value) { getContext().put(name, collectionize(stringify(value))); } - + @SuppressWarnings("unchecked") public void addContext(String name, Class value) { if (ObjectType.class.isAssignableFrom(value)) { @@ -897,24 +897,24 @@ public void addContext(String name, Class value) { getContext().put(name, collectionize(stringify(value))); } } - + public void addContext(String name, QName value) { getContext().put(name, collectionize(value == null ? null : QNameUtil.qNameToUri(value))); } - + public void addContext(String name, PolyString value) { getContext().put(name, collectionize(value == null ? null : value.getOrig())); } - + public void addContext(String name, ObjectQuery value) { getContext().put(name, collectionize(stringify(value))); } - + public void addContext(String name, ObjectDelta value) { getContext().put(name, collectionize(stringify(value))); } - - + + public void addContext(String name, String... values) { getContext().put(name, collectionize(values)); } @@ -926,18 +926,18 @@ public void addArbitraryObjectAsContext(String name, Object value) { public void addArbitraryObjectCollectionAsContext(String paramName, Collection paramValue) { getContext().put(paramName, stringifyCol(paramValue)); } - + public Map> getReturns() { if (returns == null) { returns = new HashMap<>(); } return returns; } - + public Collection getReturn(String name) { return getReturns().get(name); } - + public String getReturnSingle(String name) { Collection values = getReturns().get(name); if (values == null) { @@ -955,27 +955,27 @@ public String getReturnSingle(String name) { public void addReturn(String name, String value) { getReturns().put(name, collectionize(value)); } - + public void addReturn(String name, PrismObject value) { getReturns().put(name, collectionize(stringify(value))); } - + public void addReturn(String name, ObjectType value) { getReturns().put(name, collectionize(stringify(value))); } - + public void addReturn(String name, boolean value) { getReturns().put(name, collectionize(stringify(value))); } - + public void addReturn(String name, long value) { getReturns().put(name, collectionize(stringify(value))); } - + public void addReturn(String name, int value) { getReturns().put(name, collectionize(stringify(value))); } - + @SuppressWarnings("unchecked") public void addReturn(String name, Class value) { if (ObjectType.class.isAssignableFrom(value)) { @@ -984,24 +984,24 @@ public void addReturn(String name, Class value) { getReturns().put(name, collectionize(stringify(value))); } } - + public void addReturn(String name, QName value) { getReturns().put(name, collectionize(value == null ? null : QNameUtil.qNameToUri(value))); } - + public void addReturn(String name, PolyString value) { getReturns().put(name, collectionize(value == null ? null : value.getOrig())); } - + public void addReturn(String name, ObjectQuery value) { getReturns().put(name, collectionize(stringify(value))); } - + public void addReturn(String name, ObjectDelta value) { getReturns().put(name, collectionize(stringify(value))); } - - + + public void addReturn(String name, String... values) { getReturns().put(name, collectionize(values)); } @@ -1012,8 +1012,8 @@ public void addArbitraryObjectAsReturn(String name, Object value) { public void addArbitraryObjectCollectionAsReturn(String paramName, Collection paramValue) { getReturns().put(paramName, stringifyCol(paramValue)); - } - + } + private String stringify(Object value) { if (value == null) { return null; @@ -1021,17 +1021,17 @@ private String stringify(Object value) { return value.toString(); } } - + private Collection collectionize(String value) { Collection out = new ArrayList<>(1); out.add(value); return out; } - + private Collection collectionize(String... values) { return Arrays.asList(values); } - + private Collection stringifyCol(Collection values) { if (values == null) { return null; @@ -1060,7 +1060,7 @@ public long getToken() { /** * Contains mesage code based on module error catalog. - * + * * @return Can return null. */ public String getMessageCode() { @@ -1117,7 +1117,7 @@ public void recordUnknown() { public void recordFatalError(Throwable cause) { recordStatus(OperationResultStatus.FATAL_ERROR, cause.getMessage(), cause); } - + /** * If the operation is an error then it will switch the status to EXPECTED_ERROR. * This is used if the error is expected and properly handled. @@ -1127,7 +1127,7 @@ public void muteError() { status = OperationResultStatus.HANDLED_ERROR; } } - + public void muteLastSubresultError() { OperationResult lastSubresult = getLastSubresult(); if (lastSubresult != null) { @@ -1169,15 +1169,15 @@ public void recordPartialError(String message, Throwable cause) { public void recordWarning(String message, Throwable cause) { recordStatus(OperationResultStatus.WARNING, message, cause); } - + public void recordHandledError(String message) { recordStatus(OperationResultStatus.HANDLED_ERROR, message); } - + public void recordHandledError(String message, Throwable cause) { recordStatus(OperationResultStatus.HANDLED_ERROR, message, cause); } - + public void recordHandledError(Throwable cause) { recordStatus(OperationResultStatus.HANDLED_ERROR, cause.getMessage(), cause); } @@ -1203,7 +1203,7 @@ public void recordWarning(String message) { /** * Records result from a common exception type. This automatically * determines status and also sets appropriate message. - * + * * @param exception * common exception */ @@ -1221,7 +1221,7 @@ public void recordStatus(OperationResultStatus status, String message) { /** * Returns true if result status is UNKNOWN or any of the subresult status * is unknown (recursive). - * + * * May come handy in tests to check if all the operations fill out the * status as they should. */ @@ -1267,7 +1267,7 @@ public static OperationResult createOperationResult(OperationResultType result) String localizedMessage = message == null ? null : message.getKey(); List localizedArguments = message == null ? null : (List) (List) message.getArgument(); // FIXME: brutal hack - OperationResult opResult = new OperationResult(result.getOperation(), params, context, returns, + OperationResult opResult = new OperationResult(result.getOperation(), params, context, returns, OperationResultStatus.parseStatusType(result.getStatus()), result.getToken(), result.getMessageCode(), result.getMessage(), localizedMessage, localizedArguments, null, subresults); @@ -1505,11 +1505,11 @@ private OperationResult findSimilarSubresult(OperationResult subresult) { public void cleanupResult() { cleanupResult(null); } - + /** * Removes all the successful minor results. Also checks if the result is roughly consistent * and complete. (e.g. does not have unknown operation status, etc.) - * + * * The argument "e" is for easier use of the cleanup in the exceptions handlers. The original exception is passed * to the IAE that this method produces for easier debugging. */ @@ -1552,7 +1552,7 @@ public String debugDump(int indent) { dumpIndent(sb, indent, true); return sb.toString(); } - + public String dump(boolean withStack) { StringBuilder sb = new StringBuilder(); dumpIndent(sb, 0, withStack); @@ -1597,7 +1597,7 @@ private void dumpIndent(StringBuilder sb, int indent, boolean printStackTrace) { sb.append(dumpEntry(indent+2, entry.getValue())); sb.append("\n"); } - + for (Map.Entry> entry : getReturns().entrySet()) { DebugUtil.indentDebugDump(sb, indent + 2); sb.append("[r]"); @@ -1613,7 +1613,7 @@ private void dumpIndent(StringBuilder sb, int indent, boolean printStackTrace) { sb.append(line); sb.append("\n"); } - + if (cause != null) { DebugUtil.indentDebugDump(sb, indent + 2); sb.append("[cause]"); @@ -1770,7 +1770,7 @@ public static int getSubresultStripThreshold() { public static void setSubresultStripThreshold(Integer value) { subresultStripThreshold = value != null ? value : DEFAULT_SUBRESULT_STRIP_THRESHOLD; } - + @Override public int hashCode() { final int prime = 31; diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/OperationResultFactory.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/OperationResultFactory.java index f2cc5efc199..45e94e41df0 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/OperationResultFactory.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/OperationResultFactory.java @@ -32,9 +32,9 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ParamsType; /** - * + * * @author lazyman - * + * */ public abstract class OperationResultFactory { diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/OperationResultRunner.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/OperationResultRunner.java index dd8c5af6c57..f239ba99748 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/OperationResultRunner.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/OperationResultRunner.java @@ -20,7 +20,7 @@ * */ public class OperationResultRunner { - + public static void run(OperationResult result, Runnable runnable) { try { runnable.run(); diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/OperationResultStatus.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/OperationResultStatus.java index 1f927df5132..15970343d36 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/OperationResultStatus.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/result/OperationResultStatus.java @@ -19,9 +19,9 @@ import org.jetbrains.annotations.NotNull; /** - * + * * @author lazyman - * + * */ public enum OperationResultStatus { @@ -33,7 +33,7 @@ public enum OperationResultStatus { UNKNOWN, /** - * Used when operation and sub operations finish successfully. + * Used when operation and sub operations finish successfully. * The operation is completed and the result is final. */ SUCCESS, @@ -58,7 +58,7 @@ public enum OperationResultStatus { * The operation is completed and the result is final. */ FATAL_ERROR, - + /** * The operation didn't finish correctly but that was expected and handled. It is * equivalent to success for all practical cases except for displaying the result. But using @@ -66,7 +66,7 @@ public enum OperationResultStatus { * The operation is completed and the result is final. */ HANDLED_ERROR, - + /** * Result does not make any sense for the operation. This is useful in cases that the * operation is not supported (e.g. an optional part of the interface). @@ -75,7 +75,7 @@ public enum OperationResultStatus { * The operation is completed and the result is final. */ NOT_APPLICABLE, - + /** * The operation is being executed. This is set for operations that are executed * asynchronously or take a significant amount of time. Short synchronous operations diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/statistics/ActionsExecutedInformation.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/statistics/ActionsExecutedInformation.java index 3282056cd10..90db3763cb0 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/statistics/ActionsExecutedInformation.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/statistics/ActionsExecutedInformation.java @@ -106,7 +106,7 @@ public static void addTo(List sumEntries, List iterator = objectDetailsSet.getObjectDetailsPage().iterator(); while (iterator.hasNext()) { @@ -144,7 +144,7 @@ private static void joinObjectDetails(GuiObjectDetailsSetType objectDetailsSet, } objectDetailsSet.getObjectDetailsPage().add(newObjectDetails.clone()); } - + private static boolean isTheSameObjectType(AbstractObjectTypeConfigurationType oldConf, AbstractObjectTypeConfigurationType newConf) { return QNameUtil.match(oldConf.getType(), newConf.getType()); } @@ -193,7 +193,7 @@ private static void mergeList(GuiObjectListsType objectLists, GuiObjectListType } objectLists.getObjectList().add(newList.clone()); } - + private static void mergeWidget(DashboardLayoutType compositeDashboard, DashboardWidgetType newWidget) { String newWidgetIdentifier = newWidget.getIdentifier(); DashboardWidgetType compositeWidget = findWidget(compositeDashboard, newWidgetIdentifier); @@ -203,7 +203,7 @@ private static void mergeWidget(DashboardLayoutType compositeDashboard, Dashboar mergeWidget(compositeWidget, newWidget); } } - + public static DashboardWidgetType findWidget(DashboardLayoutType dashboard, String widgetIdentifier) { return findFeature(dashboard.getWidget(), widgetIdentifier); } @@ -212,7 +212,7 @@ private static void mergeWidget(DashboardWidgetType compositeWidget, DashboardWi mergeFeature(compositeWidget, newWidget, UserInterfaceElementVisibilityType.VACANT); // merge other widget properties (in the future) } - + private static void mergeFeature(List compositeFeatures, UserInterfaceFeatureType newFeature) { String newIdentifier = newFeature.getIdentifier(); UserInterfaceFeatureType compositeFeature = findFeature(compositeFeatures, newIdentifier); @@ -222,12 +222,12 @@ private static void mergeFeature(List compositeFeature mergeFeature(compositeFeature, newFeature, UserInterfaceElementVisibilityType.AUTOMATIC); } } - + private static void mergeFeature(T compositeFeature, T newFeature, UserInterfaceElementVisibilityType defaultVisibility) { UserInterfaceElementVisibilityType newCompositeVisibility = mergeVisibility(compositeFeature.getVisibility(), newFeature.getVisibility(), defaultVisibility); compositeFeature.setVisibility(newCompositeVisibility); } - + public static T findFeature(List features, String identifier) { for (T feature: features) { if (feature.getIdentifier().equals(identifier)) { @@ -236,7 +236,7 @@ public static T findFeature(List feature } return null; } - + public static UserInterfaceElementVisibilityType getFeatureVisibility(AdminGuiConfigurationType adminGuiConfig, String identifier) { UserInterfaceFeatureType feature = findFeature(adminGuiConfig.getFeature(), identifier); if (feature == null) { @@ -248,16 +248,16 @@ public static UserInterfaceElementVisibilityType getFeatureVisibility(AdminGuiCo } return visibility; } - + public static boolean isFeatureVisible(AdminGuiConfigurationType adminGuiConfig, String identifier) { return isFeatureVisible(adminGuiConfig, identifier, null); } - + public static boolean isFeatureVisible(AdminGuiConfigurationType adminGuiConfig, String identifier, BooleanSupplier automaticPredicate) { UserInterfaceElementVisibilityType visibility = getFeatureVisibility(adminGuiConfig, identifier); return isVisible(visibility, automaticPredicate); } - + public static boolean isVisible(UserInterfaceElementVisibilityType visibility, BooleanSupplier automaticPredicate) { if (visibility == UserInterfaceElementVisibilityType.HIDDEN) { return false; diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ConnectorTypeUtil.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ConnectorTypeUtil.java index 1cb2f764156..9a67c5428dc 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ConnectorTypeUtil.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ConnectorTypeUtil.java @@ -35,7 +35,7 @@ * */ public class ConnectorTypeUtil { - + public static String getConnectorHostTypeOid(ConnectorType connectorType) { if (connectorType.getConnectorHostRef() != null) { return connectorType.getConnectorHostRef().getOid(); @@ -45,7 +45,7 @@ public static String getConnectorHostTypeOid(ConnectorType connectorType) { return null; } } - + public static Element getConnectorXsdSchema(ConnectorType connector) { XmlSchemaType xmlSchemaType = connector.getSchema(); if (xmlSchemaType == null) { @@ -53,7 +53,7 @@ public static Element getConnectorXsdSchema(ConnectorType connector) { } return ObjectTypeUtil.findXsdElement(xmlSchemaType); } - + public static Element getConnectorXsdSchema(PrismObject connector) { PrismContainer xmlSchema = connector.findContainer(ConnectorType.F_SCHEMA); if (xmlSchema == null) { @@ -61,12 +61,12 @@ public static Element getConnectorXsdSchema(PrismObject connector } return ObjectTypeUtil.findXsdElement(xmlSchema); } - + public static void setConnectorXsdSchema(ConnectorType connectorType, Element xsdElement) { PrismObject connector = connectorType.asPrismObject(); setConnectorXsdSchema(connector, xsdElement); } - + public static void setConnectorXsdSchema(PrismObject connector, Element xsdElement) { PrismContainer schemaContainer; try { @@ -77,7 +77,7 @@ public static void setConnectorXsdSchema(PrismObject connector, E // Should not happen throw new IllegalStateException("Internal schema error: "+e.getMessage(),e); } - + } /** @@ -96,10 +96,10 @@ public static PrismSchema parseConnectorSchema(ConnectorType connectorType, Pris ((PrismContainerDefinitionImpl) configurationContainerDefintion).setCompileTimeClass(ConnectorConfigurationType.class); return connectorSchema; } - + public static PrismContainerDefinition findConfigurationContainerDefinition(ConnectorType connectorType, PrismSchema connectorSchema) { QName configContainerQName = new QName(connectorType.getNamespace(), ResourceType.F_CONNECTOR_CONFIGURATION.getLocalPart()); return connectorSchema.findContainerDefinitionByElementName(configContainerQName); } - + } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ExceptionUtil.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ExceptionUtil.java index f2fe032872e..97707df116b 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ExceptionUtil.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ExceptionUtil.java @@ -31,7 +31,7 @@ * */ public class ExceptionUtil { - + public static Throwable lookForTunneledException(Throwable ex) { if (ex instanceof TunnelException) { return ex.getCause(); @@ -51,7 +51,7 @@ public static String lookForMessage(Throwable e) { } return null; } - + public static boolean isSelected(ErrorSelectorType selector, Throwable exception, boolean defaultValue) { if (selector == null) { return defaultValue; @@ -81,7 +81,7 @@ private static boolean isSelected(Boolean value, boolean defaultValue) { return value; } } - + public static LocalizableMessage getUserFriendlyMessage(Throwable cause) { while (cause != null) { if (cause instanceof CommonException) { @@ -94,5 +94,5 @@ public static LocalizableMessage getUserFriendlyMessage(Throwable cause) { } return null; } - + } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/FocusTypeUtil.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/FocusTypeUtil.java index d9fb404cb0e..4e75b8daf2d 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/FocusTypeUtil.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/FocusTypeUtil.java @@ -42,7 +42,7 @@ * */ public class FocusTypeUtil { - + public static AssignmentType createRoleAssignment(String roleOid) { return createTargetAssignment(roleOid, RoleType.COMPLEX_TYPE); } @@ -50,7 +50,7 @@ public static AssignmentType createRoleAssignment(String roleOid) { public static AssignmentType createOrgAssignment(String roleOid) { return createTargetAssignment(roleOid, OrgType.COMPLEX_TYPE); } - + public static AssignmentType createTargetAssignment(String targetOid, QName type) { AssignmentType assignmentType = new AssignmentType(); ObjectReferenceType targetRef = new ObjectReferenceType(); @@ -59,8 +59,8 @@ public static AssignmentType createTargetAssignment(String targetOid, QName type assignmentType.setTargetRef(targetRef); return assignmentType; } - - public static String dumpAssignment(AssignmentType assignmentType) { + + public static String dumpAssignment(AssignmentType assignmentType) { StringBuilder sb = new StringBuilder(); if (assignmentType.getConstruction() != null) { sb.append("Constr(").append(assignmentType.getConstruction().getDescription()).append(") "); @@ -74,7 +74,7 @@ public static String dumpAssignment(AssignmentType assignmentType) { } return sb.toString(); } - + public static String dumpInducementConstraints(AssignmentType assignmentType) { if (assignmentType.getOrder() != null) { return assignmentType.getOrder().toString(); @@ -102,7 +102,7 @@ public static String dumpInducementConstraints(AssignmentType assignmentType) { sb.setLength(sb.length() - 1); return sb.toString(); } - + public static boolean selectorMatches(AssignmentSelectorType assignmentSelector, AssignmentType assignmentType) { if (assignmentType.getTargetRef() == null) { return false; @@ -114,7 +114,7 @@ public static boolean selectorMatches(AssignmentSelectorType assignmentSelector, } return false; } - + public static String determineConstructionResource(AssignmentType assignmentType) { ConstructionType construction = assignmentType.getConstruction(); if (construction != null){ @@ -122,37 +122,37 @@ public static String determineConstructionResource(AssignmentType assignmentType return construction.getResource().getOid(); } else if (construction.getResourceRef() != null){ return construction.getResourceRef().getOid(); - } - + } + return null; } - + return null; } - + public static String determineConstructionIntent(AssignmentType assignmentType) { ConstructionType construction = assignmentType.getConstruction(); if (construction != null){ if (construction.getIntent() != null){ return construction.getIntent(); - } - + } + return SchemaConstants.INTENT_DEFAULT; } - + throw new IllegalArgumentException("Construction not defined in the assigment."); } - + public static ShadowKindType determineConstructionKind(AssignmentType assignmentType) { ConstructionType construction = assignmentType.getConstruction(); if (construction != null){ if (construction.getKind() != null){ return construction.getKind(); - } - + } + return ShadowKindType.ACCOUNT; } - + throw new IllegalArgumentException("Construction not defined in the assigment."); } @@ -170,14 +170,14 @@ public static ProtectedStringType getPasswordValue(UserType user) { } return passwd.getValue(); } - + public static List determineSubTypes(PrismObject object) { if (object == null) { return null; } - + // TODO: get subType (from ObjectType) - + if (object.canRepresent(UserType.class)) { return (((UserType)object.asObjectable()).getEmployeeType()); } @@ -204,9 +204,9 @@ public static boolean hasSubtype(PrismObject object, S } public static void setSubtype(PrismObject object, List subtypes) { - + // TODO: set subType (from ObjectType) - + List objSubtypes = null; if (object.canRepresent(UserType.class)) { objSubtypes = (((UserType)object.asObjectable()).getEmployeeType()); diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/FormTypeUtil.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/FormTypeUtil.java index 9d4473fedff..caca52be0b4 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/FormTypeUtil.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/FormTypeUtil.java @@ -25,7 +25,7 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.FormItemsType; public class FormTypeUtil { - + public static List getFormItems(FormItemsType formItemsProperty) { List items = new ArrayList<>(); if (formItemsProperty != null) { diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/MiscSchemaUtil.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/MiscSchemaUtil.java index 03521cca010..2a36178be70 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/MiscSchemaUtil.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/MiscSchemaUtil.java @@ -57,10 +57,10 @@ * */ public class MiscSchemaUtil { - + private static final Trace LOGGER = TraceManager.getTrace(MiscSchemaUtil.class); private static final Random RND = new Random(); - + public static ObjectListType toObjectListType(List> list) { ObjectListType listType = new ObjectListType(); for (PrismObject o : list) { @@ -68,7 +68,7 @@ public static ObjectListType toObjectListType(List List> toList(Class type, ObjectListType listType) { List> list = new ArrayList<>(); for (ObjectType o : listType.getObject()) { @@ -76,7 +76,7 @@ public static List> toList(Class type, } return list; } - + public static List toObjectableList(List> objectList) { if (objectList == null) { return null; @@ -87,7 +87,7 @@ public static List toObjectableList(List itemReferenceListTypeToItemPathList(PropertyR } return itemPathList; } - + public static SelectorQualifiedGetOptionsType optionsToOptionsType(Collection> options){ SelectorQualifiedGetOptionsType optionsType = new SelectorQualifiedGetOptionsType(); List retval = new ArrayList<>(); @@ -148,7 +148,7 @@ public static SelectorQualifiedGetOptionsType optionsToOptionsType(Collection selectorOption){ OptionObjectSelectorType selectorType = selectorToSelectorType(selectorOption.getSelector()); GetOperationOptionsType getOptionsType = getOptionsToGetOptionsType(selectorOption.getOptions()); @@ -166,7 +166,7 @@ private static OptionObjectSelectorType selectorToSelectorType(ObjectSelector se selectorType.setPath(new ItemPathType(selector.getPath())); return selectorType; } - + private static GetOperationOptionsType getOptionsToGetOptionsType(GetOperationOptions options) { GetOperationOptionsType optionsType = new GetOperationOptionsType(); optionsType.setRetrieve(RetrieveOption.toRetrieveOptionType(options.getRetrieve())); @@ -224,7 +224,7 @@ private static ObjectSelector selectorTypeToSelector(OptionObjectSelectorType se } return new ObjectSelector(selectorType.getPath().getItemPath()); } - + /** * Convenience method that helps avoid some compiler warnings. */ @@ -232,7 +232,7 @@ private static ObjectSelector selectorTypeToSelector(OptionObjectSelectorType se public static Collection> createCollection(ObjectDelta... deltas) { return (Collection)MiscUtil.createCollection(deltas); } - + /** * Convenience method that helps avoid some compiler warnings. */ @@ -240,7 +240,7 @@ public static Collection> createCollection(Obj public static Collection> createCollection(ItemDelta... deltas) { return (Collection)MiscUtil.createCollection(deltas); } - + public static Collection> cloneObjectDeltaCollection( Collection> origCollection) { if (origCollection == null) { @@ -252,7 +252,7 @@ public static Collection> cloneObjectDeltaColl } return clonedCollection; } - + public static Collection> cloneObjectDeltaOperationCollection( Collection> origCollection) { if (origCollection == null) { @@ -271,7 +271,7 @@ public static ObjectReferenceType createObjectReference(String oid, QName type) ref.setType(type); return ref; } - + public static boolean equalsIntent(String intent1, String intent2) { if (intent1 == null) { intent1 = SchemaConstants.INTENT_DEFAULT; @@ -281,7 +281,7 @@ public static boolean equalsIntent(String intent1, String intent2) { } return intent1.equals(intent2); } - + public static boolean matchesKind(ShadowKindType expectedKind, ShadowKindType actualKind) { if (expectedKind == null) { return true; @@ -319,7 +319,7 @@ public static PrismReferenceValue objectReferenceTypeToReferenceValue(ObjectRefe rval.setTargetType(refType.getType()); return rval; } - + public static PropertyLimitationsType getLimitationsType(List limitationsTypes, LayerType layer) throws SchemaException { if (limitationsTypes == null) { return null; @@ -336,7 +336,7 @@ public static PropertyLimitationsType getLimitationsType(List layers, LayerType layer) { if (layers == null || layers.isEmpty()) { if (layer == null) { @@ -366,7 +366,7 @@ public static void reduceSearchResult(List } /** - * Returns modification time or creation time (if there was no mo + * Returns modification time or creation time (if there was no mo */ public static XMLGregorianCalendar getChangeTimestamp(MetadataType metadata) { if (metadata == null) { @@ -407,7 +407,7 @@ public static boolean referenceMatches(ObjectReferenceType refPattern, ObjectRef } return true; } - + /** * Make quick and reasonably reliable comparison. E.g. compare prism objects only by * comparing OIDs. This is ideal for cases when the compare is called often and the diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ObjectResolver.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ObjectResolver.java index 310007d6f12..e2ab5eb0f0f 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ObjectResolver.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ObjectResolver.java @@ -38,20 +38,20 @@ /** * The callback from some of the object utilities to resolve objects. - * + * * The classes implementing this will most likely fetch the objects from the * repository or from some kind of object cache. - * + * * @author Radovan Semancik */ public interface ObjectResolver { - + /** * Resolve the provided reference to object (ObjectType). - * + * * Note: The reference is used instead of just OID because the reference * also contains object type. This speeds up the repository operations. - * + * * @param ref object reference to resolve * @param contextDescription short description of the context of resolution, e.g. "executing expression FOO". Used in error messages. * @param task @@ -68,7 +68,7 @@ public interface ObjectResolver { T resolve(ObjectReferenceType ref, Class expectedType, Collection> options, String contextDescription, Object task, OperationResult result) throws ObjectNotFoundException, SchemaException; - + void searchIterative(Class type, ObjectQuery query, Collection> options, ResultHandler handler, Object task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException; diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ObjectTypeUtil.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ObjectTypeUtil.java index c7101adf1ee..cc53e948ced 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ObjectTypeUtil.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ObjectTypeUtil.java @@ -59,7 +59,7 @@ * @author Radovan Semancik */ public class ObjectTypeUtil { - + /** * Never returns null. Returns empty collection instead. */ @@ -71,7 +71,7 @@ public static Collection getExtensionPropertyValuesNotNull(ObjectType obj return values; } } - + public static Collection getExtensionPropertyValues(ObjectType objectType, QName propertyQname) { PrismObject object = objectType.asPrismObject(); PrismContainer extensionContainer = object.findContainer(ObjectType.F_EXTENSION); @@ -84,7 +84,7 @@ public static Collection getExtensionPropertyValues(ObjectType objectType } return property.getRealValues(); } - + public static Collection getExtensionReferenceValues(ObjectType objectType, QName propertyQname) { PrismObject object = objectType.asPrismObject(); PrismContainer extensionContainer = object.findContainer(ObjectType.F_EXTENSION); @@ -101,7 +101,7 @@ public static Collection getExtensionReferenceValues(ObjectType ob } return refs; } - + public static ObjectReferenceType findRef(String oid, List refs) { for (ObjectReferenceType ref : refs) { @@ -180,7 +180,7 @@ public static Object toShortString(ObjectReferenceType objectRef, boolean withNa public static String getShortTypeName(ObjectType object) { return getShortTypeName(object.getClass()); } - + public static String getShortTypeName(Class type) { ObjectTypes objectTypeType = ObjectTypes.getObjectType(type); if (objectTypeType != null) { @@ -219,7 +219,7 @@ public static AssignmentType createAssignmentTo(@NotNull public static AssignmentType createAssignmentTo(@NotNull PrismObject object) { return createAssignmentTo(object, SchemaConstants.ORG_DEFAULT); } - + @NotNull public static AssignmentType createAssignmentTo(@NotNull PrismObject object, QName relation) { AssignmentType assignment = new AssignmentType(object.getPrismContext()); @@ -232,7 +232,7 @@ public static AssignmentType createAssignmentTo(@NotNull } return assignment; } - + @NotNull public static AssignmentType createAssignmentTo(@NotNull T objectType, QName relation) { return createAssignmentTo((PrismObject) objectType.asPrismObject(), relation); @@ -254,7 +254,7 @@ public static ObjectReferenceType createObjectRefWithFullObject(ObjectType objec public static ObjectReferenceType createObjectRef(ObjectType objectType) { return createObjectRef(objectType, SchemaConstants.ORG_DEFAULT); } - + public static ObjectReferenceType createObjectRef(ObjectType objectType, QName relation) { if (objectType == null) { return null; @@ -265,7 +265,7 @@ public static ObjectReferenceType createObjectRef(ObjectType objectType, QName r public static ObjectReferenceType createObjectRef(PrismObject object) { return createObjectRef(object, SchemaConstants.ORG_DEFAULT); } - + public static ObjectReferenceType createObjectRef(PrismObject object, QName relation) { if (object == null) { return null; @@ -280,7 +280,7 @@ public static ObjectReferenceType createObjectRef(PrismOb ref.setRelation(relation); return ref; } - + public static ObjectReferenceType createObjectRefWithFullObject(PrismObject object) { if (object == null) { return null; @@ -306,7 +306,7 @@ public static ObjectReferenceType createObjectRef(PrismOb } return ref; } - + public static ObjectReferenceType createObjectRef(PrismReferenceValue refVal, boolean nameAsDescription) { if (refVal == null) { return null; @@ -332,11 +332,11 @@ public static ObjectReferenceType createObjectRef(PrismRe } return ref; } - + public static ObjectReferenceType createObjectRef(String oid, ObjectTypes type) { return createObjectRef(oid, null, type); } - + public static ObjectReferenceType createObjectRef(String oid, PolyStringType name, ObjectTypes type) { Validate.notEmpty(oid, "Oid must not be null or empty."); Validate.notNull(type, "Object type must not be null."); @@ -360,11 +360,11 @@ public static Element findXsdElement(XmlSchemaType xmlSchemaType) { PrismContainerValue xmlSchemaContainerValue = xmlSchemaType.asPrismContainerValue(); return findXsdElement(xmlSchemaContainerValue); } - + public static Element findXsdElement(PrismContainer xmlSchemaContainer) { return findXsdElement(xmlSchemaContainer.getValue()); } - + public static Element findXsdElement(PrismContainerValue xmlSchemaContainerValue) { PrismProperty definitionProperty = xmlSchemaContainerValue.findProperty(XmlSchemaType.F_DEFINITION); if (definitionProperty == null) { @@ -374,9 +374,9 @@ public static Element findXsdElement(PrismContainerValue xmlSchem if (schemaDefinition == null) { return null; } - + return schemaDefinition.getSchema(); - + // List schemaElements = DOMUtil.listChildElements(definitionElement); // for (Element e : schemaElements) { // if (QNameUtil.compareQName(DOMUtil.XSD_SCHEMA_ELEMENT, e)) { @@ -386,9 +386,9 @@ public static Element findXsdElement(PrismContainerValue xmlSchem // } // return null; } - + public static void setXsdSchemaDefinition(PrismProperty definitionProperty, Element xsdElement) { - + // Document document = xsdElement.getOwnerDocument(); // Element definitionElement = document.createElementNS(XmlSchemaType.F_DEFINITION.getNamespaceURI(), // XmlSchemaType.F_DEFINITION.getLocalPart()); @@ -418,7 +418,7 @@ public static boolean isModificationOf(ItemDeltaType modification, QName element // if (path == null && XPathHolder.isDefault(modification.getPath())) { // return (elementName.equals(ObjectTypeUtil.getElementName(modification))); // } - + ItemPathType modificationPath = modification.getPath(); if (ItemPathUtil.isDefault(modificationPath)){ throw new IllegalArgumentException("Path in the delta must not be null"); @@ -426,7 +426,7 @@ public static boolean isModificationOf(ItemDeltaType modification, QName element // if (path == null && ItemPathUtil.isDefault(modificationPath)) { // return (elementName.equals(getElementName(modification))); // } - + if (path == null) { return false; } @@ -454,7 +454,7 @@ public static boolean isModificationOf(ItemDeltaType modification, QName element // return (objectModification.getItemDelta() == null) || // objectModification.getItemDelta().isEmpty(); // } - + public static void assertConcreteType(Class type) { // The abstract object types are enumerated here. It should be switched to some flag later on if (type.equals(ObjectType.class)) { @@ -672,12 +672,12 @@ public static boolean isManagerRelation(QName relation) { public static boolean isDefaultRelation(QName relation) { return relation == null || QNameUtil.match(relation, SchemaConstants.ORG_DEFAULT); } - + // We want to make this configurable in the future MID-3581 public static boolean processRelationOnLogin(QName relation) { return isMembershipRelation(relation) || isDelegationRelation(relation); } - + // We want to make this configurable in the future MID-3581 public static boolean processRelationOnRecompute(QName relation) { return !QNameUtil.match(relation, SchemaConstants.ORG_APPROVER) && !QNameUtil.match(relation, SchemaConstants.ORG_OWNER); @@ -694,7 +694,7 @@ public static boolean relationsEquivalent(QName relation1, QName relation2) { return QNameUtil.match(relation1, relation2); } } - + public static boolean referenceMatches(ObjectReferenceType ref, String targetOid, QName targetType, QName relation) { if (ref == null) { return false; diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/OidUtil.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/OidUtil.java index 743c5b6942b..35b51173c60 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/OidUtil.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/OidUtil.java @@ -22,7 +22,7 @@ * */ public class OidUtil { - + public static String generateOid() { return UUID.randomUUID().toString(); } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ParamsTypeUtil.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ParamsTypeUtil.java index 2d5ac829d54..a6aca697f91 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ParamsTypeUtil.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ParamsTypeUtil.java @@ -40,7 +40,7 @@ public static ParamsType toParamsType(Map> paramsMap) Set>> params = paramsMap.entrySet(); if (!params.isEmpty()) { ParamsType paramsType = new ParamsType(); - + for (Entry> entry : params) { if (entry.getValue() == null) { paramsType.getEntry().add(createEntryElement(entry.getKey(), null)); @@ -70,7 +70,7 @@ public static Map fromParamsType(ParamsType paramsType, Pr Serializable realValue = null; for (EntryType entry : paramsType.getEntry()) { if (entry.getEntryValue() != null){ - + Serializable value = (Serializable) entry.getEntryValue().getValue(); if (value instanceof RawType){ XNode xnode = ((RawType) value).getXnode(); @@ -83,12 +83,12 @@ public static Map fromParamsType(ParamsType paramsType, Pr } params.put(entry.getKey(), (Serializable) (realValue)); } - + return params; } return null; } - + public static Map> fromParamsType(ParamsType paramsType) throws SchemaException { if (paramsType != null) { Map> params = new HashMap<>(); @@ -119,5 +119,5 @@ private static String extractString(JAXBElement jaxbElement) throws SchemaExc } return value.toString(); } - + } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ReportTypeUtil.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ReportTypeUtil.java index 6c10852d208..1cc2b04a67a 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ReportTypeUtil.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ReportTypeUtil.java @@ -52,14 +52,14 @@ * @author lazyman */ public class ReportTypeUtil { - + private static String PARAMETER_TEMPLATE_STYLES = "baseTemplateStyles"; - + public static JasperDesign loadJasperDesign(byte[] template) throws SchemaException{ try { byte[] reportTemplate = Base64.decodeBase64(template); - + InputStream inputStreamJRXML = new ByteArrayInputStream(reportTemplate); JasperDesign jasperDesign = JRXmlLoader.load(inputStreamJRXML); // LOGGER.trace("load jasper design : {}", jasperDesign); @@ -68,20 +68,20 @@ public static JasperDesign loadJasperDesign(byte[] template) throws SchemaExcept throw new SchemaException(ex.getMessage(), ex.getCause()); } } - - + + public static JasperReport loadJasperReport(ReportType reportType) throws SchemaException{ - + if (reportType.getTemplate() == null) { throw new IllegalStateException("Could not create report. No jasper template defined."); } try { // byte[] reportTemplate = Base64.decodeBase64(reportType.getTemplate()); -// +// // InputStream inputStreamJRXML = new ByteArrayInputStream(reportTemplate); JasperDesign jasperDesign = loadJasperDesign(reportType.getTemplate());//JRXmlLoader.load(inputStreamJRXML); // LOGGER.trace("load jasper design : {}", jasperDesign); - + if (reportType.getTemplateStyle() != null){ JRDesignReportTemplate templateStyle = new JRDesignReportTemplate(new JRDesignExpression("$P{" + PARAMETER_TEMPLATE_STYLES + "}")); jasperDesign.addTemplate(templateStyle); @@ -90,8 +90,8 @@ public static JasperReport loadJasperReport(ReportType reportType) throws Schema parameter.setValueClass(JRTemplate.class); parameter.setForPrompting(false); jasperDesign.addParameter(parameter); - } - + } + // if (StringUtils.isNotEmpty(finalQuery)){ JRDesignParameter parameter = new JRDesignParameter(); parameter.setName("finalQuery"); @@ -101,14 +101,14 @@ public static JasperReport loadJasperReport(ReportType reportType) throws Schema // } JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign); return jasperReport; - } catch (JRException ex){ + } catch (JRException ex){ // LOGGER.error("Couldn't create jasper report design {}", ex.getMessage()); throw new SchemaException(ex.getMessage(), ex.getCause()); } - - + + } - + public static PrismSchema parseReportConfigurationSchema(PrismObject report, PrismContext context) throws SchemaException { @@ -156,7 +156,7 @@ public static void applyDefinition(PrismObject report, PrismContext configuration.applyDefinition(definition, true); } - + public static void applyConfigurationDefinition(PrismObject report, ObjectDelta delta, PrismContext prismContext) throws SchemaException { @@ -176,9 +176,9 @@ public static void applyConfigurationDefinition(PrismObject report, itemDelta.applyDefinition(def); } } - - - + + + } } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ResourceTypeUtil.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ResourceTypeUtil.java index 3ccdffd0caf..621f0db50e0 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ResourceTypeUtil.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ResourceTypeUtil.java @@ -66,7 +66,7 @@ /** * Methods that would belong to the ResourceType class but cannot go there * because of JAXB. - * + * * @author Radovan Semancik */ public class ResourceTypeUtil { @@ -74,7 +74,7 @@ public class ResourceTypeUtil { public static String getConnectorOid(PrismObject resource) { return getConnectorOid(resource.asObjectable()); } - + public static String getConnectorOid(ResourceType resource) { if (resource.getConnectorRef() != null) { return resource.getConnectorRef().getOid(); @@ -84,11 +84,11 @@ public static String getConnectorOid(ResourceType resource) { return null; } } - + /** * The usage of "resolver" is experimental. Let's see if it will be * practical ... - * + * * @see ObjectResolver */ public static ConnectorType getConnectorType(ResourceType resource, ObjectResolver resolver, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { @@ -118,7 +118,7 @@ public static Element getResourceXsdSchema(ResourceType resource) { } return ObjectTypeUtil.findXsdElement(xmlSchemaType); } - + public static Element getResourceXsdSchema(PrismObject resource) { PrismContainer xmlSchema = resource.findContainer(ResourceType.F_SCHEMA); if (xmlSchema == null) { @@ -126,12 +126,12 @@ public static Element getResourceXsdSchema(PrismObject resource) { } return ObjectTypeUtil.findXsdElement(xmlSchema); } - + public static void setResourceXsdSchema(ResourceType resourceType, Element xsdElement) { PrismObject resource = resourceType.asPrismObject(); setResourceXsdSchema(resource, xsdElement); } - + public static void setResourceXsdSchema(PrismObject resource, Element xsdElement) { try { PrismContainer schemaContainer = resource.findOrCreateContainer(ResourceType.F_SCHEMA); @@ -141,7 +141,7 @@ public static void setResourceXsdSchema(PrismObject resource, Elem // Should not happen throw new IllegalStateException("Internal schema error: "+e.getMessage(),e); } - + } /** @@ -160,31 +160,31 @@ public static Collection getNativeCapabilitiesCollection(ResourceType re } return nativeCap.getAny(); } - + public static boolean hasSchemaGenerationConstraints(ResourceType resource){ if (resource == null){ return false; } - + if (resource.getSchema() == null){ return false; } - + if (resource.getSchema().getGenerationConstraints() == null){ return false; } - + List constainst = resource.getSchema().getGenerationConstraints().getGenerateObjectClass(); - + if (constainst == null){ return false; } - + return !constainst.isEmpty(); } - + public static List getSchemaGenerationConstraints(ResourceType resource){ - + if (hasSchemaGenerationConstraints(resource)){ return resource.getSchema().getGenerationConstraints().getGenerateObjectClass(); } @@ -199,7 +199,7 @@ public static List getSchemaGenerationConstraints(PrismObject T getEffectiveCapability(ResourceType resource, Class capabilityClass) { @@ -238,10 +238,10 @@ private static T getEffectiveCapabilityInternal(Resou return connectorCapability; } } - + return CapabilityUtil.getEffectiveCapability(resource.getCapabilities(), capabilityClass); } - + public static boolean hasEffectiveCapability(ResourceType resource, Class capabilityClass) { return getEffectiveCapability(resource, capabilityClass) != null; } @@ -254,7 +254,7 @@ public static List getAllCapabilities(ResourceType resource) throws Sche } /** - * Assumes that native capabilities are already cached. + * Assumes that native capabilities are already cached. */ public static List getEffectiveCapabilities(ResourceType resource) throws SchemaException { return getEffectiveCapabilities(resource, false); @@ -285,7 +285,7 @@ private static List getEffectiveCapabilities(ResourceType resource, bool public static boolean isActivationCapabilityEnabled(ResourceType resource) { return getEffectiveCapability(resource, ActivationCapabilityType.class) != null; } - + public static boolean isActivationLockoutStatusCapabilityEnabled(ResourceType resource) { return getEffectiveActivationLockoutStatusCapability(resource) != null; } @@ -333,19 +333,19 @@ public static ActivationValidityCapabilityType getEffectiveActivationValidToCapa public static boolean isActivationValidityCapabilityEnabled(ResourceType resource) { return getEffectiveActivationValidFromCapability(resource) != null || getEffectiveActivationValidToCapability(resource) != null; } - + public static boolean isCredentialsCapabilityEnabled(ResourceType resource) { return getEffectiveCapability(resource, CredentialsCapabilityType.class) != null; } - + public static boolean isCreateCapabilityEnabled(ResourceType resource){ return getEffectiveCapability(resource, CreateCapabilityType.class) != null; } - + public static boolean isCountObjectsCapabilityEnabled(ResourceType resource){ return getEffectiveCapability(resource, CountObjectsCapabilityType.class) != null; } - + public static boolean isPasswordCapabilityEnabled(ResourceType resource){ return getEffectivePasswordCapability(resource) != null; } @@ -362,39 +362,39 @@ public static PasswordCapabilityType getEffectivePasswordCapability(ResourceType public static boolean isLiveSyncCapabilityEnabled(ResourceType resource) { return getEffectiveCapability(resource, LiveSyncCapabilityType.class) != null; } - + public static boolean isScriptCapabilityEnabled(ResourceType resource) { return getEffectiveCapability(resource, ScriptCapabilityType.class) != null; } - + public static boolean isTestConnectionCapabilityEnabled(ResourceType resource) { return getEffectiveCapability(resource, TestConnectionCapabilityType.class) != null; } - + public static boolean isAuxiliaryObjectClassCapabilityEnabled(ResourceType resource) { return getEffectiveCapability(resource, AuxiliaryObjectClassesCapabilityType.class) != null; } - + public static boolean isPagedSearchCapabilityEnabled(ResourceType resource) { return getEffectiveCapability(resource, PagedSearchCapabilityType.class) != null; } - + public static boolean isReadCapabilityEnabled(ResourceType resource){ return getEffectiveCapability(resource, ReadCapabilityType.class) != null; } - + public static boolean isUpdateCapabilityEnabled(ResourceType resource){ return getEffectiveCapability(resource, UpdateCapabilityType.class) != null; } - + public static boolean isAddRemoveAttributesValuesCapabilityEnabled(ResourceType resource){ return getEffectiveCapability(resource, AddRemoveAttributeValuesCapabilityType.class) != null; } - + public static boolean isDeleteCapabilityEnabled(ResourceType resource){ return getEffectiveCapability(resource, DeleteCapabilityType.class) != null; } - + public static boolean hasResourceNativeActivationCapability(ResourceType resource) { ActivationCapabilityType activationCapability = null; @@ -409,7 +409,7 @@ public static boolean hasResourceNativeActivationCapability(ResourceType resourc } return true; } - + public static boolean hasResourceNativeActivationStatusCapability(ResourceType resource) { ActivationCapabilityType activationCapability = null; if (resource.getCapabilities() != null && resource.getCapabilities().getNative() != null) { @@ -418,7 +418,7 @@ public static boolean hasResourceNativeActivationStatusCapability(ResourceType r } return CapabilityUtil.getEffectiveActivationStatus(activationCapability) != null; } - + public static boolean hasResourceNativeActivationLockoutCapability(ResourceType resource) { ActivationCapabilityType activationCapability = null; // check resource native capabilities. if resource cannot do @@ -429,7 +429,7 @@ public static boolean hasResourceNativeActivationLockoutCapability(ResourceType } return CapabilityUtil.getEffectiveActivationLockoutStatus(activationCapability) != null; } - + public static boolean hasResourceConfiguredActivationCapability(ResourceType resource) { if (resource.getCapabilities() == null) { return false; @@ -475,7 +475,7 @@ public static ResourceObjectTypeDefinitionType getResourceObjectTypeDefinitionTy public static PrismContainer getConfigurationContainer(ResourceType resourceType) { return getConfigurationContainer(resourceType.asPrismObject()); } - + public static PrismContainer getConfigurationContainer(PrismObject resource) { return resource.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); } @@ -525,31 +525,31 @@ public static ResourceObjectTypeDependencyStrictnessType getDependencyStrictness return dependency.getStrictness(); } } - + public static boolean isForceLoadDependentShadow(ResourceObjectTypeDependencyType dependency){ Boolean force = dependency.isForceLoad(); if (force == null){ return false; } - + return force; } - + public static boolean isDown(ResourceType resource){ return (resource.getOperationalState() != null && AvailabilityStatusType.DOWN == resource.getOperationalState().getLastAvailabilityStatus()); } - + public static AvailabilityStatusType getLastAvailabilityStatus(ResourceType resource){ if (resource.getOperationalState() == null) { return null; } - + if (resource.getOperationalState().getLastAvailabilityStatus() == null) { return null; } - + return resource.getOperationalState().getLastAvailabilityStatus(); - + } public static boolean isAvoidDuplicateValues(ResourceType resource) { @@ -640,7 +640,7 @@ public static ObjectSynchronizationType findObjectSynchronization(@Nullable Reso public static QName fillDefaultFocusType(QName focusType) { return focusType != null ? focusType : UserType.COMPLEX_TYPE; } - + public static ShadowCheckType getShadowConstraintsCheck(ResourceType resource) { ResourceConsistencyType consistency = resource.getConsistency(); if (consistency == null) { @@ -663,16 +663,16 @@ public static boolean isValidateSchema(ResourceType resource) { // TODO: maybe later move to ResourceSchema? public static void validateSchema(ResourceSchema resourceSchema, PrismObject resource) throws SchemaException { - + Set objectClassNames = new HashSet<>(); - + for (ObjectClassComplexTypeDefinition objectClassDefinition: resourceSchema.getObjectClassDefinitions()) { QName typeName = objectClassDefinition.getTypeName(); if (objectClassNames.contains(typeName)) { throw new SchemaException("Duplicate definition of object class "+typeName+" in resource schema of "+resource); } objectClassNames.add(typeName); - + validateObjectClassDefinition(objectClassDefinition, resource); } } @@ -687,15 +687,15 @@ public static void validateObjectClassDefinition(ObjectClassComplexTypeDefinitio } attributeNames.add(attrName); } - + Collection> primaryIdentifiers = objectClassDefinition.getPrimaryIdentifiers(); Collection> secondaryIdentifiers = objectClassDefinition.getSecondaryIdentifiers(); - + if (primaryIdentifiers.isEmpty() && secondaryIdentifiers.isEmpty()) { throw new SchemaException("No identifiers in definition of object class "+objectClassDefinition.getTypeName()+" in resource schema of "+resource); } } - + public static RecordPendingOperationsType getRecordPendingOperations(ResourceType resourceType) { ResourceConsistencyType consistencyType = resourceType.getConsistency(); if (consistencyType == null) { diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/SchemaDebugUtil.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/SchemaDebugUtil.java index f06d8b1401f..39eb96a8cf8 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/SchemaDebugUtil.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/SchemaDebugUtil.java @@ -67,22 +67,22 @@ import com.evolveum.prism.xml.ns._public.types_3.RawType; /** - * + * * @author semancik */ public class SchemaDebugUtil { private static int SHOW_LIST_MEMBERS = 3; - + public static String debugDump(Collection dumpables) { return debugDump(dumpables,0); } - + public static String debugDump(Collection dumpables, int indent) { StringBuilder sb = new StringBuilder(); indentDebugDump(sb, indent); sb.append(getCollectionOpeningSymbol(dumpables)); - if (!dumpables.isEmpty()) { + if (!dumpables.isEmpty()) { sb.append("\n"); for (DebugDumpable dd : dumpables) { if (dd == null) { @@ -98,7 +98,7 @@ public static String debugDump(Collection dumpables, in sb.append(getCollectionClosingSymbol(dumpables)); return sb.toString(); } - + public static String debugDumpXsdAnyProperties(Collection xsdAnyCollection, int indent) { StringBuilder sb = new StringBuilder(); indentDebugDump(sb, indent); @@ -151,19 +151,19 @@ private static String getCollectionClosingSymbol(Collection col) { } return ")"; } - + public static void indentDebugDump(StringBuilder sb, int indent) { for(int i = 0; i < indent; i++) { sb.append(DebugDumpable.INDENT_STRING); } } - + public static String dumpMapMultiLine(Map map) { StringBuilder sb = new StringBuilder(); debugDumpMapMultiLine(sb, map, 0); return sb.toString(); } - + public static void debugDumpMapMultiLine(StringBuilder sb, Map map, int indent) { Iterator> i = map.entrySet().iterator(); while (i.hasNext()) { @@ -202,7 +202,7 @@ public static void debugDumpMapSingleLine(StringBuilder sb, Map map } } } - + public static String debugDump(ObjectType objectType, int indent) { if (objectType == null) { StringBuilder sb = new StringBuilder(); @@ -228,7 +228,7 @@ public static String prettyPrint(Collection collection) { sb.append(getCollectionClosingSymbol(collection)); return sb.toString(); } - + public static String prettyPrint(QName qname) { if (qname == null) { return "null"; @@ -238,7 +238,7 @@ public static String prettyPrint(QName qname) { } return qname.toString(); } - + public static String prettyPrint(AssignmentType assignmentType) { if (assignmentType == null) { return "null"; @@ -262,7 +262,7 @@ public static String prettyPrint(AssignmentType assignmentType) { sb.append(")"); return sb.toString(); } - + public static String prettyPrint(ConstructionType act) { if (act == null) { return "null"; @@ -289,7 +289,7 @@ public static String prettyPrint(ConstructionType act) { sb.append(")"); return sb.toString(); } - + public static String prettyPrint(ResourceAttributeDefinitionType vc) { if (vc == null) { return "null"; @@ -313,12 +313,12 @@ public static String prettyPrint(ResourceAttributeDefinitionType vc) { sb.append(", ..."); } } - + // TODO: Other properties sb.append(")"); return sb.toString(); } - + public static String prettyPrint(CachingMetadataType cachingMetadata) { if (cachingMetadata == null) { return "null"; @@ -335,7 +335,7 @@ public static String prettyPrint(CachingMetadataType cachingMetadata) { sb.append(")"); return sb.toString(); } - + public static String prettyPrint(ScheduleType scheduleType) { if (scheduleType == null) { return "null"; @@ -345,7 +345,7 @@ public static String prettyPrint(ScheduleType scheduleType) { sb.append("cronLikePattern:"); sb.append(scheduleType.getCronLikePattern()); } - + if (scheduleType.getEarliestStartTime() != null) { sb.append("earliestStartTime:"); sb.append(prettyPrint(scheduleType.getEarliestStartTime())); @@ -366,11 +366,11 @@ public static String prettyPrint(ScheduleType scheduleType) { sb.append("misfireAction:"); sb.append(prettyPrint(scheduleType.getMisfireAction())); } - + sb.append(")"); return sb.toString(); } - + public static String prettyPrint(ObjectReferenceType ref) { if (ref == null) { return "null"; @@ -407,17 +407,17 @@ public static String prettyPrint(ObjectType object) { return object.asPrismObject().toString(); } - + public static String prettyPrint(ProtectedStringType protectedStringType) { if (protectedStringType == null) { return "null"; } StringBuilder sb = new StringBuilder("ProtectedStringType("); - + if (protectedStringType.getEncryptedDataType() != null) { sb.append("[encrypted data]"); } - + if (protectedStringType.getHashedDataType() != null) { sb.append("[hashed data]"); } @@ -435,7 +435,7 @@ public static String prettyPrint(ProtectedStringType protectedStringType) { sb.append(")"); return sb.toString(); } - + public static String prettyPrint(OperationResultType resultType) { if (resultType == null) { return "null"; @@ -477,7 +477,7 @@ public static String prettyPrint(ItemDeltaType change) throws SchemaException { /** * Assumes that all elements in the lists have the same QName - * + * * @param list * @return */ @@ -626,7 +626,7 @@ public static String prettyPrint(ObjectListType list) { // // return sb.toString(); // } - + private static void prettyPrintFilter(StringBuilder sb, Element filter) { if (filter == null) { @@ -676,7 +676,7 @@ private static void prettyPrintFilter(StringBuilder sb, ObjectFilter filter) { sb.append(filter.toString()); sb.append(")"); } - + private static void prettyPrintPaging(StringBuilder sb, ObjectPaging paging) { if (paging == null) { @@ -688,7 +688,7 @@ private static void prettyPrintPaging(StringBuilder sb, ObjectPaging paging) { sb.append(paging.toString()); sb.append(")"); } - + public static String prettyPrint(PagingType paging) { if (paging == null) { @@ -723,7 +723,7 @@ public static String prettyPrint(PagingType paging) { return sb.toString(); } - + public static String prettyPrint(SynchronizationSituationDescriptionType syncDescType) { if (syncDescType == null) { return "null"; @@ -742,7 +742,7 @@ public static String prettyPrint(SynchronizationSituationDescriptionType syncDes sb.append(")"); return sb.toString(); } - + public static String prettyPrint(ObjectDeltaType deltaType) { if (deltaType == null) { return "null"; @@ -759,7 +759,7 @@ public static String prettyPrint(ObjectDeltaType deltaType) { sb.append(")"); return sb.toString(); } - + public static String prettyPrint(ObjectDeltaOperationType deltaOpType) { if (deltaOpType == null) { return "null"; @@ -777,28 +777,28 @@ public static String prettyPrint(ObjectDeltaOperationType deltaOpType) { sb.append(")"); return sb.toString(); } - + public static String prettyPrint(JAXBElement element) { return "JAXBElement("+PrettyPrinter.prettyPrint(element.getName())+"): "+element.getValue(); } - + public static String prettyPrint(UnknownJavaObjectType xml) { if (xml == null) { return "null"; } return "Java("+xml.getClazz()+","+xml.getToString()+")"; } - + // public static String prettyPrint(OperationProvisioningScriptsType scriptsType) { // if (scriptsType == null) { // return "null"; // } // StringBuilder sb = new StringBuilder("") // for (OperationProvisioningScriptType scriptType: scriptsType.getScript()) { -// +// // } // } - + public static String prettyPrint(Object value) { if (value == null) { return "null"; @@ -863,10 +863,10 @@ private static String tryPrettyPrint(Object value) { } public static String prettyPrint(ObjectQuery query){ - + return query.toString(); } - + static { PrettyPrinter.registerPrettyPrinter(SchemaDebugUtil.class); } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/SchemaTestConstants.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/SchemaTestConstants.java index 95e7af41d60..dc68a3a5fc5 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/SchemaTestConstants.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/SchemaTestConstants.java @@ -23,7 +23,7 @@ /** * Constants for use in tests. DO NOT USE IN "MAIN" CODE. This is placed in "main" just for convenience, so the * tests in other components can see it. - * + * * @author Radovan Semancik */ public class SchemaTestConstants { @@ -31,7 +31,7 @@ public class SchemaTestConstants { public static final String NS_ICFC_LDAP = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/org.identityconnectors.ldap/org.identityconnectors.ldap.LdapConnector"; public static final String NS_ICFC = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/connector-schema-3"; public static final String NS_ICFS = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/resource-schema-3"; - + public static final QName ICFC_CONFIGURATION_PROPERTIES = new QName(NS_ICFC, "configurationProperties"); public static final QName ICFC_CONFIGURATION_PROPERTIES_TYPE = new QName(NS_ICFC, "ConfigurationPropertiesType"); public static final String ICF_ACCOUNT_OBJECT_CLASS_LOCAL_NAME = "AccountObjectClass"; @@ -41,10 +41,10 @@ public class SchemaTestConstants { public static final ItemPath ICFS_UID_PATH = new ItemPath(ShadowType.F_ATTRIBUTES, ICFS_UID); public static final QName ICFS_NAME = new QName(NS_ICFS, "name"); public static final ItemPath ICFS_NAME_PATH = new ItemPath(ShadowType.F_ATTRIBUTES, ICFS_NAME); - + public static final String ACCOUNT_OBJECT_CLASS_LOCAL_NAME = "AccountObjectClass"; public static final String GROUP_OBJECT_CLASS_LOCAL_NAME = "GroupObjectClass"; - + // Extension schema loaded at runtime from the schema/src/test/resource/schema dir public static final String NS_EXTENSION = "http://midpoint.evolveum.com/xml/ns/test/extension"; public static final QName EXTENSION_LOCATIONS_ELEMENT = new QName(NS_EXTENSION, "locations"); diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/SecurityPolicyUtil.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/SecurityPolicyUtil.java index d8d59d80299..9ae67e47b49 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/SecurityPolicyUtil.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/SecurityPolicyUtil.java @@ -23,9 +23,9 @@ public static AbstractAuthenticationPolicyType getAuthenticationPolicy(String au return checkAndGetAuthPolicyConsistence(mailAuthPolicy, smsAuthPolicy); } - - - + + + public static NonceCredentialsPolicyType getCredentialPolicy(String policyName, SecurityPolicyType securityPolicy) throws SchemaException { CredentialsPolicyType credentialsPolicy = securityPolicy.getCredentials(); @@ -65,7 +65,7 @@ public static NonceCredentialsPolicyType getCredentialPolicy(String policyName, return availableNoncePolicies.iterator().next(); } - + private static MailAuthenticationPolicyType getMailAuthenticationPolicy(String authName, SecurityPolicyType securityPolicy) throws SchemaException { AuthenticationsPolicyType authPolicies = securityPolicy.getAuthentication(); @@ -99,7 +99,7 @@ private static AbstractAuthenticationPolicyType checkAndGetAuthPolicyConsistence return smsPolicy; } - + private static T getAuthenticationPolicy(String authName, List authPolicies) throws SchemaException { @@ -137,5 +137,5 @@ private static T getAuthenticationP } - + } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ShadowUtil.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ShadowUtil.java index 231ecd87c74..8bd5d58fd35 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ShadowUtil.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/ShadowUtil.java @@ -44,38 +44,38 @@ /** * Methods that would belong to the ResourceObjectShadowType class but cannot go there * because of JAXB. - * + * * @author Radovan Semancik */ public class ShadowUtil { - + private static final Trace LOGGER = TraceManager.getTrace(ShadowUtil.class); - + public static Collection> getPrimaryIdentifiers(ShadowType shadowType) { return getPrimaryIdentifiers(shadowType.asPrismObject()); } - + // TODO: rename to getPrimaryIdentifiers public static Collection> getPrimaryIdentifiers(PrismObject shadow) { ResourceAttributeContainer attributesContainer = getAttributesContainer(shadow); if (attributesContainer == null) { return null; } - return attributesContainer.getPrimaryIdentifiers(); + return attributesContainer.getPrimaryIdentifiers(); } - + public static Collection> getSecondaryIdentifiers(ShadowType shadowType) { return getSecondaryIdentifiers(shadowType.asPrismObject()); } - + public static Collection> getSecondaryIdentifiers(PrismObject shadow) { ResourceAttributeContainer attributesContainer = getAttributesContainer(shadow); if (attributesContainer == null) { return null; } - return attributesContainer.getSecondaryIdentifiers(); + return attributesContainer.getSecondaryIdentifiers(); } - + public static ResourceAttribute getSecondaryIdentifier(PrismObject shadow) throws SchemaException { Collection> secondaryIdentifiers = getSecondaryIdentifiers(shadow); if (secondaryIdentifiers == null || secondaryIdentifiers.isEmpty()) { @@ -86,7 +86,7 @@ public static ResourceAttribute getSecondaryIdentifier(PrismObject) secondaryIdentifiers.iterator().next(); } - + public static Collection> getSecondaryIdentifiers(Collection> identifiers, ObjectClassComplexTypeDefinition objectClassDefinition) throws SchemaException { if (identifiers == null) { return null; @@ -99,7 +99,7 @@ public static Collection> getSecondaryIdentifiers(Collectio } return secondaryIdentifiers; } - + public static String getSecondaryIdentifierRealValue(PrismObject shadow) throws SchemaException { ResourceAttribute secondaryIdentifier = getSecondaryIdentifier(shadow); if (secondaryIdentifier == null) { @@ -107,8 +107,8 @@ public static String getSecondaryIdentifierRealValue(PrismObject getSecondaryIdentifier(ObjectClassComplexTypeDefinition objectClassDefinition, + + public static ResourceAttribute getSecondaryIdentifier(ObjectClassComplexTypeDefinition objectClassDefinition, Collection> identifiers) throws SchemaException { if (identifiers == null) { return null; @@ -124,55 +124,55 @@ public static ResourceAttribute getSecondaryIdentifier(ObjectClassComplexType } return secondaryIdentifier; } - + public static Collection> getAllIdentifiers(PrismObject shadow) { ResourceAttributeContainer attributesContainer = getAttributesContainer(shadow); if (attributesContainer == null) { return null; } - return attributesContainer.getAllIdentifiers(); + return attributesContainer.getAllIdentifiers(); } - + public static Collection> getAllIdentifiers(ShadowType shadow) { return getAllIdentifiers(shadow.asPrismObject()); } - + public static ResourceAttribute getNamingAttribute(ShadowType shadow){ return getNamingAttribute(shadow.asPrismObject()); } - + public static ResourceAttribute getNamingAttribute(PrismObject shadow) { ResourceAttributeContainer attributesContainer = getAttributesContainer(shadow); if (attributesContainer == null) { return null; } - return attributesContainer.getNamingAttribute(); + return attributesContainer.getNamingAttribute(); } - + public static Collection> getAttributes(ShadowType shadowType) { return getAttributes(shadowType.asPrismObject()); } - + public static Collection> getAttributes(PrismObject shadow) { - return getAttributesContainer(shadow).getAttributes(); + return getAttributesContainer(shadow).getAttributes(); } - + public static ResourceAttribute getAttribute(PrismObject shadow, QName attrName) { - return getAttributesContainer(shadow).findAttribute(attrName); + return getAttributesContainer(shadow).findAttribute(attrName); } - + public static ResourceAttributeContainer getAttributesContainer(ShadowType shadowType) { return getAttributesContainer(shadowType.asPrismObject()); } - + public static ResourceAttributeContainer getAttributesContainer(PrismObject shadow) { return getAttributesContainer(shadow, ShadowType.F_ATTRIBUTES); } - + public static ResourceAttributeContainer getAttributesContainer(PrismObject shadow, QName containerName) { return getAttributesContainer(shadow.getValue(), containerName); } - + public static ResourceAttributeContainer getAttributesContainer(PrismContainerValue cval, QName containerName) { PrismContainer attributesContainer = cval.findContainer(containerName); if (attributesContainer == null) { @@ -184,8 +184,8 @@ public static ResourceAttributeContainer getAttributesContainer(PrismContainerVa throw new SystemException("Expected that <"+containerName.getLocalPart()+"> will be ResourceAttributeContainer but it is "+attributesContainer.getClass()); } } - - public static ResourceAttributeContainer getOrCreateAttributesContainer(PrismObject shadow, + + public static ResourceAttributeContainer getOrCreateAttributesContainer(PrismObject shadow, ObjectClassComplexTypeDefinition objectClassDefinition) { ResourceAttributeContainer attributesContainer = getAttributesContainer(shadow); if (attributesContainer != null) { @@ -199,24 +199,24 @@ public static ResourceAttributeContainer getOrCreateAttributesContainer(PrismObj } return emptyContainer; } - + public static ObjectClassComplexTypeDefinition getObjectClassDefinition(ShadowType shadow) { // TODO: maybe we can do something more intelligent here ResourceAttributeContainer attributesContainer = getAttributesContainer(shadow); return attributesContainer.getDefinition().getComplexTypeDefinition(); } - + public static ObjectClassComplexTypeDefinition getObjectClassDefinition(PrismObject shadow) { // TODO: maybe we can do something more intelligent here ResourceAttributeContainer attributesContainer = getAttributesContainer(shadow); return attributesContainer.getDefinition().getComplexTypeDefinition(); } - + public static String getResourceOid(ShadowType shadowType) { return getResourceOid(shadowType.asPrismObject()); } - + public static String getResourceOid(PrismObject shadow) { PrismReference resourceRef = shadow.findReference(ShadowType.F_RESOURCE_REF); if (resourceRef == null) { @@ -252,11 +252,11 @@ public static String getSingleStringAttributeValue(PrismObject shado } return attribute.getRealValue(); } - + public static String getMultiStringAttributeValueAsSingle(ShadowType shadow, QName attrName) { return getMultiStringAttributeValueAsSingle(shadow.asPrismObject(), attrName); } - + private static String getMultiStringAttributeValueAsSingle(PrismObject shadow, QName attrName) { PrismContainer attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES); @@ -280,7 +280,7 @@ private static String getMultiStringAttributeValueAsSingle(PrismObject List getAttributeValues(ShadowType shadowType, QName attrName) { return getAttributeValues(shadowType.asPrismObject(), attrName); } - + public static List getAttributeValues(PrismObject shadow, QName attrName) { PrismContainer attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES); if (attributesContainer == null || attributesContainer.isEmpty()) { @@ -299,11 +299,11 @@ public static List getAttributeValues(PrismObject s } return values; } - + public static T getAttributeValue(ShadowType shadowType, QName attrName) throws SchemaException { return (T) getAttributeValue(shadowType.asPrismObject(), attrName); } - + public static T getAttributeValue(PrismObject shadow, QName attrName) throws SchemaException { Collection values = getAttributeValues(shadow, attrName); if (values == null || values.isEmpty()) { @@ -328,7 +328,7 @@ public static void setPassword(ShadowType shadowType, ProtectedStringType passwo } passwordType.setValue(password); } - + public static void setPasswordIncomplete(ShadowType shadowType) throws SchemaException { CredentialsType credentialsType = shadowType.getCredentials(); if (credentialsType == null) { @@ -353,7 +353,7 @@ public static ActivationType getOrCreateActivation(ShadowType shadowType) { } return activation; } - + /** * This is not supposed to be used in production code! It is just for the tests. */ @@ -364,16 +364,16 @@ public static void applyResourceSchema(PrismObject shadow, ObjectClassComplexTypeDefinition objectClassDefinition = resourceSchema.findObjectClassDefinition(objectClass); applyObjectClass(shadow, objectClassDefinition); } - - private static void applyObjectClass(PrismObject shadow, + + private static void applyObjectClass(PrismObject shadow, ObjectClassComplexTypeDefinition objectClassDefinition) throws SchemaException { PrismContainer attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES); ResourceAttributeContainerDefinition racDef = new ResourceAttributeContainerDefinitionImpl(ShadowType.F_ATTRIBUTES, objectClassDefinition, objectClassDefinition.getPrismContext()); attributesContainer.applyDefinition((PrismContainerDefinition) racDef, true); } - - public static PrismObjectDefinition applyObjectClass(PrismObjectDefinition shadowDefinition, + + public static PrismObjectDefinition applyObjectClass(PrismObjectDefinition shadowDefinition, ObjectClassComplexTypeDefinition objectClassDefinition) throws SchemaException { PrismObjectDefinition shadowDefClone = shadowDefinition.cloneWithReplacedDefinition(ShadowType.F_ATTRIBUTES, objectClassDefinition.toResourceAttributeContainerDefinition()); @@ -394,7 +394,7 @@ public static String getIntent(ShadowType shadow) { } return null; } - + public static ShadowKindType getKind(ShadowType shadow) { if (shadow == null) { return null; @@ -442,7 +442,7 @@ public static QName getAttributeName(ItemPath attributePath, String message) thr } return ((NameItemPathSegment) secondPathSegment).getName(); } - + public static void checkConsistence(PrismObject shadow, String desc) { PrismReference resourceRef = shadow.findReference(ShadowType.F_RESOURCE_REF); if (resourceRef == null) { @@ -461,14 +461,14 @@ public static void checkConsistence(PrismObject shadow, St throw new IllegalStateException("The attributes element expected to be ResourceAttributeContainer but it is " +attributesContainer.getClass()+" instead in "+desc); } - checkConsistency(attributesContainer.getDefinition(), " container definition in "+desc); + checkConsistency(attributesContainer.getDefinition(), " container definition in "+desc); } - - PrismContainerDefinition attributesDefinition = + + PrismContainerDefinition attributesDefinition = shadow.getDefinition().findContainerDefinition(ShadowType.F_ATTRIBUTES); checkConsistency(attributesDefinition, " object definition in "+desc); } - + public static void checkConsistency(PrismContainerDefinition attributesDefinition, String desc) { if (attributesDefinition == null) { throw new IllegalStateException("No definition for in "+desc); @@ -487,17 +487,17 @@ public static boolean isAccount(ShadowType shadowType) { return true; // ??? } } - + public static boolean isProtected(PrismObject shadow) { if (shadow == null) { return false; } - + ShadowType shadowType = shadow.asObjectable(); Boolean protectedObject = shadowType.isProtectedObject(); return (protectedObject != null && protectedObject); } - + public static boolean isDead(ShadowType shadow){ return shadow.isDead() != null && shadow.isDead(); } @@ -520,15 +520,15 @@ public static boolean matches(ShadowType shadowType, String resourceOid, ShadowK /** * Strict mathcing. E.g. null discriminator kind is intepreted as ACCOUNT and it must match the kind - * in the shadow. + * in the shadow. */ public static boolean matches(PrismObject shadow, ResourceShadowDiscriminator discr) { return matches(shadow.asObjectable(), discr); } - + /** * Strict mathcing. E.g. null discriminator kind is intepreted as ACCOUNT and it must match the kind - * in the shadow. + * in the shadow. */ public static boolean matches(ShadowType shadowType, ResourceShadowDiscriminator discr) { if (shadowType == null) { @@ -544,7 +544,7 @@ public static boolean matches(ShadowType shadowType, ResourceShadowDiscriminator } /** - * Interprets ResourceShadowDiscriminator as a pattern. E.g. null discriminator kind is + * Interprets ResourceShadowDiscriminator as a pattern. E.g. null discriminator kind is * interpreted to match any shadow kind. */ public static boolean matchesPattern(ShadowType shadowType, ShadowDiscriminatorType discr) { @@ -562,7 +562,7 @@ public static boolean matchesPattern(ShadowType shadowType, ShadowDiscriminatorT } return ResourceShadowDiscriminator.equalsIntent(shadowType.getIntent(), discr.getIntent()); } - + public static boolean isConflicting(ShadowType shadow1, ShadowType shadow2) { if (!shadow1.getResourceRef().getOid().equals(shadow2.getResourceRef().getOid())) { return false; @@ -572,7 +572,7 @@ public static boolean isConflicting(ShadowType shadow1, ShadowType shadow2) { } return ResourceShadowDiscriminator.equalsIntent(shadow1.getIntent(), shadow2.getIntent()); } - + public static String getHumanReadableName(PrismObject shadow) { if (shadow == null) { return "null"; @@ -602,7 +602,7 @@ public static String getHumanReadableName(PrismObject shad sb.append("]"); return shadow.toString(); } - + public static String getHumanReadableName(ShadowType shadowType) { if (shadowType == null) { return "null"; @@ -683,12 +683,12 @@ public static String determineShadowStringName(PrismObjec public static ResourceObjectIdentification getResourceObjectIdentification( PrismObject shadow, ObjectClassComplexTypeDefinition objectClassDefinition) { - return new ResourceObjectIdentification(objectClassDefinition, + return new ResourceObjectIdentification(objectClassDefinition, ShadowUtil.getPrimaryIdentifiers(shadow), ShadowUtil.getSecondaryIdentifiers(shadow)); } public static boolean matchesAttribute(ItemPath path, QName attributeName) { - return (ShadowType.F_ATTRIBUTES.equals(ItemPath.getFirstName(path)) && + return (ShadowType.F_ATTRIBUTES.equals(ItemPath.getFirstName(path)) && QNameUtil.match(ItemPath.getFirstName(path.rest()), attributeName)); } diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/AbstractSchemaTest.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/AbstractSchemaTest.java index 657296479e3..ec134aa2284 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/AbstractSchemaTest.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/AbstractSchemaTest.java @@ -33,9 +33,9 @@ * */ public abstract class AbstractSchemaTest { - + protected static final File COMMON_DIR = new File("src/test/resources/common"); - + public static final File USER_JACK_FILE = new File(COMMON_DIR, "user-jack.xml"); public static final String USER_JACK_OID = "2f9b9299-6f45-498f-bc8e-8d17c6b93b20"; public static final String USER_JACK_NAME = "jack"; @@ -53,11 +53,11 @@ public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - + protected PrismObjectDefinition getUserDefinition() { return PrismTestUtil.getPrismContext().getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); } - + protected void displayTestTile(String TEST_NAME) { System.out.println("===[ "+TEST_NAME+" ]===="); } diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestConstants.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestConstants.java index 558b81a36ea..6e868877ef1 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestConstants.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestConstants.java @@ -26,10 +26,10 @@ * */ public class TestConstants { - + public static final String COMMON_DIR_PATH = "src/test/resources/common"; public static final File COMMON_DIR = new File(COMMON_DIR_PATH); - + public static final String NS_EXTENSION = SchemaConstants.NS_MIDPOINT_TEST + "/extension"; public static final String NS_FOO = "http://www.example.com/foo"; @@ -38,16 +38,16 @@ public class TestConstants { public static final QName EXTENSION_INT_TYPE_ELEMENT = new QName(NS_EXTENSION, "intType"); public static final QName EXTENSION_IGNORED_TYPE_ELEMENT = new QName(NS_EXTENSION, "ignoredType"); public static final QName EXTENSION_USER_REF_ELEMENT = new QName(NS_EXTENSION, "userRef"); - + public static final String USER_FILE_BASENAME = "user-jack"; public static final File USER_FILE = new File(COMMON_DIR, "user-jack.xml"); - + public static final Long USER_ASSIGNMENT_1_ID = 111L; - + public static final String USER_ACCOUNT_REF_1_OID = "2f9b9299-6f45-498f-aaaa-000000001111"; public static final String USER_ACCOUNT_REF_2_OID = "2f9b9299-6f45-498f-aaaa-000000002222"; public static final String USER_ACCOUNT_REF_3_OID = "2f9b9299-6f45-498f-aaaa-000000003333"; - + public static final String RESOURCE_FILE_BASENAME = "resource-opendj"; public static final String RESOURCE_FILE_SIMPLE_BASENAME = "resource-opendj-simple"; public static final File RESOURCE_FILE = new File(TestConstants.COMMON_DIR, "xml/ns/resource-opendj.xml"); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestDeltaConverter.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestDeltaConverter.java index 87e066e62c0..de75850ae7a 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestDeltaConverter.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestDeltaConverter.java @@ -61,24 +61,24 @@ * @author Radovan Semancik */ public class TestDeltaConverter extends AbstractSchemaTest { - + private static final File TEST_DIR = new File("src/test/resources/deltaconverter"); - - private static final ItemPath CREDENTIALS_PASSWORD_VALUE_PATH = + + private static final ItemPath CREDENTIALS_PASSWORD_VALUE_PATH = new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE); @Test public void testRefWithObject() throws SchemaException, IOException, JAXBException { System.out.println("===[ testRefWithObject ]===="); - + ObjectModificationType objectChange = PrismTestUtil.parseAtomicValue(new File(TEST_DIR, "user-modify-add-account.xml"), ObjectModificationType.COMPLEX_TYPE); - - ObjectDelta objectDelta = DeltaConvertor.createObjectDelta(objectChange, UserType.class, + + ObjectDelta objectDelta = DeltaConvertor.createObjectDelta(objectChange, UserType.class, getPrismContext()); - + System.out.println("delta: " + objectDelta.debugDump()); - + assertNotNull("No object delta", objectDelta); objectDelta.checkConsistence(); assertEquals("Wrong OID", "c0c010c0-d34d-b33f-f00d-111111111111", objectDelta.getOid()); @@ -88,21 +88,21 @@ public void testRefWithObject() throws SchemaException, IOException, JAXBExcepti assertEquals("Wrong number of values to add", 1, valuesToAdd.size()); PrismReferenceValue accountRefVal = valuesToAdd.iterator().next(); assertNotNull("No object in accountRef value", accountRefVal.getObject()); - + objectDelta.assertDefinitions(); } - + @Test public void testPasswordChange() throws Exception { System.out.println("===[ testPasswordChange ]===="); - + ObjectModificationType objectChange = PrismTestUtil.parseAtomicValue(new File(TEST_DIR, "user-modify-password.xml"), ObjectModificationType.COMPLEX_TYPE); - + // WHEN - ObjectDelta objectDelta = DeltaConvertor.createObjectDelta(objectChange, UserType.class, + ObjectDelta objectDelta = DeltaConvertor.createObjectDelta(objectChange, UserType.class, getPrismContext()); - + // THEN assertNotNull("No object delta", objectDelta); objectDelta.checkConsistence(); @@ -113,29 +113,29 @@ public void testPasswordChange() throws Exception { assertEquals("Wrong number of values to replace", 1, valuesToReplace.size()); PrismPropertyValue protectedStringVal = valuesToReplace.iterator().next(); assertNotNull("Null value in protectedStringDelta", protectedStringVal); - + PrismObject user = PrismTestUtil.parseObject(USER_JACK_FILE); // apply to user objectDelta.applyTo(user); - + PrismProperty protectedStringProperty = user.findProperty(CREDENTIALS_PASSWORD_VALUE_PATH); PrismPropertyValue protectedStringPropertyValue = protectedStringProperty.getValue(); assertTrue("protectedString not equivalent", protectedStringPropertyValue.equalsRealValue(protectedStringVal)); - + objectDelta.assertDefinitions(); } - + @Test public void testModifyGivenName() throws Exception { System.out.println("===[ testModifyGivenName ]===="); - + ObjectModificationType objectChange = PrismTestUtil.parseAtomicValue(new File(TEST_DIR, "user-modify-givenname.xml"), ObjectModificationType.COMPLEX_TYPE); - + // WHEN - ObjectDelta objectDelta = DeltaConvertor.createObjectDelta(objectChange, UserType.class, + ObjectDelta objectDelta = DeltaConvertor.createObjectDelta(objectChange, UserType.class, getPrismContext()); - + // THEN assertNotNull("No object delta", objectDelta); objectDelta.checkConsistence(); @@ -144,32 +144,32 @@ public void testModifyGivenName() throws Exception { assertNotNull("No givenName delta", givenNameDelta); Collection> valuesToReplace = givenNameDelta.getValuesToReplace(); assertEquals("Wrong number of values to replace", 0, valuesToReplace.size()); - + PrismObject user = PrismTestUtil.parseObject(USER_JACK_FILE); // apply to user objectDelta.applyTo(user); - + PrismProperty protectedStringProperty = user.findProperty(UserType.F_GIVEN_NAME); assertNull("givenName porperty sneaked in after delta was applied", protectedStringProperty); - + objectDelta.assertDefinitions(); } - - + + @Test public void testAddAssignment() throws Exception { System.out.println("===[ testAddAssignment ]===="); - + ObjectModificationType objectChange = PrismTestUtil.parseAtomicValue(new File(TEST_DIR, "user-modify-add-role-pirate.xml"), ObjectModificationType.COMPLEX_TYPE); - + // WHEN - ObjectDelta objectDelta = DeltaConvertor.createObjectDelta(objectChange, UserType.class, + ObjectDelta objectDelta = DeltaConvertor.createObjectDelta(objectChange, UserType.class, getPrismContext()); - + System.out.println("Delta:"); System.out.println(objectDelta.debugDump()); - + // THEN assertNotNull("No object delta", objectDelta); objectDelta.checkConsistence(); @@ -180,32 +180,32 @@ public void testAddAssignment() throws Exception { assertEquals("Wrong number of values to add", 1, valuesToAdd.size()); PrismContainerValue assignmentVal = valuesToAdd.iterator().next(); assertNotNull("Null value in protectedStringDelta", assignmentVal); - + PrismReference targetRef = assignmentVal.findReference(AssignmentType.F_TARGET_REF); assertNotNull("No targetRef in assignment", targetRef); PrismReferenceValue targetRefVal = targetRef.getValue(); assertNotNull("No targetRef value in assignment", targetRefVal); assertEquals("Wrong OID in targetRef value", "12345678-d34d-b33f-f00d-987987987988", targetRefVal.getOid()); assertEquals("Wrong type in targetRef value", RoleType.COMPLEX_TYPE, targetRefVal.getTargetType()); - + PrismObject user = PrismTestUtil.parseObject(USER_JACK_FILE); - + objectDelta.assertDefinitions("delta before test"); user.assertDefinitions("user before test"); - + // apply to user objectDelta.applyTo(user); - + objectDelta.assertDefinitions("delta after test"); user.assertDefinitions("user after test"); // TODO } - + @Test public void testAccountRefDelta() throws Exception { System.out.println("===[ testAccountRefDelta ]===="); - + // GIVEN ObjectModificationType objectChange = new ObjectModificationType(); objectChange.setOid("12345"); @@ -219,18 +219,18 @@ public void testAccountRefDelta() throws Exception { objectChange.getItemDelta().add(modificationDeleteAccountRef); ItemPathType itemPathType = new ItemPathType(new ItemPath(UserType.F_LINK_REF)); modificationDeleteAccountRef.setPath(itemPathType); - + PrismObjectDefinition objDef = PrismTestUtil.getObjectDefinition(UserType.class); - + // WHEN Collection modifications = DeltaConvertor.toModifications(objectChange, objDef); - + // THEN assertNotNull("Null modifications", modifications); assertFalse("Empty modifications", modifications.isEmpty()); // TODO: more asserts } - + @Test public void testProtectedStringObjectDelta() throws Exception { System.out.println("===[ testProtectedStringObjectDelta ]===="); @@ -251,7 +251,7 @@ public void testProtectedStringObjectDelta() throws Exception { // THEN System.out.println("ObjectDeltaType (XML)"); System.out.println(PrismTestUtil.serializeAnyDataWrapped(objectDeltaType)); - + assertEquals("Wrong changetype", ChangeTypeType.MODIFY, objectDeltaType.getChangeType()); assertEquals("Wrong OID", "12345", objectDeltaType.getOid()); List modifications = objectDeltaType.getItemDelta(); @@ -277,7 +277,7 @@ public void testProtectedStringObjectDelta() throws Exception { //// assertEquals("Wrong element name", PasswordType.F_VALUE, valueElement.getName()); // assertEquals("Wrong element value", protectedString, valueElement.getValue()); } - + @Test public void testObjectDeltaRoundtrip() throws Exception { System.out.println("===[ testObjectDeltaRoundtrip ]===="); @@ -297,7 +297,7 @@ public void testObjectDeltaRoundtrip() throws Exception { // THEN System.out.println("ObjectDeltaType (XML)"); // System.out.println(PrismTestUtil.marshalWrap(objectDeltaType)); - + assertEquals("Wrong changetype", ChangeTypeType.MODIFY, objectDeltaType.getChangeType()); assertEquals("Wrong OID", OID, objectDeltaType.getOid()); List modifications = objectDeltaType.getItemDelta(); @@ -320,16 +320,16 @@ public void testObjectDeltaRoundtrip() throws Exception { // String valueElement = (String) values.iterator().next(); // assertEquals("Wrong element name", ItemDeltaType.F_VALUE, DOMUtil.getQName(valueElement)); // assertEquals("Wrong element value", VALUE, valueElement); - + // WHEN ObjectDelta objectDeltaRoundtrip = DeltaConvertor.createObjectDelta(objectDeltaType, getPrismContext()); - + // THEN System.out.println("ObjectDelta (roundtrip)"); System.out.println(objectDelta.debugDump()); - + assertTrue("Roundtrip not equals", objectDelta.equals(objectDeltaRoundtrip)); - + // TODO: more checks } @@ -360,7 +360,7 @@ public void testTaskExtensionDeleteDelta() throws Exception { Object.class, xmlDelta)); assertNotNull(result); } - + @Test public void testItemDeltaReplace() throws Exception { System.out.println("===[ testItemDeltaReplace ]===="); @@ -369,23 +369,23 @@ public void testItemDeltaReplace() throws Exception { PrismObjectDefinition userDef = getUserDefinition(); PropertyDelta deltaBefore = PropertyDelta.createReplaceEmptyDelta(userDef, UserType.F_COST_CENTER); deltaBefore.setValueToReplace(new PrismPropertyValue("foo")); - + // WHEN Collection itemDeltaTypes = DeltaConvertor.toItemDeltaTypes(deltaBefore); - + // THEN System.out.println("Serialized"); System.out.println(itemDeltaTypes); - + // WHEN ItemDelta deltaAfter = DeltaConvertor.createItemDelta(itemDeltaTypes.iterator().next(), userDef); - + // THEN System.out.println("Parsed"); System.out.println(deltaAfter.debugDump()); assertEquals("Deltas do not match", deltaBefore, deltaAfter); - + assertNull(deltaAfter.getEstimatedOldValues()); } @@ -398,17 +398,17 @@ public void testItemDeltaReplaceOldValue() throws Exception { PropertyDelta deltaBefore = PropertyDelta.createReplaceEmptyDelta(userDef, UserType.F_COST_CENTER); deltaBefore.setValueToReplace(new PrismPropertyValue("foo")); deltaBefore.addEstimatedOldValue(new PrismPropertyValue("BAR")); - + // WHEN Collection itemDeltaTypes = DeltaConvertor.toItemDeltaTypes(deltaBefore); - + // THEN System.out.println("Serialized"); System.out.println(itemDeltaTypes); - + // WHEN ItemDelta deltaAfter = DeltaConvertor.createItemDelta(itemDeltaTypes.iterator().next(), userDef); - + // THEN System.out.println("Parsed"); System.out.println(deltaAfter.debugDump()); @@ -427,21 +427,21 @@ public void testItemDeltaReplaceEmptyString() throws Exception { PrismObjectDefinition userDef = getUserDefinition(); PropertyDelta deltaBefore = PropertyDelta.createReplaceEmptyDelta(userDef, UserType.F_COST_CENTER); // deltaBefore.setValueToReplace(new PrismPropertyValue("")); - + // WHEN Collection itemDeltaTypes = DeltaConvertor.toItemDeltaTypes(deltaBefore); - + // THEN System.out.println("Serialized"); System.out.println(itemDeltaTypes); - + // WHEN ItemDelta deltaAfter = DeltaConvertor.createItemDelta(itemDeltaTypes.iterator().next(), userDef); // THEN System.out.println("Parsed"); System.out.println(deltaAfter.debugDump()); - + assertEquals("Deltas do not match", deltaBefore, deltaAfter); } @@ -453,24 +453,24 @@ public void testItemDeltaReplaceNil() throws Exception { PrismObjectDefinition userDef = getUserDefinition(); PropertyDelta deltaBefore = PropertyDelta.createReplaceEmptyDelta(userDef, UserType.F_COST_CENTER); // The delta remains empty - + // WHEN Collection itemDeltaTypes = DeltaConvertor.toItemDeltaTypes(deltaBefore); - + // THEN System.out.println("Serialized"); System.out.println(itemDeltaTypes); ItemDeltaType itemDeltaType = itemDeltaTypes.iterator().next(); String xml = PrismTestUtil.serializeAtomicValue(itemDeltaType, new QName("wherever","whatever")); System.out.println(xml); - + // WHEN ItemDelta deltaAfter = DeltaConvertor.createItemDelta(itemDeltaType, userDef); - + // THEN System.out.println("Parsed"); System.out.println(deltaAfter.debugDump()); - + assertEquals("Deltas do not match", deltaBefore, deltaAfter); } diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestDiffEquals.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestDiffEquals.java index 7cabbb387b1..9fcb5d9081b 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestDiffEquals.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestDiffEquals.java @@ -51,9 +51,9 @@ public class TestDiffEquals { public static final File TEST_DIR = new File("src/test/resources/diff"); private static final File ROLE_COMPARE_FILE = new File(TEST_DIR, "role-compare.xml"); - + private static final String NS_TEST_RI = "http://midpoint.evolveum.com/xml/ns/test/ri-1"; - + private static final Trace LOGGER = TraceManager.getTrace(TestDiffEquals.class); @BeforeSuite @@ -108,7 +108,7 @@ public void testUserListSimpleDiff() throws SchemaException { public void testAssignmentEquals1() throws Exception { System.out.println("\n\n===[ testAssignmentEquals1 ]===\n"); PrismContext prismContext = PrismTestUtil.getPrismContext(); - + AssignmentType a1a = new AssignmentType(); prismContext.adopt(a1a); a1a.setDescription("descr1"); @@ -120,21 +120,21 @@ public void testAssignmentEquals1() throws Exception { AssignmentType a1b = new AssignmentType(); prismContext.adopt(a1b); a1b.setDescription("descr1"); - + AssignmentType a1m = new AssignmentType(); prismContext.adopt(a1m); a1m.setDescription("descr1"); MetadataType metadata1m = new MetadataType(); metadata1m.setCreateTimestamp(XmlTypeConverter.createXMLGregorianCalendar(System.currentTimeMillis())); a1m.setMetadata(metadata1m); - + AssignmentType a1e = new AssignmentType(); prismContext.adopt(a1e); a1e.setDescription("descr1"); ActivationType activation1e = new ActivationType(); activation1e.setEffectiveStatus(ActivationStatusType.ENABLED); a1e.setActivation(activation1e); - + // WHEN assertFalse(a1a.equals(a2)); assertFalse(a1b.equals(a2)); @@ -144,13 +144,13 @@ public void testAssignmentEquals1() throws Exception { assertFalse(a2.equals(a1b)); assertFalse(a2.equals(a1m)); assertFalse(a2.equals(a1e)); - + assertTrue(a1a.equals(a1a)); assertTrue(a1b.equals(a1b)); assertTrue(a1m.equals(a1m)); assertTrue(a1e.equals(a1e)); assertTrue(a2.equals(a2)); - + assertTrue(a1a.equals(a1b)); assertTrue(a1b.equals(a1a)); assertTrue(a1a.equals(a1m)); @@ -164,29 +164,29 @@ public void testAssignmentEquals1() throws Exception { assertTrue(a1e.equals(a1b)); assertTrue(a1e.equals(a1m)); } - + @Test(enabled=false) // MID-3966 public void testAssignmentEquals2() throws Exception { System.out.println("\n\n===[ testAssignmentEquals2 ]===\n"); PrismContext prismContext = PrismTestUtil.getPrismContext(); - + PrismObject roleCompare = prismContext.parseObject(ROLE_COMPARE_FILE); PrismContainer inducementContainer = roleCompare.findContainer(RoleType.F_INDUCEMENT); AssignmentType a1 = inducementContainer.findValue(1L).asContainerable(); AssignmentType a2 = inducementContainer.findValue(2L).asContainerable(); - AssignmentType a3 = inducementContainer.findValue(3L).asContainerable(); - + AssignmentType a3 = inducementContainer.findValue(3L).asContainerable(); + // WHEN assertFalse(a1.equals(a3)); assertFalse(a2.equals(a3)); - + assertTrue(a1.equals(a1)); assertTrue(a1.equals(a2)); assertTrue(a2.equals(a1)); assertTrue(a2.equals(a2)); assertTrue(a3.equals(a3)); } - + @Test public void testAssignmentEquivalent() throws Exception { System.out.println("\n\n===[ testAssignmentEquivalent ]===\n"); @@ -279,13 +279,13 @@ public void testContextlessAssignmentEquals2() throws Exception { ObjectDelta delta2 = userWithContext.asPrismObject().createDelta(ChangeType.DELETE); assertNotNull(delta2.getPrismContext()); } - + @Test public void testAssignmentHashcode() throws Exception { LOGGER.info("\n\n===[ testAssignmentHashcode ]===\n"); System.out.println("\n\n===[ testAssignmentHashcode ]===\n"); PrismContext prismContext = PrismTestUtil.getPrismContext(); - + AssignmentType a1a = new AssignmentType(); prismContext.adopt(a1a); a1a.setDescription("descr1"); @@ -297,23 +297,23 @@ public void testAssignmentHashcode() throws Exception { AssignmentType a1b = new AssignmentType(); prismContext.adopt(a1b); a1b.setDescription("descr1"); - + AssignmentType a1m = new AssignmentType(); prismContext.adopt(a1m); a1m.setDescription("descr1"); MetadataType metadata1m = new MetadataType(); metadata1m.setCreateTimestamp(XmlTypeConverter.createXMLGregorianCalendar(System.currentTimeMillis())); a1m.setMetadata(metadata1m); - + AssignmentType a1e = new AssignmentType(); prismContext.adopt(a1e); a1e.setDescription("descr1"); ActivationType activation1e = new ActivationType(); activation1e.setEffectiveStatus(ActivationStatusType.ENABLED); a1e.setActivation(activation1e); - + // WHEN - assertFalse(a1a.hashCode() == a2.hashCode()); + assertFalse(a1a.hashCode() == a2.hashCode()); assertFalse(a1b.hashCode() == a2.hashCode()); assertFalse(a1m.hashCode() == a2.hashCode()); assertFalse(a1e.hashCode() == a2.hashCode()); @@ -321,13 +321,13 @@ public void testAssignmentHashcode() throws Exception { assertFalse(a2.hashCode() == a1b.hashCode()); assertFalse(a2.hashCode() == a1m.hashCode()); assertFalse(a2.hashCode() == a1e.hashCode()); - + assertTrue(a1a.hashCode() == a1a.hashCode()); assertTrue(a1b.hashCode() == a1b.hashCode()); assertTrue(a1m.hashCode() == a1m.hashCode()); assertTrue(a1e.hashCode() == a1e.hashCode()); assertTrue(a2.hashCode() == a2.hashCode()); - + assertTrue(a1a.hashCode() == a1b.hashCode()); assertTrue(a1b.hashCode() == a1a.hashCode()); assertTrue(a1a.hashCode() == a1m.hashCode()); @@ -354,7 +354,7 @@ public void testDiffShadow() throws Exception { shadow1Type.setFailedOperationType(FailedOperationTypeType.ADD); shadow1Type.getAuxiliaryObjectClass().add(new QName(NS_TEST_RI, "foo")); PrismContainer shadow1Attrs = shadow1.findOrCreateContainer(ShadowType.F_ATTRIBUTES); - + ShadowType shadow2Type = new ShadowType(); PrismObject shadow2 = shadow2Type.asPrismObject(); prismContext.adopt(shadow2Type); @@ -362,26 +362,26 @@ public void testDiffShadow() throws Exception { shadow2Type.getAuxiliaryObjectClass().add(new QName(NS_TEST_RI, "foo")); shadow2Type.getAuxiliaryObjectClass().add(new QName(NS_TEST_RI, "bar")); PrismContainer shadow2Attrs = shadow2.findOrCreateContainer(ShadowType.F_ATTRIBUTES); - + PrismProperty attrEntryUuid = new PrismProperty<>(new QName(NS_TEST_RI, "entryUuid"), prismContext); PrismPropertyDefinition attrEntryUuidDef = new PrismPropertyDefinitionImpl<>(new QName(NS_TEST_RI, "entryUuid"), DOMUtil.XSD_STRING, prismContext); attrEntryUuid.setDefinition(attrEntryUuidDef); shadow2Attrs.add(attrEntryUuid); attrEntryUuid.addRealValue("1234-5678-8765-4321"); - + PrismProperty attrDn = new PrismProperty<>(new QName(NS_TEST_RI, "dn"), prismContext); PrismPropertyDefinition attrDnDef = new PrismPropertyDefinitionImpl<>(new QName(NS_TEST_RI, "dn"), DOMUtil.XSD_STRING, prismContext); attrDn.setDefinition(attrDnDef); shadow2Attrs.add(attrDn); attrDn.addRealValue("uid=foo,o=bar"); - + System.out.println("Shadow 1"); System.out.println(shadow1.debugDump(1)); System.out.println("Shadow 2"); System.out.println(shadow2.debugDump(1)); - + // WHEN ObjectDelta delta = shadow1.diff(shadow2); @@ -389,7 +389,7 @@ public void testDiffShadow() throws Exception { assertNotNull("No delta", delta); System.out.println("Delta"); System.out.println(delta.debugDump(1)); - + PrismAsserts.assertIsModify(delta); PrismAsserts.assertPropertyDelete(delta, ShadowType.F_FAILED_OPERATION_TYPE, FailedOperationTypeType.ADD); PrismAsserts.assertPropertyAdd(delta, ShadowType.F_AUXILIARY_OBJECT_CLASS, new QName(NS_TEST_RI, "bar")); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestDynamicSchema.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestDynamicSchema.java index 3b5e14c909f..b0effcd0740 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestDynamicSchema.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestDynamicSchema.java @@ -48,21 +48,21 @@ * */ public class TestDynamicSchema { - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - - + + @Test public void testAssignmentExtensionContainerProperty() throws Exception { System.out.println("===[ testAssignmentExtensionContainerProperty ]==="); // GIVEN PrismContainer assignmentExtensionContainer = parseUserAssignmentContainer(); - + // WHEN PrismProperty assignmentExtensionStringProperty = assignmentExtensionContainer.findOrCreateProperty(EXTENSION_STRING_TYPE_ELEMENT); @@ -78,7 +78,7 @@ public void testAssignmentExtensionContainerItem() throws Exception { // GIVEN PrismContainer assignmentExtensionContainer = parseUserAssignmentContainer(); - + // WHEN PrismProperty assignmentExtensionStringProperty = assignmentExtensionContainer.findOrCreateItem( new ItemPath(EXTENSION_STRING_TYPE_ELEMENT), PrismProperty.class); @@ -96,7 +96,7 @@ public void testAssignmentExtensionValueProperty() throws Exception { // GIVEN PrismContainer assignmentExtensionContainer = parseUserAssignmentContainer(); PrismContainerValue assignmentExtensionContainerValue = assignmentExtensionContainer.getValue(); - + // WHEN PrismProperty assignmentExtensionStringProperty = assignmentExtensionContainerValue.findOrCreateProperty(EXTENSION_STRING_TYPE_ELEMENT); @@ -105,7 +105,7 @@ public void testAssignmentExtensionValueProperty() throws Exception { assertNotNull("stringType has no definition", assignmentExtensionStringProperty.getDefinition()); PrismAsserts.assertDefinition(assignmentExtensionStringProperty.getDefinition(), EXTENSION_STRING_TYPE_ELEMENT, DOMUtil.XSD_STRING, 0, -1); } - + @Test public void testAssignmentExtensionValueItem() throws Exception { System.out.println("===[ testAssignmentExtensionValueItem ]==="); @@ -113,7 +113,7 @@ public void testAssignmentExtensionValueItem() throws Exception { // GIVEN PrismContainer assignmentExtensionContainer = parseUserAssignmentContainer(); PrismContainerValue assignmentExtensionContainerValue = assignmentExtensionContainer.getValue(); - + // WHEN PrismProperty assignmentExtensionStringProperty = assignmentExtensionContainerValue.findOrCreateItem( EXTENSION_STRING_TYPE_ELEMENT, PrismProperty.class); @@ -123,16 +123,16 @@ public void testAssignmentExtensionValueItem() throws Exception { assertNotNull("stringType has no definition", assignmentExtensionStringProperty.getDefinition()); PrismAsserts.assertDefinition(assignmentExtensionStringProperty.getDefinition(), EXTENSION_STRING_TYPE_ELEMENT, DOMUtil.XSD_STRING, 0, -1); } - - - - + + + + private PrismContainer parseUserAssignmentContainer() throws SchemaException, IOException { PrismContext prismContext = PrismTestUtil.getPrismContext(); PrismObject user = prismContext.parseObject(USER_FILE); System.out.println("Parsed user:"); System.out.println(user.debugDump()); - + return user.findContainer( new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestEmptyItems.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestEmptyItems.java index c70388b1084..6d066e9e234 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestEmptyItems.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestEmptyItems.java @@ -38,13 +38,13 @@ * @author mederly */ public class TestEmptyItems { - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - + @Test public void testEmptyItemsOnGet() throws Exception { System.out.println("===[ testEmptyItemsOnGet ]==="); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestFilterSimplifier.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestFilterSimplifier.java index cd2d8f34748..52bd53cf8ba 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestFilterSimplifier.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestFilterSimplifier.java @@ -40,20 +40,20 @@ * */ public class TestFilterSimplifier { - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - + @Test public void test010All() throws Exception { System.out.println("===[ test010All ]==="); // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); - + // WHEN ObjectFilter filter = QueryBuilder.queryFor(UserType.class, prismContext) .all().buildFilter(); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestJaxbConstruction.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestJaxbConstruction.java index dc3fd7cdfb7..774298061ab 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestJaxbConstruction.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestJaxbConstruction.java @@ -66,7 +66,7 @@ * */ public class TestJaxbConstruction { - + private static final String FAUX_RESOURCE_OID = "fuuuuuuuuuuu"; private static final String ACCOUNT_NAME = "jack"; @@ -75,69 +75,69 @@ public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - + @Test public void testUserConstruction() throws JAXBException, SchemaException { System.out.println("\n\n ===[ testUserConstruction ]===\n"); - + // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); - + UserType userType = new UserType(); prismContext.adopt(userType); - + PrismObject user = userType.asPrismObject(); assertNotNull("No object definition after adopt", user.getDefinition()); SchemaTestUtil.assertUserDefinition(user.getDefinition()); - + // fullName: PolyString userType.setFullName(new PolyStringType("Čučoriedka")); PrismProperty fullNameProperty = user.findProperty(UserType.F_FULL_NAME); PolyString fullName = fullNameProperty.getRealValue(); assertEquals("Wrong fullName orig", "Čučoriedka", fullName.getOrig()); assertEquals("Wrong fullName norm", "cucoriedka", fullName.getNorm()); - + // description: setting null value userType.setDescription(null); PrismProperty descriptionProperty = user.findProperty(UserType.F_DESCRIPTION); assertNull("Unexpected description property "+descriptionProperty, descriptionProperty); - + // description: setting null value userType.setDescription("blah blah"); descriptionProperty = user.findProperty(UserType.F_DESCRIPTION); assertEquals("Wrong description value", "blah blah", descriptionProperty.getRealValue()); - + // description: resetting null value userType.setDescription(null); descriptionProperty = user.findProperty(UserType.F_DESCRIPTION); assertNull("Unexpected description property (after reset) "+descriptionProperty, descriptionProperty); - + // Extension ExtensionType extension = new ExtensionType(); userType.setExtension(extension); - + user.checkConsistence(); - + PrismContainer extensionContainer = user.findContainer(GenericObjectType.F_EXTENSION); checkExtension(extensionContainer,"user extension after setExtension"); checkExtension(extension,"user extension after setExtension"); - + AssignmentType assignmentType = new AssignmentType(); userType.getAssignment().add(assignmentType); - + user.checkConsistence(); user.assertDefinitions(); - + // Assignment ExtensionType assignmentExtension = new ExtensionType(); assignmentType.setExtension(assignmentExtension); - + user.assertDefinitions(); user.checkConsistence(); checkExtension(assignmentExtension,"assignment extension after setExtension"); user.checkConsistence(); user.assertDefinitions(); - + // accountRef/account ObjectReferenceType accountRefType = new ObjectReferenceType(); accountRefType.setOid(USER_ACCOUNT_REF_1_OID); @@ -146,7 +146,7 @@ public void testUserConstruction() throws JAXBException, SchemaException { filter.setFilterClauseXNode(filterElement); accountRefType.setFilter(filter); userType.getLinkRef().add(accountRefType); - + assertAccountRefs(userType, USER_ACCOUNT_REF_1_OID); user.checkConsistence(); user.assertDefinitions(); @@ -172,49 +172,49 @@ public void testUserConstruction() throws JAXBException, SchemaException { userType.getLink().add(accountShadowType); assertEquals("3/ Wrong accountRef values", 2, user.findReference(UserType.F_LINK_REF).getValues().size()); - + assertAccountRefs(userType, USER_ACCOUNT_REF_1_OID, USER_ACCOUNT_REF_2_OID); user.checkConsistence(); user.assertDefinitions(); - + assertEquals("4/ Wrong accountRef values", 2, accountRef.getValues().size()); PrismAsserts.assertReferenceValues(accountRef, USER_ACCOUNT_REF_1_OID, USER_ACCOUNT_REF_2_OID); - + } @Test public void testUserConstructionBeforeAdopt() throws Exception { System.out.println("\n\n ===[ testUserConstructionBeforeAdopt ]===\n"); - + // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); - + UserType userType = new UserType(); - + userType.setFullName(new PolyStringType("Čučoriedka")); userType.setDescription("blah blah"); ExtensionType extension = new ExtensionType(); userType.setExtension(extension); - + AssignmentType assignmentType = new AssignmentType(); userType.getAssignment().add(assignmentType); - + // Assignment ExtensionType assignmentExtension = new ExtensionType(); assignmentType.setExtension(assignmentExtension); - - + + // accountRef/account ObjectReferenceType accountRefType = new ObjectReferenceType(); accountRefType.setOid(USER_ACCOUNT_REF_1_OID); - + MapXNode filterElement = createFilter(); SearchFilterType filter = new SearchFilterType(); filter.setFilterClauseXNode(filterElement); accountRefType.setFilter(filter); userType.getLinkRef().add(accountRefType); - + ShadowType accountShadowType = new ShadowType(); accountShadowType.setOid(USER_ACCOUNT_REF_1_OID); @@ -226,44 +226,44 @@ public void testUserConstructionBeforeAdopt() throws Exception { // WHEN prismContext.adopt(userType); - + // THEN PrismObject user = userType.asPrismObject(); assertNotNull("No object definition after adopt", user.getDefinition()); SchemaTestUtil.assertUserDefinition(user.getDefinition()); - + // fullName: PolyString PrismProperty fullNameProperty = user.findProperty(UserType.F_FULL_NAME); user.checkConsistence(); user.assertDefinitions(); - - + + PolyString fullName = fullNameProperty.getRealValue(); assertEquals("Wrong fullName orig", "Čučoriedka", fullName.getOrig()); assertEquals("Wrong fullName norm", "cucoriedka", fullName.getNorm()); - + PrismProperty descriptionProperty = user.findProperty(UserType.F_DESCRIPTION); assertEquals("Wrong description value", "blah blah", descriptionProperty.getRealValue()); - + PrismContainer extensionContainer = user.findContainer(GenericObjectType.F_EXTENSION); checkExtension(extensionContainer,"user extension"); checkExtension(extension,"user extension"); - + PrismReference accountRef = user.findReference(UserType.F_LINK_REF); assertEquals("Wrong accountRef values", 2, accountRef.getValues().size()); PrismAsserts.assertReferenceValues(accountRef, USER_ACCOUNT_REF_1_OID, USER_ACCOUNT_REF_2_OID); - + PrismReferenceValue accountRefVal0 = accountRef.getValue(0); SearchFilterType prismFilter = accountRefVal0.getFilter(); assertNotNull("Filter have not passed", prismFilter); // assertTrue("Wrong filter in reference " , prismFilter instanceof EqualsFilter); // assertEquals("Difference filter", filterElement, prismFilter); - + assertAccountRefs(userType, USER_ACCOUNT_REF_1_OID, USER_ACCOUNT_REF_2_OID); user.assertDefinitions(); user.checkConsistence(); - + } @@ -291,43 +291,43 @@ private void assertAccountRef(List accountRefs, String expe @Test public void testUserConstructionReverse() throws JAXBException, SchemaException { System.out.println("\n\n ===[ testUserConstructionReverse ]===\n"); - + // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); - + UserType userType = new UserType(prismContext); PrismObject user = userType.asPrismObject(); assertNotNull("No object definition after adopt", user.getDefinition()); - + // Extension ExtensionType extension = new ExtensionType(); userType.setExtension(extension); - + user.checkConsistence(); - + PrismContainer extensionContainer = user.findContainer(GenericObjectType.F_EXTENSION); checkExtension(extensionContainer,"user extension after setExtension"); checkExtension(extension,"user extension after setExtension"); - + AssignmentType assignmentType = new AssignmentType(prismContext); ExtensionType assignmentExtension = new ExtensionType(); assignmentType.setExtension(assignmentExtension); - + PrismContainerValue assignmentExtensionValueFromJaxb = assignmentExtension.asPrismContainerValue(); PrismProperty intProperty = assignmentExtensionValueFromJaxb.findOrCreateProperty(EXTENSION_INT_TYPE_ELEMENT); intProperty.setRealValue(15); - + PrismProperty stringProperty = assignmentExtensionValueFromJaxb.findOrCreateItem(EXTENSION_STRING_TYPE_ELEMENT, PrismProperty.class); stringProperty.setRealValue("fifteen men on a dead man chest"); // Adding assignemnt to the user should cause application of definitions userType.getAssignment().add(assignmentType); - PrismAsserts.assertDefinition(assignmentType.asPrismContainerValue().getParent().getDefinition(), + PrismAsserts.assertDefinition(assignmentType.asPrismContainerValue().getParent().getDefinition(), UserType.F_ASSIGNMENT, AssignmentType.COMPLEX_TYPE, 0, -1); - PrismAsserts.assertDefinition(assignmentExtensionValueFromJaxb.getParent().getDefinition(), + PrismAsserts.assertDefinition(assignmentExtensionValueFromJaxb.getParent().getDefinition(), AssignmentType.F_EXTENSION, ExtensionType.COMPLEX_TYPE, 0, 1); assertTrue("assignment extension definition is not runtime", assignmentExtensionValueFromJaxb.getParent().getDefinition().isRuntimeSchema()); assertTrue("assignment extension definition is not dynamic", assignmentExtensionValueFromJaxb.getParent().getDefinition().isDynamic()); @@ -343,50 +343,50 @@ public void testUserConstructionReverse() throws JAXBException, SchemaException @Test public void testGenericConstruction() throws JAXBException, SchemaException { System.out.println("\n\n ===[ testGenericConstruction ]===\n"); - + // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); - + GenericObjectType genericType = new GenericObjectType(); prismContext.adopt(genericType); - + PrismObject generic = genericType.asPrismObject(); assertNotNull("No object definition after adopt", generic.getDefinition()); - + // WHEN ExtensionType extension = new ExtensionType(); genericType.setExtension(extension); - + // THEN generic.checkConsistence(); - + PrismContainer extensionContainer = generic.findContainer(GenericObjectType.F_EXTENSION); checkExtension(extensionContainer,"user extension after setExtension"); checkExtension(extension,"user extension after setExtension"); - + generic.checkConsistence(); } - + @Test public void testAccountConstruction() throws JAXBException, SchemaException { System.out.println("\n\n ===[ testAccountConstruction ]===\n"); - + // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); - + ShadowType accountType = new ShadowType(); prismContext.adopt(accountType); - + PrismObject account = accountType.asPrismObject(); assertNotNull("No object definition after adopt", account.getDefinition()); - + // WHEN accountType.setName(PrismTestUtil.createPolyStringType(ACCOUNT_NAME)); ObjectReferenceType resourceRefType = new ObjectReferenceType(); resourceRefType.setOid(FAUX_RESOURCE_OID); resourceRefType.setType(ResourceType.COMPLEX_TYPE); accountType.setResourceRef(resourceRefType); - + // THEN (prism) account.checkConsistence(); PrismAsserts.assertPropertyValue(account, ShadowType.F_NAME, PrismTestUtil.createPolyString(ACCOUNT_NAME)); @@ -398,7 +398,7 @@ public void testAccountConstruction() throws JAXBException, SchemaException { assertEquals("Wrong type in resourceRef value", ResourceType.COMPLEX_TYPE, resourceRefVal.getTargetType()); // Element filter = resourceRefVal.getFilter(); // assertNotNull("No filter in resourceRef value", filter); - + // THEN (JAXB) assertEquals("Wrong name (JAXB)", PrismTestUtil.createPolyStringType(ACCOUNT_NAME), accountType.getName()); resourceRefType = accountType.getResourceRef(); @@ -411,20 +411,20 @@ public void testAccountConstruction() throws JAXBException, SchemaException { // assertNotNull("No filter element in connectorRef value (JAXB)", filterElement); } - + @Test public void testExtensionTypeConstruction() throws Exception { System.out.println("\n\n ===[ testExtensionTypeConstruction ]===\n"); - + // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); - + GenericObjectType object = new GenericObjectType(); prismContext.adopt(object.asPrismObject(), GenericObjectType.class); ExtensionType extension = new ExtensionType(); object.setExtension(extension); - + PrismContainerValue extValue = extension.asPrismContainerValue(); assertNotNull("No extension definition", extValue.getParent().getDefinition()); @@ -435,98 +435,98 @@ public void testExtensionTypeConstruction() throws Exception { assertNotNull(item); object.asPrismObject().checkConsistence(); } - + @Test public void testResourceConstruction() throws Exception { System.out.println("\n\n ===[ testResourceConstruction ]===\n"); - + // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); - + ResourceType resourceType = new ResourceType(); prismContext.adopt(resourceType); - + PrismObject resource = resourceType.asPrismObject(); assertNotNull("No object definition after adopt", resource.getDefinition()); - + // name: PolyString resourceType.setName(new PolyStringType("Môj risórs")); PrismProperty fullNameProperty = resource.findProperty(ResourceType.F_NAME); PolyString fullName = fullNameProperty.getRealValue(); assertEquals("Wrong name orig", "Môj risórs", fullName.getOrig()); assertEquals("Wrong name norm", "moj risors", fullName.getNorm()); - + // description: setting null value resourceType.setDescription(null); PrismProperty descriptionProperty = resource.findProperty(UserType.F_DESCRIPTION); assertNull("Unexpected description property "+descriptionProperty, descriptionProperty); - + // description: setting null value resourceType.setDescription("blah blah"); descriptionProperty = resource.findProperty(UserType.F_DESCRIPTION); assertEquals("Wrong description value", "blah blah", descriptionProperty.getRealValue()); - + // description: resetting null value resourceType.setDescription(null); descriptionProperty = resource.findProperty(UserType.F_DESCRIPTION); assertNull("Unexpected description property (after reset) "+descriptionProperty, descriptionProperty); - + // Extension ExtensionType extension = new ExtensionType(); resourceType.setExtension(extension); - + resource.checkConsistence(); - + PrismContainer extensionContainer = resource.findContainer(GenericObjectType.F_EXTENSION); checkExtension(extensionContainer,"resource extension after setExtension"); checkExtension(extension,"resource extension after setExtension"); - + // Schema XmlSchemaType xmlSchemaType = new XmlSchemaType(); CachingMetadataType cachingMetadata = new CachingMetadataType(); cachingMetadata.setSerialNumber("serial123"); xmlSchemaType.setCachingMetadata(cachingMetadata); - + resourceType.setSchema(xmlSchemaType); - + SchemaDefinitionType schemaDefinition = new SchemaDefinitionType(); - Element xsdSchemaElement = DOMUtil.createElement(DOMUtil.XSD_SCHEMA_ELEMENT); + Element xsdSchemaElement = DOMUtil.createElement(DOMUtil.XSD_SCHEMA_ELEMENT); schemaDefinition.getAny().add(xsdSchemaElement); xmlSchemaType.setDefinition(schemaDefinition); PrismContainer schemaContainer = resource.findContainer(ResourceType.F_SCHEMA); assertNotNull("No schema container", schemaContainer); - + // TODO - + // Schema: null resourceType.setSchema(null); schemaContainer = resource.findContainer(ResourceType.F_SCHEMA); assertNull("Unexpected schema container", schemaContainer); - + } - + private void checkExtension(PrismContainer extensionContainer, String sourceDescription) { assertNotNull("No extension container in "+sourceDescription+" (prism)", extensionContainer); assertNotNull("No extension definition in "+sourceDescription+" (prism)", extensionContainer.getDefinition()); - assertTrue("Not runtime in definition in "+sourceDescription+" (prism)", extensionContainer.getDefinition().isRuntimeSchema()); + assertTrue("Not runtime in definition in "+sourceDescription+" (prism)", extensionContainer.getDefinition().isRuntimeSchema()); } - + private void checkExtension(ExtensionType extension, String sourceDescription) throws SchemaException { PrismContainerValue extensionValueFromJaxb = extension.asPrismContainerValue(); assertNotNull("No extension container in "+sourceDescription+" (jaxb)", extensionValueFromJaxb); assertNotNull("No extension definition in "+sourceDescription+" (jaxb)", extensionValueFromJaxb.getParent().getDefinition()); assertTrue("Not runtime in definition in "+sourceDescription+" (jaxb)", extensionValueFromJaxb.getParent().getDefinition().isRuntimeSchema()); - + PrismProperty intProperty = extensionValueFromJaxb.findOrCreateProperty(EXTENSION_INT_TYPE_ELEMENT); PrismAsserts.assertDefinition(intProperty.getDefinition(), EXTENSION_INT_TYPE_ELEMENT, DOMUtil.XSD_INT, 0, -1); intProperty.setRealValue(15); - + PrismProperty stringProperty = extensionValueFromJaxb.findOrCreateItem(EXTENSION_STRING_TYPE_ELEMENT, PrismProperty.class); PrismAsserts.assertDefinition(stringProperty.getDefinition(), EXTENSION_STRING_TYPE_ELEMENT, DOMUtil.XSD_STRING, 0, -1); stringProperty.setRealValue("fifteen men on a dead man chest"); } - + private MapXNode createFilter(){ MapXNode filter = new MapXNode(); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestJaxbParsing.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestJaxbParsing.java index 99cae954bbd..bd6930f2388 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestJaxbParsing.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestJaxbParsing.java @@ -134,9 +134,9 @@ public void testParseAccountFromJaxb() throws SchemaException, SAXException, IOE System.out.println("Parsed account:"); System.out.println(account.debugDump()); - account.checkConsistence(); + account.checkConsistence(); assertPropertyValue(account, ShadowType.F_NAME, PrismTestUtil.createPolyString("jack")); - assertPropertyValue(account, ShadowType.F_OBJECT_CLASS, + assertPropertyValue(account, ShadowType.F_OBJECT_CLASS, new QName("http://midpoint.evolveum.com/xml/ns/public/resource/instance/ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff", "AccountObjectClass")); assertPropertyValue(account, ShadowType.F_INTENT, "default"); @@ -180,21 +180,21 @@ public void testParseGenericObjectFromJaxb() throws Exception { PrismObject prism = object.asPrismObject(); prism.revive(prismContext); - prism.checkConsistence(); + prism.checkConsistence(); assertPropertyValue(prism, GenericObjectType.F_NAME, PrismTestUtil.createPolyString("My Sample Config Object")); assertPropertyValue(prism, GenericObjectType.F_DESCRIPTION, "Sample description"); assertPropertyValue(prism, GenericObjectType.F_OBJECT_TYPE, "http://midpoint.evolveum.com/xml/ns/test/extension#SampleConfigType"); //assert extension PrismContainer extension = prism.findContainer(GenericObjectType.F_EXTENSION); assertNotNull(extension); - + PrismAsserts.assertPropertyValue(extension, SchemaTestConstants.EXTENSION_STRING_TYPE_ELEMENT, "X marks the spot"); PrismAsserts.assertPropertyValue(extension, SchemaTestConstants.EXTENSION_INT_TYPE_ELEMENT, 1234); PrismAsserts.assertPropertyValue(extension, SchemaTestConstants.EXTENSION_DOUBLE_TYPE_ELEMENT, 456.789D); PrismAsserts.assertPropertyValue(extension, SchemaTestConstants.EXTENSION_LONG_TYPE_ELEMENT, 567890L); XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar("2002-05-30T09:10:11"); PrismAsserts.assertPropertyValue(extension, SchemaTestConstants.EXTENSION_DATE_TYPE_ELEMENT, calendar); - + //todo locations ????? how to test DOM ?????? } @@ -261,7 +261,7 @@ public void testParseValueFilterWithAny() throws Exception { Document doc = DOMUtil.parseFile(new File(TestConstants.COMMON_DIR, "value-filter-with-any.xml")); Element rootElement = DOMUtil.getFirstChildElement(doc); - + // WHEN Object parsedObject = prismContext.parserFor(rootElement).parseRealValue(); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestJaxbSanity.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestJaxbSanity.java index 782db9634c3..e2524d66f1e 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestJaxbSanity.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestJaxbSanity.java @@ -60,17 +60,17 @@ public class TestJaxbSanity { public static final String TEST_DIR = "src/test/resources/common"; public static final String USER_BARBOSSA_FILENAME = TEST_DIR + "/user-barbossa.xml"; public static final String RESOURCE_OPENDJ_FILENAME = TEST_DIR + "/resource-opendj.xml"; - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - + @Test public void testGeneratedEquals() throws JAXBException { System.out.println("\n\n ===[ testGeneratedEquals ]===\n"); - + assertHasEquals(ObjectType.class); assertHasEquals(AssignmentType.class); assertHasEquals(MappingType.class); @@ -81,7 +81,7 @@ public void testGeneratedEquals() throws JAXBException { assertHasHashCode(MappingType.class); assertHasHashCode(ProtectedStringType.class); } - + private void assertHasEquals(Class clazz) { try { Method method = clazz.getDeclaredMethod("equals", Object.class); @@ -92,7 +92,7 @@ private void assertHasEquals(Class clazz) { AssertJUnit.fail("No equals method in "+clazz.getSimpleName()); } } - + private void assertHasHashCode(Class clazz) { try { Method method = clazz.getDeclaredMethod("hashCode"); @@ -107,54 +107,54 @@ private void assertHasHashCode(Class clazz) { @Test public void testUnmarshallAndEqualsUserJaxb() throws Exception { System.out.println("\n\n ===[ testUnmarshallAndEqualsUserJaxb ]===\n"); - + // GIVEN JAXBElement userEl1 = JaxbTestUtil.getInstance().unmarshalElement(new File(USER_BARBOSSA_FILENAME),UserType.class); UserType user1Type = userEl1.getValue(); assertNotNull(user1Type); PrismObject user1 = user1Type.asPrismObject(); - + JAXBElement userEl2 = JaxbTestUtil.getInstance().unmarshalElement(new File(USER_BARBOSSA_FILENAME),UserType.class); UserType user2Type = userEl2.getValue(); assertNotNull(user2Type); PrismObject user2 = user2Type.asPrismObject(); - + // Compare plain JAXB objects (not backed by containers) ConstructionType ac1 = user1Type.getAssignment().get(0).getConstruction(); ConstructionType ac2 = user2Type.getAssignment().get(0).getConstruction(); assertTrue("ConstructionType not equals", ac1.equals(ac2)); - + // WHEN, THEN ObjectDelta objectDelta = user1.diff(user2); System.out.println("User delta:"); System.out.println(objectDelta.debugDump()); assertTrue("User delta is not empty", objectDelta.isEmpty()); - + assertTrue("User not equals (PrismObject)", user1.equals(user2)); assertTrue("User not equivalent (PrismObject)", user1.equivalent(user2)); assertTrue("User not equals (Objectable)", user1Type.equals(user2Type)); - + assertTrue("HashCode does not match (PrismObject)", user1.hashCode() == user2.hashCode()); assertTrue("HashCode does not match (Objectable)", user1Type.hashCode() == user2Type.hashCode()); } - + @Test public void testUnmarshallAndEqualsUserPrism() throws Exception { System.out.println("\n\n ===[testUnmarshallAndEqualsUserPrism]===\n"); - + // GIVEN PrismObject user1 = PrismTestUtil.parseObject(new File(USER_BARBOSSA_FILENAME)); UserType user1Type = user1.asObjectable(); - + PrismObject user2 = PrismTestUtil.parseObject(new File(USER_BARBOSSA_FILENAME)); UserType user2Type = user2.asObjectable(); - + // Compare plain JAXB objects (not backed by containers) ConstructionType ac1 = user1Type.getAssignment().get(0).getConstruction(); ConstructionType ac2 = user2Type.getAssignment().get(0).getConstruction(); assertTrue("ConstructionType not equals (JAXB)", ac1.equals(ac2)); assertTrue("ConstructionType hashcode does not match (JAXB)", ac1.hashCode() == ac2.hashCode()); - + AssignmentType as1Type = user1Type.getAssignment().get(0); PrismContainerValue as1ContVal = as1Type.asPrismContainerValue(); PrismContainer as1Cont = as1ContVal.getContainer(); @@ -170,20 +170,20 @@ public void testUnmarshallAndEqualsUserPrism() throws Exception { assertTrue("AssignmentType not equals (JAXB)", as1Type.equals(as2Type)); assertTrue("Assignment hashcode does not match (Container)", as1Cont.hashCode() == as2Cont.hashCode()); assertTrue("Assignment hashcode does not match (Objectable)", as1Type.hashCode() == as2Type.hashCode()); - + // Compare object inner value assertTrue("User prism values do not match", user1.getValue().equals(user2.getValue())); - + // WHEN, THEN ObjectDelta objectDelta = user1.diff(user1); System.out.println("User delta:"); System.out.println(objectDelta.debugDump()); assertTrue("User delta is not empty", objectDelta.isEmpty()); - + assertTrue("User not equals (PrismObject)", user1.equals(user2)); assertTrue("User not equivalent (PrismObject)", user1.equivalent(user2)); assertTrue("User not equals (Objectable)", user1Type.equals(user2Type)); - + assertTrue("User hashcode does not match (PrismObject)", user1.hashCode() == user2.hashCode()); assertTrue("User hashcode does not match (Objectable)", user1Type.hashCode() == user2Type.hashCode()); } @@ -191,16 +191,16 @@ public void testUnmarshallAndEqualsUserPrism() throws Exception { @Test public void testUnmarshallAndEqualsUserMixed() throws Exception { System.out.println("\n\n ===[testUnmarshallAndEqualsUserMixed]===\n"); - + // GIVEN PrismObject user1 = PrismTestUtil.parseObject(new File(USER_BARBOSSA_FILENAME)); UserType user1Type = user1.asObjectable(); - + JAXBElement userEl2 = JaxbTestUtil.getInstance().unmarshalElement(new File(USER_BARBOSSA_FILENAME),UserType.class); UserType user2Type = userEl2.getValue(); assertNotNull(user2Type); PrismObject user2 = user2Type.asPrismObject(); - + // Compare plain JAXB objects (not backed by containers) ConstructionType ac1 = user1Type.getAssignment().get(0).getConstruction(); ConstructionType ac2 = user2Type.getAssignment().get(0).getConstruction(); @@ -211,77 +211,77 @@ public void testUnmarshallAndEqualsUserMixed() throws Exception { assertTrue("User not equals (PrismObject)", user1.equals(user2)); assertTrue("User not equivalent (PrismObject)", user1.equivalent(user2)); assertTrue("User not equals (Objectable)", user1Type.equals(user2Type)); - + assertTrue("HashCode does not match (PrismObject)", user1.hashCode() == user2.hashCode()); assertTrue("HashCode does not match (Objectable)", user1Type.hashCode() == user2Type.hashCode()); } - + @Test public void testUnmarshallAndEqualsResourceSchema() throws JAXBException, SchemaException, FileNotFoundException { System.out.println("\n\n ===[testUnmarshallAndEqualsResourceSchema]===\n"); - + // GIVEN ResourceType resource1Type = JaxbTestUtil.getInstance().unmarshalObject(new File(RESOURCE_OPENDJ_FILENAME), ResourceType.class); assertNotNull(resource1Type); SchemaDefinitionType schemaDefinition1 = resource1Type.getSchema().getDefinition(); - + ResourceType resource2Type = JaxbTestUtil.getInstance().unmarshalObject(new File(RESOURCE_OPENDJ_FILENAME), ResourceType.class); assertNotNull(resource2Type); SchemaDefinitionType schemaDefinition2 = resource2Type.getSchema().getDefinition(); - + // WHEN boolean equals = schemaDefinition1.equals(schemaDefinition2); - + // THEN assertTrue("Schema definition not equal", equals); - + assertEquals("Hashcode does not match", schemaDefinition1.hashCode(), schemaDefinition2.hashCode()); } - + @Test public void testUnmarshallAndEqualsResource() throws JAXBException, SchemaException, FileNotFoundException { System.out.println("\n\n ===[testUnmarshallAndEqualsResource]===\n"); - + // GIVEN ResourceType resource1Type = JaxbTestUtil.getInstance().unmarshalObject(new File(RESOURCE_OPENDJ_FILENAME), ResourceType.class); assertNotNull(resource1Type); System.out.println("Resource1 " + resource1Type.asPrismObject().debugDump()); PrismObject resource1 = resource1Type.asPrismObject(); - + ResourceType resource2Type = JaxbTestUtil.getInstance().unmarshalObject(new File(RESOURCE_OPENDJ_FILENAME), ResourceType.class); assertNotNull(resource2Type); System.out.println("Resource2 " + resource2Type.asPrismObject().debugDump()); PrismObject resource2 = resource2Type.asPrismObject(); - + // WHEN, THEN ObjectDelta objectDelta = resource1.diff(resource2); System.out.println("Resource delta:"); System.out.println(objectDelta.debugDump()); assertTrue("Resource delta is not empty", objectDelta.isEmpty()); - + assertTrue("Resource not equal", resource1Type.equals(resource2Type)); - + System.out.println("HASH"); System.out.println(resource1Type.hashCode()); System.out.println(resource2Type.hashCode()); assertTrue("Resource hashcode does not match", resource1Type.hashCode() == resource2Type.hashCode()); - + PrismPropertyValue pv1 = new PrismPropertyValue(resource1Type.getConnectorConfiguration()); PrismPropertyValue pv2 = new PrismPropertyValue(resource2Type.getConnectorConfiguration()); - + assertTrue("Real property values not equal",pv1.equalsRealValue(pv2)); } @Test public void testAssignmentEquals() throws JAXBException, SchemaException, FileNotFoundException { System.out.println("\n\n ===[testAssnignmentEquals]===\n"); - + // GIVEN JAXBElement userEl1 = JaxbTestUtil.getInstance().unmarshalElement(new File(USER_BARBOSSA_FILENAME), UserType.class); UserType user = userEl1.getValue(); assertNotNull(user); - + AssignmentType userAssignmentType = user.getAssignment().get(0); assertNotNull(userAssignmentType); @@ -291,7 +291,7 @@ public void testAssignmentEquals() throws JAXBException, SchemaException, FileNo JAXBElement modEl = JaxbTestUtil.getInstance().unmarshalElement(new File(TEST_DIR, "user-barbossa-modify-delete-assignment-account-opendj-attr.xml"),ObjectModificationType.class); ObjectModificationType mod = modEl.getValue(); assertNotNull(mod); - + //FIXME : modification value -> rawType... RawType rawType = mod.getItemDelta().get(0).getValue().get(0); ItemDefinition assignmentDefinition = PrismTestUtil.getPrismContext().getSchemaRegistry().findContainerDefinitionByCompileTimeClass(AssignmentType.class); @@ -299,14 +299,14 @@ public void testAssignmentEquals() throws JAXBException, SchemaException, FileNo AssignmentType assignmentType = ((PrismContainerValue) rawType.getParsedValue(assignmentDefinition, null)).getValue(); // was: (JAXBElement) mod.getItemDelta().get(0).getValue().get(0).getContent().get(0); assertNotNull(assignmentType); - + System.out.println("\n*** assignment"); System.out.println(PrismTestUtil.serializeAnyDataWrapped(assignmentType)); - + // WHEN, THEN - + assertTrue("Assignment not equals", userAssignmentType.equals(assignmentType)); - + assertTrue("HashCode does not match", userAssignmentType.hashCode() == assignmentType.hashCode()); } diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestObjectConstruction.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestObjectConstruction.java index 6f9536c33fb..5325a24d0d5 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestObjectConstruction.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestObjectConstruction.java @@ -40,45 +40,45 @@ * */ public class TestObjectConstruction { - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - + @Test public void testUserConstruction() throws Exception { System.out.println("\n\n ===[ testUserConstruction ]===\n"); - + // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); - + // WHEN PrismObject user = prismContext.createObject(UserType.class); - + // THEN assertNotNull(user); - SchemaTestUtil.assertUserDefinition(user.getDefinition()); + SchemaTestUtil.assertUserDefinition(user.getDefinition()); } - + @Test public void testObjectTypeConstruction() throws Exception { System.out.println("\n\n ===[ testObjectTypeConstruction ]===\n"); - + // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); - + try { // WHEN PrismObject object = prismContext.createObject(ObjectType.class); - + fail("unexpected success"); } catch (SchemaException e) { // This is expected, abstract object types cannot be instantiated assertTrue(e.getMessage().contains("abstract")); } - + } diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestOperationResult.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestOperationResult.java index 35abc60e6c8..f3abf35da70 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestOperationResult.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestOperationResult.java @@ -38,13 +38,13 @@ * */ public class TestOperationResult { - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - + @Test public void testCleanup() throws Exception { System.out.println("===[ testCleanup ]==="); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseDiffPatch.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseDiffPatch.java index 6fd6486b003..d91d453c1be 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseDiffPatch.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseDiffPatch.java @@ -72,7 +72,7 @@ public class TestParseDiffPatch { private static final String TEST_DIR = "src/test/resources/diff/"; - + private static final File USER_BEFORE_FILE = new File(TEST_DIR, "user-before.xml"); private static final File USER_AFTER_FILE = new File(TEST_DIR, "user-after.xml"); private static final File TASK_BEFORE_FILE = new File(TEST_DIR, "task-before.xml"); @@ -116,7 +116,7 @@ public void testUserCredentialsDiff() throws Exception { assertNotNull("Property delta for "+path+" not found",propertyDelta); assertEquals(1, propertyDelta.getValuesToAdd().size()); } - + //@Test public void testAssignmentActivationDiff() throws Exception { System.out.println("===[ testUserCredentialsDiff ]==="); @@ -128,14 +128,14 @@ public void testAssignmentActivationDiff() throws Exception { activation.setAdministrativeStatus(ActivationStatusType.DISABLED); assignmentBefore.setActivation(activation); userBefore.asObjectable().getAssignment().add(assignmentBefore); - + AssignmentType assignmentAfter = new AssignmentType(); activation = new ActivationType(); activation.setAdministrativeStatus(ActivationStatusType.ENABLED); assignmentAfter.setActivation(activation); userAfter.asObjectable().getAssignment().add(assignmentAfter); - + Collection userDelta = assignmentBefore.asPrismContainerValue().diff(assignmentAfter.asPrismContainerValue()); // ObjectDelta userDelta = userBefore.diff(userAfter); System.out.println("DELTA:"); @@ -145,7 +145,7 @@ public void testAssignmentActivationDiff() throws Exception { // userAfter.checkConsistence(); // userDelta.checkConsistence(); // userDelta.assertDefinitions(); - + ItemDelta assignmentDelta = userDelta.iterator().next(); System.out.println("Assignment delta: " + assignmentDelta); System.out.println("Assignment delta: " + assignmentDelta.debugDump()); @@ -158,7 +158,7 @@ public void testAssignmentActivationDiff() throws Exception { PropertyDelta propertyDelta = ItemDelta.findPropertyDelta(userDelta, path); assertNotNull("Property delta for "+path+" not found",propertyDelta); // assertEquals(1, propertyDelta.getValuesToAdd().size()); - + assignmentAfter = new AssignmentType(); activation = new ActivationType(); activation.setAdministrativeStatus(null); @@ -172,7 +172,7 @@ public void testAssignmentActivationDiff() throws Exception { // userAfter.checkConsistence(); // userDelta.checkConsistence(); // userDelta.assertDefinitions(); - + assignmentDelta = userDelta.iterator().next(); System.out.println("Assignment delta: " + assignmentDelta); System.out.println("Assignment delta: " + assignmentDelta.debugDump()); @@ -184,8 +184,8 @@ public void testAssignmentActivationDiff() throws Exception { // CredentialsType.F_PASSWORD, PasswordType.F_FAILED_LOGINS); propertyDelta = ItemDelta.findPropertyDelta(userDelta, path); - - + + userDelta = assignmentAfter.asPrismContainerValue().diff(assignmentBefore.asPrismContainerValue()); // ObjectDelta userDelta = userBefore.diff(userAfter); System.out.println("DELTA:"); @@ -195,7 +195,7 @@ public void testAssignmentActivationDiff() throws Exception { // userAfter.checkConsistence(); // userDelta.checkConsistence(); // userDelta.assertDefinitions(); - + assignmentDelta = userDelta.iterator().next(); System.out.println("Assignment delta: " + assignmentDelta); System.out.println("Assignment delta: " + assignmentDelta.debugDump()); @@ -241,9 +241,9 @@ public void testUser() throws SchemaException, SAXException, IOException, JAXBEx assertEquals("Unexpected number of modifications", 3, modifications.size()); PrismAsserts.assertPropertyReplace(userDelta, new QName(SchemaConstants.NS_C,"fullName"), new PolyString("Cpt. Jack Sparrow", "cpt jack sparrow")); - PrismAsserts.assertPropertyAdd(userDelta, new QName(SchemaConstants.NS_C,"honorificPrefix"), + PrismAsserts.assertPropertyAdd(userDelta, new QName(SchemaConstants.NS_C,"honorificPrefix"), new PolyString("Cpt.", "cpt")); - PrismAsserts.assertPropertyAdd(userDelta, new QName(SchemaConstants.NS_C,"locality"), + PrismAsserts.assertPropertyAdd(userDelta, new QName(SchemaConstants.NS_C,"locality"), new PolyString("Tortuga", "tortuga")); ObjectModificationType objectModificationType = DeltaConvertor.toObjectModificationType(userDelta); @@ -309,10 +309,10 @@ public void testUserReal() throws SchemaException, SAXException, IOException, JA Collection modifications = userDelta.getModifications(); assertEquals("Unexpected number of modifications", 4, modifications.size()); PrismAsserts.assertPropertyReplace(userDelta, new QName(SchemaConstants.NS_C,"emailAddress"), "jack@blackpearl.com"); - PrismAsserts.assertPropertyReplace(userDelta, new QName(SchemaConstants.NS_C,"locality"), + PrismAsserts.assertPropertyReplace(userDelta, new QName(SchemaConstants.NS_C,"locality"), new PolyString("World's End", "worlds end")); PrismAsserts.assertPropertyReplace(userDelta, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, ActivationStatusType.DISABLED); - PrismAsserts.assertPropertyAdd(userDelta, new QName(SchemaConstants.NS_C,"organizationalUnit"), + PrismAsserts.assertPropertyAdd(userDelta, new QName(SchemaConstants.NS_C,"organizationalUnit"), new PolyString("Brethren of the Coast", "brethren of the coast")); } @@ -611,7 +611,7 @@ public void testResourceRoundTrip() throws SchemaException, SAXException, IOExce resourceBefore.checkConsistence(); resourceAfter.checkConsistence(); } - + @Test public void testResourceNsChange() throws SchemaException, SAXException, IOException, JAXBException { System.out.println("===[ testResourceNsChange ]==="); @@ -639,12 +639,12 @@ public void testResourceNsChange() throws SchemaException, SAXException, IOExcep if (!resourceDelta.isEmpty()) { AssertJUnit.fail("The delta is not empty; it is "+resourceDelta); } - - // "post" sanity + + // "post" sanity assertTrue("equals does not work", resourceBefore.equals(resourceAfter)); assertTrue("equivalent does not work", resourceBefore.equivalent(resourceAfter)); } - + @Test public void testResourceNsChangeLiteral() throws SchemaException, SAXException, IOException, JAXBException { System.out.println("===[ testResourceNsChangeLiteral ]==="); @@ -669,7 +669,7 @@ public void testResourceNsChangeLiteral() throws SchemaException, SAXException, resourceAfter.checkConsistence(); assertFalse("The delta is empty", resourceDelta.isEmpty()); - + } @Test @@ -825,7 +825,7 @@ protected PrismObject getRawShadowBefore(PrismContext prismContext) private void assertXmlPolyMod(ObjectModificationType objectModificationType, QName propertyName, ModificationTypeType modType, PolyStringType... expectedValues) throws SchemaException { - //FIXME: + //FIXME: for (ItemDeltaType mod : objectModificationType.getItemDelta()) { if (!propertyName.equals(mod.getPath().getItemPath().last())) { continue; @@ -836,7 +836,7 @@ private void assertXmlPolyMod(ObjectModificationType objectModificationType, QNa } } } - + private void assertModificationPolyStringValue(RawType value, PolyStringType... expectedValues) throws SchemaException { XNode xnode = value.serializeToXNode(); assertFalse(xnode.isEmpty()); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseFilter.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseFilter.java index 27b192d995c..45ddb5e2517 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseFilter.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseFilter.java @@ -38,7 +38,7 @@ * */ public class TestParseFilter { - + public static final File FILTER_FILE = new File(TestConstants.COMMON_DIR, "filter.xml"); @BeforeSuite @@ -46,15 +46,15 @@ public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - - + + @Test public void testParseFilterFile() throws Exception { System.out.println("===[ testParseFilterFile ]==="); // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); - + // WHEN SearchFilterType filter = prismContext.parserFor(FILTER_FILE).parseRealValue(SearchFilterType.class); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseGenericObject.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseGenericObject.java index 7b0020b628a..623c9d974f1 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseGenericObject.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseGenericObject.java @@ -58,30 +58,30 @@ * */ public class TestParseGenericObject { - + public static final File GENERIC_FILE = new File("src/test/resources/common/generic-sample-configuration.xml"); - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - - + + @Test public void testParseGenericFile() throws Exception { System.out.println("===[ testParseGenericFile ]==="); // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); - + // WHEN PrismObject generic = prismContext.parserFor(GENERIC_FILE).xml().parse(); - + // THEN System.out.println("Parsed generic object:"); System.out.println(generic.debugDump()); - + assertGenericObject(generic); } @@ -91,17 +91,17 @@ public void testParseGenericDom() throws SchemaException, DatatypeConfigurationE // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); - + Document document = DOMUtil.parseFile(GENERIC_FILE); Element resourceElement = DOMUtil.getFirstChildElement(document); - + // WHEN PrismObject generic = prismContext.parserFor(resourceElement).parse(); - + // THEN System.out.println("Parsed generic object:"); System.out.println(generic.debugDump()); - + assertGenericObject(generic); } @@ -109,129 +109,129 @@ public void testParseGenericDom() throws SchemaException, DatatypeConfigurationE @Test(enabled = false) public void testPrismParseJaxb() throws JAXBException, SchemaException, SAXException, IOException, DatatypeConfigurationException { System.out.println("===[ testPrismParseJaxb ]==="); - + // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); JaxbTestUtil jaxbProcessor = JaxbTestUtil.getInstance(); // WHEN GenericObjectType genericType = jaxbProcessor.unmarshalObject(GENERIC_FILE, GenericObjectType.class); - + // THEN assertGenericObject(genericType.asPrismObject()); } - + /** * The definition should be set properly even if the declared type is ObjectType. The Prism should determine * the actual type. - * @throws DatatypeConfigurationException + * @throws DatatypeConfigurationException */ @Deprecated @Test(enabled = false) public void testPrismParseJaxbObjectType() throws JAXBException, SchemaException, SAXException, IOException, DatatypeConfigurationException { System.out.println("===[ testPrismParseJaxbObjectType ]==="); - + // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); JaxbTestUtil jaxbProcessor = JaxbTestUtil.getInstance(); - + // WHEN GenericObjectType genericType = jaxbProcessor.unmarshalObject(GENERIC_FILE, GenericObjectType.class); - + // THEN assertGenericObject(genericType.asPrismObject()); } - + /** * Parsing in form of JAXBELement - * @throws DatatypeConfigurationException + * @throws DatatypeConfigurationException */ @Deprecated @Test(enabled = false) public void testPrismParseJaxbElement() throws JAXBException, SchemaException, SAXException, IOException, DatatypeConfigurationException { System.out.println("===[ testPrismParseJaxbElement ]==="); - + // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); JaxbTestUtil jaxbProcessor = JaxbTestUtil.getInstance(); - + // WHEN JAXBElement jaxbElement = jaxbProcessor.unmarshalElement(GENERIC_FILE, GenericObjectType.class); GenericObjectType genericType = jaxbElement.getValue(); - + // THEN assertGenericObject(genericType.asPrismObject()); } /** * Parsing in form of JAXBELement, with declared ObjectType - * @throws DatatypeConfigurationException + * @throws DatatypeConfigurationException */ @Deprecated @Test(enabled = false) public void testPrismParseJaxbElementObjectType() throws JAXBException, SchemaException, SAXException, IOException, DatatypeConfigurationException { System.out.println("===[ testPrismParseJaxbElementObjectType ]==="); - + // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); JaxbTestUtil jaxbProcessor = JaxbTestUtil.getInstance(); - + // WHEN JAXBElement jaxbElement = jaxbProcessor.unmarshalElement(GENERIC_FILE, GenericObjectType.class); GenericObjectType genericType = jaxbElement.getValue(); - + // THEN assertGenericObject(genericType.asPrismObject()); } - + @Test public void testParseGenericRoundtrip() throws Exception { System.out.println("===[ testParseGenericRoundtrip ]==="); // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); - + PrismObject generic = prismContext.parseObject(GENERIC_FILE); - + System.out.println("Parsed generic object:"); System.out.println(generic.debugDump()); - + assertGenericObject(generic); - + // SERIALIZE - + String serializedGeneric = prismContext.serializeObjectToString(generic, PrismContext.LANG_XML); - + System.out.println("serialized generic object:"); System.out.println(serializedGeneric); - + // RE-PARSE - + PrismObject reparsedGeneric = prismContext.parseObject(serializedGeneric); - + System.out.println("Re-parsed generic object:"); System.out.println(reparsedGeneric.debugDump()); - + assertGenericObject(generic); - + ObjectDelta objectDelta = generic.diff(reparsedGeneric); System.out.println("Delta:"); System.out.println(objectDelta.debugDump()); assertTrue("Delta is not empty", objectDelta.isEmpty()); - + PrismAsserts.assertEquivalent("generic object re-parsed quivalence", generic, reparsedGeneric); - + // // Compare schema container -// +// // PrismContainer originalSchemaContainer = resource.findContainer(ResourceType.F_SCHEMA); // PrismContainer reparsedSchemaContainer = reparsedResource.findContainer(ResourceType.F_SCHEMA); } - + private void assertGenericObject(PrismObject generic) throws DatatypeConfigurationException { - + generic.checkConsistence(); - + assertEquals("Wrong oid", "c0c010c0-d34d-b33f-f00d-999111111111", generic.getOid()); // assertEquals("Wrong version", "42", resource.getVersion()); PrismObjectDefinition resourceDefinition = generic.getDefinition(); @@ -243,11 +243,11 @@ private void assertGenericObject(PrismObject generic) throws assertNotNull("asObjectable resulted in null", genericType); assertPropertyValue(generic, "name", PrismTestUtil.createPolyString("My Sample Config Object")); - assertPropertyDefinition(generic, "name", PolyStringType.COMPLEX_TYPE, 0, 1); + assertPropertyDefinition(generic, "name", PolyStringType.COMPLEX_TYPE, 0, 1); assertPropertyValue(generic, "objectType", QNameUtil.qNameToUri( new QName(SchemaTestConstants.NS_EXTENSION, "SampleConfigType"))); assertPropertyDefinition(generic, "objectType", DOMUtil.XSD_ANYURI, 1, 1); - + PrismContainer extensionContainer = generic.findContainer(GenericObjectType.F_EXTENSION); assertContainerDefinition(extensionContainer, "extension", ExtensionType.COMPLEX_TYPE, 0, 1); PrismContainerDefinition extensionContainerDefinition = extensionContainer.getDefinition(); @@ -266,29 +266,29 @@ private void assertGenericObject(PrismObject generic) throws // assertEquals("Wrong name of ", SchemaTestConstants.EXTENSION_LOCATIONS_ELEMENT, locationsProperty.getElementName()); // PrismPropertyDefinition locationsDefinition = locationsProperty.getDefinition(); // assertNotNull("No definition for ", locationsDefinition); -// PrismAsserts.assertDefinition(locationsDefinition, SchemaTestConstants.EXTENSION_LOCATIONS_ELEMENT, +// PrismAsserts.assertDefinition(locationsDefinition, SchemaTestConstants.EXTENSION_LOCATIONS_ELEMENT, // SchemaTestConstants.EXTENSION_LOCATIONS_TYPE, 0, -1); - + PrismAsserts.assertPropertyValue(extensionContainerValue, SchemaTestConstants.EXTENSION_STRING_TYPE_ELEMENT, "X marks the spot"); PrismAsserts.assertPropertyValue(extensionContainerValue, SchemaTestConstants.EXTENSION_INT_TYPE_ELEMENT, 1234); PrismAsserts.assertPropertyValue(extensionContainerValue, SchemaTestConstants.EXTENSION_DOUBLE_TYPE_ELEMENT, 456.789D); PrismAsserts.assertPropertyValue(extensionContainerValue, SchemaTestConstants.EXTENSION_LONG_TYPE_ELEMENT, 567890L); XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar("2002-05-30T09:10:11"); PrismAsserts.assertPropertyValue(extensionContainerValue, SchemaTestConstants.EXTENSION_DATE_TYPE_ELEMENT, calendar); - + } - + private void assertPropertyDefinition(PrismContainer container, String propName, QName xsdType, int minOccurs, int maxOccurs) { QName propQName = new QName(SchemaConstantsGenerated.NS_COMMON, propName); PrismAsserts.assertPropertyDefinition(container, propQName, xsdType, minOccurs, maxOccurs); } - + public static void assertPropertyValue(PrismContainer container, String propName, Object propValue) { QName propQName = new QName(SchemaConstantsGenerated.NS_COMMON, propName); PrismAsserts.assertPropertyValue(container, propQName, propValue); } - + private void assertContainerDefinition(PrismContainer container, String contName, QName xsdType, int minOccurs, int maxOccurs) { QName qName = new QName(SchemaConstantsGenerated.NS_COMMON, contName); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseModelContext.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseModelContext.java index 4cfa21c7f69..21018cb44f6 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseModelContext.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseModelContext.java @@ -36,23 +36,23 @@ * */ public class TestParseModelContext { - + public static final File MODEL_CONTEXT_FILE = new File("src/test/resources/common/model-context-1.xml"); - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - - + + @Test public void testParseModelContextPrism() throws Exception { System.out.println("===[ testParseModelContextPrism ]==="); // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); - + // WHEN LensContextType lensContextType = prismContext.parserFor(MODEL_CONTEXT_FILE).xml().parseRealValue(LensContextType.class); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseObjectTemplate.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseObjectTemplate.java index ba6f842a2d2..e355f8b405b 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseObjectTemplate.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseObjectTemplate.java @@ -47,25 +47,25 @@ * */ public class TestParseObjectTemplate { - + public static final File TEST_DIR = new File("src/test/resources/object-template"); private static final File OBJECT_TEMPLATE_FILE = new File(TEST_DIR, "object-template.xml"); private static final File USER_TEMPLATE_FILE = new File(TEST_DIR, "user-template.xml"); private static final File WRONG_TEMPLATE_FILE = new File(TEST_DIR, "wrong-template.xml"); - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - - + + @Test public void testParseObjectTemplateFile() throws Exception { roundTrip("testParseObjectTemplateFile", OBJECT_TEMPLATE_FILE, new QName(SchemaConstantsGenerated.NS_COMMON, "objectTemplate")); } - + @Test public void testParseUserTemplateFile() throws Exception { roundTrip("testParseUserTemplateFile", USER_TEMPLATE_FILE, @@ -100,32 +100,32 @@ private void roundTrip(final String TEST_NAME, File file, QName elementName) thr // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); - + // WHEN PrismObject object = prismContext.parseObject(file); - + // THEN System.out.println("Parsed object:"); System.out.println(object.debugDump()); - + assertObjectTemplate(object, elementName); - + // WHEN String xml = prismContext.serializeObjectToString(object, PrismContext.LANG_XML); - + // THEN System.out.println("Serialized object:"); System.out.println(xml); - + assertSerializedObject(xml, elementName); - + // WHEN PrismObject reparsedObject = prismContext.parseObject(xml); - + // THEN System.out.println("Re-parsed object:"); System.out.println(reparsedObject.debugDump()); - + assertObjectTemplate(reparsedObject, elementName); assertObjectTemplateInternals(reparsedObject, elementName); } @@ -136,7 +136,7 @@ private void assertObjectTemplate(PrismObject object, QName } private void assertObjectTemplatePrism(PrismObject object, QName elementName) { - + assertEquals("Wrong oid", "10000000-0000-0000-0000-000000000002", object.getOid()); PrismObjectDefinition objectDefinition = object.getDefinition(); assertNotNull("No object definition", objectDefinition); @@ -146,10 +146,10 @@ private void assertObjectTemplatePrism(PrismObject object, Q assertEquals("Wrong object item name", elementName, object.getElementName()); ObjectTemplateType objectType = object.asObjectable(); assertNotNull("asObjectable resulted in null", objectType); - + assertPropertyValue(object, "name", PrismTestUtil.createPolyString("Default User Template")); assertPropertyDefinition(object, "name", PolyStringType.COMPLEX_TYPE, 0, 1); - + assertPropertyDefinition(object, "mapping", ObjectTemplateMappingType.COMPLEX_TYPE, 0, -1); } @@ -193,7 +193,7 @@ private void assertPropertyDefinition(PrismContainer container, String propNa QName propQName = new QName(SchemaConstantsGenerated.NS_COMMON, propName); PrismAsserts.assertPropertyDefinition(container, propQName, xsdType, minOccurs, maxOccurs); } - + public static void assertPropertyValue(PrismContainer container, String propName, Object propValue) { QName propQName = new QName(SchemaConstantsGenerated.NS_COMMON, propName); PrismAsserts.assertPropertyValue(container, propQName, propValue); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParsePasswordPolicy.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParsePasswordPolicy.java index 8e8f3a217a3..3a6e8c80db1 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParsePasswordPolicy.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParsePasswordPolicy.java @@ -46,30 +46,30 @@ * */ public class TestParsePasswordPolicy { - + public static final File FILE = new File("src/test/resources/common/password-policy.xml"); - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - - + + @Test public void testParsePasswordPolicyFile() throws Exception { System.out.println("===[ testParsePasswordPolicyFile ]==="); // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); - + // WHEN PrismObject policy = prismContext.parserFor(FILE).xml().parse(); - + // THEN System.out.println("Parsed policy:"); System.out.println(policy.debugDump()); - + assertPolicy(policy); } @@ -113,9 +113,9 @@ public void testParsePolicyRoundtrip() throws Exception { } private void assertPolicy(PrismObject policy) { - + policy.checkConsistence(); - + assertEquals("Wrong oid", "00000000-0000-0000-0000-000000000003", policy.getOid()); PrismObjectDefinition usedDefinition = policy.getDefinition(); assertNotNull("No definition", usedDefinition); @@ -127,16 +127,16 @@ private void assertPolicy(PrismObject policy) { assertPropertyValue(policy, "name", PrismTestUtil.createPolyString("Testing Complex Password Policy")); assertPropertyDefinition(policy, "name", PolyStringType.COMPLEX_TYPE, 0, 1); - + // TODO... } - + private void assertPropertyDefinition(PrismContainer container, String propName, QName xsdType, int minOccurs, int maxOccurs) { QName propQName = new QName(SchemaConstantsGenerated.NS_COMMON, propName); PrismAsserts.assertPropertyDefinition(container, propQName, xsdType, minOccurs, maxOccurs); } - + public static void assertPropertyValue(PrismContainer container, String propName, Object propValue) { QName propQName = new QName(SchemaConstantsGenerated.NS_COMMON, propName); PrismAsserts.assertPropertyValue(container, propQName, propValue); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseTask.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseTask.java index 9a3da02b94a..a18c848f429 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseTask.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseTask.java @@ -54,30 +54,30 @@ * */ public class TestParseTask { - + public static final File TASK_FILE = new File("src/test/resources/common/task-1.xml"); - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - - + + @Test public void testParseTaskFile() throws Exception { System.out.println("===[ testParseTaskFile ]==="); // GIVEN PrismContext prismContext = getPrismContext(); - + // WHEN PrismObject task = prismContext.parserFor(TASK_FILE).xml().parse(); - + // THEN System.out.println("Parsed task:"); System.out.println(task.debugDump()); - + assertTask(task); } @@ -87,17 +87,17 @@ public void testParseTaskDom() throws SchemaException { // GIVEN PrismContext prismContext = getPrismContext(); - + Document document = DOMUtil.parseFile(TASK_FILE); Element taskElement = DOMUtil.getFirstChildElement(document); - + // WHEN PrismObject task = prismContext.parserFor(taskElement).parse(); - + // THEN System.out.println("Parsed task:"); System.out.println(task.debugDump()); - + assertTask(task); } @@ -105,21 +105,21 @@ public void testParseTaskDom() throws SchemaException { @Test(enabled = false) public void testPrismParseJaxb() throws JAXBException, SchemaException, SAXException, IOException { System.out.println("===[ testPrismParseJaxb ]==="); - + // GIVEN PrismContext prismContext = getPrismContext(); JaxbTestUtil jaxbProcessor = JaxbTestUtil.getInstance(); - + // WHEN TaskType taskType = jaxbProcessor.unmarshalObject(TASK_FILE, TaskType.class); - + // THEN System.out.println("Parsed task:"); System.out.println(taskType.asPrismObject().debugDump()); - + assertTask(taskType.asPrismObject()); } - + /** * The definition should be set properly even if the declared type is ObjectType. The Prism should determine * the actual type. @@ -128,21 +128,21 @@ public void testPrismParseJaxb() throws JAXBException, SchemaException, SAXExcep @Test(enabled = false) public void testPrismParseJaxbObjectType() throws JAXBException, SchemaException, SAXException, IOException { System.out.println("===[ testPrismParseJaxbObjectType ]==="); - + // GIVEN PrismContext prismContext = getPrismContext(); JaxbTestUtil jaxbProcessor = JaxbTestUtil.getInstance(); - + // WHEN TaskType taskType = jaxbProcessor.unmarshalObject(TASK_FILE, TaskType.class); - + // THEN System.out.println("Parsed task:"); System.out.println(taskType.asPrismObject().debugDump()); - + assertTask(taskType.asPrismObject()); } - + /** * Parsing in form of JAXBELement */ @@ -150,19 +150,19 @@ public void testPrismParseJaxbObjectType() throws JAXBException, SchemaException @Test(enabled = false) public void testPrismParseJaxbElement() throws JAXBException, SchemaException, SAXException, IOException { System.out.println("===[ testPrismParseJaxbElement ]==="); - + // GIVEN PrismContext prismContext = getPrismContext(); JaxbTestUtil jaxbProcessor = JaxbTestUtil.getInstance(); - + // WHEN JAXBElement jaxbElement = jaxbProcessor.unmarshalElement(TASK_FILE, TaskType.class); TaskType taskType = jaxbElement.getValue(); - + // THEN System.out.println("Parsed task:"); System.out.println(taskType.asPrismObject().debugDump()); - + assertTask(taskType.asPrismObject()); } @@ -173,27 +173,27 @@ public void testPrismParseJaxbElement() throws JAXBException, SchemaException, S @Test(enabled = false) public void testPrismParseJaxbElementObjectType() throws JAXBException, SchemaException, SAXException, IOException { System.out.println("===[ testPrismParseJaxbElementObjectType ]==="); - + // GIVEN PrismContext prismContext = getPrismContext(); JaxbTestUtil jaxbProcessor = JaxbTestUtil.getInstance(); - + // WHEN JAXBElement jaxbElement = jaxbProcessor.unmarshalElement(TASK_FILE, TaskType.class); TaskType taskType = jaxbElement.getValue(); - + // THEN System.out.println("Parsed task:"); System.out.println(taskType.asPrismObject().debugDump()); - + assertTask(taskType.asPrismObject()); } - + private void assertTask(PrismObject task) { - + task.checkConsistence(); - + assertEquals("Wrong oid", "44444444-4444-4444-4444-000000001111", task.getOid()); // assertEquals("Wrong version", "42", user.getVersion()); PrismObjectDefinition usedDefinition = task.getDefinition(); @@ -206,47 +206,47 @@ private void assertTask(PrismObject task) { assertPropertyValue(task, "name", PrismTestUtil.createPolyString("Example Task")); assertPropertyDefinition(task, "name", PolyStringType.COMPLEX_TYPE, 0, 1); - + assertPropertyValue(task, "taskIdentifier", "44444444-4444-4444-4444-000000001111"); assertPropertyDefinition(task, "taskIdentifier", DOMUtil.XSD_STRING, 0, 1); - + assertPropertyDefinition(task, "executionStatus", JAXBUtil.getTypeQName(TaskExecutionStatusType.class), 1, 1); PrismProperty executionStatusProperty = task.findProperty(TaskType.F_EXECUTION_STATUS); PrismPropertyValue executionStatusValue = executionStatusProperty.getValue(); TaskExecutionStatusType executionStatus = executionStatusValue.getValue(); assertEquals("Wrong execution status", TaskExecutionStatusType.RUNNABLE, executionStatus); - + // TODO: more tests - + // PrismContainer extension = user.getExtension(); // assertContainerDefinition(extension, "extension", DOMUtil.XSD_ANY, 0, 1); // PrismContainerValue extensionValue = extension.getValue(); // assertTrue("Extension parent", extensionValue.getParent() == extension); // assertNull("Extension ID", extensionValue.getId()); - + // PropertyPath enabledPath = new PropertyPath(UserType.F_ACTIVATION, ActivationType.F_ENABLED); // PrismProperty enabledProperty1 = task.findProperty(enabledPath); // PrismAsserts.assertDefinition(enabledProperty1.getDefinition(), ActivationType.F_ENABLED, DOMUtil.XSD_BOOLEAN, 0, 1); // assertNotNull("Property "+enabledPath+" not found", enabledProperty1); // PrismAsserts.assertPropertyValue(enabledProperty1, true); - + // PrismProperty validFromProperty = user.findProperty(new PropertyPath(UserType.F_ACTIVATION, ActivationType.F_VALID_FROM)); // assertNotNull("Property "+ActivationType.F_VALID_FROM+" not found", validFromProperty); // PrismAsserts.assertPropertyValue(validFromProperty, USER_JACK_VALID_FROM); - + // PrismReference accountRef = task.findReference(UserType.F_ACCOUNT_REF); // assertEquals("Wrong number of accountRef values", 3, accountRef.getValues().size()); // PrismAsserts.assertReferenceValue(accountRef, "2f9b9299-6f45-498f-aaaa-000000001111"); // PrismAsserts.assertReferenceValue(accountRef, "2f9b9299-6f45-498f-aaaa-000000002222"); // PrismAsserts.assertReferenceValue(accountRef, "2f9b9299-6f45-498f-aaaa-000000003333"); } - + private void assertPropertyDefinition(PrismContainer container, String propName, QName xsdType, int minOccurs, int maxOccurs) { QName propQName = new QName(SchemaConstantsGenerated.NS_COMMON, propName); PrismAsserts.assertPropertyDefinition(container, propQName, xsdType, minOccurs, maxOccurs); } - + public static void assertPropertyValue(PrismContainer container, String propName, Object propValue) { QName propQName = new QName(SchemaConstantsGenerated.NS_COMMON, propName); PrismAsserts.assertPropertyValue(container, propQName, propValue); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseTaskBulkAction.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseTaskBulkAction.java index 370224692f2..64a09a61530 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseTaskBulkAction.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestParseTaskBulkAction.java @@ -53,9 +53,9 @@ * */ public class TestParseTaskBulkAction { - + public static final File TASK_FILE = new File("src/test/resources/common/task-bulk-action-1.xml"); - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); @@ -68,10 +68,10 @@ public void testParseTaskFileToXNode() throws Exception { // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); - + // WHEN RootXNode node = prismContext.parserFor(TASK_FILE).xml().parseToXNode(); - + // THEN System.out.println("Parsed task (XNode):"); System.out.println(node.debugDump()); @@ -144,9 +144,9 @@ public void testParseTaskRoundtrip() throws Exception { private void assertTask(PrismObject task) { - + task.checkConsistence(); - + assertEquals("Wrong oid", "44444444-4444-4444-4444-000000001111", task.getOid()); PrismObjectDefinition usedDefinition = task.getDefinition(); assertNotNull("No task definition", usedDefinition); @@ -158,29 +158,29 @@ private void assertTask(PrismObject task) { assertPropertyValue(task, "name", PrismTestUtil.createPolyString("Task2")); assertPropertyDefinition(task, "name", PolyStringType.COMPLEX_TYPE, 0, 1); - + assertPropertyValue(task, "taskIdentifier", "44444444-4444-4444-4444-000000001111"); assertPropertyDefinition(task, "taskIdentifier", DOMUtil.XSD_STRING, 0, 1); - + assertPropertyDefinition(task, "executionStatus", JAXBUtil.getTypeQName(TaskExecutionStatusType.class), 1, 1); PrismProperty executionStatusProperty = task.findProperty(TaskType.F_EXECUTION_STATUS); PrismPropertyValue executionStatusValue = executionStatusProperty.getValue(); TaskExecutionStatusType executionStatus = executionStatusValue.getValue(); assertEquals("Wrong execution status", TaskExecutionStatusType.RUNNABLE, executionStatus); - + PrismContainer extension = task.getExtension(); PrismContainerValue extensionValue = extension.getValue(); assertTrue("Extension parent", extensionValue.getParent() == extension); assertNull("Extension ID", extensionValue.getId()); - + } - + private void assertPropertyDefinition(PrismContainer container, String propName, QName xsdType, int minOccurs, int maxOccurs) { QName propQName = new QName(SchemaConstantsGenerated.NS_COMMON, propName); PrismAsserts.assertPropertyDefinition(container, propQName, xsdType, minOccurs, maxOccurs); } - + public static void assertPropertyValue(PrismContainer container, String propName, Object propValue) { QName propQName = new QName(SchemaConstantsGenerated.NS_COMMON, propName); PrismAsserts.assertPropertyValue(container, propQName, propValue); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestQueryConvertor.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestQueryConvertor.java index 27c764d3c6a..c2679591a17 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestQueryConvertor.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestQueryConvertor.java @@ -115,7 +115,7 @@ public void testAccountFilter() throws Exception { QueryType convertedQueryType = toQueryType(query); System.out.println("Re-converted query type"); System.out.println(convertedQueryType.debugDump()); - + SearchFilterType convertedFilterType = convertedQueryType.getFilter(); MapXNode xFilter = convertedFilterType.serializeToXNode(); PrismAsserts.assertSize(xFilter, 1); @@ -125,19 +125,19 @@ public void testAccountFilter() throws Exception { PrismAsserts.assertSubnode(xandmap, EqualFilter.ELEMENT_NAME, ListXNode.class); ListXNode xequalsList = (ListXNode) xandmap.get(EqualFilter.ELEMENT_NAME); PrismAsserts.assertSize(xequalsList, 2); - + Element filterClauseElement = convertedFilterType.getFilterClauseAsElement(getPrismContext()); System.out.println("Serialized filter (JAXB->DOM)"); System.out.println(DOMUtil.serializeDOMToString(filterClauseElement)); - + DomAsserts.assertElementQName(filterClauseElement, AndFilter.ELEMENT_NAME); DomAsserts.assertSubElements(filterClauseElement, 2); - + Element firstSubelement = DOMUtil.getChildElement(filterClauseElement, 0); DomAsserts.assertElementQName(firstSubelement, EqualFilter.ELEMENT_NAME); Element firstValueElement = DOMUtil.getChildElement(firstSubelement, PrismConstants.Q_VALUE); DomAsserts.assertTextContent(firstValueElement, "add"); - + Element secondSubelement = DOMUtil.getChildElement(filterClauseElement, 1); DomAsserts.assertElementQName(secondSubelement, EqualFilter.ELEMENT_NAME); Element secondValueElement = DOMUtil.getChildElement(secondSubelement, PrismConstants.Q_VALUE); @@ -262,11 +262,11 @@ public void testConnectorQuery() throws Exception { } } - + private PrismObjectDefinition getUserDefinition(){ return getPrismContext().getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); } - + @Test public void testTypeFilterQuery() throws Exception { displayTestTitle("testConnectorQuery"); @@ -279,7 +279,7 @@ public void testTypeFilterQuery() throws Exception { assertNotNull(query); ObjectFilter filter = query.getFilter(); assertTrue("filter is not an instance of type filter", filter instanceof TypeFilter); - + TypeFilter typeFilter = (TypeFilter) filter; assertEquals(typeFilter.getType(), UserType.COMPLEX_TYPE); assertNotNull("filter in type filter must not be null", typeFilter.getFilter()); @@ -299,7 +299,7 @@ public void testTypeFilterQuery() throws Exception { } } - + @Test public void testShadowKindTypeQuery() throws Exception { displayTestTitle("testShadowKindTypeQuery"); @@ -313,14 +313,14 @@ public void testShadowKindTypeQuery() throws Exception { assertNotNull(query); ObjectFilter filter = query.getFilter(); assertTrue("filter is not an instance of type filter", filter instanceof EqualFilter); - + EqualFilter typeFilter = (EqualFilter) filter; assertEquals(typeFilter.getSingleValue().getRealValue(), ShadowKindType.ACCOUNT); - + QueryType convertedQueryType = toQueryType(query); - + toObjectQuery(ShadowType.class, convertedQueryType); - + displayQueryType(convertedQueryType); } catch (Exception ex) { LOGGER.error("Error while converting query: {}", ex.getMessage(), ex); @@ -344,7 +344,7 @@ private ObjectQuery toObjectQuery(Class type, QueryType queryType) throws Except return QueryJaxbConvertor.createObjectQuery(type, queryType, getPrismContext()); } - + private ObjectQuery toObjectQuery(Class type, SearchFilterType filterType) throws Exception { return QueryJaxbConvertor.createObjectQuery(type, filterType, getPrismContext()); @@ -396,7 +396,7 @@ public void testGenericQuery() throws Exception { @Test public void testUserQuery() throws Exception { displayTestTitle("testUserQuery"); - + File[] userQueriesToTest = new File[] { new File(TEST_DIR, "filter-user-by-fullName.xml"), new File(TEST_DIR, "filter-user-by-name.xml"), new File(TEST_DIR, "filter-user-substring-fullName.xml"), @@ -576,18 +576,18 @@ public void test360Ref() throws Exception { .or().item(ShadowType.F_RESOURCE_REF).ref("oid4", ResourceType.COMPLEX_TYPE) .build(); q1object.getFilter().checkConsistence(true); - + String q2xml = FileUtils.readFileToString(new File(TEST_DIR + "/" + TEST_NAME + ".xml")); displayQueryXml(q2xml); QueryType q2jaxb = toQueryType(q2xml); displayQueryType(q2jaxb); ObjectQuery q2object = toObjectQuery(ShadowType.class, q2jaxb); - + System.out.println("q1object:\n"+q1object.debugDump(1)); System.out.println("q2object:\n"+q2object.debugDump(1)); - + assertEquals("Reparsed query is not as original one (via toString)", q1object.toString(), q2object.toString()); // primitive way of comparing parsed queries - + if (!q1object.equivalent(q2object)) { AssertJUnit.fail("Reparsed query is not as original one (via equivalent):\nq1="+q1object+"\nq2="+q2object); } diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestSchemaDelta.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestSchemaDelta.java index 3f6a5fec8ff..bb506565e5a 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestSchemaDelta.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestSchemaDelta.java @@ -45,16 +45,16 @@ /** * Test delta operation on real midpoint schema. Similar to TestDelta in prism, but this is using the * real thing and not just testing schema. - * + * * @author Radovan Semancik */ public class TestSchemaDelta extends AbstractSchemaTest { - + @Test public void testAssignmentSameNullIdApplyToObject() throws Exception { final String TEST_NAME = "testAssignmentSameNullIdApplyToObject"; displayTestTile(TEST_NAME); - + // GIVEN PrismObject user = PrismTestUtil.parseObject(USER_JACK_FILE); @@ -62,13 +62,13 @@ public void testAssignmentSameNullIdApplyToObject() throws Exception { PrismContainerValue assignmentValue = new PrismContainerValue(getPrismContext()); // The value id is null assignmentValue.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "jamalalicha patlama paprtala", getPrismContext()); - - ObjectDelta userDelta = ObjectDelta.createModificationAddContainer(UserType.class, USER_JACK_OID, + + ObjectDelta userDelta = ObjectDelta.createModificationAddContainer(UserType.class, USER_JACK_OID, UserType.F_ASSIGNMENT, getPrismContext(), assignmentValue); - + // WHEN userDelta.applyTo(user); - + // THEN System.out.println("User after delta application:"); System.out.println(user.debugDump()); @@ -83,7 +83,7 @@ public void testAssignmentSameNullIdApplyToObject() throws Exception { public void testAddInducementConstructionSameNullIdApplyToObject() throws Exception { final String TEST_NAME = "testAddInducementConstructionSameNullIdApplyToObject"; displayTestTile(TEST_NAME); - + // GIVEN PrismObject role = PrismTestUtil.parseObject(ROLE_CONSTRUCTION_FILE); @@ -91,13 +91,13 @@ public void testAddInducementConstructionSameNullIdApplyToObject() throws Except PrismContainerValue inducementValue = new PrismContainerValue(getPrismContext()); // The value id is null inducementValue.setPropertyRealValue(AssignmentType.F_DESCRIPTION, "jamalalicha patlama paprtala", getPrismContext()); - - ObjectDelta roleDelta = ObjectDelta.createModificationAddContainer(RoleType.class, ROLE_CONSTRUCTION_OID, + + ObjectDelta roleDelta = ObjectDelta.createModificationAddContainer(RoleType.class, ROLE_CONSTRUCTION_OID, RoleType.F_INDUCEMENT, getPrismContext(), inducementValue); - + // WHEN roleDelta.applyTo(role); - + // THEN System.out.println("Role after delta application:"); System.out.println(role.debugDump()); @@ -107,12 +107,12 @@ public void testAddInducementConstructionSameNullIdApplyToObject() throws Except assertNotNull("No inducement", assignment); assertEquals("Unexpected number of inducement values", 2, assignment.size()); } - + @Test public void testDeleteInducementValidIdSameValueApplyToObject() throws Exception { final String TEST_NAME = "testDeleteInducementValidIdSameValueApplyToObject"; displayTestTile(TEST_NAME); - + // GIVEN PrismObject role = PrismTestUtil.parseObject(ROLE_CONSTRUCTION_FILE); @@ -124,12 +124,12 @@ public void testDeleteInducementValidIdSameValueApplyToObject() throws Exception AssignmentType inducement = new AssignmentType(); inducement.setConstruction(construction); inducement.setId(ROLE_CONSTRUCTION_INDUCEMENT_ID); - ObjectDelta roleDelta = ObjectDelta.createModificationDeleteContainer(RoleType.class, ROLE_CONSTRUCTION_OID, + ObjectDelta roleDelta = ObjectDelta.createModificationDeleteContainer(RoleType.class, ROLE_CONSTRUCTION_OID, RoleType.F_INDUCEMENT, getPrismContext(), inducement); - + // WHEN roleDelta.applyTo(role); - + // THEN System.out.println("Role after delta application:"); System.out.println(role.debugDump()); @@ -143,19 +143,19 @@ public void testDeleteInducementValidIdSameValueApplyToObject() throws Exception public void testDeleteInducementValidIdEmptyValueApplyToObject() throws Exception { final String TEST_NAME = "testDeleteInducementValidIdEmptyValueApplyToObject"; displayTestTile(TEST_NAME); - + // GIVEN PrismObject role = PrismTestUtil.parseObject(ROLE_CONSTRUCTION_FILE); //Delta AssignmentType inducement = new AssignmentType(); inducement.setId(ROLE_CONSTRUCTION_INDUCEMENT_ID); - ObjectDelta roleDelta = ObjectDelta.createModificationDeleteContainer(RoleType.class, ROLE_CONSTRUCTION_OID, + ObjectDelta roleDelta = ObjectDelta.createModificationDeleteContainer(RoleType.class, ROLE_CONSTRUCTION_OID, RoleType.F_INDUCEMENT, getPrismContext(), inducement); - + // WHEN roleDelta.applyTo(role); - + // THEN System.out.println("Role after delta application:"); System.out.println(role.debugDump()); @@ -164,12 +164,12 @@ public void testDeleteInducementValidIdEmptyValueApplyToObject() throws Exceptio PrismContainer assignment = role.findContainer(RoleType.F_INDUCEMENT); assertNull("Unexpected inducement", assignment); } - + @Test public void testDeleteInducementValidIdEmptyValueApplyToObjectStatic() throws Exception { final String TEST_NAME = "testDeleteInducementValidIdEmptyValueApplyToObjectStatic"; displayTestTile(TEST_NAME); - + // GIVEN PrismObject role = PrismTestUtil.parseObject(ROLE_CONSTRUCTION_FILE); System.out.println("Role before delta application:"); @@ -178,12 +178,12 @@ public void testDeleteInducementValidIdEmptyValueApplyToObjectStatic() throws Ex //Delta AssignmentType inducement = new AssignmentType(); inducement.setId(ROLE_CONSTRUCTION_INDUCEMENT_ID); - ObjectDelta roleDelta = ObjectDelta.createModificationDeleteContainer(RoleType.class, ROLE_CONSTRUCTION_OID, + ObjectDelta roleDelta = ObjectDelta.createModificationDeleteContainer(RoleType.class, ROLE_CONSTRUCTION_OID, RoleType.F_INDUCEMENT, getPrismContext(), inducement); - + // WHEN PropertyDelta.applyTo(roleDelta.getModifications(), role); - + // THEN System.out.println("Role after delta application:"); System.out.println(role.debugDump()); @@ -197,7 +197,7 @@ public void testDeleteInducementValidIdEmptyValueApplyToObjectStatic() throws Ex public void testDeleteInducementConstructionSameNullIdApplyToObject() throws Exception { final String TEST_NAME = "testDeleteInducementConstructionSameNullIdApplyToObject"; displayTestTile(TEST_NAME); - + // GIVEN PrismObject role = PrismTestUtil.parseObject(ROLE_CONSTRUCTION_FILE); @@ -208,16 +208,16 @@ public void testDeleteInducementConstructionSameNullIdApplyToObject() throws Exc resourceRef.setType(ObjectTypes.RESOURCE.getTypeQName()); construction.setResourceRef(resourceRef); // No container ID - ObjectDelta roleDelta = ObjectDelta.createModificationDeleteContainer(RoleType.class, ROLE_CONSTRUCTION_OID, + ObjectDelta roleDelta = ObjectDelta.createModificationDeleteContainer(RoleType.class, ROLE_CONSTRUCTION_OID, new ItemPath( new NameItemPathSegment(RoleType.F_INDUCEMENT), new IdItemPathSegment(ROLE_CONSTRUCTION_INDUCEMENT_ID), new NameItemPathSegment(AssignmentType.F_CONSTRUCTION)), getPrismContext(), construction); - + // WHEN roleDelta.applyTo(role); - + // THEN System.out.println("Role after delta application:"); System.out.println(role.debugDump()); @@ -231,14 +231,14 @@ public void testDeleteInducementConstructionSameNullIdApplyToObject() throws Exc ConstructionType constructionAfter = inducement.getConstruction(); // construction should be gone (the error is that it is empty and not gone) assertNull("Construction is not gone", constructionAfter); - + } - + @Test public void testDeleteInducementActivationSameNullIdApplyToObject() throws Exception { final String TEST_NAME = "testDeleteInducementActivationSameNullIdApplyToObject"; displayTestTile(TEST_NAME); - + // GIVEN PrismObject role = PrismTestUtil.parseObject(ROLE_CONSTRUCTION_FILE); @@ -246,16 +246,16 @@ public void testDeleteInducementActivationSameNullIdApplyToObject() throws Excep ActivationType activationType = new ActivationType(); activationType.setAdministrativeStatus(ActivationStatusType.ENABLED); // No container ID - ObjectDelta roleDelta = ObjectDelta.createModificationDeleteContainer(RoleType.class, ROLE_CONSTRUCTION_OID, + ObjectDelta roleDelta = ObjectDelta.createModificationDeleteContainer(RoleType.class, ROLE_CONSTRUCTION_OID, new ItemPath( new NameItemPathSegment(RoleType.F_INDUCEMENT), new IdItemPathSegment(ROLE_CONSTRUCTION_INDUCEMENT_ID), new NameItemPathSegment(AssignmentType.F_ACTIVATION)), getPrismContext(), activationType); - + // WHEN roleDelta.applyTo(role); - + // THEN System.out.println("Role after delta application:"); System.out.println(role.debugDump()); @@ -270,12 +270,12 @@ public void testDeleteInducementActivationSameNullIdApplyToObject() throws Excep // activation should be gone (the error is that it is empty and not gone) assertNull("Activation is not gone", activation); } - + @Test public void testDeleteUserAssignmentActivationSameNullIdApplyToObject() throws Exception { final String TEST_NAME = "testDeleteUserAssignmentActivationSameNullIdApplyToObject"; displayTestTile(TEST_NAME); - + // GIVEN PrismObject user = PrismTestUtil.parseObject(USER_JACK_FILE); @@ -283,16 +283,16 @@ public void testDeleteUserAssignmentActivationSameNullIdApplyToObject() throws E ActivationType activationType = new ActivationType(); activationType.setAdministrativeStatus(ActivationStatusType.ENABLED); // No container ID - ObjectDelta userDelta = ObjectDelta.createModificationDeleteContainer(UserType.class, USER_JACK_OID, + ObjectDelta userDelta = ObjectDelta.createModificationDeleteContainer(UserType.class, USER_JACK_OID, new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(USER_JACK_ASSIGNMENT_ID), new NameItemPathSegment(AssignmentType.F_ACTIVATION)), getPrismContext(), activationType); - + // WHEN userDelta.applyTo(user); - + // THEN System.out.println("User after delta application:"); System.out.println(user.debugDump()); @@ -306,7 +306,7 @@ public void testDeleteUserAssignmentActivationSameNullIdApplyToObject() throws E ActivationType assignmentActivation = assignment.getActivation(); // activation should be gone (the error is that it is empty and not gone) assertNull("Assignment activation is not gone", assignmentActivation); - + ActivationType activation = user.asObjectable().getActivation(); assertNotNull("Activation missing", activation); assertEquals("Wrong activation administrativeStatus", ActivationStatusType.ENABLED, activation.getAdministrativeStatus()); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestSchemaRegistry.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestSchemaRegistry.java index c8b557a5761..50d549e105b 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestSchemaRegistry.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestSchemaRegistry.java @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.schema; @@ -85,13 +85,13 @@ public class TestSchemaRegistry { */ @Test public void testBasic() throws SAXException, IOException, SchemaException { - + MidPointPrismContextFactory factory = getContextFactory(); PrismContext context = factory.createInitializedPrismContext(); SchemaRegistry reg = context.getSchemaRegistry(); Schema javaxSchema = reg.getJavaxSchema(); assertNotNull(javaxSchema); - + // Try to use the schema to validate Jack // PrismObject user = context.parseObject(new File("src/test/resources/common/user-jack.xml")); // Element document = context.serializeToDom(user); @@ -110,12 +110,12 @@ public void testCommonSchema() throws SchemaException, SAXException, IOException MidPointPrismContextFactory factory = getContextFactory(); PrismContext context = factory.createInitializedPrismContext(); SchemaRegistry schemaRegistry = context.getSchemaRegistry(); - + PrismSchema commonSchema = schemaRegistry.findSchemaByNamespace(SchemaConstants.NS_C); assertNotNull("No parsed common schema", commonSchema); System.out.println("Parsed common schema:"); System.out.println(commonSchema.debugDump()); - + // TODO } @@ -125,10 +125,10 @@ public void testReferenceInExtension() throws SchemaException, SAXException, IOE MidPointPrismContextFactory factory = getContextFactory(); PrismContext context = factory.createInitializedPrismContext(); SchemaRegistry schemaRegistry = context.getSchemaRegistry(); - + // Common schema should be parsed during creation of the context ((SchemaRegistryImpl) schemaRegistry).loadPrismSchemaResource("schema/extension.xsd"); - + // Check that the extension schema was loaded PrismSchema extensionSchema = schemaRegistry.findSchemaByNamespace(EXTENSION_SCHEMA_NAMESPACE); assertNotNull("Extension schema not parsed", extensionSchema); @@ -143,29 +143,29 @@ public void testReferenceInExtension() throws SchemaException, SAXException, IOE @Test public void testUserType() throws Exception { - + MidPointPrismContextFactory factory = getContextFactory(); PrismContext context = factory.createInitializedPrismContext(); SchemaRegistry schemaRegistry = context.getSchemaRegistry(); PrismObjectDefinition userDefinition = schemaRegistry.findObjectDefinitionByCompileTimeClass(UserType.class); assertNotNull("No user definition", userDefinition); - + System.out.println("testUserType:"); System.out.println(userDefinition.debugDump()); - + assertFalse("User definition is marked as runtime", userDefinition.isRuntimeSchema()); - + PrismPropertyDefinition nameDef = userDefinition.findPropertyDefinition(ObjectType.F_NAME); assertNotNull("No name definition", nameDef); PrismContainerDefinition extensionDef = userDefinition.findContainerDefinition(UserType.F_EXTENSION); assertNotNull("No 'extension' definition", extensionDef); assertTrue("Extension definition is NOT marked as runtime", extensionDef.isRuntimeSchema()); - + PrismPropertyDefinition givenNameDef = userDefinition.findPropertyDefinition(UserType.F_GIVEN_NAME); assertNotNull("No givenName definition", givenNameDef); - + PrismPropertyDefinition preferredLanguageDef = userDefinition.findPropertyDefinition(UserType.F_PREFERRED_LANGUAGE); assertNotNull("No preferredLanguage definition", preferredLanguageDef); PrismReferenceValue preferredLanguageValueEnumerationRef = preferredLanguageDef.getValueEnumerationRef(); @@ -174,35 +174,35 @@ public void testUserType() throws Exception { SystemObjectsType.LOOKUP_LANGUAGES.value(), preferredLanguageValueEnumerationRef.getOid()); assertEquals("Wrong type in valueEnumerationRef in preferredLanguage definition", LookupTableType.COMPLEX_TYPE, preferredLanguageValueEnumerationRef.getTargetType()); - + // Just make sure this does not end with NPE or stack overflow PrismObjectDefinition shallowClone = userDefinition.clone(); PrismObjectDefinition deepClone = userDefinition.deepClone(false); PrismObjectDefinition ultraDeepClone = userDefinition.deepClone(true); } - + @Test public void testRoleType() throws Exception { - + MidPointPrismContextFactory factory = getContextFactory(); PrismContext context = factory.createInitializedPrismContext(); SchemaRegistry schemaRegistry = context.getSchemaRegistry(); PrismObjectDefinition roleDefinition = schemaRegistry.findObjectDefinitionByCompileTimeClass(RoleType.class); assertNotNull("No role definition", roleDefinition); - + assertFalse("Role definition is marked as runtime", roleDefinition.isRuntimeSchema()); - + PrismPropertyDefinition nameDef = roleDefinition.findPropertyDefinition(ObjectType.F_NAME); assertNotNull("No name definition", nameDef); PrismContainerDefinition extensionDef = roleDefinition.findContainerDefinition(ObjectType.F_EXTENSION); assertNotNull("No 'extension' definition", extensionDef); assertTrue("Extension definition is NOT marked as runtime", extensionDef.isRuntimeSchema()); - + PrismPropertyDefinition identifierDef = roleDefinition.findPropertyDefinition(RoleType.F_IDENTIFIER); assertNotNull("No identifier definition", identifierDef); - + // Just make sure this does not end with NPE or stack overflow PrismObjectDefinition shallowClone = roleDefinition.clone(); PrismObjectDefinition deepClone = roleDefinition.deepClone(false); @@ -215,27 +215,27 @@ public void testCommonSchemaAccountType() throws SchemaException, SAXException, MidPointPrismContextFactory factory = getContextFactory(); PrismContext context = factory.createInitializedPrismContext(); SchemaRegistry schemaRegistry = context.getSchemaRegistry(); - + PrismObjectDefinition accountDef = schemaRegistry.findObjectDefinitionByCompileTimeClass(ShadowType.class); assertNotNull("No account definition", accountDef); System.out.println("testCommonSchemaAccountType:"); System.out.println(accountDef.debugDump()); - + PrismPropertyDefinition nameDef = accountDef.findPropertyDefinition(ShadowType.F_NAME); assertNotNull("No name definition", nameDef); - + PrismContainerDefinition extensionDef = accountDef.findContainerDefinition(ShadowType.F_EXTENSION); assertNotNull("No 'extension' definition", extensionDef); assertTrue("'extension' definition is not marked as runtime", extensionDef.isRuntimeSchema()); - + PrismContainerDefinition attributesDef = accountDef.findContainerDefinition(ShadowType.F_ATTRIBUTES); assertNotNull("No 'attributes' definition", attributesDef); assertTrue("'attributes' definition is not marked as runtime", attributesDef.isRuntimeSchema()); } - + private MidPointPrismContextFactory getContextFactory() { return new MidPointPrismContextFactory(); } - + } diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestSchemaSanity.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestSchemaSanity.java index d376ea35575..1ec250b625d 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestSchemaSanity.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestSchemaSanity.java @@ -70,13 +70,13 @@ * */ public class TestSchemaSanity { - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - + @Test public void testPrefixMappings() { System.out.println("===[ testPrefixMappings ]==="); @@ -88,7 +88,7 @@ public void testPrefixMappings() { assertNotNull("No schema registry in context", schemaRegistry); DynamicNamespacePrefixMapper prefixMapper = schemaRegistry.getNamespacePrefixMapper(); assertNotNull("No prefix mapper in context", prefixMapper); - + System.out.println("Prefix mapper:"); System.out.println(prefixMapper.debugDump()); // WHEN, THEN @@ -97,27 +97,27 @@ public void testPrefixMappings() { assertMapping(prefixMapper, MidPointConstants.NS_RA, MidPointConstants.PREFIX_NS_RA); assertMapping(prefixMapper, SchemaTestConstants.NS_ICFC, "icfc"); assertMapping(prefixMapper, SchemaTestConstants.NS_ICFS, "icfs"); - + QName cBarQName = new QName(SchemaConstantsGenerated.NS_COMMON, "bar"); QName cBarQNameWithPrefix = prefixMapper.setQNamePrefix(cBarQName); assertQName("common namespace implicit", SchemaConstantsGenerated.NS_COMMON, "bar", "", cBarQNameWithPrefix); QName cBarQNameWithPrefixExplixit = prefixMapper.setQNamePrefixExplicit(cBarQName); assertQName("common namespace implicit", SchemaConstantsGenerated.NS_COMMON, "bar", "c", cBarQNameWithPrefixExplixit); - + } - + private void assertQName(String message, String expectedNamespace, String expectedLocalName, String expectedPrefix, QName actual) { assertEquals("Wrong qname namespace in "+message, expectedNamespace, actual.getNamespaceURI()); assertEquals("Wrong qname local part in "+message, expectedLocalName, actual.getLocalPart()); assertEquals("Wrong qname prefix in "+message, expectedPrefix, actual.getPrefix()); - + } private void assertMapping(DynamicNamespacePrefixMapper prefixMapper, String namespace, String prefix) { assertEquals("Wrong prefix mapping for namespace "+namespace, prefix, prefixMapper.getPrefix(namespace)); } - + @Test public void testUserDefinition() { System.out.println("===[ testUserDefinition ]==="); @@ -125,19 +125,19 @@ public void testUserDefinition() { // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); SchemaRegistry schemaRegistry = prismContext.getSchemaRegistry(); - + // WHEN PrismObjectDefinition userDefinition = schemaRegistry.findObjectDefinitionByElementName(new QName(SchemaConstantsGenerated.NS_COMMON,"user")); - + // THEN assertNotNull("No user definition", userDefinition); System.out.println("User definition:"); System.out.println(userDefinition.debugDump()); - + PrismObjectDefinition userDefinitionByClass = schemaRegistry.findObjectDefinitionByCompileTimeClass(UserType.class); assertTrue("Different user def", userDefinition == userDefinitionByClass); - SchemaTestUtil.assertUserDefinition(userDefinition); + SchemaTestUtil.assertUserDefinition(userDefinition); } @Test @@ -147,15 +147,15 @@ public void testAccountDefinition() { // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); SchemaRegistry schemaRegistry = prismContext.getSchemaRegistry(); - + // WHEN PrismObjectDefinition accountDefinition = schemaRegistry.findObjectDefinitionByElementName( SchemaConstants.C_SHADOW); assertNotNull("No account definition", accountDefinition); System.out.println("Account definition:"); System.out.println(accountDefinition.debugDump()); - - PrismObjectDefinition accountDefinitionByClass = + + PrismObjectDefinition accountDefinitionByClass = schemaRegistry.findObjectDefinitionByCompileTimeClass(ShadowType.class); assertTrue("Different account def", accountDefinition == accountDefinitionByClass); @@ -163,7 +163,7 @@ public void testAccountDefinition() { PrismAsserts.assertPropertyDefinition(accountDefinition, ShadowType.F_NAME, PolyStringType.COMPLEX_TYPE, 0, 1); PrismAsserts.assertPropertyDefinition(accountDefinition, ShadowType.F_DESCRIPTION, DOMUtil.XSD_STRING, 0, 1); assertFalse("Account definition is marked as runtime", accountDefinition.isRuntimeSchema()); - + PrismContainerDefinition attributesContainer = accountDefinition.findContainerDefinition(ShadowType.F_ATTRIBUTES); PrismAsserts.assertDefinition(attributesContainer, ShadowType.F_ATTRIBUTES, ShadowAttributesType.COMPLEX_TYPE, 0, 1); assertTrue("Attributes is NOT runtime", attributesContainer.isRuntimeSchema()); @@ -178,15 +178,15 @@ public void testResourceDefinition() { // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); SchemaRegistry schemaRegistry = prismContext.getSchemaRegistry(); - + // WHEN PrismObjectDefinition resourceDefinition = schemaRegistry.findObjectDefinitionByElementName( new QName(SchemaConstantsGenerated.NS_COMMON, "resource")); assertNotNull("No resource definition", resourceDefinition); System.out.println("Resource definition:"); System.out.println(resourceDefinition.debugDump()); - - PrismObjectDefinition resourceDefinitionByClass = + + PrismObjectDefinition resourceDefinitionByClass = schemaRegistry.findObjectDefinitionByCompileTimeClass(ResourceType.class); assertTrue("Different user def", resourceDefinition == resourceDefinitionByClass); @@ -200,20 +200,20 @@ public void testResourceDefinition() { assertTrue(" is NOT dynamic", connectorConfContainerDef.isDynamic()); // assertFalse(" is runtime", connectorConfContainerDef.isRuntimeSchema()); assertEquals("Wrong compile-time class for in resource definition", ConnectorConfigurationType.class, connectorConfContainerDef.getCompileTimeClass()); - + PrismContainerDefinition schemaContainerDef = resourceDefinition.findContainerDefinition(ResourceType.F_SCHEMA); PrismAsserts.assertDefinition(schemaContainerDef, ResourceType.F_SCHEMA, XmlSchemaType.COMPLEX_TYPE, 0, 1); assertFalse("Schema is runtime", schemaContainerDef.isRuntimeSchema()); assertEquals("Wrong compile-time class for in resource definition", XmlSchemaType.class, schemaContainerDef.getCompileTimeClass()); assertEquals("Unexpected number of definitions in ", 3, schemaContainerDef.getDefinitions().size()); - PrismAsserts.assertPropertyDefinition(schemaContainerDef, XmlSchemaType.F_CACHING_METADATA, - CachingMetadataType.COMPLEX_TYPE, 0, 1); + PrismAsserts.assertPropertyDefinition(schemaContainerDef, XmlSchemaType.F_CACHING_METADATA, + CachingMetadataType.COMPLEX_TYPE, 0, 1); PrismAsserts.assertPropertyDefinition(schemaContainerDef, XmlSchemaType.F_DEFINITION, SchemaDefinitionType.COMPLEX_TYPE, 0, 1); PrismPropertyDefinition definitionPropertyDef = schemaContainerDef.findPropertyDefinition(XmlSchemaType.F_DEFINITION); assertNotNull("Null definition", definitionPropertyDef); // assertFalse("schema/definition is NOT runtime", definitionPropertyDef.isRuntimeSchema()); } - + @Test public void testResourceConfigurationDefinition() { System.out.println("===[ testResourceConfigurationDefinition ]==="); @@ -221,22 +221,22 @@ public void testResourceConfigurationDefinition() { // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); SchemaRegistry schemaRegistry = prismContext.getSchemaRegistry(); - + // WHEN PrismContainerDefinition configurationPropertiesDefinition = schemaRegistry.findContainerDefinitionByElementName( SchemaConstantsGenerated.ICF_C_CONFIGURATION_PROPERTIES); assertNotNull("No configurationProperties definition", configurationPropertiesDefinition); System.out.println("configurationProperties definition:"); System.out.println(configurationPropertiesDefinition.debugDump()); - + assertTrue("configurationProperties definition is NOT marked as runtime", configurationPropertiesDefinition.isRuntimeSchema()); // assertNull("Unexpected compile-time class in configurationProperties definition", configurationPropertiesDefinition.getCompileTimeClass()); // assertTrue("configurationProperties definition is NOT marked as wildcard", configurationPropertiesDefinition.isWildcard()); - + // TODO } - + @Test public void testRoleDefinition() { System.out.println("===[ testRoleDefinition ]==="); @@ -244,15 +244,15 @@ public void testRoleDefinition() { // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); SchemaRegistry schemaRegistry = prismContext.getSchemaRegistry(); - + // WHEN PrismObjectDefinition roleDefinition = schemaRegistry.findObjectDefinitionByElementName(new QName(SchemaConstantsGenerated.NS_COMMON,"role")); - + // THEN assertNotNull("No role definition", roleDefinition); System.out.println("Role definition:"); System.out.println(roleDefinition.debugDump()); - + PrismObjectDefinition roleDefinitionByClass = schemaRegistry.findObjectDefinitionByCompileTimeClass(RoleType.class); assertTrue("Different role def", roleDefinition == roleDefinitionByClass); @@ -265,7 +265,7 @@ public void testRoleDefinition() { PrismAsserts.assertItemDefinitionDisplayOrder(roleDefinition, ObjectType.F_DESCRIPTION, 10); PrismAsserts.assertPropertyDefinition(roleDefinition, RoleType.F_REQUESTABLE, DOMUtil.XSD_BOOLEAN, 0, 1); } - + @Test public void testFocusDefinition() { System.out.println("===[ testFocusDefinition ]==="); @@ -273,18 +273,18 @@ public void testFocusDefinition() { // GIVEN PrismContext prismContext = PrismTestUtil.getPrismContext(); SchemaRegistry schemaRegistry = prismContext.getSchemaRegistry(); - + // WHEN ComplexTypeDefinition focusDefinition = schemaRegistry.findComplexTypeDefinition(FocusType.COMPLEX_TYPE); - + // THEN assertNotNull("No focus definition", focusDefinition); System.out.println("Focus definition:"); System.out.println(focusDefinition.debugDump()); - + SchemaTestUtil.assertFocusDefinition(focusDefinition, "focus"); } - + @Test public void testIcfSchema() { System.out.println("===[ testIcfSchema ]==="); @@ -295,7 +295,7 @@ public void testIcfSchema() { assertNotNull("No prism context", prismContext); SchemaRegistry schemaRegistry = prismContext.getSchemaRegistry(); assertNotNull("No schema registry in context", schemaRegistry); - + System.out.println("Schema registry:"); System.out.println(schemaRegistry.debugDump()); @@ -303,15 +303,15 @@ public void testIcfSchema() { assertNotNull("No ICF schema", icfSchema); System.out.println("ICF schema:"); System.out.println(icfSchema.debugDump()); - - + + PrismContainerDefinition configurationPropertiesContainerDef = icfSchema.findContainerDefinitionByElementName(ICFC_CONFIGURATION_PROPERTIES); PrismAsserts.assertDefinition(configurationPropertiesContainerDef, ICFC_CONFIGURATION_PROPERTIES, ICFC_CONFIGURATION_PROPERTIES_TYPE, 0, 1); assertTrue("configurationPropertiesContainer definition is NOT marked as runtime", configurationPropertiesContainerDef.isRuntimeSchema()); assertTrue("configurationPropertiesContainer definition is NOT marked as dynamic", configurationPropertiesContainerDef.isDynamic()); - + } - + /** * Extension schema should be loaded from src/test/resources/schema during test initialization. */ @@ -324,17 +324,17 @@ public void testExtensionSchema() { assertNotNull("No prism context", prismContext); SchemaRegistry schemaRegistry = prismContext.getSchemaRegistry(); assertNotNull("No schema registry in context", schemaRegistry); - + PrismSchema extensionSchema = schemaRegistry.findSchemaByNamespace(SchemaTestConstants.NS_EXTENSION); assertNotNull("No extension schema", extensionSchema); System.out.println("Extension schema:"); System.out.println(extensionSchema.debugDump()); - - + + PrismPropertyDefinition locationsProperty = extensionSchema.findPropertyDefinitionByElementName(EXTENSION_LOCATIONS_ELEMENT); PrismAsserts.assertDefinition(locationsProperty, EXTENSION_LOCATIONS_ELEMENT, EXTENSION_LOCATIONS_TYPE, 0, -1); } - + public static void assertPropertyValue(PrismContainer container, String propName, Object propValue) { QName propQName = new QName(SchemaConstantsGenerated.NS_COMMON, propName); PrismAsserts.assertPropertyValue(container, propQName, propValue); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestSerialization.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestSerialization.java index 2ff5386390d..4d8e840a508 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestSerialization.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestSerialization.java @@ -41,16 +41,16 @@ * */ public class TestSerialization { - - - + + + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - - + + @Test public void testSerializeResource() throws Exception { System.out.println("===[ testSerializeResource ]==="); @@ -64,27 +64,27 @@ public void testSerializeUser() throws Exception { serializationRoundTrip(TestConstants.USER_FILE); } - + @Test public void testSerializeRole() throws Exception { System.out.println("===[ testSerializeRole ]==="); PrismContext prismContext = PrismTestUtil.getPrismContext(); - + PrismObject parsedObject = prismContext.parseObject(TestConstants.ROLE_FILE); - + System.out.println("Parsed object:"); System.out.println(parsedObject.debugDump()); - + RoleType parsedRoleType = parsedObject.asObjectable(); PolicyConstraintsType policyConstraints = parsedRoleType.getPolicyConstraints(); List minAssignees = policyConstraints.getMinAssignees(); minAssignees.iterator().next(); - + // WHEN serializationRoundTripPrismObject(parsedObject); serializationRoundTripObjectType(parsedRoleType); - + // WHEN String serializedMinAssignees = SerializationUtil.toString(minAssignees); List deserializedMinAssignees = SerializationUtil.fromString(serializedMinAssignees); @@ -93,29 +93,29 @@ public void testSerializeRole() throws Exception { private void serializationRoundTrip(File file) throws Exception { PrismContext prismContext = PrismTestUtil.getPrismContext(); - + PrismObject parsedObject = prismContext.parseObject(file); System.out.println("\nParsed object:"); System.out.println(parsedObject.debugDump()); - + serializationRoundTripPrismObject(parsedObject); serializationRoundTripObjectType(parsedObject.asObjectable()); } private void serializationRoundTripPrismObject(PrismObject parsedObject) throws Exception { - + // WHEN String serializedObject = SerializationUtil.toString(parsedObject); - + // THEN System.out.println("\nSerialized object:"); System.out.println(serializedObject); PrismObject deserializedObject = SerializationUtil.fromString(serializedObject); - + System.out.println("\nDeserialized object (PrismObject):"); System.out.println(deserializedObject.debugDump()); - + ObjectDelta diff = parsedObject.diff(deserializedObject); assertTrue("Something changed in serialization of "+parsedObject+" (PrismObject): "+diff, diff.isEmpty()); } @@ -124,13 +124,13 @@ private void serializationRoundTripObjectType(O parsedObj // WHEN String serializedObject = SerializationUtil.toString(parsedObject); - + // THEN O deserializedObject = SerializationUtil.fromString(serializedObject); - + System.out.println("Deserialized object (ObjectType):"); System.out.println(deserializedObject.asPrismObject().debugDump()); - + ObjectDelta diff = parsedObject.asPrismObject().diff((PrismObject) deserializedObject.asPrismObject()); assertTrue("Something changed in serializetion of "+parsedObject+" (ObjectType): "+diff, diff.isEmpty()); } diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseCertificationCase.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseCertificationCase.java index 8645a053182..c4f9c9a099c 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseCertificationCase.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseCertificationCase.java @@ -79,7 +79,7 @@ protected void assertPrismValue(PrismContainerValue assertEquals("Wrong CTD typeName", AccessCertificationAssignmentCaseType.COMPLEX_TYPE, ctd.getTypeName()); assertEquals("Wrong real class in PCV", AccessCertificationAssignmentCaseType.class, pcv.getRealClass()); } - + private void assertJaxb(AccessCertificationCaseType aCase) throws SchemaException { PrismAsserts.assertRefEquivalent("Wrong objectRef", new PrismReferenceValue("ee53eba7-5c16-4c16-ad15-dd6a2360ab1a", UserType.COMPLEX_TYPE), diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseForm.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseForm.java index 386a6ac054d..6e71e18090f 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseForm.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseForm.java @@ -134,7 +134,7 @@ private void assertFormPrism(PrismObject form, boolean isObject) { assertEquals("Wrong class in form", FormType.class, form.getCompileTimeClass()); FormType formType = form.asObjectable(); assertNotNull("asObjectable resulted in null", formType); - + assertPropertyValue(form, "name", PrismTestUtil.createPolyString("form1")); assertPropertyDefinition(form, "name", PolyStringType.COMPLEX_TYPE, 0, 1); @@ -142,7 +142,7 @@ private void assertFormPrism(PrismObject form, boolean isObject) { assertNotNull("no formDefinition property", formDefinition); } - + private void assertFormJaxb(FormType form, boolean isObject) throws SchemaException { assertEquals("Wrong name", PrismTestUtil.createPolyStringType("form1"), form.getName()); FormDefinitionType formDefinition = form.getFormDefinition(); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMapping.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMapping.java index cfb6b1b9e21..60cb0556e22 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMapping.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMapping.java @@ -84,7 +84,7 @@ protected void assertPrismPropertyValueLocal(PrismPropertyValue val // assertEquals("Wrong CTD typeName", AccessCertificationAssignmentCaseType.COMPLEX_TYPE, ctd.getTypeName()); // assertEquals("Wrong real class in PCV", AccessCertificationAssignmentCaseType.class, pcv.getRealClass()); // } - + // private void assertJaxb(AccessCertificationCaseType aCase) throws SchemaException { // PrismAsserts.assertRefEquivalent("Wrong objectRef", // new PrismReferenceValue("ee53eba7-5c16-4c16-ad15-dd6a2360ab1a", UserType.COMPLEX_TYPE), diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMappingConst.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMappingConst.java index 47d1d9a53f1..01862163917 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMappingConst.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMappingConst.java @@ -59,16 +59,16 @@ public void testParseFile() throws Exception { @Test public void testParseSerialize() throws Exception{ displayTestTitle("testParseSerialize"); - + PrismContext prismContext = getPrismContext(); PrismParser parser = prismContext.parserFor(getFile()); PrismPropertyValue mappingPval = parser.parseItemValue(); - + System.out.println("\nmappingPval:\n"+mappingPval.debugDump(1)); - + PrismSerializer xserializer = prismContext.xnodeSerializer(); RootXNode xnode = xserializer.root(new QName("dummy")).serialize(mappingPval); - + System.out.println("\nSerialized xnode:\n"+xnode.debugDump(1)); MapXNode xexpression = (MapXNode)((MapXNode)xnode.getSubnode()).get(new QName("expression")); ListXNode xconstList = (ListXNode) xexpression.get(new QName("const")); @@ -77,7 +77,7 @@ public void testParseSerialize() throws Exception{ AssertJUnit.fail("const is not primitive: "+xconst); } } - + @Test public void testParseRoundTrip() throws Exception{ displayTestTitle("testParseRoundTrip"); @@ -85,7 +85,7 @@ public void testParseRoundTrip() throws Exception{ processParsings(v -> getPrismContext().serializerFor(language).root(new QName("dummy")).serialize(v), "s1"); processParsings(v -> getPrismContext().serializerFor(language).root(SchemaConstantsGenerated.C_USER).serialize(v), "s2"); // misleading item name } - + private void processParsings(SerializingFunction> serializer, String serId) throws Exception { PrismPropertyDefinition definition = getPrismContext().getSchemaRegistry().findPropertyDefinitionByElementName(SchemaConstantsGenerated.C_MAPPING); processParsings(MappingType.class, MappingType.COMPLEX_TYPE, definition, serializer, serId); @@ -100,7 +100,7 @@ protected void assertPrismPropertyValueLocal(PrismPropertyValue val JAXBElement expressionEvaluatorElement = expressionEvaluatorElements.get(0); Object evaluatorElementObject = expressionEvaluatorElement.getValue(); if (!(evaluatorElementObject instanceof ConstExpressionEvaluatorType)) { - AssertJUnit.fail("Const expression is of type " + AssertJUnit.fail("Const expression is of type " + evaluatorElementObject.getClass().getName()); } ConstExpressionEvaluatorType constExpressionEvaluatorType = (ConstExpressionEvaluatorType)evaluatorElementObject; diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMappings.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMappings.java index bb11331a927..d111294f1c8 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMappings.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMappings.java @@ -72,7 +72,7 @@ public void assertPrismContainerValueLocal(PrismContainerValue val // assertEquals("Wrong CTD typeName", AccessCertificationAssignmentCaseType.COMPLEX_TYPE, ctd.getTypeName()); // assertEquals("Wrong real class in PCV", AccessCertificationAssignmentCaseType.class, pcv.getRealClass()); // } - + // private void assertJaxb(AccessCertificationCaseType aCase) throws SchemaException { // PrismAsserts.assertRefEquivalent("Wrong objectRef", // new PrismReferenceValue("ee53eba7-5c16-4c16-ad15-dd6a2360ab1a", UserType.COMPLEX_TYPE), diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMetarole.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMetarole.java index a2ebdf49098..d2ad5a93f1c 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMetarole.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseMetarole.java @@ -117,7 +117,7 @@ private void assertMetarolePrism(PrismObject metarole, boolean isObjec assertEquals("Wrong class in role", RoleType.class, metarole.getCompileTimeClass()); RoleType roleType = metarole.asObjectable(); assertNotNull("asObjectable resulted in null", roleType); - + assertPropertyValue(metarole, "name", PrismTestUtil.createPolyString("Generic Metarole")); assertPropertyDefinition(metarole, "name", PolyStringType.COMPLEX_TYPE, 0, 1); @@ -127,7 +127,7 @@ private void assertMetarolePrism(PrismObject metarole, boolean isObjec assertEquals("Wrong # of assignment constraints", 1, assignmentConstraints.size()); assertTrue("Wrong (not empty) assignment constraints", assignmentConstraints.getValues().get(0).isEmpty()); } - + private void assertMetaroleJaxb(RoleType roleType, boolean isObject) throws SchemaException { assertEquals("Wrong name", PrismTestUtil.createPolyStringType("Generic Metarole"), roleType.getName()); boolean found = false; diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseResource.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseResource.java index af0454c9673..653d2c04f59 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseResource.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseResource.java @@ -231,14 +231,14 @@ public void testParseResourceFileExpression() throws Exception { // THEN System.out.println("Parsed resource:"); System.out.println(resource.debugDump()); - + assertResourceExpression(resource, prismContext, true); } - + private void assertResourceExpression(PrismObject resource, PrismContext prismContext, boolean checkExpressions) throws SchemaException { resource.checkConsistence(); - + AssertJUnit.assertEquals("Wrong oid (prism)", TestConstants.RESOURCE_OID, resource.getOid()); PrismObjectDefinition resourceDefinition = resource.getDefinition(); assertNotNull("No resource definition", resourceDefinition); @@ -270,14 +270,14 @@ private void assertResourceExpression(PrismObject resource, PrismC hostProp.applyDefinition(new PrismPropertyDefinitionImpl<>(new QName("whatever","host"), DOMUtil.XSD_STRING, prismContext)); assertNotRaw(hostProp); assertExpression(hostProp, "const"); - + PrismProperty baseContextsProp = findProp(ldapConfigPropItems, "baseContexts"); assertRaw(baseContextsProp); baseContextsProp.applyDefinition(new PrismPropertyDefinitionImpl<>(new QName("whatever","baseContexts"), DOMUtil.XSD_STRING, prismContext)); assertNotRaw(baseContextsProp); assertExpression(baseContextsProp, "script"); } - + PrismContainer schemaContainer = resource.findContainer(ResourceType.F_SCHEMA); assertNull("Schema sneaked in", schemaContainer); @@ -285,7 +285,7 @@ private void assertResourceExpression(PrismObject resource, PrismC assertNull("SchemaHandling sneaked in", schemaHandlingContainer); } - + @Test public void testParseResourceExpressionRoundtripXml() throws Exception { displayTestTitle("testParseResourceExpressionRoundtripXml"); @@ -342,14 +342,14 @@ private void doTestParseResourceExpressionRoundtrip(String serializeInto) throws assertTrue("Delta is not empty", objectDelta.isEmpty()); PrismAsserts.assertEquivalent("Resource re-parsed equivalence", resource, reparsedResource); - + // SERIALIZE (2) // Do roundtrip again, this time after the expressions were checked and definitions applied. - + assertResourceExpression(resource, prismContext, true); System.out.println("\nResource (2):"); System.out.println(resource.debugDump()); - + serializedResource = prismContext.serializerFor(serializeInto).serialize(resource); System.out.println("\nserialized resource (2):"); @@ -369,11 +369,11 @@ private void doTestParseResourceExpressionRoundtrip(String serializeInto) throws assertResourceExpression(reparsedResource, prismContext, true); } - + private void assertRaw(PrismProperty prop) { assertTrue("Prop "+prop+" no raw", prop.isRaw()); } - + private void assertNotRaw(PrismProperty prop) { assertFalse("Prop "+prop+" raw (unexpected)", prop.isRaw()); } @@ -404,7 +404,7 @@ private void assertExpression(PrismProperty prop, String evaluatorName) assertEquals("Wrong expression evaluator name", evaluatorName, evaluatorElement.getName().getLocalPart()); } } - + @Override protected void assertPrismContainerValueLocal(PrismContainerValue value) throws SchemaException { //assertResource(object.asContainerable().asPrismObject(), true, true); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseShadow.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseShadow.java index 6a1f91dbc7f..d80e313d1de 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseShadow.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseShadow.java @@ -114,7 +114,7 @@ void assertPrism(PrismObject shadow, boolean isObject) { assertEquals("Wrong class in object", ShadowType.class, shadow.getCompileTimeClass()); ShadowType objectType = shadow.asObjectable(); assertNotNull("asObjectable resulted in null", objectType); - + assertPropertyValue(shadow, "name", PrismTestUtil.createPolyString("hbarbossa")); assertPropertyDefinition(shadow, "name", PolyStringType.COMPLEX_TYPE, 0, 1); @@ -122,19 +122,19 @@ void assertPrism(PrismObject shadow, boolean isObject) { // assertPropertyValues(shadow, "organizationalUnit", // new PolyString("Brethren of the Coast", "brethren of the coast"), // new PolyString("Davie Jones' Locker", "davie jones locker")); - + ItemPath admStatusPath = new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS); PrismProperty admStatusProperty1 = shadow.findProperty(admStatusPath); PrismAsserts.assertDefinition(admStatusProperty1.getDefinition(), ActivationType.F_ADMINISTRATIVE_STATUS, SchemaConstants.C_ACTIVATION_STATUS_TYPE, 0, 1); assertNotNull("Property "+admStatusPath+" not found", admStatusProperty1); PrismAsserts.assertPropertyValue(admStatusProperty1, ActivationStatusType.ENABLED); - + PrismReference resourceRef = shadow.findReference(ShadowType.F_RESOURCE_REF); assertEquals("Wrong number of resourceRef values", 1, resourceRef.getValues().size()); PrismAsserts.assertReferenceValue(resourceRef, "10000000-0000-0000-0000-000000000003"); } - + private void assertJaxb(ShadowType shadow, boolean isObject) throws SchemaException { if (isObject) { assertEquals("88519fca-3f4a-44ca-91c8-dc9be5bf3d03", shadow.getOid()); @@ -144,7 +144,7 @@ private void assertJaxb(ShadowType shadow, boolean isObject) throws SchemaExcept ActivationType activation = shadow.getActivation(); assertNotNull("No activation", activation); assertEquals("User not enabled", ActivationStatusType.ENABLED, activation.getAdministrativeStatus()); - + ObjectReferenceType resourceRef = shadow.getResourceRef(); assertNotNull("No resourceRef", resourceRef); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseUser.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseUser.java index 4602ec23335..24bb41479c4 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseUser.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/parser/TestParseUser.java @@ -127,7 +127,7 @@ void assertUserPrism(PrismObject user, boolean isObject) { assertEquals("Wrong class in user", UserType.class, user.getCompileTimeClass()); UserType userType = user.asObjectable(); assertNotNull("asObjectable resulted in null", userType); - + assertPropertyValue(user, "name", PrismTestUtil.createPolyString("jack")); assertPropertyDefinition(user, "name", PolyStringType.COMPLEX_TYPE, 0, 1); assertPropertyValue(user, "fullName", new PolyString("Jack Sparrow", "jack sparrow")); @@ -136,33 +136,33 @@ void assertUserPrism(PrismObject user, boolean isObject) { assertPropertyDefinition(user, "givenName", PolyStringType.COMPLEX_TYPE, 0, 1); assertPropertyValue(user, "familyName", new PolyString("Sparrow", "sparrow")); assertPropertyDefinition(user, "familyName", PolyStringType.COMPLEX_TYPE, 0, 1); - + assertPropertyDefinition(user, "organizationalUnit", PolyStringType.COMPLEX_TYPE, 0, -1); - assertPropertyValues(user, "organizationalUnit", + assertPropertyValues(user, "organizationalUnit", new PolyString("Brethren of the Coast", "brethren of the coast"), new PolyString("Davie Jones' Locker", "davie jones locker")); - + // PrismContainer extension = user.getExtension(); // assertContainerDefinition(extension, "extension", DOMUtil.XSD_ANY, 0, 1); // PrismContainerValue extensionValue = extension.getValue(); // assertTrue("Extension parent", extensionValue.getParent() == extension); // assertNull("Extension ID", extensionValue.getId()); - + ItemPath admStatusPath = new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS); PrismProperty admStatusProperty1 = user.findProperty(admStatusPath); PrismAsserts.assertDefinition(admStatusProperty1.getDefinition(), ActivationType.F_ADMINISTRATIVE_STATUS, SchemaConstants.C_ACTIVATION_STATUS_TYPE, 0, 1); assertNotNull("Property "+admStatusPath+" not found", admStatusProperty1); PrismAsserts.assertPropertyValue(admStatusProperty1, ActivationStatusType.ENABLED); - + // PrismProperty validFromProperty = user.findProperty(new PropertyPath(UserType.F_ACTIVATION, ActivationType.F_VALID_FROM)); // assertNotNull("Property "+ActivationType.F_VALID_FROM+" not found", validFromProperty); // PrismAsserts.assertPropertyValue(validFromProperty, USER_JACK_VALID_FROM); - + PrismContainer assignmentContainer = user.findContainer(UserType.F_ASSIGNMENT); PrismAsserts.assertDefinition(assignmentContainer.getDefinition(), UserType.F_ASSIGNMENT, AssignmentType.COMPLEX_TYPE, 0, -1); assertEquals("Wrong number of assignment values", 1, assignmentContainer.getValues().size()); PrismContainerValue firstAssignmentValue = assignmentContainer.getValues().iterator().next(); - + PrismContainer assignmentExtensionContainer = firstAssignmentValue.findContainer(AssignmentType.F_EXTENSION); PrismAsserts.assertDefinition(assignmentExtensionContainer.getDefinition(), AssignmentType.F_EXTENSION, ExtensionType.COMPLEX_TYPE, 0, 1); List> assignmentExtensionItems = assignmentExtensionContainer.getValue().getItems(); @@ -188,13 +188,13 @@ void assertUserPrism(PrismObject user, boolean isObject) { PrismAsserts.assertReferenceValue(accountRef, USER_ACCOUNT_REF_1_OID); PrismAsserts.assertReferenceValue(accountRef, USER_ACCOUNT_REF_2_OID); PrismAsserts.assertReferenceValue(accountRef, USER_ACCOUNT_REF_3_OID); - + PrismReferenceValue accountRef1Val = accountRef.findValueByOid(USER_ACCOUNT_REF_1_OID); assertNotNull("No object in ref1 (prism)", accountRef1Val.getObject()); assertNotNull("No object definition in ref1 (prism)", accountRef1Val.getObject().getDefinition()); assertEquals("Wrong ref1 oid (prism)", USER_ACCOUNT_REF_1_OID, accountRef1Val.getOid()); assertEquals("Wrong ref1 type (prism)", ShadowType.COMPLEX_TYPE, accountRef1Val.getTargetType()); - + PrismReferenceValue accountRef3Val = accountRef.findValueByOid(USER_ACCOUNT_REF_3_OID); assertEquals("Wrong ref3 oid (prism)", USER_ACCOUNT_REF_3_OID, accountRef3Val.getOid()); assertEquals("Wrong ref3 type (prism)", ShadowType.COMPLEX_TYPE, accountRef3Val.getTargetType()); @@ -202,7 +202,7 @@ void assertUserPrism(PrismObject user, boolean isObject) { SearchFilterType accountRef3ValFilterElement = accountRef3Val.getFilter(); assertFilter("ref3", accountRef3ValFilterElement); } - + private void assertFilterElement(String message, Element filterElement) { assertNotNull("No "+message+" filter", filterElement); System.out.println("Filter element "+message); @@ -229,11 +229,11 @@ private void assertUserJaxb(UserType userType, boolean isObject) throws SchemaEx ActivationType activation = userType.getActivation(); assertNotNull("No activation", activation); assertEquals("User not enabled", ActivationStatusType.ENABLED, activation.getAdministrativeStatus()); - + List accountRefs = userType.getLinkRef(); assertNotNull("No accountRef list", accountRefs); assertEquals("Wrong number of list entries", 3, accountRefs.size()); - + ObjectReferenceType ref1 = ObjectTypeUtil.findRef(USER_ACCOUNT_REF_1_OID, accountRefs); assertEquals("Wrong ref1 oid (jaxb)", USER_ACCOUNT_REF_1_OID, ref1.getOid()); assertEquals("Wrong ref1 type (jaxb)", ShadowType.COMPLEX_TYPE, ref1.getType()); @@ -241,7 +241,7 @@ private void assertUserJaxb(UserType userType, boolean isObject) throws SchemaEx ObjectReferenceType ref2 = ObjectTypeUtil.findRef(USER_ACCOUNT_REF_2_OID, accountRefs); assertEquals("Wrong ref2 oid (jaxb)", USER_ACCOUNT_REF_2_OID, ref2.getOid()); assertEquals("Wrong ref2 type (jaxb)", ShadowType.COMPLEX_TYPE, ref2.getType()); - + ObjectReferenceType ref3 = ObjectTypeUtil.findRef(USER_ACCOUNT_REF_3_OID, accountRefs); assertEquals("Wrong ref3 oid (jaxb)", USER_ACCOUNT_REF_3_OID, ref3.getOid()); assertEquals("Wrong ref3 type (jaxb)", ShadowType.COMPLEX_TYPE, ref3.getType()); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/processor/SchemaProcessorTest.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/processor/SchemaProcessorTest.java index b2dbce98c0a..6c6f5b1980a 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/processor/SchemaProcessorTest.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/processor/SchemaProcessorTest.java @@ -53,47 +53,47 @@ public class SchemaProcessorTest { private static final String SCHEMA_NS = "http://foo.com/xml/ns/schema"; - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - + @Test public void testAccessList() throws Exception { String filename = "src/test/resources/processor/resource-schema-complex.xsd"; Document schemaDom = DOMUtil.parseFile(filename); ResourceSchema schema = ResourceSchemaImpl.parse(DOMUtil.getFirstChildElement(schemaDom), filename, PrismTestUtil.getPrismContext()); - + final String defaultNS = "http://midpoint.evolveum.com/xml/ns/public/resource/instances/ef2bc95b-76e0-48e2-86d6-3d4f02d3e1a2"; final String icfNS = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/resource-schema-3"; ObjectClassComplexTypeDefinition objectDef = schema.findObjectClassDefinition(new QName(defaultNS, "AccountObjectClass")); assertNotNull("AccountObjectClass definition not found", objectDef); - + ResourceAttributeDefinition attrDef = objectDef.findAttributeDefinition(new QName(icfNS, "uid")); AssertJUnit.assertTrue("uid readability", attrDef.canRead()); AssertJUnit.assertFalse("uid updateability", attrDef.canModify()); AssertJUnit.assertFalse("uid createability", attrDef.canAdd()); - + attrDef = objectDef.findAttributeDefinition(new QName(defaultNS, "title")); AssertJUnit.assertTrue(attrDef.canRead()); AssertJUnit.assertTrue(attrDef.canModify()); AssertJUnit.assertTrue(attrDef.canAdd()); - + attrDef = objectDef.findAttributeDefinition(new QName(defaultNS, "photo")); AssertJUnit.assertFalse(attrDef.canRead()); AssertJUnit.assertTrue(attrDef.canModify()); AssertJUnit.assertTrue(attrDef.canAdd()); } - + @Test public void testRoundTripGeneric() throws SchemaException { // GIVEN PrismSchemaImpl schema = new PrismSchemaImpl(SCHEMA_NS, PrismTestUtil.getPrismContext()); // Ordinary property schema.createPropertyDefinition("number1", DOMUtil.XSD_INT); - + // Property container PrismContainerDefinitionImpl containerDefinition = schema.createPropertyContainerDefinition("ContainerType"); // ... in it ordinary property @@ -102,7 +102,7 @@ public void testRoundTripGeneric() throws SchemaException { containerDefinition.createPropertyDefinition("password", ProtectedStringType.COMPLEX_TYPE); // ... property reference containerDefinition.createPropertyDefinition(SchemaConstants.C_CREDENTIALS, CredentialsType.COMPLEX_TYPE); - // ... read-only int property + // ... read-only int property PrismPropertyDefinition counterProperty = containerDefinition.createPropertyDefinition("counter", DOMUtil.XSD_INT); ((PrismPropertyDefinitionImpl) counterProperty).setReadOnly(); @@ -111,32 +111,32 @@ public void testRoundTripGeneric() throws SchemaException { System.out.println(); // WHEN - + Document xsd = schema.serializeToXsd(); - + String stringXmlSchema = DOMUtil.serializeDOMToString(xsd); - + System.out.println("Generic schema after serializing to XSD: "); System.out.println(stringXmlSchema); System.out.println(); - + Document parsedXsd = DOMUtil.parseDocument(stringXmlSchema); - + PrismSchema newSchema = PrismSchemaImpl.parse(DOMUtil.getFirstChildElement(parsedXsd), true, "serialized schema", PrismTestUtil.getPrismContext()); System.out.println("Generic schema after parsing from XSD: "); System.out.println(newSchema.debugDump()); System.out.println(); - + // THEN - + PrismPropertyDefinition number1def = newSchema.findItemDefinitionByElementName(new QName(SCHEMA_NS,"number1"), PrismPropertyDefinition.class); assertEquals(new QName(SCHEMA_NS,"number1"),number1def.getName()); assertEquals(DOMUtil.XSD_INT,number1def.getTypeName()); - + PrismContainerDefinition newContainerDef = schema.findContainerDefinitionByType(new QName(SCHEMA_NS,"ContainerType")); assertEquals(new QName(SCHEMA_NS,"ContainerType"),newContainerDef.getTypeName()); - + PrismPropertyDefinition loginDef = newContainerDef.findPropertyDefinition(new QName(SCHEMA_NS,"login")); assertEquals(new QName(SCHEMA_NS,"login"), loginDef.getName()); assertEquals(DOMUtil.XSD_STRING, loginDef.getTypeName()); @@ -160,12 +160,12 @@ public void testRoundTripGeneric() throws SchemaException { assertFalse("Update flag is wrong",countDef.canModify()); } - + @Test public void testRoundTripResource() throws SchemaException { // GIVEN ResourceSchemaImpl schema = new ResourceSchemaImpl(SCHEMA_NS, PrismTestUtil.getPrismContext()); - + // Property container ObjectClassComplexTypeDefinitionImpl containerDefinition = (ObjectClassComplexTypeDefinitionImpl) schema.createObjectClassDefinition("AccountObjectClass"); containerDefinition.setKind(ShadowKindType.ACCOUNT); @@ -191,30 +191,30 @@ public void testRoundTripResource() throws SchemaException { System.out.println(); // WHEN - + Document xsd = schema.serializeToXsd(); - + String stringXmlSchema = DOMUtil.serializeDOMToString(xsd); - + System.out.println("Resource schema after serializing to XSD: "); System.out.println(stringXmlSchema); System.out.println(); - + Document parsedXsd = DOMUtil.parseDocument(stringXmlSchema); - + ResourceSchema newSchema = ResourceSchemaImpl.parse(DOMUtil.getFirstChildElement(parsedXsd), "serialized schema", PrismTestUtil.getPrismContext()); System.out.println("Resource schema after parsing from XSD: "); System.out.println(newSchema.debugDump()); System.out.println(); - + // THEN - + ObjectClassComplexTypeDefinition newObjectClassDef = newSchema.findObjectClassDefinition(new QName(SCHEMA_NS,"AccountObjectClass")); assertEquals(new QName(SCHEMA_NS,"AccountObjectClass"),newObjectClassDef.getTypeName()); assertEquals(ShadowKindType.ACCOUNT, newObjectClassDef.getKind()); assertTrue(newObjectClassDef.isDefaultInAKind()); - + PrismPropertyDefinition loginDef = newObjectClassDef.findPropertyDefinition(new QName(SCHEMA_NS,"login")); assertEquals(new QName(SCHEMA_NS,"login"), loginDef.getName()); assertEquals(DOMUtil.XSD_STRING, loginDef.getTypeName()); @@ -229,12 +229,12 @@ public void testRoundTripResource() throws SchemaException { // assertEquals(new QName(SchemaConstants.NS_C,"credentials"), credDef.getName()); // assertEquals(new QName(SchemaConstants.NS_C,"CredentialsType"), credDef.getTypeName()); // assertFalse(credDef.isIgnored()); - + PrismPropertyDefinition sepDef = newObjectClassDef.findPropertyDefinition(new QName(SCHEMA_NS,"sep")); assertEquals(new QName(SCHEMA_NS,"sep"), sepDef.getName()); assertEquals(DOMUtil.XSD_STRING, sepDef.getTypeName()); assertTrue(sepDef.isIgnored()); - + } } diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/processor/TestResourceSchema.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/processor/TestResourceSchema.java index c57ec37595c..297926e3c0d 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/processor/TestResourceSchema.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/processor/TestResourceSchema.java @@ -71,7 +71,7 @@ public class TestResourceSchema { private static final String RESOURCE_SCHEMA_SIMPLE_FILENAME = TEST_DIR + "resource-schema-simple.xsd"; private static final String RESOURCE_SCHEMA_SIMPLE_DEPRECATED_FILENAME = TEST_DIR + "resource-schema-simple-deprecated.xsd"; - + private static final String SCHEMA_NAMESPACE = "http://schema.foo.com/bar"; public TestResourceSchema() { @@ -82,7 +82,7 @@ public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - + @Test public void testParseSchema() throws Exception { System.out.println("===[ testParseSchema ]==="); @@ -98,7 +98,7 @@ public void testParseSchema() throws Exception { // THEN assertSimpleSchema(schema, RESOURCE_SCHEMA_SIMPLE_FILENAME); } - + @Test public void testParseSchemaDeprecated() throws Exception { System.out.println("===[ testParseSchemaDeprecated ]==="); @@ -114,7 +114,7 @@ public void testParseSchemaDeprecated() throws Exception { // THEN assertSimpleSchema(schema, RESOURCE_SCHEMA_SIMPLE_DEPRECATED_FILENAME); } - + private void assertSimpleSchema(ResourceSchema schema, String filename) { assertNotNull(schema); System.out.println("Parsed schema from " + filename + ":"); @@ -125,35 +125,35 @@ private void assertSimpleSchema(ResourceSchema schema, String filename) { assertEquals("Wrong account kind", ShadowKindType.ACCOUNT, accDef.getKind()); assertEquals("Wrong account intent", "admin", accDef.getIntent()); assertTrue("Not a default account", accDef.isDefaultInAKind()); - + PrismPropertyDefinition loginAttrDef = accDef.findPropertyDefinition(new QName(SCHEMA_NAMESPACE, "login")); assertEquals(new QName(SCHEMA_NAMESPACE, "login"), loginAttrDef.getName()); assertEquals(DOMUtil.XSD_STRING, loginAttrDef.getTypeName()); assertFalse("Ignored while it should not be", loginAttrDef.isIgnored()); - + PrismPropertyDefinition groupAttrDef = accDef.findPropertyDefinition(new QName(SCHEMA_NAMESPACE, "group")); assertEquals(new QName(SCHEMA_NAMESPACE, "group"), groupAttrDef.getName()); assertEquals(DOMUtil.XSD_INT, groupAttrDef.getTypeName()); assertFalse("Ignored while it should not be", groupAttrDef.isIgnored()); - + PrismPropertyDefinition ufoAttrDef = accDef.findPropertyDefinition(new QName(SCHEMA_NAMESPACE, "ufo")); assertEquals(new QName(SCHEMA_NAMESPACE, "ufo"), ufoAttrDef.getName()); assertTrue("Not ignored as it should be", ufoAttrDef.isIgnored()); - + ObjectClassComplexTypeDefinition groupDef = schema.findObjectClassDefinition(new QName(SCHEMA_NAMESPACE, "GroupObjectClass")); assertEquals("Wrong group objectclass", new QName(SCHEMA_NAMESPACE, "GroupObjectClass"), groupDef.getTypeName()); assertEquals("Wrong group kind", ShadowKindType.ENTITLEMENT, groupDef.getKind()); assertEquals("Wrong group intent", null, groupDef.getIntent()); assertFalse("Default group but it should not be", groupDef.isDefaultInAKind()); } - + // The support for the xsd:any properties is missing in JAXB generator. Otherwise this test should work. @Test(enabled=false) public void testResourceSchemaJaxbRoundTrip() throws SchemaException, JAXBException { System.out.println("\n===[ testResourceSchemaJaxbRoundTrip ]====="); // GIVEN ResourceSchema schema = createResourceSchema(); - + System.out.println("Resource schema before serializing to XSD: "); System.out.println(schema.debugDump()); System.out.println(); @@ -163,41 +163,41 @@ public void testResourceSchemaJaxbRoundTrip() throws SchemaException, JAXBExcept ResourceType resource = new ResourceType(); resource.setName(PrismTestUtil.createPolyStringType("JAXB With Dynamic Schemas Test")); ResourceTypeUtil.setResourceXsdSchema(resource, DOMUtil.getFirstChildElement(xsd)); - + // WHEN - + // JAXBElement resourceElement = new JAXBElement(SchemaConstants.C_RESOURCE, ResourceType.class, resource); // String marshalledResource = PrismTestUtil.marshalElementToString(resourceElement); String marshalledResource = PrismTestUtil.serializeObjectToString(resource.asPrismObject()); System.out.println("Marshalled resource"); - System.out.println(marshalledResource); - + System.out.println(marshalledResource); + ResourceType unmarshalledResource = (ResourceType) PrismTestUtil.parseObject(marshalledResource).asObjectable(); - + System.out.println("unmarshalled resource"); System.out.println(ObjectTypeUtil.dump(unmarshalledResource)); XmlSchemaType unXmlSchemaType = unmarshalledResource.getSchema(); Element unXsd = unXmlSchemaType.getDefinition().getAny().get(0); ResourceSchema unSchema = ResourceSchemaImpl.parse(unXsd, "unmarshalled resource", PrismTestUtil.getPrismContext()); - + System.out.println("unmarshalled schema"); System.out.println(unSchema.debugDump()); - + // THEN assertResourceSchema(unSchema); } - + @Test public void testResourceSchemaPrismRoundTrip() throws SchemaException, JAXBException { System.out.println("\n===[ testResourceSchemaPrismRoundTrip ]====="); // GIVEN ResourceSchema schema = createResourceSchema(); - + System.out.println("Resource schema before serializing to XSD: "); System.out.println(schema.debugDump()); System.out.println(); - + PrismContext prismContext = PrismTestUtil.getPrismContext(); Document xsd = schema.serializeToXsd(); @@ -207,39 +207,39 @@ public void testResourceSchemaPrismRoundTrip() throws SchemaException, JAXBExcep ResourceType resourceType = resource.asObjectable(); resourceType.setName(PrismTestUtil.createPolyStringType("Prism With Dynamic Schemas Test")); ResourceTypeUtil.setResourceXsdSchema(resource, DOMUtil.getFirstChildElement(xsd)); - + // WHEN - + String marshalledResource = prismContext.serializeObjectToString(resource, PrismContext.LANG_XML); - + System.out.println("Marshalled resource"); - System.out.println(marshalledResource); - + System.out.println(marshalledResource); + PrismObject unmarshalledResource = PrismTestUtil.parseObject(marshalledResource); - + System.out.println("unmarshalled resource"); System.out.println(unmarshalledResource.debugDump()); - + Element unXsd = ResourceTypeUtil.getResourceXsdSchema(unmarshalledResource); - + System.out.println("unmarshalled resource schema"); System.out.println(DOMUtil.serializeDOMToString(unXsd)); - + ResourceSchema unSchema = ResourceSchemaImpl.parse(unXsd, "unmarshalled resource schema", PrismTestUtil.getPrismContext()); - + System.out.println("unmarshalled parsed schema"); System.out.println(unSchema.debugDump()); - + // THEN assertResourceSchema(unSchema); } - + private void assertResourceSchema(ResourceSchema unSchema) { ObjectClassComplexTypeDefinition objectClassDef = unSchema.findObjectClassDefinition(new QName(SCHEMA_NAMESPACE,"AccountObjectClass")); assertEquals(new QName(SCHEMA_NAMESPACE,"AccountObjectClass"),objectClassDef.getTypeName()); assertEquals("AccountObjectClass class not an account", ShadowKindType.ACCOUNT, objectClassDef.getKind()); assertTrue("AccountObjectClass class not a DEFAULT account", objectClassDef.isDefaultInAKind()); - + PrismPropertyDefinition loginDef = objectClassDef.findPropertyDefinition(new QName(SCHEMA_NAMESPACE,"login")); assertEquals(new QName(SCHEMA_NAMESPACE,"login"), loginDef.getName()); assertEquals(DOMUtil.XSD_STRING, loginDef.getTypeName()); @@ -252,20 +252,20 @@ private void assertResourceSchema(ResourceSchema unSchema) { // assertEquals(new QName(SchemaConstants.NS_C,"credentials"), credDef.getName()); // assertEquals(new QName(SchemaConstants.NS_C,"CredentialsType"), credDef.getTypeName()); } - + @Test public void testResourceSchemaSerializationDom() throws SchemaException, JAXBException { System.out.println("\n===[ testResourceSchemaSerializationDom ]====="); // GIVEN ResourceSchema schema = createResourceSchema(); - + // WHEN Document xsdDocument = schema.serializeToXsd(); Element xsdElement = DOMUtil.getFirstChildElement(xsdDocument); - + System.out.println("Serialized XSD schema"); System.out.println(DOMUtil.serializeDOMToString(xsdElement)); - + assertDomSchema(xsdElement); } @@ -274,32 +274,32 @@ public void testResourceSchemaSerializationInResource() throws SchemaException, System.out.println("\n===[ testResourceSchemaSerializationInResource ]====="); // GIVEN ResourceSchema schema = createResourceSchema(); - + // WHEN Document xsdDocument = schema.serializeToXsd(); Element xsdElement = DOMUtil.getFirstChildElement(xsdDocument); - + PrismObject resource = wrapInResource(xsdElement); String resourceXmlString = PrismTestUtil.getPrismContext().serializeObjectToString(resource, PrismContext.LANG_XML); - + System.out.println("Serialized resource"); System.out.println(resourceXmlString); - + PrismObject reparsedResource = PrismTestUtil.getPrismContext().parseObject(resourceXmlString); - + System.out.println("Re-parsed resource"); System.out.println(reparsedResource.debugDump()); - + XmlSchemaType reparsedSchemaType = reparsedResource.asObjectable().getSchema(); Element reparsedXsdElement = ObjectTypeUtil.findXsdElement(reparsedSchemaType); - + System.out.println("Reparsed XSD schema"); System.out.println(DOMUtil.serializeDOMToString(reparsedXsdElement)); - + assertDomSchema(reparsedXsdElement); } - + private PrismObject wrapInResource(Element xsdElement) throws SchemaException { PrismObjectDefinition resourceDefinition = PrismTestUtil.getPrismContext().getSchemaRegistry().findObjectDefinitionByCompileTimeClass(ResourceType.class); @@ -325,13 +325,13 @@ private void assertDomSchema(Element xsdElement) { assertPrefix("ra", dnaAnnotationElement); QName dna = DOMUtil.getQNameValue(dnaAnnotationElement); assertEquals("Wrong value prefix", "tns", dna.getPrefix()); - + assertEquals("Wrong 'tns' prefix declaration", SCHEMA_NAMESPACE, xsdElement.lookupNamespaceURI("tns")); } private ResourceSchema createResourceSchema() { ResourceSchemaImpl schema = new ResourceSchemaImpl(SCHEMA_NAMESPACE, PrismTestUtil.getPrismContext()); - + // Property container ObjectClassComplexTypeDefinitionImpl containerDefinition = (ObjectClassComplexTypeDefinitionImpl) schema.createObjectClassDefinition("AccountObjectClass"); containerDefinition.setKind(ShadowKindType.ACCOUNT); @@ -354,47 +354,47 @@ private ResourceSchema createResourceSchema() { return schema; } - + private void assertPrefix(String expectedPrefix, Element element) { assertEquals("Wrong prefix on element "+DOMUtil.getQName(element), expectedPrefix, element.getPrefix()); - } - + } + @Test public void testParseResource() throws Exception { System.out.println("===[ testParseResource ]==="); // WHEN PrismObject resource = PrismTestUtil.parseObject(new File("src/test/resources/common/xml/ns/resource-opendj.xml")); - + // THEN assertCapabilities(resource.asObjectable()); } - + @Test public void testUnmarshallResource() throws Exception { System.out.println("===[ testUnmarshallResource ]==="); // WHEN ResourceType resourceType = (ResourceType) PrismTestUtil.parseObject(new File("src/test/resources/common/xml/ns/resource-opendj.xml")).asObjectable(); - + // THEN assertCapabilities(resourceType); } - + private void assertCapabilities(ResourceType resourceType) throws SchemaException { - if (resourceType.getCapabilities() != null) { + if (resourceType.getCapabilities() != null) { if (resourceType.getCapabilities().getNative() != null) { for (Object capability : resourceType.getCapabilities().getNative().getAny()) { System.out.println("Native Capability: "+CapabilityUtil.getCapabilityDisplayName(capability)+" : "+capability); } } - + if (resourceType.getCapabilities().getConfigured() != null) { for (Object capability : resourceType.getCapabilities().getConfigured().getAny()) { System.out.println("Configured Capability: "+CapabilityUtil.getCapabilityDisplayName(capability)+" : "+capability); } } } - + List effectiveCapabilities = ResourceTypeUtil.getEffectiveCapabilities(resourceType); for (Object capability : effectiveCapabilities) { System.out.println("Efective Capability: "+CapabilityUtil.getCapabilityDisplayName(capability)+" : "+capability); @@ -403,19 +403,19 @@ private void assertCapabilities(ResourceType resourceType) throws SchemaExceptio assertNotNull("null native capabilities", resourceType.getCapabilities().getNative()); assertFalse("empty native capabilities", resourceType.getCapabilities().getNative().getAny().isEmpty()); assertEquals("Unexepected number of native capabilities", 3, resourceType.getCapabilities().getNative().getAny().size()); - + assertNotNull("null configured capabilities", resourceType.getCapabilities().getConfigured()); assertFalse("empty configured capabilities", resourceType.getCapabilities().getConfigured().getAny().isEmpty()); assertEquals("Unexepected number of configured capabilities", 2, resourceType.getCapabilities().getConfigured().getAny().size()); - + assertEquals("Unexepected number of effective capabilities", 3,effectiveCapabilities.size()); - assertNotNull("No credentials effective capability", + assertNotNull("No credentials effective capability", ResourceTypeUtil.getEffectiveCapability(resourceType, CredentialsCapabilityType.class)); - assertNotNull("No activation effective capability", + assertNotNull("No activation effective capability", ResourceTypeUtil.getEffectiveCapability(resourceType, ActivationCapabilityType.class)); - assertNull("Unexpected liveSync effective capability", + assertNull("Unexpected liveSync effective capability", ResourceTypeUtil.getEffectiveCapability(resourceType, LiveSyncCapabilityType.class)); - + } diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/test/XPathTest.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/test/XPathTest.java index c64e17c8012..b73cee68780 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/test/XPathTest.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/test/XPathTest.java @@ -85,7 +85,7 @@ public class XPathTest { public XPathTest() { } - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); @@ -171,7 +171,7 @@ public void xpathTest() throws JAXBException, FileNotFoundException, IOException public void xPathFromDomNode1() throws ParserConfigurationException, SAXException, IOException { // Given - Element el1 = parseDataGetEl1(); + Element el1 = parseDataGetEl1(); String xpathString = "/root/x:el1[100]"; el1.setTextContent(xpathString); @@ -217,7 +217,7 @@ private Element parseDataGetEl1() throws ParserConfigurationException, SAXExcept NodeList nodes = ((Element) rootNode).getElementsByTagNameNS("http://xx.com/", "el1"); Node el1 = nodes.item(0); - + return (Element)el1; } @@ -316,7 +316,7 @@ public void pureXPathRoundTripTest() { Map namespaceMap = new HashMap(); namespaceMap.put("foo", "http://foo"); namespaceMap.put("bar", "http://bar"); - + String xpathStr = "foo:foo/bar:bar"; ItemPathHolder xpath = new ItemPathHolder(xpathStr, namespaceMap); @@ -357,21 +357,21 @@ public void strangeCharsTest() throws IOException { System.out.println("Stragechars ROUND TRIP: "+xpath.getXPathWithDeclarations()); } - + @Test public void xpathFromQNameTest() { // GIVEN QName qname = new QName(NS_FOO, "foo"); ItemPathHolder xpath = new ItemPathHolder(qname); QName elementQName = new QName(NS_BAR, "bar"); - + // WHEN Element element = xpath.toElement(elementQName, DOMUtil.getDocument()); - + // THEN System.out.println("XPath from Qname:"); System.out.println(DOMUtil.serializeDOMToString(element)); - + assertEquals("Wrong element name", "bar", element.getLocalName()); assertEquals("Wrong element namespace", NS_BAR, element.getNamespaceURI()); Map nsdecls = DOMUtil.getNamespaceDeclarations(element); @@ -430,7 +430,7 @@ public void testUndefinedPrefix() throws ParserConfigurationException, SAXExcept try { // WHEN ItemPathHolder xpath = new ItemPathHolder(el1); - + AssertJUnit.fail("Unexpected success"); } catch (IllegalArgumentException e) { // This is expected diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/util/JAXBUtilTest.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/util/JAXBUtilTest.java index db72091955b..75204264260 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/util/JAXBUtilTest.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/util/JAXBUtilTest.java @@ -43,7 +43,7 @@ */ @Deprecated public class JAXBUtilTest { - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); @@ -53,10 +53,10 @@ public void setup() throws SchemaException, SAXException, IOException { @Test public void testUnmarshallerUtf() throws JAXBException, SchemaException, FileNotFoundException { // GIVEN - + UserType user = JaxbTestUtil.getInstance().unmarshalElement(new File("src/test/resources/util/user-utf8.xml"), UserType.class) .getValue(); - + // WHEN PolyStringType fullName = user.getFullName(); @@ -69,10 +69,10 @@ public void testUnmarshallerUtf() throws JAXBException, SchemaException, FileNot @Test public void testUnmarshallerIso88592() throws JAXBException, SchemaException, FileNotFoundException { // GIVEN - + UserType user = JaxbTestUtil.getInstance().unmarshalElement(new File("src/test/resources/util/user-8859-2.xml"),UserType.class) .getValue(); - + // WHEN PolyStringType fullname = user.getFullName(); @@ -94,7 +94,7 @@ public void testUnmarshallerStringUtf8() throws JAXBException, SchemaException { ""; UserType user = JaxbTestUtil.getInstance().unmarshalElement(s, UserType.class).getValue(); - + // WHEN PolyStringType fullname = user.getFullName(); @@ -103,7 +103,7 @@ public void testUnmarshallerStringUtf8() throws JAXBException, SchemaException { assertTrue("Diacritics correctly decoded", "Jožko Nováčik".equals(fullname.getOrig())); } - + @Test public void testUnmarshallerStringIso88592() throws JAXBException, SchemaException { // GIVEN @@ -116,7 +116,7 @@ public void testUnmarshallerStringIso88592() throws JAXBException, SchemaExcepti ""; UserType user = JaxbTestUtil.getInstance().unmarshalElement(s, UserType.class).getValue(); - + // WHEN PolyStringType fullname = user.getFullName(); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/util/SchemaTestUtil.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/util/SchemaTestUtil.java index 0a4d21186ba..5b108c5c15e 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/util/SchemaTestUtil.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/util/SchemaTestUtil.java @@ -44,10 +44,10 @@ * */ public class SchemaTestUtil { - + public static void assertUserDefinition(PrismObjectDefinition userDefinition) { assertEquals("Wrong compile-time class in user definition", UserType.class, userDefinition.getCompileTimeClass()); - + assertFocusDefinition(userDefinition.getComplexTypeDefinition(), "user"); PrismAsserts.assertPropertyDefinition(userDefinition, UserType.F_FULL_NAME, SchemaConstants.T_POLY_STRING_TYPE, 0, 1); @@ -57,10 +57,10 @@ public static void assertUserDefinition(PrismObjectDefinition userDefi PrismAsserts.assertPropertyDefinition(userDefinition, UserType.F_FAMILY_NAME, PrismConstants.POLYSTRING_TYPE_QNAME, 0, 1); PrismAsserts.assertPropertyDefinition(userDefinition, UserType.F_ADDITIONAL_NAME, PrismConstants.POLYSTRING_TYPE_QNAME, 0, 1); } - + public static void assertFocusDefinition(ComplexTypeDefinition complexTypeDefinition, String defDesc) { assertNotNull("No "+defDesc+" definition", complexTypeDefinition); - + PrismAsserts.assertPropertyDefinition(complexTypeDefinition, ObjectType.F_NAME, PolyStringType.COMPLEX_TYPE, 0, 1); PrismAsserts.assertItemDefinitionDisplayName(complexTypeDefinition, ObjectType.F_NAME, "ObjectType.name"); PrismAsserts.assertItemDefinitionDisplayOrder(complexTypeDefinition, ObjectType.F_NAME, 0); @@ -68,7 +68,7 @@ public static void assertFocusDefinition(ComplexTypeDefinition complexTypeDefini PrismAsserts.assertItemDefinitionDisplayName(complexTypeDefinition, ObjectType.F_DESCRIPTION, "ObjectType.description"); PrismAsserts.assertItemDefinitionDisplayOrder(complexTypeDefinition, ObjectType.F_DESCRIPTION, 10); assertFalse(""+defDesc+" definition is marked as runtime", complexTypeDefinition.isRuntimeSchema()); - + PrismContainerDefinition extensionContainer = complexTypeDefinition.findContainerDefinition(UserType.F_EXTENSION); PrismAsserts.assertDefinition(extensionContainer, UserType.F_EXTENSION, ExtensionType.COMPLEX_TYPE, 0, 1); assertTrue("Extension is NOT runtime", extensionContainer.isRuntimeSchema()); @@ -82,21 +82,21 @@ public static void assertFocusDefinition(ComplexTypeDefinition complexTypeDefini assertFalse("Activation is runtime", activationContainer.isRuntimeSchema()); assertEquals("Activation size", 12, activationContainer.getDefinitions().size()); PrismAsserts.assertPropertyDefinition(activationContainer, ActivationType.F_ADMINISTRATIVE_STATUS, SchemaConstants.C_ACTIVATION_STATUS_TYPE, 0, 1); - + PrismContainerDefinition assignmentContainer = complexTypeDefinition.findContainerDefinition(UserType.F_ASSIGNMENT); PrismAsserts.assertDefinition(assignmentContainer, UserType.F_ASSIGNMENT, AssignmentType.COMPLEX_TYPE, 0, -1); assertFalse("Assignment is runtime", assignmentContainer.isRuntimeSchema()); assertEquals("Assignment definition size", 21, assignmentContainer.getDefinitions().size()); - + PrismContainerDefinition constructionContainer = assignmentContainer.findContainerDefinition(AssignmentType.F_CONSTRUCTION); PrismAsserts.assertDefinition(constructionContainer, AssignmentType.F_CONSTRUCTION, ConstructionType.COMPLEX_TYPE, 0, 1); assertFalse("Construction is runtime", constructionContainer.isRuntimeSchema()); - + PrismReferenceDefinition accountRefDef = complexTypeDefinition.findItemDefinition(UserType.F_LINK_REF, PrismReferenceDefinition.class); PrismAsserts.assertDefinition(accountRefDef, UserType.F_LINK_REF, ObjectReferenceType.COMPLEX_TYPE, 0, -1); assertEquals("Wrong target type in accountRef", ShadowType.COMPLEX_TYPE, accountRefDef.getTargetTypeName()); assertEquals("Wrong composite object element name in accountRef", UserType.F_LINK, accountRefDef.getCompositeObjectElementName()); - + PrismContainerDefinition metadataContainer = complexTypeDefinition.findContainerDefinition(UserType.F_METADATA);PrismAsserts.assertDefinition(extensionContainer, UserType.F_EXTENSION, ExtensionType.COMPLEX_TYPE, 0, 1); assertFalse("Metadata is runtime", metadataContainer.isRuntimeSchema()); assertFalse("Metadata is dynamic", metadataContainer.isDynamic()); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/util/XsdTypeConverterTest.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/util/XsdTypeConverterTest.java index a2d4cb92c74..e17be5ee691 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/util/XsdTypeConverterTest.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/util/XsdTypeConverterTest.java @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.schema.util; @@ -51,13 +51,13 @@ */ public class XsdTypeConverterTest { - // TODO: convert this test to create a Protected string structure in prism and then check it in the DOM view - + // TODO: convert this test to create a Protected string structure in prism and then check it in the DOM view + private static final String FOO_NAMESPACE = "http://foo.com/"; private static final QName FOO_QNAME = new QName(FOO_NAMESPACE,"foo"); private static final QName BAR_QNAME = new QName(FOO_NAMESPACE,"bar"); - + @Test(enabled=false) public void testConvertFromProtectedString() throws SchemaException { Document document = DOMUtil.parseDocument( @@ -67,29 +67,29 @@ public void testConvertFromProtectedString() throws SchemaException { "xsi:type=\"c:ProtectedStringType\">"+ "3lizab3th"); Element element = DOMUtil.getFirstChildElement(document); - + Object value = XmlTypeConverter.toJavaValue(element); - + System.out.println("XML -> ProtectedStringType: "+value); assertNotNull(value); assertTrue(value instanceof ProtectedStringType); assertEquals("3lizab3th",((ProtectedStringType)value).getClearValue()); } - + @Test(enabled=false) public void testConvertToProtectedString() throws JAXBException, SchemaException { ProtectedStringType ps = new ProtectedStringType(); ps.setClearValue("abra kadabra"); Document doc = DOMUtil.getDocument(); - + Object xsdElement = XmlTypeConverter.toXsdElement(ps, FOO_QNAME, doc, true); - + System.out.println("ProtectedStringType -> XML"); System.out.println(xsdElement); - + assertTrue(xsdElement instanceof JAXBElement); Object value = ((JAXBElement)xsdElement).getValue(); - + System.out.println(value); assertTrue(value instanceof ProtectedStringType); assertEquals("abra kadabra",((ProtectedStringType)value).getClearValue()); @@ -107,31 +107,31 @@ public void testAccountMarshall() throws JAXBException, SchemaException, IOExcep ps.setClearValue("foo"); JAXBElement pse = new JAXBElement(FOO_QNAME,ProtectedStringType.class,ps); shadow.getAttributes().getAny().add(pse); - + shadow.getAttributes().getAny().add(XmlTypeConverter.toXsdElement(42, BAR_QNAME, null, true)); - + Document doc = DOMUtil.getDocument(); - JAXBElement accountElement = + JAXBElement accountElement = new JAXBElement(ObjectTypes.SHADOW.getQName(), ShadowType.class,shadow); JaxbTestUtil.getInstance().marshalElementToDom(accountElement, doc); - + System.out.println("marshalled shadow: "+DOMUtil.serializeDOMToString(doc)); Element rootElement = DOMUtil.getFirstChildElement(doc); System.out.println("root element: "+rootElement); - + Element attrElement = (Element) rootElement.getElementsByTagNameNS(SchemaConstants.NS_C,"attributes").item(0); System.out.println("attrElement element: "+attrElement); - + Element fooElement = (Element) attrElement.getElementsByTagNameNS(FOO_QNAME.getNamespaceURI(), FOO_QNAME.getLocalPart()).item(0); System.out.println("fooElement element: "+fooElement); Element clearValue = DOMUtil.getFirstChildElement(fooElement); assertEquals("foo",clearValue.getTextContent()); - + Element barElement = (Element) attrElement.getElementsByTagNameNS(BAR_QNAME.getNamespaceURI(), BAR_QNAME.getLocalPart()).item(0); System.out.println("barElement element: "+barElement); assertEquals(DOMUtil.XSD_INT,DOMUtil.resolveXsiType(barElement)); assertEquals("42",barElement.getTextContent()); } - + } diff --git a/infra/test-util/src/main/java/com/evolveum/midpoint/test/ldap/AbstractResourceController.java b/infra/test-util/src/main/java/com/evolveum/midpoint/test/ldap/AbstractResourceController.java index 0258dd39588..f75605582a4 100644 --- a/infra/test-util/src/main/java/com/evolveum/midpoint/test/ldap/AbstractResourceController.java +++ b/infra/test-util/src/main/java/com/evolveum/midpoint/test/ldap/AbstractResourceController.java @@ -28,9 +28,9 @@ * */ public abstract class AbstractResourceController { - + protected PrismObject resource; - + public String getNamespace() { return ResourceTypeUtil.getResourceNamespace(resource); } @@ -42,7 +42,7 @@ public PrismObject getResource() { public void setResource(PrismObject resource) { this.resource = resource; } - + public ResourceType getResourceType() { return resource.asObjectable(); } @@ -50,7 +50,7 @@ public ResourceType getResourceType() { public QName getAttributeQName(String attributeName) { return new QName(getNamespace(), attributeName); } - + public ItemPath getAttributePath(String attributeName) { return new ItemPath( ShadowType.F_ATTRIBUTES, 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 c66e9d5591f..85e8805663a 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 @@ -78,11 +78,11 @@ /** * This class controls embedded OpenDJ instance. - * + * * It is used in Unit tests. It configures and starts and stops the instance. It * can even manage a "template" configuration of OpenDJ and copy it to working * instance configuration. - * + * * @author Radovan Semancik */ public class OpenDJController extends AbstractResourceController { @@ -90,10 +90,10 @@ public class OpenDJController extends AbstractResourceController { private String DATA_TEMPLATE_DIR = "test-data"; private String SERVER_ROOT = "target/test-data/opendj"; private String LDAP_SUFFIX = "dc=example,dc=com"; - + public static final String DEFAULT_TEMPLATE_NAME = "opendj.template"; public static final String RI_TEMPLATE_NAME = "opendj.template.ri"; - + public static final String OBJECT_CLASS_INETORGPERSON_NAME = "inetOrgPerson"; public static final String RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME = "entryUUID"; public static final String RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME = "dn"; @@ -118,7 +118,7 @@ public OpenDJController(String serverRoot) { /** * Initialize - * + * */ private void init() { @@ -133,10 +133,10 @@ private void init() { /** * Get the value of serverRoot. - * + * * The top directory of working OpenDS installation. The OpenDS placed in * this directory will be used during the tests. - * + * * @return the value of serverRoot */ public File getServerRoot() { @@ -145,10 +145,10 @@ public File getServerRoot() { /** * Set the value of serverRoot - * + * * The top directory of working OpenDS installation. The OpenDS placed in * this directory will be used during the tests. - * + * * @param serverRoot * new value of serverRoot */ @@ -158,10 +158,10 @@ public void setServerRoot(File serverRoot) { /** * Get the value of configFile - * + * * File name of primary OpenDS configuration file. Normally * /config/config.ldif - * + * * @return the value of configFile */ public File getConfigFile() { @@ -170,10 +170,10 @@ public File getConfigFile() { /** * Set the value of configFile - * + * * File name of primary OpenDS configuration file. Normally * /config/config.ldif - * + * * @param configFile * new value of configFile */ @@ -183,11 +183,11 @@ public void setConfigFile(File configFile) { /** * Get the value of templateServerRoot - * + * * The top directory of template OpenDS installation. All the files from * this directory will be copied to the working OpenDS directory * (serverRoot). This usually happens before the tests. - * + * * @return the value of templateServerRoot */ public File getTemplateServerRoot() { @@ -197,22 +197,22 @@ public File getTemplateServerRoot() { public String getSuffix() { return LDAP_SUFFIX; } - - + + public String getSuffixPeople() { return "ou=People,"+LDAP_SUFFIX; } - + public String getAccountDn(String username) { return "uid="+username+","+getSuffixPeople(); } - + /** * Get the value of internalConnection - * + * * The connection to the OpenDS instance. It can be used to fetch and * manipulate the data. - * + * * @return the value of internelConnection */ public InternalClientConnection getInternalConnection() { @@ -222,13 +222,13 @@ public InternalClientConnection getInternalConnection() { /** * Refresh working OpenDS installation from the template. - * + * * The existing working OpenDS installation (in serverRoot) will be * discarded and replaced by a fresh known-state setup (from * templateServerRoot). - * + * * @throws IOException - * @throws URISyntaxException + * @throws URISyntaxException */ public void refreshFromTemplate(String templateName) throws IOException, URISyntaxException { deleteDirectory(serverRoot); @@ -245,7 +245,7 @@ private void extractTemplate(File dst, String templateName) throws IOException, LOGGER.debug("Creating target dir {}", dst.getPath()); dst.mkdirs(); } - + templateRoot = new File(DATA_TEMPLATE_DIR, templateName); String templateRootPath = DATA_TEMPLATE_DIR + "/" + templateName; // templateRoot.getPath does not work on Windows, as it puts "\" into the path name (leading to problems with getSystemResource) @@ -358,9 +358,9 @@ public InternalClientConnection startCleanServer(String templateName) throws IOE /** * Start the embedded OpenDJ directory server. - * + * * Configuration and databases from serverRoot location will be used. - * + * * @return */ public InternalClientConnection start() { @@ -407,7 +407,7 @@ public InternalClientConnection start() { /** * Stop the embedded OpenDS server. - * + * */ public void stop() { if (EmbeddedUtils.isRunning()) { @@ -418,17 +418,17 @@ public void stop() { LOGGER.warn("Attempt to stop OpenDJ server that is already stopped."); } } - + public boolean isRunning() { return EmbeddedUtils.isRunning(); } - + public void assumeRunning() { if (!isRunning()) { start(); } } - + public void assumeStopped() { if (isRunning()) { stop(); @@ -437,7 +437,7 @@ public void assumeStopped() { /** * Delete a directory and its contents. - * + * * @param dir * The name of the directory to delete. * @throws IOException @@ -470,9 +470,9 @@ public Set asSet(List attributes) { return result; } - + // Generic utility methods - + public Entry searchByEntryUuid(String entryUuid) throws DirectoryException { InternalSearchOperation op = getInternalConnection().processSearch( "dc=example,dc=com", SearchScope.WHOLE_SUBTREE, DereferencePolicy.NEVER_DEREF_ALIASES, 100, @@ -495,7 +495,7 @@ public Entry searchAndAssertByEntryUuid(String entryUuid) throws DirectoryExcept } return entry; } - + public Entry searchSingle(String filter) throws DirectoryException { InternalSearchOperation op = getInternalConnection().processSearch( getSuffix(), SearchScope.WHOLE_SUBTREE, DereferencePolicy.NEVER_DEREF_ALIASES, 100, @@ -508,11 +508,11 @@ public Entry searchSingle(String filter) throws DirectoryException { } return op.getSearchEntries().get(0); } - + public Entry searchByUid(String string) throws DirectoryException { return searchSingle("(uid=" + string + ")"); } - + public Entry fetchEntry(String dn) throws DirectoryException { Validate.notNull(dn); InternalSearchOperation op = getInternalConnection().processSearch( @@ -526,7 +526,7 @@ public Entry fetchEntry(String dn) throws DirectoryException { } return op.getSearchEntries().get(0); } - + public Entry fetchAndAssertEntry(String dn, String objectClass) throws DirectoryException { Entry entry = fetchEntry(dn); AssertJUnit.assertNotNull("No entry for DN "+dn, entry); @@ -562,11 +562,11 @@ public static String getAttributeValue(Entry response, String name) { Attribute attribute = attrs.get(0); return getAttributeValue(attribute); } - + public static String getAttributeValue(Attribute attribute) { return attribute.iterator().next().getValue().toString(); } - + public static byte[] getAttributeValueBinary(Entry response, String name) { List attrs = response.getAttribute(name.toLowerCase()); if (attrs == null || attrs.size() == 0) { @@ -578,7 +578,7 @@ public static byte[] getAttributeValueBinary(Entry response, String name) { ByteString value = attribute.iterator().next().getValue(); return value.toByteArray(); } - + public static Collection getAttributeValues(Entry response, String name) { List attrs = response.getAttribute(name.toLowerCase()); if (attrs == null || attrs.size() == 0) { @@ -600,27 +600,27 @@ public static String getDn(Entry response) { DN dn = response.getDN(); return dn.toString(); } - + public static void assertDn(Entry response, String expected) throws DirectoryException { DN actualDn = response.getDN(); if (actualDn.compareTo(DN.decode(expected)) != 0) { AssertJUnit.fail("Wrong DN, expected "+expected+" but was "+actualDn.toString()); } } - + public void assertNoEntry(String dn) throws DirectoryException { Entry entry = fetchEntry(dn); if (entry != null) { AssertJUnit.fail("Found entry for dn "+dn+" while not expecting it: "+entry); } } - + public static void assertObjectClass(Entry response, String expected) throws DirectoryException { Collection objectClassValues = getAttributeValues(response, "objectClass"); AssertJUnit.assertTrue("Wrong objectclass for entry "+getDn(response)+", expected "+expected+" but got "+objectClassValues, objectClassValues.contains(expected)); } - + public static void assertNoObjectClass(Entry response, String unexpected) throws DirectoryException { Collection objectClassValues = getAttributeValues(response, "objectClass"); AssertJUnit.assertFalse("Unexpected objectclass for entry "+getDn(response)+": "+unexpected+", got "+objectClassValues, @@ -632,7 +632,7 @@ public void assertUniqueMember(Entry groupEntry, String accountDn) throws Direct assertContainsDn("No member "+accountDn+" in group "+getDn(groupEntry), members, accountDn); } - + public static void assertContainsDn(String message, Collection actualValues, String expectedValue) throws DirectoryException { AssertJUnit.assertNotNull(message+", expected "+expectedValue+", got null", actualValues); DN expectedDn = DN.decode(expectedValue); @@ -644,17 +644,17 @@ public static void assertContainsDn(String message, Collection actualVal } AssertJUnit.fail(message+", expected "+expectedValue+", got "+actualValues); } - + public void assertUniqueMember(String groupDn, String accountDn) throws DirectoryException { Entry groupEntry = fetchEntry(groupDn); assertUniqueMember(groupEntry, accountDn); } - + public void assertNoUniqueMember(String groupDn, String accountDn) throws DirectoryException { Entry groupEntry = fetchEntry(groupDn); assertNoUniqueMember(groupEntry, accountDn); } - + public void assertNoUniqueMember(Entry groupEntry, String accountDn) { Collection members = getAttributeValues(groupEntry, "uniqueMember"); MidPointAsserts.assertNotContainsCaseIgnore("Member "+accountDn+" in group "+getDn(groupEntry), @@ -693,7 +693,7 @@ public static void assertAttribute(Entry response, String name, String... values } } } - + public static void assertNoAttribute(Entry response, String name) { List attrs = response.getAttribute(name.toLowerCase()); if (attrs == null || attrs.size() == 0) { @@ -710,15 +710,15 @@ public static void assertNoAttribute(Entry response, String name) { } AssertJUnit.fail("Attribute "+name+" exists while not expecting it: "+attribute); } - + public void assertActive(Entry response, boolean active) { assertEquals("Unexpected activation of entry "+response, active, isAccountEnabled(response)); } - + public Entry addEntryFromLdifFile(File file) throws IOException, LDIFException { return addEntryFromLdifFile(file.getPath()); } - + public Entry addEntryFromLdifFile(String filename) throws IOException, LDIFException { LDIFImportConfig importConfig = new LDIFImportConfig(filename); LDIFReader ldifReader = new LDIFReader(importConfig); @@ -741,7 +741,7 @@ public List addEntriesFromLdifFile(String filename) throws IOException, L } return retval; } - + public void addEntry(Entry ldapEntry) { AddOperation addOperation = getInternalConnection().processAdd(ldapEntry); @@ -756,48 +756,48 @@ public void addEntry(String ldif) throws IOException, LDIFException { Entry ldifEntry = ldifReader.readEntry(); addEntry(ldifEntry); } - + public ChangeRecordEntry executeRenameChange(String filename) throws LDIFException, IOException{ LDIFImportConfig importConfig = new LDIFImportConfig(filename); LDIFReader ldifReader = new LDIFReader(importConfig); ChangeRecordEntry entry = ldifReader.readChangeRecord(false); - + if (!(entry instanceof ModifyDNChangeRecordEntry)){ throw new LDIFException(new MessageBuilder("Could not execute rename..Bad change").toMessage()); } - + ModifyDNOperation modifyOperation = getInternalConnection().processModifyDN((ModifyDNChangeRecordEntry)entry); - + if (ResultCode.SUCCESS != modifyOperation.getResultCode()) { throw new RuntimeException("LDAP operation error: "+modifyOperation.getResultCode()+": "+modifyOperation.getErrorMessage()); } return entry; - + } - + public ChangeRecordEntry executeLdifChange(File file) throws IOException, LDIFException { LDIFImportConfig importConfig = new LDIFImportConfig(file.getPath()); 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; } - + public ChangeRecordEntry executeLdifChange(String ldif) throws IOException, LDIFException { InputStream ldifInputStream = IOUtils.toInputStream(ldif, "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()); } @@ -808,24 +808,24 @@ public ChangeRecordEntry modifyReplace(String entryDn, String attributeName, Str String ldif = "dn: " + entryDn + "\nchangetype: modify\nreplace: "+attributeName+"\n"+attributeName+": " + value; return executeLdifChange(ldif); } - + public ChangeRecordEntry modifyAdd(String entryDn, String attributeName, String value) throws IOException, LDIFException { String ldif = "dn: " + entryDn + "\nchangetype: modify\nadd: "+attributeName+"\n"+attributeName+": " + value; return executeLdifChange(ldif); } - + public ChangeRecordEntry modifyDelete(String entryDn, String attributeName, String value) throws IOException, LDIFException { String ldif = "dn: " + entryDn + "\nchangetype: modify\ndelete: "+attributeName+"\n"+attributeName+": " + value; return executeLdifChange(ldif); } - + public void delete(String entryDn) { DeleteOperation deleteOperation = getInternalConnection().processDelete(entryDn); if (ResultCode.SUCCESS != deleteOperation.getResultCode()) { throw new RuntimeException("LDAP operation error: "+deleteOperation.getResultCode()+": "+deleteOperation.getErrorMessage()); } } - + public String dumpEntries() throws DirectoryException { InternalSearchOperation op = getInternalConnection().processSearch( LDAP_SUFFIX, SearchScope.WHOLE_SUBTREE, DereferencePolicy.NEVER_DEREF_ALIASES, 100, @@ -836,17 +836,17 @@ public String dumpEntries() throws DirectoryException { sb.append(toHumanReadableLdifoid(searchEntry)); sb.append("\n"); } - + return sb.toString(); } - + public String dumpTree() throws DirectoryException { StringBuilder sb = new StringBuilder(); sb.append(LDAP_SUFFIX).append("\n"); dumpTreeLevel(sb, LDAP_SUFFIX, 1); return sb.toString(); } - + private void dumpTreeLevel(StringBuilder sb, String dn, int indent) throws DirectoryException { InternalSearchOperation op = getInternalConnection().processSearch( dn, SearchScope.SINGLE_LEVEL, DereferencePolicy.NEVER_DEREF_ALIASES, 100, @@ -916,7 +916,7 @@ public ChangeRecordEntry addGroupUniqueMembers(String groupDn, List memb } return executeLdifChange(sb.toString()); } - + public boolean checkPassword(String entryDn, String password) throws DirectoryException { InternalClientConnection conn = new InternalClientConnection(DN.decode(entryDn)); BindOperation op = conn.processSimpleBind(entryDn, password); @@ -927,7 +927,7 @@ public boolean checkPassword(String entryDn, String password) throws DirectoryEx return false; } } - + public void assertPassword(String entryDn, String password) throws DirectoryException { if (!checkPassword(entryDn, password)) { AssertJUnit.fail("Expected that entry "+entryDn+" will have password '"+password+"'. But the check failed."); diff --git a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/Counter.java b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/Counter.java index 75bc1994c73..6e51fa06136 100644 --- a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/Counter.java +++ b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/Counter.java @@ -21,19 +21,19 @@ */ public class Counter { private int count = 0; - + public int getCount() { return count; } - + public synchronized void click() { count++; } - + public void assertCount(int expectedCount) { assert count == expectedCount : "Wrong counter, expected "+expectedCount+", was "+count; } - + public void assertCount(String message, int expectedCount) { assert count == expectedCount : message + ", expected "+expectedCount+", was "+count; } @@ -69,5 +69,5 @@ public String toString() { return "Counter(" + count + ")"; } - + } diff --git a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/DerbyController.java b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/DerbyController.java index 0fdc41fa099..2d134b3b00a 100644 --- a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/DerbyController.java +++ b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/DerbyController.java @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.test.util; @@ -31,19 +31,19 @@ import com.evolveum.midpoint.util.logging.TraceManager; /** - * + * * @author Radovan Semancik * */ public class DerbyController { - + public static final int DEFAULT_LISTEN_PORT = 11527; - + public static String COLUMN_LOGIN = "login"; public static String COLUMN_PASSWORD = "password"; public static String COLUMN_FULL_NAME = "full_name"; public static String COLUMN_CHANGELOG = "changelog"; - + private NetworkServerControl server; private String listenHostname; private InetAddress listenAddress; @@ -52,23 +52,23 @@ public class DerbyController { private String dbName; private String username = "midpoint"; private String password = "secret"; - + private static final Trace LOGGER = TraceManager.getTrace(DerbyController.class); - + public DerbyController() { super(); listenHostname = "localhost"; this.listentPort = DEFAULT_LISTEN_PORT; dbName = "target/derbyMidPointTest"; - } - + } + public DerbyController(String dbName, String listenHostname, int listentPort) { super(); this.listenHostname = listenHostname; this.listentPort = listentPort; this.dbName = dbName; } - + public String getListenHostname() { return listenHostname; } @@ -80,8 +80,8 @@ public int getListentPort() { public String getDbName() { return dbName; } - - + + public String getUsername() { return username; } @@ -93,7 +93,7 @@ public String getPassword() { public Connection getConnection() throws SQLException { return DriverManager.getConnection(jdbcUrl, "", ""); } - + public void startCleanServer() throws Exception { start(); cleanup(); @@ -124,12 +124,12 @@ public void start() throws Exception { System.setProperty("derby.stream.error.file", "target/derby.log"); server.start(null); } - + public void stop() throws Exception { LOGGER.info("Stopping Derby embedded network server"); server.shutdown(); } - + public Statement getExecutedStatementWhereLoginName(String loginName) throws SQLException { Connection conn = getConnection(); // Check if it empty @@ -137,5 +137,5 @@ public Statement getExecutedStatementWhereLoginName(String loginName) throws SQL stmt.execute("select * from users where "+COLUMN_LOGIN+"='"+loginName+"'"); return stmt; } - + } diff --git a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/DirectoryFileObjectResolver.java b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/DirectoryFileObjectResolver.java index e4bc001f820..60d499f0c3b 100644 --- a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/DirectoryFileObjectResolver.java +++ b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/DirectoryFileObjectResolver.java @@ -42,7 +42,7 @@ public class DirectoryFileObjectResolver implements ObjectResolver { private File directory; - + public DirectoryFileObjectResolver(File directory) { super(); this.directory = directory; @@ -63,7 +63,7 @@ public T resolve(ObjectReferenceType ref, Class expect throw new ObjectNotFoundException("Object "+ref.getOid()+" does not exists"); } } - + private String oidToFilename(String oid) { return oid+".xml"; } diff --git a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/LogfileTestTailer.java b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/LogfileTestTailer.java index e12bf975eae..6e965fa9cc5 100644 --- a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/LogfileTestTailer.java +++ b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/LogfileTestTailer.java @@ -39,10 +39,10 @@ * */ public class LogfileTestTailer { - + public static final File TEST_LOG_FILE = new File("target/test.log"); public static final String MARKER = "_M_A_R_K_E_R_"; - + public static final String LEVEL_ERROR = "ERROR"; public static final String LEVEL_WARN = "WARN"; public static final String LEVEL_INFO = "INFO"; @@ -52,14 +52,14 @@ public class LogfileTestTailer { // see also the 'optimization' at the beginning of processLogLine() - interfering with these patterns private static final Pattern PATTERN_MARKER = Pattern.compile(".*\\[[^]]*\\](\\s+\\[\\w+\\])?\\s+(\\S+)\\s+\\(\\S+\\):\\s+"+MARKER+"\\s+(\\w+).*"); private static final Pattern PATTERN_MARKER_PREFIX = Pattern.compile(".*\\[[^]]*\\](\\s+\\[\\w+\\])?\\s+(\\S+)\\s+.*"+MARKER+"\\s+(\\w+).*"); - public static final Pattern PATTERN_LEVEL = + public static final Pattern PATTERN_LEVEL = Pattern.compile(".*\\[[^]]*\\](\\s+\\[\\w+\\])?\\s+(\\S+)\\s+(.*)"); - + final static Trace LOGGER = TraceManager.getTrace(LogfileTestTailer.class); - + private String auditLoggerName; public Pattern auditPattern; - + private File logFile; private Reader fileReader; private BufferedReader reader; @@ -71,15 +71,15 @@ public class LogfileTestTailer { private boolean allowPrefix = false; private Collection errors = new ArrayList(); private Collection warnings = new ArrayList(); - + public LogfileTestTailer(String auditLoggerName) throws IOException { this(TEST_LOG_FILE, auditLoggerName, true); } - + public LogfileTestTailer(String auditLoggerName, boolean skipCurrentContent) throws IOException { this(TEST_LOG_FILE, auditLoggerName, skipCurrentContent); } - + public LogfileTestTailer(File logFile, String auditLoggerName, boolean skipCurrentContent) throws IOException { this.logFile = logFile; this.auditLoggerName = auditLoggerName; @@ -96,7 +96,7 @@ public LogfileTestTailer(File logFile, String auditLoggerName, boolean skipCurre fileReader = new InputStreamReader(fileInputStream); reader = new BufferedReader(fileReader); } - + public boolean isAllowPrefix() { return allowPrefix; } @@ -117,7 +117,7 @@ public void close() throws IOException { reader.close(); fileReader.close(); } - + public void reset() { seenMarker = false; loggedMarkers = new HashSet(); @@ -150,7 +150,7 @@ private void processLogLine(String line) { if (line.length() > 0 && Character.isWhitespace(line.charAt(0))) { return; // ugly hack: getting rid of long 'continuation' lines that are not matched by any patterns but terribly slow down the processing } - + // Match marker Pattern pattern = PATTERN_MARKER; if (allowPrefix) { @@ -170,7 +170,7 @@ private void processLogLine(String line) { } recordMarker(level,subsystemName); } - + // Match audit matcher = auditPattern.matcher(line); if (!line.contains("Details of event")) { @@ -187,11 +187,11 @@ private void processLogLine(String line) { recordAuditMessage(level,message); } } - + if (expectedMessage != null && line.contains(expectedMessage)) { expectedMessageLine = line; } - + // Match errors and warnings matcher = PATTERN_LEVEL.matcher(line); while (matcher.find()) { @@ -205,13 +205,13 @@ private void processLogLine(String line) { } } } - + private void recordMarker(String level, String subsystemName) { LOGGER.trace("Found marker ({}): {}", level, subsystemName); String key = constructKey(level, subsystemName); loggedMarkers.add(key); } - + private void recordAuditMessage(String level, String message) { LOGGER.trace("Found audit message ({})", level); auditMessages.add(message); @@ -224,28 +224,28 @@ public List getAuditMessages() { private String constructKey(String level, String subsystemName) { return level+":"+subsystemName; } - + public void assertMarkerLogged(String level, String subsystemName) { assert loggedMarkers.contains(constructKey(level, subsystemName)) : level + " in " + subsystemName + " was not logged"; } - + public void assertMarkerNotLogged(String level, String subsystemName) { assert !loggedMarkers.contains(constructKey(level, subsystemName)) : level + " in " + subsystemName + " was logged (while not expecting it)"; } - + public void setExpecteMessage(String expectedMessage) { this.expectedMessage = expectedMessage; this.expectedMessageLine = null; } - + public void assertExpectedMessage() { assert expectedMessageLine != null : "The expected message was not seen"; } - + public void assertNoAudit() { assert auditMessages.isEmpty() : "Audit messages not empty: "+auditMessages; } - + public void assertAudit() { assert !auditMessages.isEmpty() : "No audit message"; } @@ -253,7 +253,7 @@ public void assertAudit() { public void assertAudit(String message) { assert auditMessages.contains(message) : "No audit message: "+message; } - + public void assertAuditRequest() { for (String message: auditMessages) { if (message.contains("stage REQUEST")) { @@ -291,7 +291,7 @@ public void log() { } logAllLevels(LOGGER, null); } - + private void logAllLevels(Trace logger, String subsystemName) { String message = MARKER+" "+subsystemName; String previousSubsystem = MidpointInterceptor.swapSubsystemMark(subsystemName); @@ -302,7 +302,7 @@ private void logAllLevels(Trace logger, String subsystemName) { logger.error(message); MidpointInterceptor.swapSubsystemMark(previousSubsystem); } - + public void logAndTail() throws IOException { log(); // Some pause here? 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 df3cdb4a670..2e1fad58d3e 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 @@ -34,34 +34,34 @@ /** * WARNING! Only works on Linux. - * + * * @author semancik */ public class Lsof implements DebugDumpable { - + private static final Trace LOGGER = TraceManager.getTrace(Lsof.class); - + private int pid; private int toleranceUp = 2; private int toleranceDown = 10; - + private String lsofOutput; private int totalFds; private Map typeMap; private Map miscMap; private Map nodeMap; - + private String baselineLsofOutput; private int baselineTotalFds; private Map baselineTypeMap; private Map baselineMiscMap; private Map baselineNodeMap; - + public Lsof(int pid) { super(); this.pid = pid; } - + public int getToleranceUp() { return toleranceUp; } @@ -84,33 +84,33 @@ public int rememberBaseline() throws NumberFormatException, IOException, Interru baselineTypeMap = typeMap; baselineMiscMap = miscMap; baselineNodeMap = nodeMap; - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Baseline LSOF output:\n{}", baselineLsofOutput); } - + return baselineTotalFds; } - + public int count() throws NumberFormatException, IOException, InterruptedException { lsofOutput = execLsof(pid); - + // if (LOGGER.isTraceEnabled()) { // LOGGER.trace("LSOF output:\n{}", lsofOutput); // } - + String[] lines = lsofOutput.split("\n"); - + Pattern fdPattern = Pattern.compile("(\\d+)(\\S*)"); Pattern namePatternJar = Pattern.compile("/.+\\.jar"); Pattern namePatternFile = Pattern.compile("/.*"); Pattern namePatternPipe = Pattern.compile("pipe"); Pattern namePatternEventpoll = Pattern.compile("\\[eventpoll\\]"); - + typeMap = new HashMap<>(); miscMap = new HashMap<>(); nodeMap = new HashMap<>(); - + totalFds = 0; for (int lineNum = 1; lineNum < lines.length; lineNum++) { String line = lines[lineNum]; @@ -119,26 +119,26 @@ public int count() throws NumberFormatException, IOException, InterruptedExcepti if (Integer.parseInt(pidCol) != pid) { throw new IllegalStateException("Unexpected pid in line "+lineNum+", expected "+pid+"\n"+line); } - + String fd = columns[3]; Matcher fdMatcher = fdPattern.matcher(fd); // if (!fdMatcher.matches()) { // LOGGER.trace("SKIP fd {}", fd); // continue; // } - + totalFds++; - + String type = columns[4]; increment(typeMap, type); - + String node = columns[7]; String nodeKey = node; if (!StringUtils.isNumeric(nodeKey)) { nodeKey = nodeKey + ":" + fd; } nodeMap.put(nodeKey, line); - + String name = columns[8]; if (namePatternJar.matcher(name).matches()) { increment(miscMap, "jar"); @@ -154,11 +154,11 @@ public int count() throws NumberFormatException, IOException, InterruptedExcepti increment(miscMap, "other"); } } - + if (LOGGER.isDebugEnabled()) { LOGGER.debug("lsof counts:\n{}", debugDump(1)); } - + return totalFds; } @@ -168,7 +168,7 @@ private void increment(Map map, String key) { typeCount = 0; } typeCount++; - map.put(key, typeCount); + map.put(key, typeCount); } private String execLsof(int pid) throws IOException, InterruptedException { @@ -204,7 +204,7 @@ private String execLsof(int pid) throws IOException, InterruptedException { } return output; } - + public void assertStable() throws NumberFormatException, IOException, InterruptedException { count(); if (!checkWithinTolerance(baselineTotalFds, totalFds)) { @@ -215,7 +215,7 @@ public void assertStable() throws NumberFormatException, IOException, Interrupte LOGGER.debug("FD situation stable (total {})", totalFds); } } - + public void assertFdIncrease(int increase) throws NumberFormatException, IOException, InterruptedException { count(); if (!checkWithinTolerance(baselineTotalFds + increase, totalFds)) { @@ -240,7 +240,7 @@ private void logFailDump() { LOGGER.trace("LSOF output:\n{}", lsofOutput); } } - + private String diffNodeMap() { StringBuilder sb = new StringBuilder(); for (Entry baselineEntry: baselineNodeMap.entrySet()) { @@ -253,7 +253,7 @@ private String diffNodeMap() { sb.append("+ ").append(currentEntry.getValue()).append("\n"); } } - + return sb.toString(); } @@ -310,6 +310,6 @@ public String debugDump(int indent) { // Do not display output and nodemap, that is too much return sb.toString(); } - - + + } diff --git a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/MidPointAsserts.java b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/MidPointAsserts.java index fa63f2ae2d7..d15c6b9e300 100644 --- a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/MidPointAsserts.java +++ b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/MidPointAsserts.java @@ -49,7 +49,7 @@ * */ public class MidPointAsserts { - + public static AssignmentType assertAssigned(PrismObject user, String targetOid, QName refType) { F userType = user.asObjectable(); for (AssignmentType assignmentType: userType.getAssignment()) { @@ -65,7 +65,7 @@ public static AssignmentType assertAssigned(PrismObject AssertJUnit.fail(user + " does not have assigned "+refType.getLocalPart()+" "+targetOid); return null; // not reachable } - + public static void assertAssigned(PrismObject focus, String targetOid, QName refType, QName relation) { FocusType focusType = focus.asObjectable(); for (AssignmentType assignmentType: focusType.getAssignment()) { @@ -81,7 +81,7 @@ public static void assertAssigned(PrismObject focus, String } AssertJUnit.fail(focus + " does not have assigned "+refType.getLocalPart()+" "+targetOid+ ", relation "+relation); } - + public static void assertNotAssigned(PrismObject user, String targetOid, QName refType) { F userType = user.asObjectable(); for (AssignmentType assignmentType: userType.getAssignment()) { @@ -103,7 +103,7 @@ public static void assertAssignments(PrismObject user, public static void assertInducements(PrismObject role, int expectedNumber) { R roleType = role.asObjectable(); - assertEquals("Unexepected number of inducements in "+role+": "+roleType.getInducement(), + assertEquals("Unexepected number of inducements in "+role+": "+roleType.getInducement(), expectedNumber, roleType.getInducement().size()); } @@ -125,29 +125,29 @@ public static void assertAssignments(PrismObject user, } assertEquals("Unexepected number of assignments of type "+expectedType+" in "+user+": "+userType.getAssignment(), expectedNumber, actualAssignments); } - + public static void assertNoAssignments(PrismObject user) { F userType = user.asObjectable(); List assignments = userType.getAssignment(); assertTrue(user + " does have assignments "+assignments+" while not expecting it", assignments.isEmpty()); } - + public static AssignmentType assertAssignedRole(PrismObject user, String roleOid) { return assertAssigned(user, roleOid, RoleType.COMPLEX_TYPE); } - + public static void assertNotAssignedRole(PrismObject user, String roleOid) { assertNotAssigned(user, roleOid, RoleType.COMPLEX_TYPE); } - + public static void assertAssignedRoles(PrismObject user, String... roleOids) { assertAssignedTargets(user, "roles", RoleType.COMPLEX_TYPE, roleOids); } - + public static void assertAssignedOrgs(PrismObject user, String... orgOids) { assertAssignedTargets(user, "orgs", OrgType.COMPLEX_TYPE, orgOids); } - + public static void assertAssignedTargets(PrismObject user, String typeDesc, QName type, String... expectedTargetOids) { F userType = user.asObjectable(); List haveTagetOids = new ArrayList<>(); @@ -206,19 +206,19 @@ public static void assertNotAssignedOrg(PrismObject use } } } - + public static void assertAssignedOrg(PrismObject focus, String orgOid) { assertAssigned(focus, orgOid, OrgType.COMPLEX_TYPE); } - + public static void assertNotAssignedOrg(PrismObject focus, String orgOid) { assertNotAssigned(focus, orgOid, OrgType.COMPLEX_TYPE); } - + public static void assertAssignedOrg(PrismObject focus, String orgOid, QName relation) { assertAssigned(focus, orgOid, OrgType.COMPLEX_TYPE, relation); } - + public static void assertHasOrg(PrismObject object, String orgOid) { for (ObjectReferenceType orgRef: object.asObjectable().getParentOrgRef()) { if (orgOid.equals(orgRef.getOid())) { @@ -227,7 +227,7 @@ public static void assertHasOrg(PrismObject object, St } AssertJUnit.fail(object + " does not have org " + orgOid); } - + public static boolean hasOrg(PrismObject user, String orgOid, QName relation) { for (ObjectReferenceType orgRef: user.asObjectable().getParentOrgRef()) { if (orgOid.equals(orgRef.getOid()) && @@ -245,7 +245,7 @@ public static void assertHasOrg(PrismObject user, Stri public static void assertHasNoOrg(PrismObject user, String orgOid, QName relation) { AssertJUnit.assertFalse(user + " has org " + orgOid + ", relation "+relation+ " even if should NOT have it", hasOrg(user, orgOid, relation)); } - + public static void assertHasNoOrg(PrismObject user) { assertTrue(user + " does have orgs "+user.asObjectable().getParentOrgRef()+" while not expecting them", user.asObjectable().getParentOrgRef().isEmpty()); } @@ -254,8 +254,8 @@ public static void assertHasOrgs(PrismObject user, int O userType = user.asObjectable(); assertEquals("Unexepected number of orgs in "+user+": "+userType.getParentOrgRef(), expectedNumber, userType.getParentOrgRef().size()); } - - + + public static void assertVersionIncrease(PrismObject objectOld, PrismObject objectNew) { Long versionOld = parseVersion(objectOld); Long versionNew = parseVersion(objectNew); @@ -273,11 +273,11 @@ public static Long parseVersion(PrismObject object) { public static void assertVersion(PrismObject object, int expectedVersion) { assertVersion(object, Integer.toString(expectedVersion)); } - + public static void assertVersion(PrismObject object, String expectedVersion) { assertEquals("Wrong version for "+object, expectedVersion, object.getVersion()); } - + public static void assertOid(PrismObject object, String expectedOid) { assertEquals("Wrong OID for "+object, expectedOid, object.getOid()); } @@ -291,7 +291,7 @@ public static void assertContainsCaseIgnore(String message, Collection a } AssertJUnit.fail(message+", expected "+expectedValue+", got "+actualValues); } - + public static void assertNotContainsCaseIgnore(String message, Collection actualValues, String expectedValue) { if (actualValues == null) { return; diff --git a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/MidPointTestConstants.java b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/MidPointTestConstants.java index 2b7f5b41605..a02954a0493 100644 --- a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/MidPointTestConstants.java +++ b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/MidPointTestConstants.java @@ -3,7 +3,7 @@ import java.io.File; public class MidPointTestConstants { - + public static final String TEST_RESOURCES_PATH = "src/test/resources"; public static File TEST_RESOURCES_DIR = new File (TEST_RESOURCES_PATH); public static File OBJECTS_DIR = new File(TEST_RESOURCES_DIR, "objects"); @@ -12,5 +12,5 @@ public class MidPointTestConstants { public static final String KEYSTORE_PATH = "src/test/resources/keystore.jceks"; public static final String KEYSTORE_PASSWORD = "changeit"; - + } diff --git a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/MultithreadRunner.java b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/MultithreadRunner.java new file mode 100644 index 00000000000..40b10d2a6e7 --- /dev/null +++ b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/MultithreadRunner.java @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2017 Evolveum + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.evolveum.midpoint.test.util; + +/** + * Used mostly in tests to simplify error handling. + * + * @author semancik + */ +@FunctionalInterface +public interface MultithreadRunner { + + public abstract void run(int i) throws Exception; + +} diff --git a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/ParallelTestThread.java b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/ParallelTestThread.java index 50995d3a9b4..13cc19268c5 100644 --- a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/ParallelTestThread.java +++ b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/ParallelTestThread.java @@ -15,7 +15,6 @@ */ package com.evolveum.midpoint.test.util; -import com.evolveum.midpoint.util.FailableRunnable; import com.evolveum.midpoint.util.exception.SystemException; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; @@ -27,19 +26,21 @@ public class ParallelTestThread extends Thread { private static final Trace LOGGER = TraceManager.getTrace(ParallelTestThread.class); - - private FailableRunnable target; + + private int i; + private MultithreadRunner target; private Throwable exception; - public ParallelTestThread(FailableRunnable target) { + public ParallelTestThread(int i, MultithreadRunner target) { super(); + this.i = i; this.target = target; } @Override public void run() { try { - target.run(); + target.run(i); } catch (RuntimeException | Error e) { recordException(e); throw e; @@ -57,5 +58,5 @@ public void recordException(Throwable e) { LOGGER.error("Test thread failed: {}", e.getMessage(), e); this.exception = e; } - + } diff --git a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/TestUtil.java b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/TestUtil.java index b62dfb82ce4..f7878dde525 100644 --- a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/TestUtil.java +++ b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/TestUtil.java @@ -76,9 +76,9 @@ * @author Radovan Semancik */ public class TestUtil { - + public static final int MAX_EXCEPTION_MESSAGE_LENGTH = 500; - + public static final String TEST_LOG_PREFIX = "=====[ "; public static final String TEST_LOG_SUFFIX = " ]======================================"; public static final String TEST_OUT_PREFIX = "\n\n=====[ "; @@ -87,13 +87,13 @@ public class TestUtil { public static final String TEST_OUT_SECTION_SUFFIX = " --------------------------------------\n"; public static final String TEST_LOG_SECTION_PREFIX = "----- "; public static final String TEST_LOG_SECTION_SUFFIX = " --------------------------------------"; - + private static final Pattern JAVA_VERSION_PATTERN = Pattern.compile("1\\.(\\d+)\\.\\d+_\\d+"); - + public static boolean checkResults = true; - + private static DatatypeFactory datatypeFactory = null; - + private static final Trace LOGGER = TraceManager.getTrace(TestUtil.class); public static void assertPropertyValueSetEquals(Collection> actual, T... expected) { @@ -119,12 +119,12 @@ public static void assertSetEquals(String message, Collection actual, T.. assertEquals(expectedSet, actualSet); } } - + public static void assertSetEquals(String message, T[] actual, T[] expected) { - assertTrue(message+"expected "+Arrays.toString(expected)+", was "+Arrays.toString(actual), + assertTrue(message+"expected "+Arrays.toString(expected)+", was "+Arrays.toString(actual), MiscUtil.unorderedArrayEquals(actual, expected)); } - + public static String getNodeOid(Node node) { Node oidNode = null; if ((null == node.getAttributes()) @@ -136,8 +136,8 @@ public static String getNodeOid(Node node) { String oid = oidNode.getNodeValue(); return oid; } - - public static void setAttribute(PrismObject account, QName attrName, QName typeName, + + public static void setAttribute(PrismObject account, QName attrName, QName typeName, PrismContext prismContext, String value) throws SchemaException { PrismContainer attributesContainer = account.findContainer(ShadowType.F_ATTRIBUTES); ResourceAttributeDefinition attrDef = new ResourceAttributeDefinitionImpl(attrName, typeName, prismContext); @@ -193,12 +193,12 @@ public static void displayThen(String testName) { System.out.println(TEST_OUT_SECTION_PREFIX + " THEN " + testName + TEST_OUT_SECTION_SUFFIX); LOGGER.info(TEST_LOG_SECTION_PREFIX + " THEN " + testName + TEST_LOG_SECTION_SUFFIX); } - + public static void displayCleanup(String testName) { System.out.println(TEST_OUT_SECTION_PREFIX + " CLEANUP " + testName + TEST_OUT_SECTION_SUFFIX); LOGGER.info(TEST_LOG_SECTION_PREFIX + " CLEANUP " + testName + TEST_LOG_SECTION_SUFFIX); } - + public static void info(String message) { System.out.println(TEST_OUT_SECTION_PREFIX + message + TEST_OUT_SECTION_SUFFIX); LOGGER.info(TEST_LOG_SECTION_PREFIX + message + TEST_LOG_SECTION_SUFFIX); @@ -215,7 +215,7 @@ public static void assertSuccess(String message, OperationResult result, Operati System.out.println(logmsg + "\n" + originalResult.debugDump()); fail(logmsg); } - + if (result.isHandledError()) { // There may be errors deeper in this result, even fatal errors. that's ok, we can ignore them. return; @@ -228,9 +228,9 @@ public static void assertSuccess(String message, OperationResult result, Operati LOGGER.error(logmsg); LOGGER.trace(logmsg + "\n" + originalResult.debugDump()); System.out.println(logmsg + "\n" + originalResult.debugDump()); - assert false : logmsg; + assert false : logmsg; } - + if (stopLevel == currentLevel) { return; } @@ -245,7 +245,7 @@ public static void assertSuccess(String message, OperationResult result, Operati * level=0 - check only the top-level * level=1 - check one level below top-level * ... - * + * * @param message * @param result * @param level @@ -261,7 +261,7 @@ public static void assertSuccess(String message, OperationResult result) { public static void assertSuccess(OperationResultType result) { assertSuccess(result.getOperation(), result); } - + public static void assertSuccess(String message, OperationResultType result) { if (!checkResults) { return; @@ -299,17 +299,17 @@ public static void assertInProgressOrSuccess(OperationResult result) { public static void assertSuccess(OperationResult result) { assertSuccess("Operation "+result.getOperation()+" result", result); } - + public static void assertSuccess(OperationResult result, int depth) { assertSuccess("Operation "+result.getOperation()+" result", result, depth); } - + public static void assertStatus(OperationResult result, OperationResultStatus expectedStatus) { - assertEquals("Operation "+result.getOperation()+" result", expectedStatus, result.getStatus()); + assertEquals("Operation "+result.getOperation()+" result", expectedStatus, result.getStatus()); } public static void assertStatus(OperationResultType result, OperationResultStatusType expectedStatus) { - assertEquals("Operation "+result.getOperation()+" result", expectedStatus, result.getStatus()); + assertEquals("Operation "+result.getOperation()+" result", expectedStatus, result.getStatus()); } public static boolean hasWarningAssertSuccess(String message, OperationResultType result) { @@ -322,7 +322,7 @@ public static boolean hasWarningAssertSuccess(String message, OperationResultTyp } else { if (result.getStatus() == null || result.getStatus() == OperationResultStatusType.UNKNOWN) { fail(message + ": undefined status ("+result.getStatus()+") on operation "+result.getOperation()); - } + } if (result.getStatus() != OperationResultStatusType.SUCCESS && result.getStatus() != OperationResultStatusType.NOT_APPLICABLE && result.getStatus() != OperationResultStatusType.HANDLED_ERROR) { @@ -384,9 +384,9 @@ public static void assertFailure(OperationResultType result) { } public static void assertFailure(String message, OperationResultType result) { - assertTrue((message == null ? "" : message + ": ") + - "Expected that operation "+result.getOperation()+" fails, but the result was "+result.getStatus(), - OperationResultStatusType.FATAL_ERROR == result.getStatus() || + assertTrue((message == null ? "" : message + ": ") + + "Expected that operation "+result.getOperation()+" fails, but the result was "+result.getStatus(), + OperationResultStatusType.FATAL_ERROR == result.getStatus() || OperationResultStatusType.PARTIAL_ERROR == result.getStatus()) ; assertNoUnknown(result); } @@ -429,12 +429,12 @@ public static boolean hasWarningAssertSuccess(String message, OperationResult re System.out.println(logmsg + "\n" + originalResult.debugDump()); fail(logmsg); } - + if (result.isWarning()) { // Do not descent into warnings. There may be lions inside. Or errors. return true; } - + if (result.isSuccess() || result.isHandledError() || result.isNotApplicable()) { // OK ... expected error is as good as success } else { @@ -442,9 +442,9 @@ public static boolean hasWarningAssertSuccess(String message, OperationResult re LOGGER.error(logmsg); LOGGER.trace(logmsg + "\n" + originalResult.debugDump()); System.out.println(logmsg + "\n" + originalResult.debugDump()); - assert false : logmsg; + assert false : logmsg; } - + if (stopLevel == currentLevel) { return false; } @@ -503,7 +503,7 @@ private static void selectSubresultsInternal(List retval, Opera selectSubresultsInternal(retval, subresult, operationNames); } } - + public static String execSystemCommand(String command) throws IOException, InterruptedException { return execSystemCommand(command, false); } @@ -535,15 +535,15 @@ public static void assertBetween(String message, XMLGregorianCalendar start, XML XMLGregorianCalendar actual) { assertNotNull(message + " is null", actual); if (start != null) { - assertTrue(message+": expected time to be after "+start+" but it was "+actual, + assertTrue(message+": expected time to be after "+start+" but it was "+actual, actual.compare(start) == DatatypeConstants.GREATER || actual.compare(start) == DatatypeConstants.EQUAL); } if (end != null) { - assertTrue(message+": expected time to be before "+end+" but it was "+actual, + assertTrue(message+": expected time to be before "+end+" but it was "+actual, actual.compare(end) == DatatypeConstants.LESSER || actual.compare(end) == DatatypeConstants.EQUAL); } } - + public static void assertBetween(String message, Long start, Long end, Long actual) { assertNotNull(message + " is null", actual); @@ -571,7 +571,7 @@ public static void assertModifyTimestamp(PrismObject objec XMLGregorianCalendar end) { assertModifyTimestamp(object, start, end, null); } - + public static void assertModifyTimestamp(PrismObject object, XMLGregorianCalendar start, XMLGregorianCalendar end, String channel) { MetadataType metadata = object.asObjectable().getMetadata(); @@ -588,7 +588,7 @@ public static XMLGregorianCalendar currentTime() { gregorianCalendar.setTimeInMillis(System.currentTimeMillis()); return getDatatypeFactory().newXMLGregorianCalendar(gregorianCalendar); } - + private static DatatypeFactory getDatatypeFactory() { if (datatypeFactory == null) { try { @@ -599,7 +599,7 @@ private static DatatypeFactory getDatatypeFactory() { } return datatypeFactory; } - + public static int getJavaMajorVersion() { String javaVersionString = System.getProperty("java.version"); Matcher matcher = JAVA_VERSION_PATTERN.matcher(javaVersionString); @@ -608,14 +608,14 @@ public static int getJavaMajorVersion() { } else { throw new IllegalStateException("Cannot match java version string '"+javaVersionString+"'"); } - + } public static void assertMessageContains(String message, String expectedSubstring) { assertTrue("Expected that message will contain substring '"+expectedSubstring+"', but it did not. Message: "+message, message.contains(expectedSubstring)); } - + // WARNING! Only works on Linux public static int getPid() throws NumberFormatException, IOException { return Integer.parseInt(new File("/proc/self").getCanonicalFile().getName()); diff --git a/infra/test-util/src/test/java/com/evolveum/midpoint/test/util/DerbyControllerTest.java b/infra/test-util/src/test/java/com/evolveum/midpoint/test/util/DerbyControllerTest.java index 7d914a42e1d..9a75a15ae00 100644 --- a/infra/test-util/src/test/java/com/evolveum/midpoint/test/util/DerbyControllerTest.java +++ b/infra/test-util/src/test/java/com/evolveum/midpoint/test/util/DerbyControllerTest.java @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.test.util; @@ -38,12 +38,12 @@ public class DerbyControllerTest { @Test public void testStartStopDerby() throws Exception { DerbyController controller = new DerbyController(); - + // Start Derby controller.startCleanServer(); - + Connection conn = controller.getConnection(); - + // Check if it is empty Statement stmt = conn.createStatement(); stmt.execute("select * from users"); @@ -51,12 +51,12 @@ public void testStartStopDerby() throws Exception { assertFalse("The \"users\" table is not empty",rs.next()); rs.close(); stmt.close(); - + // Try insert stmt = conn.createStatement(); stmt.execute("insert into users values ('jack','d3adm3nt3lln0t4l3s','cpt. Jack Sparrow',1)"); conn.commit(); - + // Try to connect over the "network" (localhost) Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance(); String networkJdbcUrl = "jdbc:derby://"+controller.getListenHostname()+":"+controller.getListentPort()+"/"+controller.getDbName(); @@ -73,7 +73,7 @@ public void testStartStopDerby() throws Exception { assertTrue("The \"users\" empty after insert",rs.next()); rs.close(); stmt.close(); - + // stop derby controller.stop(); } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/ClassPathUtil.java b/infra/util/src/main/java/com/evolveum/midpoint/util/ClassPathUtil.java index d9139aae0dd..f42168e9493 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/ClassPathUtil.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/ClassPathUtil.java @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.util; @@ -52,13 +52,13 @@ public class ClassPathUtil { public static Set listClasses(Package pkg) { return listClasses(pkg.getName()); } - + public static Set listClasses(String packageName) { Set classes = new HashSet(); searchClasses(packageName, c -> classes.add(c)); return classes; } - + /** * This is not entirely reliable method. * Maybe it would be better to rely on Spring ClassPathScanningCandidateComponentProvider @@ -80,21 +80,21 @@ public static void searchClasses(String packageName, Consumer consumer) { LOGGER.trace("Candidates from: " + candidateUrl); // test if it is a directory or JAR - String protocol = candidateUrl.getProtocol(); + String protocol = candidateUrl.getProtocol(); if ("file".contentEquals(protocol)) { getFromDirectory(candidateUrl, packageName, consumer); } else if ("jar".contentEquals(protocol) || "zip".contentEquals(protocol)) { getFromJar(candidateUrl, packageName, consumer); } else { LOGGER.warn("Unsupported protocol for candidate URL {}", candidateUrl); - } + } } } /** * Extract specified source on class path to file system dst - * + * * @param src * source * @param dst @@ -110,7 +110,7 @@ public static boolean extractFileFromClassPath(String src, String dst) { return copyFile(is, src, dst); } - + public static boolean copyFile(InputStream srcStream, String srcName, String dstPath) { OutputStream dstStream = null; try { @@ -121,7 +121,7 @@ public static boolean copyFile(InputStream srcStream, String srcName, String dst } return copyFile(srcStream, srcName, dstStream, dstPath); } - + public static boolean copyFile(InputStream srcStream, String srcName, File dstFile) { OutputStream dstStream = null; try { @@ -132,7 +132,7 @@ public static boolean copyFile(InputStream srcStream, String srcName, File dstFi } return copyFile(srcStream, srcName, dstStream, dstFile.toString()); } - + public static boolean copyFile(InputStream srcStream, String srcName, OutputStream dstStream, String dstName) { byte buf[] = new byte[655360]; int len; @@ -164,7 +164,7 @@ public static boolean copyFile(InputStream srcStream, String srcName, OutputStre return true; } - + /** * Extracts all files in a directory on a classPath (system resource) to * a directory on a file system. @@ -192,21 +192,21 @@ public static boolean extractFilesFromClassPath(String srcPath, String dstPath, LOGGER.trace("Not relevant: ", jarEntry.getName()); continue; } - + // prepare destination file String filepath = jarEntry.getName().substring(srcPath.length()); File dstFile = new File(dstPath, filepath); - + if (!overwrite && dstFile.exists()) { LOGGER.debug("Skipping file {}: exists", dstFile); continue; } - + if (jarEntry.isDirectory()) { dstFile.mkdirs(); continue; } - + InputStream is = ClassLoader.getSystemResourceAsStream(jarEntry.getName()); LOGGER.debug("Copying {} from {} to {} ", jarEntry.getName(), srcFile, dstFile); copyFile(is, jarEntry.getName(), dstFile); @@ -235,7 +235,7 @@ public static boolean extractFilesFromClassPath(String srcPath, String dstPath, /** * Get clasess from JAR - * + * * @param srcUrl * @param packageName * @return @@ -252,12 +252,12 @@ private static void getFromJar(URL srcUrl, String packageName, Consumer c //in Tomcat the form is jar:file:/ //in Weblogic the form is only zip:/ LOGGER.trace("srcUrl.getProtocol(): {}", srcUrl.getProtocol()); - + if ("zip".equals(srcUrl.getProtocol())) { srcName = "file:" + srcName; } LOGGER.trace("srcName: {}", srcName); - + // Probably hepls fix error in windows with URI File jarTmp = null; try { @@ -321,7 +321,7 @@ private static void getFromJar(URL srcUrl, String packageName, Consumer c /** * get classes from directory - * + * * @param candidateUrl * @param packageName * @return diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/Cloner.java b/infra/util/src/main/java/com/evolveum/midpoint/util/Cloner.java index 46de383abfe..8c4c96f200c 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/Cloner.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/Cloner.java @@ -23,5 +23,5 @@ public interface Cloner { public T clone(T original); - + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/DOMUtil.java b/infra/util/src/main/java/com/evolveum/midpoint/util/DOMUtil.java index c23ad1bdff5..191bae75985 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/DOMUtil.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/DOMUtil.java @@ -25,7 +25,7 @@ import java.io.StringWriter; import java.util.*; import java.util.Map.Entry; - +import java.util.regex.Pattern; import javax.xml.XMLConstants; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; @@ -107,7 +107,7 @@ public class DOMUtil { NS_W3C_XML_SCHEMA_PREFIX); public static final QName XSD_ATTR_SCHEMA_LOCATION = new QName(W3C_XML_SCHEMA_NS_URI, "schemaLocation", NS_W3C_XML_SCHEMA_PREFIX); - + public static final QName XSD_DECIMAL = new QName(W3C_XML_SCHEMA_NS_URI, "decimal", NS_W3C_XML_SCHEMA_PREFIX); public static final QName XSD_STRING = new QName(W3C_XML_SCHEMA_NS_URI, "string", @@ -162,7 +162,7 @@ public class DOMUtil { // To generate random namespace prefixes private static Random rnd = new Random(); - + private static final DocumentBuilder loader; static { @@ -178,9 +178,9 @@ public class DOMUtil { public static String serializeDOMToString(org.w3c.dom.Node node) { return printDom(node).toString(); } - + public static void serializeDOMToFile(org.w3c.dom.Node node, File file) throws TransformerFactoryConfigurationError, TransformerException { - + Transformer transformer = TransformerFactory.newInstance().newTransformer(); Result output = new StreamResult(file); Source input = new DOMSource(node); @@ -395,7 +395,7 @@ public static Element getLastChildElement(Node parent) { return null; } - + public static List getChildElements(Element element, QName elementName) { Validate.notNull(elementName, "Element name to get must not be null"); List elements = new ArrayList<>(); @@ -645,7 +645,7 @@ public static String lookupOrCreateNamespaceDeclaration(Element element, String return preferredPrefix; } else { // Prefix conflict, we need to create different prefix - // Just going on will do that + // Just going on will do that } } } @@ -700,9 +700,9 @@ public static void setNamespaceDeclaration(Element element, String prefix, Strin attr.setValue(namespaceUri); attributes.setNamedItem(attr); } - + /** - * Returns map of all namespace declarations from specified element (prefix -> namespace). + * Returns map of all namespace declarations from specified element (prefix -> namespace). */ public static Map getNamespaceDeclarations(Element element) { Map nsDeclMap = new HashMap<>(); @@ -868,7 +868,7 @@ public static Collection listApplicationAttributes(Element element) { return attrs; } - + public static boolean hasApplicationAttributes(Element element) { NamedNodeMap attributes = element.getAttributes(); for(int i=0; i aList, List bList, boolean considerNamespacePrefixes) { return compareElementList(aList, bList, considerNamespacePrefixes, true); } - + public static boolean compareElementList(List aList, List bList, boolean considerNamespacePrefixes, boolean considerWhitespaces) { if (aList.size() != bList.size()) { return false; @@ -1192,7 +1192,7 @@ private static boolean compareNodeList(NodeList a, NodeList b, boolean considerN public static boolean compareTextNodeValues(String a, String b) { return compareTextNodeValues(a, b, true); } - + public static boolean compareTextNodeValues(String a, String b, boolean considerWhitespaces) { if (StringUtils.equals(a,b)) { return true; @@ -1206,6 +1206,9 @@ public static boolean compareTextNodeValues(String a, String b, boolean consider return false; } + private static final String SPACE_REGEX = "\\s*"; + private static final Pattern SPACE_PATTERN = Pattern.compile(SPACE_REGEX); + private static List canonizeNodeList(NodeList nodelist) { List list = new ArrayList(nodelist.getLength()); for (int i = 0; i < nodelist.getLength(); i++) { @@ -1213,14 +1216,14 @@ private static List canonizeNodeList(NodeList nodelist) { if (aItem.getNodeType() == Node.ELEMENT_NODE || aItem.getNodeType() == Node.ATTRIBUTE_NODE) { list.add(aItem); } else if (aItem.getNodeType() == Node.TEXT_NODE || aItem.getNodeType() == Node.CDATA_SECTION_NODE) { - if (!aItem.getTextContent().matches("\\s*")) { + if (!SPACE_PATTERN.matcher(aItem.getTextContent()).matches()) { list.add(aItem); } } } return list; } - + public static void normalize(Node node, boolean keepWhitespaces) { NodeList childNodes = node.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { @@ -1229,7 +1232,7 @@ public static void normalize(Node node, boolean keepWhitespaces) { node.removeChild(aItem); i--; } else if (aItem.getNodeType() == Node.TEXT_NODE) { - if (aItem.getTextContent().matches("\\s*")) { + if (SPACE_PATTERN.matcher(aItem.getTextContent()).matches()) { node.removeChild(aItem); i--; } else { @@ -1243,6 +1246,9 @@ public static void normalize(Node node, boolean keepWhitespaces) { } } + private static final String WS_ONLY_REGEX = "^\\s*$"; + private static final Pattern WS_ONLY_PATTERN = Pattern.compile(WS_ONLY_REGEX); + public static boolean isJunk(Node node) { if (node.getNodeType() == Node.COMMENT_NODE) { return true; @@ -1252,7 +1258,7 @@ public static boolean isJunk(Node node) { } if (node.getNodeType() == Node.TEXT_NODE) { Text text = (Text)node; - if (text.getTextContent().matches("^\\s*$")) { + if (WS_ONLY_PATTERN.matcher(text.getTextContent()).matches()) { return true; } return false; @@ -1288,7 +1294,7 @@ public static Element findElementRecursive(Element element, QName elementQName) } return null; } - + public static QName getQNameWithoutPrefix(Node node) { QName qname = getQName(node); return new QName(qname.getNamespaceURI(), qname.getLocalPart()); diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/DebugDumpable.java b/infra/util/src/main/java/com/evolveum/midpoint/util/DebugDumpable.java index 1a8b2c913ab..d1067c769af 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/DebugDumpable.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/DebugDumpable.java @@ -21,29 +21,29 @@ */ @FunctionalInterface public interface DebugDumpable { - + String INDENT_STRING = " "; - + /** * Show the content of the object intended for diagnostics by system administrator. The out * put should be suitable to use in system logs at "debug" level. It may be multi-line, but in * that case it should be well indented and quite terse. - * + * * As it is intended to be used by system administrator, it should not use any developer terms * such as class names, exceptions or stack traces. - * + * * @return content of the object intended for diagnostics by system administrator. */ default String debugDump() { return debugDump(0); } - + String debugDump(int indent); default Object debugDumpLazily() { return DebugUtil.debugDumpLazily(this); } - + default Object debugDumpLazily(int index) { return DebugUtil.debugDumpLazily(this, index); } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/DebugUtil.java b/infra/util/src/main/java/com/evolveum/midpoint/util/DebugUtil.java index 7480fb5cf3f..f7682c767c2 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/DebugUtil.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/DebugUtil.java @@ -40,7 +40,7 @@ * @author semancik */ public class DebugUtil { - + private static boolean detailedDebugDump = false; private static String prettyPrintBeansAs = null; @@ -79,7 +79,7 @@ public static String dump(DebugDumpable dumpable) { } return dumpable.debugDump(); } - + public static String dump(Object object) { if (object == null) { return "null"; @@ -107,17 +107,17 @@ public static String debugDump(Collection dumpables, int indent) { debugDump(sb, dumpables, indent, true); return sb.toString(); } - + public static String debugDump(Map dumpables, int indent) { StringBuilder sb = new StringBuilder(); debugDumpMapMultiLine(sb, dumpables, indent, true); return sb.toString(); } - + public static void debugDump(StringBuilder sb, Collection dumpables, int indent, boolean openCloseSymbols) { debugDump(sb, dumpables, indent, openCloseSymbols, null); } - + public static void debugDump(StringBuilder sb, Collection dumpables, int indent, boolean openCloseSymbols, String dumpSuffix) { if (dumpables == null) { return; @@ -170,7 +170,7 @@ public static String debugDump(DebugDumpable dd, int indent) { return dd.debugDump(indent); } } - + public static String debugDump(Object object, int indent) { if (object == null) { StringBuilder sb = new StringBuilder(); @@ -196,17 +196,17 @@ public static void debugDumpLabel(StringBuilder sb, String label, int indent) { indentDebugDump(sb, indent); sb.append(label).append(":"); } - + public static void debugDumpLabelLn(StringBuilder sb, String label, int indent) { debugDumpLabel(sb, label, indent); sb.append("\n"); } - + public static void debugDumpWithLabelLn(StringBuilder sb, String label, DebugDumpable dd, int indent) { debugDumpWithLabel(sb,label,dd,indent); sb.append("\n"); } - + public static void debugDumpWithLabel(StringBuilder sb, String label, DebugDumpable dd, int indent) { debugDumpLabel(sb, label, indent); if (dd == null) { @@ -216,24 +216,24 @@ public static void debugDumpWithLabel(StringBuilder sb, String label, DebugDumpa sb.append(dd.debugDump(indent + 1)); } } - + public static void debugDumpWithLabel(StringBuilder sb, String label, String val, int indent) { debugDumpLabel(sb, label, indent); sb.append(" "); sb.append(val); } - + public static void debugDumpWithLabelLn(StringBuilder sb, String label, String val, int indent) { debugDumpWithLabel(sb, label, val, indent); sb.append("\n"); } - + public static void debugDumpWithLabel(StringBuilder sb, String label, QName val, int indent) { debugDumpLabel(sb, label, indent); sb.append(" "); sb.append(PrettyPrinter.prettyPrint(val)); } - + public static void debugDumpWithLabelLn(StringBuilder sb, String label, QName val, int indent) { debugDumpWithLabel(sb, label, val, indent); sb.append("\n"); @@ -249,7 +249,7 @@ public static void debugDumpWithLabelLn(StringBuilder sb, String label, Boolean debugDumpWithLabel(sb, label, val, indent); sb.append("\n"); } - + public static void debugDumpWithLabel(StringBuilder sb, String label, Integer val, int indent) { debugDumpLabel(sb, label, indent); sb.append(" "); @@ -260,13 +260,13 @@ public static void debugDumpWithLabelLn(StringBuilder sb, String label, Integer debugDumpWithLabel(sb, label, val, indent); sb.append("\n"); } - + public static void debugDumpWithLabel(StringBuilder sb, String label, Long val, int indent) { debugDumpLabel(sb, label, indent); sb.append(" "); sb.append(val); } - + public static void debugDumpWithLabelLn(StringBuilder sb, String label, Long val, int indent) { debugDumpWithLabel(sb, label, val, indent); sb.append("\n"); @@ -277,12 +277,12 @@ public static void debugDumpWithLabel(StringBuilder sb, String label, Class val, sb.append(" "); sb.append(val); } - + public static void debugDumpWithLabelLn(StringBuilder sb, String label, Class val, int indent) { debugDumpWithLabel(sb, label, val, indent); sb.append("\n"); } - + public static void debugDumpWithLabel(StringBuilder sb, String label, Collection values, int indent) { debugDumpLabel(sb, label, indent); if (values == null) { @@ -296,12 +296,12 @@ public static void debugDumpWithLabel(StringBuilder sb, String label, Collection sb.append(debugDump(values, indent + 1)); } } - + public static void debugDumpWithLabelLn(StringBuilder sb, String label, Collection values, int indent) { debugDumpWithLabel(sb, label, values, indent); sb.append("\n"); } - + public static void debugDumpWithLabel(StringBuilder sb, String label, Map map, int indent) { debugDumpLabel(sb, label, indent); if (map == null) { @@ -311,12 +311,12 @@ public static void debugDumpWithLabel(StringBuilder sb, String label, Map debugDumpMapMultiLine(sb, map, indent + 1); } } - + public static void debugDumpWithLabelLn(StringBuilder sb, String label, Map map, int indent) { debugDumpWithLabel(sb, label, map, indent); sb.append("\n"); } - + public static void debugDumpWithLabelToString(StringBuilder sb, String label, Object object, int indent) { debugDumpLabel(sb, label, indent); if (object == null) { @@ -326,7 +326,7 @@ public static void debugDumpWithLabelToString(StringBuilder sb, String label, Ob sb.append(object.toString()); } } - + public static void debugDumpWithLabelToStringLn(StringBuilder sb, String label, Object object, int indent) { debugDumpWithLabelToString(sb, label, object, indent); sb.append("\n"); @@ -372,29 +372,29 @@ public static void indentDebugDump(StringBuilder sb, int indent) { sb.append(DebugDumpable.INDENT_STRING); } } - + public static StringBuilder createIndentedStringBuilder(int indent) { StringBuilder sb = new StringBuilder(); indentDebugDump(sb, indent); return sb; } - + public static StringBuilder createTitleStringBuilderLn(Class titleClass, int indent) { StringBuilder sb = createTitleStringBuilder(titleClass, indent); sb.append("\n"); return sb; } - + public static StringBuilder createTitleStringBuilder(Class titleClass, int indent) { return createTitleStringBuilder(titleClass.getSimpleName(), indent); } - + public static StringBuilder createTitleStringBuilder(String label, int indent) { StringBuilder sb = createIndentedStringBuilder(indent); sb.append(label); return sb; } - + public static String debugDumpMapMultiLine(Map map) { StringBuilder sb = new StringBuilder(); debugDumpMapMultiLine(sb, map, 0); @@ -404,11 +404,11 @@ public static String debugDumpMapMultiLine(Map map) { public static void debugDumpMapMultiLine(StringBuilder sb, Map map, int indent) { debugDumpMapMultiLine(sb, map, indent, false); } - + public static void debugDumpMapMultiLine(StringBuilder sb, Map map, int indent, boolean openCloseSymbols) { debugDumpMapMultiLine(sb, map, indent, openCloseSymbols, null); } - + public static void debugDumpMapMultiLine(StringBuilder sb, Map map, int indent, boolean openCloseSymbols, String dumpSuffix) { int inindent = indent; if (openCloseSymbols) { @@ -534,18 +534,18 @@ public static int estimateObjectSize(Serializable o) { throw new IllegalStateException(e.getMessage(), e); } } - + public static void dumpObjectSizeEstimateLn(StringBuilder sb, String label, Serializable o, int indent) { dumpObjectSizeEstimate(sb, label, o, indent); sb.append("\n"); } - + public static void dumpObjectSizeEstimate(StringBuilder sb, String label, Serializable o, int indent) { indentDebugDump(sb, indent); sb.append(label).append(": "); sb.append(estimateObjectSize(o)); } - + public static String dumpObjectFieldsSizeEstimate(final Serializable o) { final StringBuilder sb = new StringBuilder(); sb.append(o).append(": ").append(estimateObjectSize(o)).append("\n"); @@ -583,7 +583,7 @@ public void doWith(Field field) throws IllegalArgumentException, IllegalAccessEx public static Object debugDumpLazily(DebugDumpable dumpable) { return debugDumpLazily(dumpable, 0); } - + public static Object debugDumpLazily(DebugDumpable dumpable, int index) { if (dumpable == null) { return null; @@ -619,7 +619,7 @@ public String toString() { } }; } - + public static Object shortDumpLazily(ShortDumpable dumpable) { if (dumpable == null) { return null; diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/DisplayableValue.java b/infra/util/src/main/java/com/evolveum/midpoint/util/DisplayableValue.java index 8bb7090e020..5ed1e60eaec 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/DisplayableValue.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/DisplayableValue.java @@ -25,18 +25,18 @@ public interface DisplayableValue { * Retuns actual value. This may not be user-friendly. */ T getValue(); - + /** * Returns short user-friendly label. * Catalog key may be returned instead of actual text. */ String getLabel(); - + /** - * Returns longer description that can be used as a help text, - * tooltip or for similar purpose. + * Returns longer description that can be used as a help text, + * tooltip or for similar purpose. * Catalog key may be returned instead of actual text. */ String getDescription(); - + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/DomAsserts.java b/infra/util/src/main/java/com/evolveum/midpoint/util/DomAsserts.java index 2734bba0ed1..54c650afc95 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/DomAsserts.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/DomAsserts.java @@ -28,9 +28,9 @@ public static void assertElementQName(Element element, QName expectedQName) { QName actual = DOMUtil.getQName(element); assertEquals("Wrong element name", expectedQName, actual); } - + public static void assertEquals(String message, Object expected, Object actual) { - assert MiscUtil.equals(expected, actual) : message + assert MiscUtil.equals(expected, actual) : message + ": expected " + MiscUtil.getValueWithClass(expected) + ", was " + MiscUtil.getValueWithClass(actual); } @@ -48,5 +48,5 @@ public static void assertSubElement(Element element, QName expectedSubElementNam public static void assertTextContent(Element element, String expected) { assertEquals("Wrong content in element "+DOMUtil.getQName(element), expected, element.getTextContent()); } - + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/DomElementVisitor.java b/infra/util/src/main/java/com/evolveum/midpoint/util/DomElementVisitor.java index 97258758695..7fe4c0e0a55 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/DomElementVisitor.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/DomElementVisitor.java @@ -25,5 +25,5 @@ public interface DomElementVisitor { public void visit(Element element); - + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/DomVisitorUtil.java b/infra/util/src/main/java/com/evolveum/midpoint/util/DomVisitorUtil.java index 783e3e68254..3e0b52adb6f 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/DomVisitorUtil.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/DomVisitorUtil.java @@ -25,7 +25,7 @@ * */ public class DomVisitorUtil { - + public static void visitElements(Node node, DomElementVisitor visitor) { if (node instanceof Element) { visitor.visit((Element)node); diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/FailableFunction.java b/infra/util/src/main/java/com/evolveum/midpoint/util/FailableFunction.java index c2a93b61696..b2b85b9fa88 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/FailableFunction.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/FailableFunction.java @@ -23,5 +23,5 @@ public interface FailableFunction { R apply(T object) throws Exception; - + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/FailableProcessor.java b/infra/util/src/main/java/com/evolveum/midpoint/util/FailableProcessor.java index a6415c48cc7..96e91df3247 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/FailableProcessor.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/FailableProcessor.java @@ -23,5 +23,5 @@ public interface FailableProcessor { void process(T object) throws Exception; - + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/FailableProducer.java b/infra/util/src/main/java/com/evolveum/midpoint/util/FailableProducer.java index ac80872d0ee..5ac193b122c 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/FailableProducer.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/FailableProducer.java @@ -20,12 +20,12 @@ /** * Almost the same as java.util.function.Supplier, but this one is Serializable. * That is very useful especially in use in Wicket models. - * + * * @author Radovan Semancik */ @FunctionalInterface public interface FailableProducer extends Serializable { T run() throws Exception; - + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/FailableRunnable.java b/infra/util/src/main/java/com/evolveum/midpoint/util/FailableRunnable.java index f439b65a082..91a2742571d 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/FailableRunnable.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/FailableRunnable.java @@ -17,12 +17,12 @@ /** * Used mostly in tests to simplify error handling. - * + * * @author semancik */ @FunctionalInterface public interface FailableRunnable { - + public abstract void run() throws Exception; } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/Foreachable.java b/infra/util/src/main/java/com/evolveum/midpoint/util/Foreachable.java index 420c55eaf37..199e6559ed7 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/Foreachable.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/Foreachable.java @@ -21,7 +21,7 @@ */ @FunctionalInterface public interface Foreachable { - + /** * Will call processor for every element in the instance. * This is NOT recursive. E.g. in case of collection of collections diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/Handler.java b/infra/util/src/main/java/com/evolveum/midpoint/util/Handler.java index c55ff63455f..fc151c17ceb 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/Handler.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/Handler.java @@ -24,5 +24,5 @@ public interface Handler { // returns false if the iteration (if any) has to be stopped boolean handle(T t); - + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/HeteroComparator.java b/infra/util/src/main/java/com/evolveum/midpoint/util/HeteroComparator.java index f8df520ca4e..2778e14a3b5 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/HeteroComparator.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/HeteroComparator.java @@ -23,5 +23,5 @@ public interface HeteroComparator { boolean isEquivalent(A a, B b); - + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/Holder.java b/infra/util/src/main/java/com/evolveum/midpoint/util/Holder.java index 5b989811c62..b53e745f6eb 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/Holder.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/Holder.java @@ -17,8 +17,8 @@ /** * Very simple object to hold a single value. This comes handy when a final value is required but there is a - * need to use immutable value (e.g. int, String). This comes very handy in Java anonymous instances (almost-closures). - * + * need to use immutable value (e.g. int, String). This comes very handy in Java anonymous instances (almost-closures). + * * @author Radovan Semancik */ public class Holder { @@ -29,7 +29,7 @@ public Holder() { super(); this.value = null; } - + public Holder(T value) { super(); this.value = value; @@ -76,5 +76,5 @@ public boolean equals(Object obj) { public String toString() { return "Holder(" + value + ")"; } - + } \ No newline at end of file diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/HumanReadableDescribable.java b/infra/util/src/main/java/com/evolveum/midpoint/util/HumanReadableDescribable.java index fd4a6cfe989..b836bf85a32 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/HumanReadableDescribable.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/HumanReadableDescribable.java @@ -18,12 +18,12 @@ /** * Object that can provide short, human-readable description. The description should * be suitable for logging and presentation to users (non-developers). - * + * * @author semancik */ @FunctionalInterface public interface HumanReadableDescribable { String toHumanReadableDescription(); - + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/JAXBUtil.java b/infra/util/src/main/java/com/evolveum/midpoint/util/JAXBUtil.java index e08acd8d290..c09c15f59ac 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/JAXBUtil.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/JAXBUtil.java @@ -35,9 +35,9 @@ import com.evolveum.midpoint.util.logging.TraceManager; /** - * + * * @author lazyman - * + * */ public final class JAXBUtil { @@ -84,7 +84,7 @@ public static boolean isElement(Object element) { return false; } } - + public static QName getElementQName(Object element) { if (element == null) { return null; @@ -114,9 +114,9 @@ public static String getElementLocalName(Object element) { /** * Returns short description of element content for diagnostics use (logs, * dumps). - * + * * Works with DOM and JAXB elements. - * + * * @param element * DOM or JAXB element * @return short description of element content @@ -147,7 +147,7 @@ public static Document getDocument(Object element) { /** * Looks for an element with specified name. Considers both DOM and JAXB * elements. Assumes single element instance in the list. - * + * * @param elements * @param elementName */ @@ -210,7 +210,7 @@ public static List listChildElements(Object parentElement) { } return childElements; } - + private static Method lookForXsdAnyElementMethod(Object jaxbObject) { Class jaxbClass = jaxbObject.getClass(); for (Method method: jaxbClass.getMethods()) { @@ -259,7 +259,7 @@ public static Class findClassForType(QName typeName, Package pkg) { return null; } - + public static boolean compareElementList(List aList, List bList, boolean considerNamespacePrefixes) { if (aList.size() != bList.size()) { return false; @@ -279,7 +279,7 @@ public static boolean compareElementList(List aList, List bList, return false; } } - + } return true; } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/LocalizableMessage.java b/infra/util/src/main/java/com/evolveum/midpoint/util/LocalizableMessage.java index cda2f90278c..bbff6aef708 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/LocalizableMessage.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/LocalizableMessage.java @@ -37,8 +37,8 @@ public LocalizableMessage(String key, Object[] args, String fallbackMessage) { } /** - * Message key. This is the key in localization files that - * determine message or message template. + * Message key. This is the key in localization files that + * determine message or message template. */ public String getKey() { return key; @@ -124,5 +124,5 @@ public void shortDump(StringBuilder sb) { sb.append(fallbackMessage); }; } - + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/LocalizableMessageBuilder.java b/infra/util/src/main/java/com/evolveum/midpoint/util/LocalizableMessageBuilder.java index b1bbd4ee170..e558b86eb18 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/LocalizableMessageBuilder.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/LocalizableMessageBuilder.java @@ -22,9 +22,9 @@ * */ public class LocalizableMessageBuilder { - + private String key; - private Object[] args; + private Object[] args; private String fallbackMessage; public LocalizableMessageBuilder() { @@ -34,7 +34,7 @@ public LocalizableMessageBuilder() { public void key(String key) { this.key = key; } - + public static LocalizableMessage buildKey(String key) { return new LocalizableMessage(key, null, null); } @@ -42,7 +42,7 @@ public static LocalizableMessage buildKey(String key) { public void args(Object... args) { this.args = args; } - + public void args(List args) { this.args = args.toArray(); } @@ -50,7 +50,7 @@ public void args(List args) { public void fallbackMessage(String fallbackMessage) { this.fallbackMessage = fallbackMessage; } - + public static LocalizableMessage buildFallbackMessage(String fallbackMessage) { return new LocalizableMessage(null, null, fallbackMessage); } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/MiscUtil.java b/infra/util/src/main/java/com/evolveum/midpoint/util/MiscUtil.java index 3673406fadf..f26f216c5e3 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/MiscUtil.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/MiscUtil.java @@ -38,11 +38,11 @@ * */ public class MiscUtil { - - private static final int BUFFER_SIZE = 2048; - + + private static final int BUFFER_SIZE = 2048; + private static final Trace LOGGER = TraceManager.getTrace(MiscUtil.class); - + private static DatatypeFactory df = null; static { @@ -63,7 +63,7 @@ public static Collection union(Collection... sets) { } return resultSet; } - + public static Collection unionExtends(Collection... sets) { Set resultSet = new HashSet(); for (Collection set: sets) { @@ -73,7 +73,7 @@ public static Collection unionExtends(Collection.. } return resultSet; } - + public static boolean listEquals(List a, List b) { if (a == null && b == null) { return true; @@ -91,20 +91,20 @@ public static boolean listEquals(List a, List b) { } return true; } - + public static boolean unorderedCollectionEquals(Collection a, Collection b) { return unorderedCollectionEquals(a, b, (xa, xb) -> xa.equals(xb)); } - + /** - * Only zero vs non-zero value of comparator is important. + * Only zero vs non-zero value of comparator is important. */ public static boolean unorderedCollectionCompare(Collection a, Collection b, final Comparator comparator) { return unorderedCollectionEquals(a, b, (xa, xb) -> comparator.compare(xa, xb) == 0); } - + /** - * Only zero vs non-zero value of comparator is important. + * Only zero vs non-zero value of comparator is important. */ public static boolean unorderedCollectionEquals(Collection a, Collection b, HeteroComparator comparator) { if (a == null && b == null) { @@ -137,7 +137,7 @@ public static boolean unorderedCollectionEquals(Collection a, Collectio } return true; } - + public static boolean unorderedArrayEquals(T[] a, T[] b) { Comparator comparator = new Comparator() { @Override @@ -147,9 +147,9 @@ public int compare(T o1, T o2) { }; return unorderedArrayEquals(a, b, comparator); } - + /** - * Only zero vs non-zero value of comparator is important. + * Only zero vs non-zero value of comparator is important. */ public static boolean unorderedArrayEquals(T[] a, T[] b, Comparator comparator) { if (a == null && b == null) { @@ -181,7 +181,7 @@ public static boolean unorderedArrayEquals(T[] a, T[] b, Comparator compa } return true; } - + public static int unorderedCollectionHashcode(Collection collection, Predicate filter) { // Stupid implmentation, just add all the hashcodes int hashcode = 0; @@ -194,9 +194,9 @@ public static int unorderedCollectionHashcode(Collection collection, Pred } return hashcode; } - + public static String readFile(File file) throws IOException { - StringBuffer fileData = new StringBuffer(BUFFER_SIZE); + StringBuilder fileData = new StringBuilder(BUFFER_SIZE); BufferedReader reader = new BufferedReader(new FileReader(file)); char[] buf = new char[BUFFER_SIZE]; int numRead=0; @@ -208,7 +208,7 @@ public static String readFile(File file) throws IOException { reader.close(); return fileData.toString(); } - + public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); @@ -263,7 +263,7 @@ public static Collection createCollection(T... items) { } return collection; } - + /** * n-ary and that ignores null values. */ @@ -318,7 +318,7 @@ public static XMLGregorianCalendar asXMLGregorianCalendar(Long timeInMilis) { return df.newXMLGregorianCalendar(gc); } } - + /** * Converts an XMLGregorianCalendar to an instance of java.util.Date * @@ -334,7 +334,7 @@ public static java.util.Date asDate(XMLGregorianCalendar xgc) { return xgc.toGregorianCalendar().getTime(); } } - + public static Long asLong(XMLGregorianCalendar xgc) { if (xgc == null) { return null; @@ -342,20 +342,20 @@ public static Long asLong(XMLGregorianCalendar xgc) { return xgc.toGregorianCalendar().getTimeInMillis(); } } - + public static java.util.Date asDate(int year, int month, int date, int hrs, int min, int sec) { Calendar cal = Calendar.getInstance(); cal.set(year, month - 1, date, hrs, min, sec); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } - + public static void carthesian(Collection> dimensions, Processor> processor) { List> dimensionList = new ArrayList>(dimensions.size()); dimensionList.addAll(dimensions); carthesian(new ArrayList(dimensions.size()), dimensionList, 0, processor); } - + private static void carthesian(List items, List> dimensions, int dimensionNum, Processor> processor) { Collection myDimension = dimensions.get(dimensionNum); for (T item: myDimension) { @@ -368,7 +368,7 @@ private static void carthesian(List items, List> dimensions items.remove(items.size() - 1); } } - + public static String concat(Collection stringCollection) { StringBuilder sb = new StringBuilder(); for (String s: stringCollection) { @@ -376,7 +376,7 @@ public static String concat(Collection stringCollection) { } return sb.toString(); } - + public static boolean isAllNull(Collection collection) { for (Object o: collection) { if (o != null) { @@ -392,7 +392,7 @@ public static String getValueWithClass(Object object) { } return "("+object.getClass().getSimpleName() + ")" + object; } - + public static boolean isNoValue(Collection collection) { if (collection == null) return true; @@ -435,7 +435,7 @@ public static Map cloneMap(Map orig) { } return clone; } - + public static String toString(Object o) { if (o == null) { return "null"; @@ -451,7 +451,7 @@ public static List splitLines(String string) { } return lines; } - + public static boolean isBetween(XMLGregorianCalendar date, XMLGregorianCalendar start, XMLGregorianCalendar end) { return (date.compare(start) == DatatypeConstants.GREATER || date.compare(start) == DatatypeConstants.EQUAL) && (date.compare(end) == DatatypeConstants.LESSER || date.compare(end) == DatatypeConstants.EQUAL); @@ -472,7 +472,7 @@ public static String stripHtmlMarkup(String htmlString) { } return htmlString.replaceAll("<[^>]*>", ""); } - + public static Collection getValuesFromDisplayableValues(Collection> disps) { if (disps == null) { return null; @@ -483,7 +483,7 @@ public static Collection getValuesFromDisplayableValues(Collection void addAllIfNotPresent(List receivingList, List supplyi addIfNotPresent(receivingList, supplyingElement); } } - + public static void addIfNotPresent(List receivingList, T supplyingElement) { if (!receivingList.contains(supplyingElement)) { receivingList.add(supplyingElement); diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/PrettyPrinter.java b/infra/util/src/main/java/com/evolveum/midpoint/util/PrettyPrinter.java index 47762531ee0..1605dd142ee 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/PrettyPrinter.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/PrettyPrinter.java @@ -39,13 +39,13 @@ * */ public class PrettyPrinter { - + private static final int BYTE_ARRAY_MAX_LEN = 64; private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss"); - + private static String defaultNamespacePrefix = null; - + private static List> prettyPrinters = new ArrayList<>(); public static void setDefaultNamespacePrefix(String prefix) { @@ -210,24 +210,24 @@ public static String prettyPrint(Element element, boolean displayTag) { } child = child.getNextSibling(); } - + sb.append(content); - + return sb.toString(); } - + public static String prettyPrint(Date date) { if (date == null) { return "null"; } return dateFormat.format(date); } - + public static String prettyPrint(Object[] value) { return prettyPrint(Arrays.asList(value)); } - + public static String prettyPrint(byte[] value) { StringBuilder sb = new StringBuilder(); sb.append("byte["); @@ -265,7 +265,7 @@ public static String prettyPrint(Object value) { } return out; } - + private static String tryPrettyPrint(Object value) { if (value instanceof Class) { Class c = (Class)value; @@ -302,7 +302,7 @@ private static String tryPrettyPrint(Object value) { // Fallback to this class return tryPrettyPrint(value, PrettyPrinter.class); } - + private static String tryPrettyPrint(Object value, Class prettyPrinterClass) { for (Method method : prettyPrinterClass.getMethods()) { if (method.getName().equals("prettyPrint")) { @@ -324,7 +324,7 @@ private static String tryPrettyPrint(Object value, Class prettyPrinterClass) } return null; } - + public static void registerPrettyPrinter(Class printerClass) { prettyPrinters.add(printerClass); } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/Processor.java b/infra/util/src/main/java/com/evolveum/midpoint/util/Processor.java index 4ae8df4664b..94fde5ecf69 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/Processor.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/Processor.java @@ -23,5 +23,5 @@ public interface Processor { void process(T object); - + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/Producer.java b/infra/util/src/main/java/com/evolveum/midpoint/util/Producer.java index b9e37eae604..84a8a23c10e 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/Producer.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/Producer.java @@ -20,12 +20,12 @@ /** * Almost the same as java.util.function.Supplier, but this one is Serializable. * That is very useful especially in use in Wicket models. - * + * * @author Radovan Semancik */ @FunctionalInterface public interface Producer extends Serializable { T run(); - + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/QNameUtil.java b/infra/util/src/main/java/com/evolveum/midpoint/util/QNameUtil.java index 7fed1b30954..e4361c82c3e 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/QNameUtil.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/QNameUtil.java @@ -17,6 +17,7 @@ package com.evolveum.midpoint.util; import java.util.*; +import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.xml.namespace.QName; @@ -31,9 +32,8 @@ import org.w3c.dom.Node; /** + * QName <-> URI conversion. * - * QName <-> URI conversion. - * * Very simplistic but better than nothing. * * @author semancik @@ -201,11 +201,11 @@ public static QNameInfo uriToQNameInfo(@NotNull String uri, boolean allowUnquali throw new IllegalArgumentException("The URI (" + uri + ") does not contain slash character"); } } - + public static QName getNodeQName(Node node) { return new QName(node.getNamespaceURI(),node.getLocalName()); } - + public static boolean compareQName(QName qname, Node node) { return (qname.getNamespaceURI().equals(node.getNamespaceURI()) && qname.getLocalPart().equals(node.getLocalName())); } @@ -254,7 +254,7 @@ public static boolean matchWithUri(QName qname, String uri) { return match(qname, uriToQName(uri, true)); } - + public static QName resolveNs(QName a, Collection col){ if (col == null) { return null; @@ -270,7 +270,7 @@ public static QName resolveNs(QName a, Collection col){ } return found; } - + public static boolean matchAny(QName a, Collection col) { if (resolveNs(a, col) == null){ return false; @@ -286,7 +286,7 @@ public static boolean matchAny(QName a, Collection col) { // } // return false; } - + public static Collection createCollection(QName... qnames) { return Arrays.asList(qnames); } @@ -333,11 +333,14 @@ public static boolean isPrefixUndeclared(String namespacePrefix) { return namespacePrefix != null && namespacePrefix.startsWith(UNDECLARED_PREFIX_MARK); } + private static final String WORDS_COLON_REGEX = "^\\w+:.*"; + private static final Pattern WORDS_COLON_PATTERN = Pattern.compile(WORDS_COLON_REGEX); + public static boolean isUri(String string) { if (string == null) { return false; } - return string.matches("^\\w+:.*"); + return WORDS_COLON_PATTERN.matcher(string).matches(); } public static String getLocalPart(QName name) { diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/RandomString.java b/infra/util/src/main/java/com/evolveum/midpoint/util/RandomString.java index 97a41e9ddc9..996a2e7e531 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/RandomString.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/RandomString.java @@ -52,7 +52,7 @@ public class RandomString { public RandomString(int length) { this(length, false); } - + public RandomString(int length, boolean readable) { if (length < 1) { throw new IllegalArgumentException("length < 1: " + length); diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/ReflectionUtil.java b/infra/util/src/main/java/com/evolveum/midpoint/util/ReflectionUtil.java index d3d32aa58c4..0177d6301de 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/ReflectionUtil.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/ReflectionUtil.java @@ -70,7 +70,7 @@ public static Method findGetter(Object object, String propertyName) { String getterName = getterName(propertyName); return findMethod(object, getterName, 0); } - + private static String getterName(String propertyName) { return "get" + StringUtils.capitalize(propertyName); } @@ -99,7 +99,7 @@ public static Method findMethod(Object object, String methodName, List argLis method = findVarArgsMethod(object, methodName); return method; } - + private static Method findMethodDirect(Object object, String methodName, List argList) throws SecurityException { Class[] parameterTypes = new Class[argList.size()]; for (int i=0; i < argList.size(); i++) { @@ -111,7 +111,7 @@ private static Method findMethodDirect(Object object, String methodName, List return null; } } - + /** * Rough lookup of a compatible method. It takes first method with matching name, number of parameters and compatible * parameter values. It is not perfect, e.g. it cannot select foo(String) instead of foo(Object). But it is better than @@ -140,10 +140,10 @@ private static Method findMethodCompatible(Object object, String methodName, Lis } } } - } + } return null; } - + public static Method findVarArgsMethod(Object object, String methodName) { for (Method method: object.getClass().getMethods()) { if (method.getName().equals(methodName) && method.isVarArgs()) { @@ -152,7 +152,7 @@ public static Method findVarArgsMethod(Object object, String methodName) { } return null; } - + public static Object invokeMethod(Object object, String methodName, List argList) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { Method method = findMethod(object, methodName, argList); if (method == null) { diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/SchemaFailableProcessor.java b/infra/util/src/main/java/com/evolveum/midpoint/util/SchemaFailableProcessor.java index 68bacd6e520..b637ea2b988 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/SchemaFailableProcessor.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/SchemaFailableProcessor.java @@ -25,5 +25,5 @@ public interface SchemaFailableProcessor { void process(T object) throws SchemaException; - + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/SerializationUtil.java b/infra/util/src/main/java/com/evolveum/midpoint/util/SerializationUtil.java index 28833207850..43aa3691786 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/SerializationUtil.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/SerializationUtil.java @@ -25,10 +25,10 @@ /** * Collection of java.io serialization utilities. - * + * * WARNING: these utilities are not supposed to be used in a production code. They are intended to be used * in tests, prototyping and maybe some run-time diagnostics tools (but think twice before using them anyway). - * + * * @author Radovan Semancik * */ @@ -50,5 +50,5 @@ public static String toString(Object object) throws IOException { return new String(Base64.encodeBase64(byteArrayOutputStream.toByteArray())); } - + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/ShortDumpable.java b/infra/util/src/main/java/com/evolveum/midpoint/util/ShortDumpable.java index 488c09f54e6..13dae56d1d5 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/ShortDumpable.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/ShortDumpable.java @@ -20,15 +20,16 @@ */ @FunctionalInterface public interface ShortDumpable { - + /** * Show the content of the object intended for diagnostics. This method is supposed - * to return a compact, human-readable output in a single line. Unlike toString() method, + * to append a compact, human-readable output in a single line. Unlike toString() method, * there is no requirement to identify the actual class or type of the object. * It is assumed that the class/type will be obvious from the context in which the * output is used. - * - * @return compact one-line content of the object intended for diagnostics by system administrator. + * + * @param sb StringBuilder to which to a compact one-line content of the object intended + * for diagnostics by system administrator should be appended. */ void shortDump(StringBuilder sb); @@ -38,7 +39,7 @@ default String shortDump() { shortDump(sb); return sb.toString(); } - + default Object shortDumpLazily() { return DebugUtil.shortDumpLazily(this); } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/Transformer.java b/infra/util/src/main/java/com/evolveum/midpoint/util/Transformer.java index c0993921241..f47a4ffbfe4 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/Transformer.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/Transformer.java @@ -23,5 +23,5 @@ public interface Transformer { X transform(T in); - + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/UglyHacks.java b/infra/util/src/main/java/com/evolveum/midpoint/util/UglyHacks.java index 15ce6bf2d9c..24a5795cba7 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/UglyHacks.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/UglyHacks.java @@ -31,7 +31,7 @@ * */ public class UglyHacks { - + // We hope that nobody will chose a crazy name like this. We don't want to use namespaces // here as that may be messed up as well. private static final String FORTIFIED_NAMESPACE_DECLARATIONS_ELEMENT_NAME = "FORtiFIed__xmlNS"; @@ -77,7 +77,7 @@ public static String forceXsiNsDeclaration(String originalXml) { sb.append(originalXml.substring(iEndOfElementName)); return sb.toString(); } - + public static void fortifyNamespaceDeclarations(Node node) { DomElementVisitor visitor = new DomElementVisitor() { @Override @@ -87,9 +87,9 @@ public void visit(Element element) { }; DomVisitorUtil.visitElements(node, visitor); } - + public static void fortifyNamespaceDeclarationsSingleElement(Element element) { - List xmlnss = new ArrayList(); + List xmlnss = new ArrayList(); NamedNodeMap attributes = element.getAttributes(); for(int i=0; i { - + /** * Validate the provided object. Throws appropriate exception if * the object is not valid. - * + * * @param object object to validate * @param name short string name of the object. Designed to be used in exception messages. * @throws Exception appropriate exception if the object is not valid. diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/aspect/MidpointInterceptor.java b/infra/util/src/main/java/com/evolveum/midpoint/util/aspect/MidpointInterceptor.java index 4cdca6aa3f6..54896dd401c 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/aspect/MidpointInterceptor.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/aspect/MidpointInterceptor.java @@ -271,5 +271,5 @@ private String formatVal(Object value) { return "###INTERNAL#ERROR### "+t.getClass().getName()+": "+t.getMessage()+" value="+value; } } - + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/aspect/ObjectFormatter.java b/infra/util/src/main/java/com/evolveum/midpoint/util/aspect/ObjectFormatter.java index e7632091d3b..91c6c9b58fb 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/aspect/ObjectFormatter.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/aspect/ObjectFormatter.java @@ -21,7 +21,7 @@ */ @FunctionalInterface public interface ObjectFormatter { - + public String format(Object o); - + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/AuthorizationException.java b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/AuthorizationException.java index 28cab262c65..0c425e471fd 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/AuthorizationException.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/AuthorizationException.java @@ -19,7 +19,7 @@ /** * Exception indicating violation of authorization policies. - * + * * @author Radovan Semancik * */ @@ -32,7 +32,7 @@ public AuthorizationException() { public AuthorizationException(String message) { super(message); } - + public AuthorizationException(LocalizableMessage userFriendlyMessage) { super(userFriendlyMessage); } @@ -44,7 +44,7 @@ public AuthorizationException(Throwable cause) { public AuthorizationException(String message, Throwable cause) { super(message, cause); } - + public AuthorizationException(LocalizableMessage userFriendlyMessage, Throwable cause) { super(userFriendlyMessage, cause); } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/CommonException.java b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/CommonException.java index 18a49674407..de1f2937b6c 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/CommonException.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/CommonException.java @@ -19,12 +19,12 @@ /** * Superclass for all common midPoint exceptions. - * - * + * + * * @author Radovan Semancik */ public abstract class CommonException extends Exception { - + LocalizableMessage userFriendlyMessage; public CommonException() { @@ -33,7 +33,7 @@ public CommonException() { public CommonException(String message) { super(message); } - + public CommonException(LocalizableMessage userFriendlyMessage) { super(userFriendlyMessage.getFallbackMessage()); this.userFriendlyMessage = userFriendlyMessage; @@ -46,23 +46,23 @@ public CommonException(Throwable cause) { public CommonException(String message, Throwable cause) { super(message, cause); } - + public CommonException(LocalizableMessage userFriendlyMessage, Throwable cause) { super(userFriendlyMessage.getFallbackMessage(), cause); this.userFriendlyMessage = userFriendlyMessage; } - + public CommonException(String message, Throwable cause, LocalizableMessage userFriendlyMessage) { super(message, cause); this.userFriendlyMessage = userFriendlyMessage; } - + /** * Returns a human-readable message that describes the type or class of errors * that the exception represents. E.g. "Communication error", "Policy violation", etc. - * + * * TOTO: switch return value to a localized message - * + * * @return */ public abstract String getErrorTypeMessage(); @@ -88,7 +88,7 @@ public String toString() { return super.toString() + " [" + userFriendlyMessage.shortDump() + "]"; } } - - - + + + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/CommunicationException.java b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/CommunicationException.java index 7ddad90ddea..c793eaa141e 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/CommunicationException.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/CommunicationException.java @@ -19,12 +19,12 @@ /** * Generic communication exception. - * + * * May happen in case of various network communication errors, including * (but not limited to) connection refused and timeouts. - * + * * TODO - * + * * @author Radovan Semancik * */ diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/ConcurrencyException.java b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/ConcurrencyException.java index 85ee4dd2d52..ec6f2423b13 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/ConcurrencyException.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/ConcurrencyException.java @@ -19,14 +19,14 @@ /** * Exceptional concurrency state or operation invocation. - * + * * This exception is thrown in case of race conditions and similar conflicting concurrency conditions. * It is also thrown in an attempt to acquire already acquired locks and similar cases. - * + * * This condition is implemented as exception in a hope that it will help avoid silently ignoring the * concurrency problems and that the developers will be forced to handle the condition. * It is much easier to ignore a return value than to ignore an exception. - * + * * @author Radovan Semancik * */ @@ -39,7 +39,7 @@ public ConcurrencyException() { public ConcurrencyException(String message) { super(message); } - + public ConcurrencyException(LocalizableMessage userFriendlyMessage) { super(userFriendlyMessage); } @@ -51,7 +51,7 @@ public ConcurrencyException(Throwable cause) { public ConcurrencyException(String message, Throwable cause) { super(message, cause); } - + public ConcurrencyException(LocalizableMessage userFriendlyMessage, Throwable cause) { super(userFriendlyMessage, cause); } @@ -60,7 +60,7 @@ public ConcurrencyException(LocalizableMessage userFriendlyMessage, Throwable ca public String getErrorTypeMessage() { return "Concurrency exception"; } - - + + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/ConfigurationException.java b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/ConfigurationException.java index bb1428c3b2e..9fa05b97004 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/ConfigurationException.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/ConfigurationException.java @@ -19,10 +19,10 @@ /** * Configuration exception indicates that something is mis-configured. - * + * * The system or its part is misconfigured and therefore the intended operation * cannot be executed. - * + * * @author Radovan Semancik * */ diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/ExpressionEvaluationException.java b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/ExpressionEvaluationException.java index 4fa9d4ed310..65171575cf5 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/ExpressionEvaluationException.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/ExpressionEvaluationException.java @@ -19,7 +19,7 @@ /** * Error during evaluation of expression. The expressions are defined by system administrator. - * + * * @author Radovan Semancik * */ @@ -44,7 +44,7 @@ public ExpressionEvaluationException(Throwable cause) { public ExpressionEvaluationException(String message, Throwable cause) { super(message, cause); } - + public ExpressionEvaluationException(String message, Throwable cause, LocalizableMessage userFriendlyMessage) { super(message, cause, userFriendlyMessage); } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/NoFocusNameSchemaException.java b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/NoFocusNameSchemaException.java index dad08a6a598..71914ad6216 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/NoFocusNameSchemaException.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/NoFocusNameSchemaException.java @@ -19,9 +19,9 @@ /** * Specific kind of SchemaException. Used e.g. to treat "no name" problems in previewChanges method nicely. * SchemaException.propertyName:=UserType.F_NAME could be used as well, but it's a bit ambiguous. - * + * * A little bit experimental. (We certainly don't want to have millions of exception types.) - * + * * @author mederly */ public class NoFocusNameSchemaException extends SchemaException { diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/ObjectAlreadyExistsException.java b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/ObjectAlreadyExistsException.java index 3bbc7bbf01d..2615f73ebe8 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/ObjectAlreadyExistsException.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/ObjectAlreadyExistsException.java @@ -19,7 +19,7 @@ /** * Object already exists. - * + * * @author Radovan Semancik * */ @@ -32,7 +32,7 @@ public ObjectAlreadyExistsException() { public ObjectAlreadyExistsException(String message) { super(message); } - + public ObjectAlreadyExistsException(LocalizableMessage userFriendlyMessage) { super(userFriendlyMessage); } @@ -44,7 +44,7 @@ public ObjectAlreadyExistsException(Throwable cause) { public ObjectAlreadyExistsException(String message, Throwable cause) { super(message, cause); } - + public ObjectAlreadyExistsException(LocalizableMessage userFriendlyMessage, Throwable cause) { super(userFriendlyMessage, cause); } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/ObjectNotFoundException.java b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/ObjectNotFoundException.java index 1d849ef9da0..3c29b275b0a 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/ObjectNotFoundException.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/ObjectNotFoundException.java @@ -19,15 +19,15 @@ /** * Object with specified criteria (OID) has not been found in the repository. - * + * * @author Radovan Semancik - * + * */ public class ObjectNotFoundException extends CommonException { private static final long serialVersionUID = -9003686713018111855L; private String oid = null;; - + public ObjectNotFoundException() { super(); } @@ -35,7 +35,7 @@ public ObjectNotFoundException() { public ObjectNotFoundException(String message, Throwable cause) { super(message, cause); } - + public ObjectNotFoundException(LocalizableMessage userFriendlyMessage, Throwable cause) { super(userFriendlyMessage, cause); } @@ -44,11 +44,11 @@ public ObjectNotFoundException(String message, Throwable cause, String oid) { super(message, cause); this.oid = oid; } - + public ObjectNotFoundException(String message) { super(message); } - + public ObjectNotFoundException(LocalizableMessage userFriendlyMessage) { super(userFriendlyMessage); } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/PolicyViolationException.java b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/PolicyViolationException.java index b61745bafcf..ec33d84b077 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/PolicyViolationException.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/PolicyViolationException.java @@ -30,7 +30,7 @@ public PolicyViolationException() { public PolicyViolationException(String message) { super(message); } - + public PolicyViolationException(LocalizableMessage userFriendlyMessage) { super(userFriendlyMessage); } @@ -42,7 +42,7 @@ public PolicyViolationException(Throwable cause) { public PolicyViolationException(LocalizableMessage userFriendlyMessage, Throwable cause) { super(userFriendlyMessage, cause); } - + public PolicyViolationException(String message, Throwable cause) { super(message, cause); } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/SchemaException.java b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/SchemaException.java index 9672bad451e..59d11c58156 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/SchemaException.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/SchemaException.java @@ -21,15 +21,15 @@ /** * Error regarding schema. - * - * E.g. Object class violation, missing object class, inconsistent schema, etc. - * + * + * E.g. Object class violation, missing object class, inconsistent schema, etc. + * * @author Radovan Semancik * */ public class SchemaException extends CommonException { private static final long serialVersionUID = -6016220825724355014L; - + private QName propertyName; public SchemaException() { @@ -39,7 +39,7 @@ public SchemaException() { public SchemaException(String message, Throwable cause) { super(message, cause); } - + public SchemaException(LocalizableMessage userFriendlyMessage, Throwable cause) { super(userFriendlyMessage, cause); } @@ -48,11 +48,11 @@ public SchemaException(String message, Throwable cause, QName propertyName) { super(message, cause); this.propertyName = propertyName; } - + public SchemaException(String message) { super(message); } - + public SchemaException(LocalizableMessage userFriendlyMessage) { super(userFriendlyMessage); } @@ -61,12 +61,12 @@ public SchemaException(String message, QName propertyName) { super(message); this.propertyName = propertyName; } - + @Override public String getErrorTypeMessage() { return "Schema problem"; } - + public QName getPropertyName() { return propertyName; } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/SecurityViolationException.java b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/SecurityViolationException.java index e93fc0222d3..6c494f338f3 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/SecurityViolationException.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/SecurityViolationException.java @@ -20,7 +20,7 @@ /** * Exception indicating violation of security policies. * It is SecurityViolationException to avoid confusion with java.lang.SecurityException - * + * * @author Radovan Semancik * */ @@ -33,7 +33,7 @@ public SecurityViolationException() { public SecurityViolationException(String message) { super(message); } - + public SecurityViolationException(LocalizableMessage userFriendlyMessage) { super(userFriendlyMessage); } @@ -45,7 +45,7 @@ public SecurityViolationException(Throwable cause) { public SecurityViolationException(String message, Throwable cause) { super(message, cause); } - + public SecurityViolationException(LocalizableMessage userFriendlyMessage, Throwable cause) { super(userFriendlyMessage, cause); } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/TunnelException.java b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/TunnelException.java index 82b82e44542..88634dba8fc 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/exception/TunnelException.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/exception/TunnelException.java @@ -17,9 +17,9 @@ /** * Exception used for tunneling checked exceptions through places where checked exceptipons are not allowed (e.g. callbacks). - * + * * This exception must not appear to the "outside", it must be caught and transformed back to the original form. - * + * * @author Radovan Semancik * */ @@ -41,5 +41,5 @@ public TunnelException(String message) { public TunnelException(Throwable cause) { super(cause); } - + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/logging/LoggingUtils.java b/infra/util/src/main/java/com/evolveum/midpoint/util/logging/LoggingUtils.java index 0a3dd4eac47..c4f8578c3e6 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/logging/LoggingUtils.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/logging/LoggingUtils.java @@ -23,9 +23,9 @@ import org.apache.commons.lang.Validate; /** - * + * * @author lazyman - * + * */ public class LoggingUtils { @@ -99,7 +99,7 @@ public static void logStackTrace(final Trace LOGGER, String message) { } } } - + public static String dumpStackTrace(Class... classesToSkip) { StackTraceElement[] fullStack = Thread.currentThread().getStackTrace(); String immediateClass = null; diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/logging/MDCLevelTurboFilter.java b/infra/util/src/main/java/com/evolveum/midpoint/util/logging/MDCLevelTurboFilter.java index d0452062688..fffc12186f3 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/logging/MDCLevelTurboFilter.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/logging/MDCLevelTurboFilter.java @@ -82,7 +82,7 @@ public FilterReply decide(Marker marker, Logger logger, Level level, String form } /** - * @param onMatch action to set on success + * @param action the action to set on success */ public void setOnMatch(String action) { if ("NEUTRAL".equals(action)) { @@ -95,7 +95,7 @@ public void setOnMatch(String action) { } /** - * @param onMismatch the onMismatch to set on failure + * @param action the onMismatch to set on failure */ public void setOnMismatch(String action) { if ("NEUTRAL".equals(action)) { @@ -124,7 +124,7 @@ public void setMDCValue(String mdcValue) { } /** - * @param level the level to breach + * @param loggingLevel the level to breach */ public void setLevel(String loggingLevel) { String level = loggingLevel.toUpperCase(); diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/logging/Trace.java b/infra/util/src/main/java/com/evolveum/midpoint/util/logging/Trace.java index a2941033814..f833b5ec77f 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/logging/Trace.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/logging/Trace.java @@ -21,7 +21,7 @@ /** * Just am empty extension of SLF4J logger. This is supposed * to be used for future extensions. - * + * */ public interface Trace extends Logger { 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 861ad8d3a26..f337aafd4db 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 @@ -35,7 +35,7 @@ public static Trace getTrace(Class clazz) { Logger logger = org.slf4j.LoggerFactory.getLogger(clazz); return new TraceImpl(logger); } - + public static Trace getTrace(String loggerName) { Logger logger = org.slf4j.LoggerFactory.getLogger(loggerName); return new TraceImpl(logger); @@ -45,7 +45,7 @@ public static Trace getPerformanceAdvisorTrace() { Logger logger = org.slf4j.LoggerFactory.getLogger(PERFORMANCE_ADVISOR); return new TraceImpl(logger); } - + public static ILoggerFactory getILoggerFactory() { return LoggerFactory.getILoggerFactory(); } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/logging/impl/TraceImpl.java b/infra/util/src/main/java/com/evolveum/midpoint/util/logging/impl/TraceImpl.java index a2630d464c9..366d9d4020e 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/logging/impl/TraceImpl.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/logging/impl/TraceImpl.java @@ -23,7 +23,7 @@ /** * Wrapper for logging library. It is empty now. But as this is used through all the code - * this may be a convenient place to add some future functionality quite easily. + * this may be a convenient place to add some future functionality quite easily. */ public class TraceImpl implements Trace { diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/xml/DomAwareEqualsStrategy.java b/infra/util/src/main/java/com/evolveum/midpoint/util/xml/DomAwareEqualsStrategy.java index 34462c00a9d..45adb915377 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/xml/DomAwareEqualsStrategy.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/xml/DomAwareEqualsStrategy.java @@ -25,12 +25,12 @@ /** * Strategy for equals() methods used in JAXB generated code. The strategy is using our DOMUtil to * compare DOM elements. The comparison is quite liberal when it comes to namespaces. - * + * * @author Radovan Semancik * */ public class DomAwareEqualsStrategy extends JAXBEqualsStrategy { - + public static EqualsStrategy INSTANCE = new DomAwareEqualsStrategy(); @Override @@ -49,5 +49,5 @@ protected boolean equalsInternal(ObjectLocator leftLocator, return super.equalsInternal(leftLocator, rightLocator, lhs, rhs); } } - + } diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/xml/DomAwareHashCodeStrategy.java b/infra/util/src/main/java/com/evolveum/midpoint/util/xml/DomAwareHashCodeStrategy.java index 6b115448382..0d457973c09 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/xml/DomAwareHashCodeStrategy.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/xml/DomAwareHashCodeStrategy.java @@ -26,13 +26,13 @@ * a constant. This makes the hashing somehow less efficient if the JAXB objects differ just in * the DOM parts. This this is quite unlikely under usual circumstances. However the main reason * for this is to avoid namespace-related problems. - * + * * @author Radovan Semancik * */ public class DomAwareHashCodeStrategy extends JAXBHashCodeStrategy { - + public static HashCodeStrategy INSTANCE = new DomAwareHashCodeStrategy(); @Override diff --git a/infra/util/src/test/java/com/evolveum/midpoint/util/ClassPathTest.java b/infra/util/src/test/java/com/evolveum/midpoint/util/ClassPathTest.java index 5d82e0d6383..248ffaebfc3 100644 --- a/infra/util/src/test/java/com/evolveum/midpoint/util/ClassPathTest.java +++ b/infra/util/src/test/java/com/evolveum/midpoint/util/ClassPathTest.java @@ -25,19 +25,19 @@ public class ClassPathTest { @Test public void listClassesLocalTest() { - + Set cs = ClassPathUtil.listClasses("com.evolveum.midpoint.util"); assertNotNull(cs); assertTrue(cs.contains(ClassPathUtil.class)); } - + @Test public void listClassesJarTest() { - + Set cs = ClassPathUtil.listClasses("org.testng.annotations"); // Set cs = ClassPathUtil.listClasses("org.testng"); assertNotNull(cs); assertTrue(cs.contains(Test.class)); } - + } diff --git a/infra/util/src/test/java/com/evolveum/midpoint/util/DOMUtilTest.java b/infra/util/src/test/java/com/evolveum/midpoint/util/DOMUtilTest.java index 38d165e76cc..7b53b8445bc 100644 --- a/infra/util/src/test/java/com/evolveum/midpoint/util/DOMUtilTest.java +++ b/infra/util/src/test/java/com/evolveum/midpoint/util/DOMUtilTest.java @@ -32,7 +32,7 @@ * */ public class DOMUtilTest { - + private static final String QNAME_IN_NS = "http://foo.com/bar"; private static final String QNAME_IN_LOCAL = "baz"; private static final String ELEMENT_NS = "http://foo.com/barbar"; @@ -41,11 +41,11 @@ public class DOMUtilTest { private static final String ELEMENT_TOP_LOCAL = "top"; private static final String FOO_NS = "http://foo.com/foo"; private static final QName QNAME_ATTR_QNAME = new QName(ELEMENT_NS, "qname"); - + private static final String XSD_TYPE_FILENAME = "src/test/resources/domutil/xsi-type.xml"; private static final String QNAMES_FILENAME = "src/test/resources/domutil/qnames.xml"; private static final String FIX_NAMESPACE_FILENAME = "src/test/resources/domutil/fix-namespace.xml"; - + public static final String NS_W3C_XML_SCHEMA_PREFIX = "xsd"; public static final QName XSD_SCHEMA_ELEMENT = new QName(W3C_XML_SCHEMA_NS_URI, "schema", NS_W3C_XML_SCHEMA_PREFIX); @@ -55,7 +55,7 @@ public class DOMUtilTest { NS_W3C_XML_SCHEMA_PREFIX); private static final int MAX_GENERATE_QNAME_ITERATIONS = 200; - + public DOMUtilTest() { } @@ -64,18 +64,18 @@ public void testQNameRoundTrip() { System.out.println("===[ testQNameRoundTrip ]==="); // GIVEN Document doc = DOMUtil.getDocument(); - + QName in = new QName(QNAME_IN_NS, QNAME_IN_LOCAL, "x"); Element e = doc.createElementNS(ELEMENT_NS, ELEMENT_LOCAL); - + // WHEN - + DOMUtil.setQNameValue(e, in); - + // THEN - + System.out.println(DOMUtil.serializeDOMToString(e)); - + String content = e.getTextContent(); String[] split = content.split(":"); // Default namespace should not be used unless explicitly matches existing declaration @@ -87,22 +87,22 @@ public void testQNameRoundTrip() { String namespaceURI = e.lookupNamespaceURI(prefix); AssertJUnit.assertEquals(QNAME_IN_NS, namespaceURI); AssertJUnit.assertEquals(QNAME_IN_LOCAL, localPart); - + // WHEN - + QName out = DOMUtil.getQNameValue(e); - + // THEN - + AssertJUnit.assertEquals(in, out); } - + @Test public void testQNameDefaultNamespace1() { System.out.println("===[ testQNameDefaultNamespace1 ]==="); // GIVEN Document doc = DOMUtil.getDocument(); - + QName in = new QName(DEFAULT_NS, QNAME_IN_LOCAL); Element topElement = doc.createElementNS(DEFAULT_NS, ELEMENT_TOP_LOCAL); // Make sure there is a default ns declaration @@ -113,17 +113,17 @@ public void testQNameDefaultNamespace1() { e.setPrefix("e"); e.setTextContent("foofoo"); topElement.appendChild(e); - + System.out.println(DOMUtil.serializeDOMToString(topElement)); - + // WHEN - + DOMUtil.setQNameValue(e, in); - + // THEN - + System.out.println(DOMUtil.serializeDOMToString(topElement)); - + String content = e.getTextContent(); // Default namespace should NOT be reused AssertJUnit.assertTrue(content.contains(":")); @@ -201,87 +201,87 @@ public void testXsiType() { Document doc = DOMUtil.parseFile(XSD_TYPE_FILENAME); Element root = DOMUtil.getFirstChildElement(doc); Element el1 = DOMUtil.getFirstChildElement(root); - + // WHEN QName xsiType = DOMUtil.resolveXsiType(el1); - + // THEN assertNotNull(xsiType); AssertJUnit.assertTrue(XSD_INTEGER.equals(xsiType)); - + AssertJUnit.assertTrue("Failed to detect xsi:type", DOMUtil.hasXsiType(el1)); - + } - + @Test public void testQNameMethods() { System.out.println("===[ testQNameMethods ]==="); Document doc = DOMUtil.parseFile(QNAMES_FILENAME); Element root = DOMUtil.getFirstChildElement(doc); - + Element el1 = (Element) root.getElementsByTagNameNS(DEFAULT_NS, "el1").item(0); QName refAttrValue = DOMUtil.getQNameAttribute(el1, "ref"); assertEquals("getQNameAttribute failed",new QName(FOO_NS,"bar"),refAttrValue); - + Element el2 = (Element) root.getElementsByTagNameNS(DEFAULT_NS, "el2").item(0); QName el2Value = DOMUtil.getQNameValue(el2); assertEquals("getQNameValue failed",new QName(FOO_NS,"BAR"),el2Value); } - + @Test public void testFixNamespaceDeclarations() { System.out.println("===[ testFixNamespaceDeclarations ]==="); Document doc = DOMUtil.parseFile(FIX_NAMESPACE_FILENAME); - + System.out.println("Original XML:"); System.out.println(DOMUtil.serializeDOMToString(doc)); - + Element root = DOMUtil.getFirstChildElement(doc); - + Element target = (Element) root.getElementsByTagNameNS(DEFAULT_NS, "target").item(0); - + DOMUtil.fixNamespaceDeclarations(target); - + System.out.println("Fixed namespaces (doc):"); System.out.println(DOMUtil.serializeDOMToString(doc)); - + System.out.println("Fixed namespaces (target):"); System.out.println(DOMUtil.serializeDOMToString(target)); - + Map decls = DOMUtil.getNamespaceDeclarations(target); assertEquals("bar decl", "http://foo.com/bar", decls.get("bar")); assertEquals("foo decl", "http://foo.com/foo", decls.get("foo")); assertEquals("default decl", "http://foo.com/default", decls.get(null)); } - + @Test public void testGeneratedQNamePrefixes() { System.out.println("===[ testGeneratedQNamePrefixes ]==="); // GIVEN Document doc = DOMUtil.getDocument(); - + Element topElement = doc.createElementNS(ELEMENT_NS, ELEMENT_TOP_LOCAL); doc.appendChild(topElement); - + System.out.println("Before"); System.out.println(DOMUtil.serializeDOMToString(topElement)); - - // WHEN + + // WHEN for(int i=0; i calledIds = new ArrayList(); - + // Test functions - + public void m(String a1) { calledIds.add("m1"); } - + public void m(String a1, Integer a2) { calledIds.add("m2i"); } - + public void m(String a1, String a2) { calledIds.add("m2s"); } - + public void m(String a1, Object a2) { calledIds.add("m2o"); } - + public void m(String a1, Integer a2, Long a3) { calledIds.add("m3"); } @@ -51,27 +51,27 @@ public void m(String a1, Integer a2, Long a3) { public void m(String a1, Integer a2, Long a3, Boolean a4) { calledIds.add("m4"); } - + public void l(String s) { calledIds.add("ls"); } - + public void l(Collection c) { calledIds.add("lc"); } - + // Test functions: varargs - + public void v(String... strings) { calledIds.add("v:"+strings.length); } - + // Utility - + public boolean wasCalled(String methodId) { return calledIds.contains(methodId); } - + public void reset() { calledIds.clear(); } diff --git a/infra/util/src/test/java/com/evolveum/midpoint/util/TestMiscUtil.java b/infra/util/src/test/java/com/evolveum/midpoint/util/TestMiscUtil.java index f0e9b64bc45..1851f2adac9 100644 --- a/infra/util/src/test/java/com/evolveum/midpoint/util/TestMiscUtil.java +++ b/infra/util/src/test/java/com/evolveum/midpoint/util/TestMiscUtil.java @@ -46,11 +46,11 @@ public void testUnion() { c.add("C1"); c.add("X"); c.add("Y"); - + Collection union = MiscUtil.union(a,b,c); - + System.out.println("Union: "+union); - + assertEquals(6,union.size()); assertTrue(union.contains("A1")); assertTrue(union.contains("X")); @@ -59,7 +59,7 @@ public void testUnion() { assertTrue(union.contains("B2")); assertTrue(union.contains("C1")); } - + @Test public void testUglyXsiHack1() { System.out.println("===[ testUglyXsiHack1 ]==="); @@ -83,11 +83,11 @@ public void testUglyXsiHack3() { String out = UglyHacks.forceXsiNsDeclaration(in); assertEquals(in, out); } - + @Test public void testCarthesian() { System.out.println("===[ testCarthesian ]==="); - + // GIVEN Collection> dimensions = new ArrayList>(); Collection dim1 = new ArrayList(); @@ -105,7 +105,7 @@ public void testCarthesian() { dim3.add("y"); dim3.add("z"); dimensions.add(dim3); - + final List combinations = new ArrayList(); Processor> processor = new Processor>() { @Override @@ -114,10 +114,10 @@ public void process(Collection s) { combinations.add(MiscUtil.concat(s)); } }; - + // WHEN MiscUtil.carthesian(dimensions, processor); - + // THEN System.out.println(combinations); assertEquals("Wrong number of results", 24, combinations.size()); diff --git a/infra/util/src/test/java/com/evolveum/midpoint/util/TestReflectionUtil.java b/infra/util/src/test/java/com/evolveum/midpoint/util/TestReflectionUtil.java index 19df32d9351..3842c10cfe0 100644 --- a/infra/util/src/test/java/com/evolveum/midpoint/util/TestReflectionUtil.java +++ b/infra/util/src/test/java/com/evolveum/midpoint/util/TestReflectionUtil.java @@ -34,17 +34,17 @@ public class TestReflectionUtil { public void testFindMethodByArity3() throws Exception { // GIVEN ReflectionTestFunctionLibrary library = new ReflectionTestFunctionLibrary(); - + // WHEN Method method = ReflectionUtil.findMethod(library, "m", 3); - + // THEN assertNotNull("No method", method); method.invoke(library, "foo", 1, 2L); - + assertCalled(library, "m3"); } - + @Test public void testFindMethodByArglist3() throws Exception { // GIVEN @@ -53,17 +53,17 @@ public void testFindMethodByArglist3() throws Exception { argList.add("foo"); argList.add(1); argList.add(2L); - + // WHEN Method method = ReflectionUtil.findMethod(library, "m", argList); - + // THEN assertNotNull("No method", method); method.invoke(library, "foo", 1, 2L); - + assertCalled(library, "m3"); } - + @Test public void testFindMethodByArglist2() throws Exception { // GIVEN @@ -71,17 +71,17 @@ public void testFindMethodByArglist2() throws Exception { List argList = new ArrayList(); argList.add("foo"); argList.add(1); - + // WHEN Method method = ReflectionUtil.findMethod(library, "m", argList); - + // THEN assertNotNull("No method", method); method.invoke(library, "foo", 1); - + assertCalled(library, "m2i"); } - + @Test public void testFindMethodByArglistVararg() throws Exception { // GIVEN @@ -90,14 +90,14 @@ public void testFindMethodByArglistVararg() throws Exception { argList.add("foo"); argList.add("bar"); argList.add("baz"); - + // WHEN Method method = ReflectionUtil.findMethod(library, "v", argList); - + // THEN assertNotNull("No method", method); method.invoke(library, new Object[] { new String[] {"foo", "bar", "baz"}}); - + assertCalled(library, "v:3"); } @@ -109,14 +109,14 @@ public void testInvokeMethodByArglist3() throws Exception { argList.add("foo"); argList.add(1); argList.add(2L); - + // WHEN ReflectionUtil.invokeMethod(library, "m", argList); - - // THEN + + // THEN assertCalled(library, "m3"); } - + @Test public void testInvokeMethodByArglist2() throws Exception { // GIVEN @@ -124,14 +124,14 @@ public void testInvokeMethodByArglist2() throws Exception { List argList = new ArrayList(); argList.add("foo"); argList.add(1); - + // WHEN ReflectionUtil.invokeMethod(library, "m", argList); - - // THEN + + // THEN assertCalled(library, "m2i"); } - + @Test public void testInvokeMethodByArglistVararg() throws Exception { // GIVEN @@ -140,14 +140,14 @@ public void testInvokeMethodByArglistVararg() throws Exception { argList.add("foo"); argList.add("bar"); argList.add("baz"); - + // WHEN ReflectionUtil.invokeMethod(library, "v", argList); - + // THEN assertCalled(library, "v:3"); } - + @Test public void testInvokeMethodByArglistCollection() throws Exception { // GIVEN @@ -156,17 +156,17 @@ public void testInvokeMethodByArglistCollection() throws Exception { List l = new ArrayList(); l.add("foo"); argList.add(l); - + // WHEN ReflectionUtil.invokeMethod(library, "l", argList); - + // THEN assertCalled(library, "lc"); } - + private void assertCalled(ReflectionTestFunctionLibrary library, String methodId) { assertTrue("The method "+methodId+" was not called. Called: "+library.getCalledIds(), library.wasCalled(methodId)); } - + } diff --git a/infra/ws-util/src/main/java/com/evolveum/midpoint/infra/wsutil/AbstractWebServiceClient.java b/infra/ws-util/src/main/java/com/evolveum/midpoint/infra/wsutil/AbstractWebServiceClient.java index 3b995d38222..56726955391 100644 --- a/infra/ws-util/src/main/java/com/evolveum/midpoint/infra/wsutil/AbstractWebServiceClient.java +++ b/infra/ws-util/src/main/java/com/evolveum/midpoint/infra/wsutil/AbstractWebServiceClient.java @@ -39,11 +39,11 @@ * */ public abstract class AbstractWebServiceClient { - + private Options options = new Options(); private CommandLine commandLine; private boolean verbose = false; - + public boolean isVerbose() { return verbose; } @@ -51,13 +51,13 @@ public boolean isVerbose() { public void setVerbose(boolean verbose) { this.verbose = verbose; } - + protected abstract S createService() throws Exception; - + protected abstract Class

    getPortClass(); - + protected abstract String getDefaultUsername(); - + protected String getPasswordType() { if (commandLine.hasOption('P')) { String optionValue = commandLine.getOptionValue('P'); @@ -72,13 +72,13 @@ protected String getPasswordType() { return WSConstants.PW_TEXT; } } - + protected abstract String getDefaultPassword(); - + protected abstract String getDefaultEndpointUrl(); - + protected abstract int invoke(P port); - + public void main(String[] args) { try { init(args); @@ -90,7 +90,7 @@ public void main(String[] args) { System.exit(-1); } } - + protected void init(String[] args) throws ParseException { options.addOption("a", "authentication", true, "Authentication type ("+WSHandlerConstants.USERNAME_TOKEN+", none)"); options.addOption("u", "user", true, "Username"); @@ -129,11 +129,11 @@ protected void extendOptions(Options options) { } protected P createPort() throws Exception { - + String password = getDefaultPassword(); String username = getDefaultUsername(); String endpointUrl = getDefaultEndpointUrl(); - + if (commandLine.hasOption('p')) { password = commandLine.getOptionValue('p'); } @@ -143,7 +143,7 @@ protected P createPort() throws Exception { if (commandLine.hasOption('e')) { endpointUrl = commandLine.getOptionValue('e'); } - + if (verbose) { System.out.println("Username: "+username); System.out.println("Password: "); @@ -152,26 +152,26 @@ protected P createPort() throws Exception { // uncomment this if you want to use Fiddler or any other proxy //ProxySelector.setDefault(new MyProxySelector("127.0.0.1", 8888)); - + P modelPort = createService().getPort(getPortClass()); BindingProvider bp = (BindingProvider)modelPort; Map requestContext = bp.getRequestContext(); requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointUrl); - + org.apache.cxf.endpoint.Client client = ClientProxy.getClient(modelPort); org.apache.cxf.endpoint.Endpoint cxfEndpoint = client.getEndpoint(); - + Map wssProps = new HashMap(); - - if (!commandLine.hasOption('a') || + + if (!commandLine.hasOption('a') || (commandLine.hasOption('a') && WSHandlerConstants.USERNAME_TOKEN.equals(commandLine.getOptionValue('a')))) { - + wssProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN); wssProps.put(WSHandlerConstants.USER, username); wssProps.put(WSHandlerConstants.PASSWORD_TYPE, getPasswordType()); wssProps.put(WSHandlerConstants.PW_CALLBACK_CLASS, ClientPasswordHandler.class.getName()); ClientPasswordHandler.setPassword(password); - + WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(wssProps); cxfEndpoint.getOutInterceptors().add(wssOut); } else if (commandLine.hasOption('a') && "none".equals(commandLine.getOptionValue('a'))) { @@ -179,7 +179,7 @@ protected P createPort() throws Exception { } else { throw new IllegalArgumentException("Unknown authentication mechanism '"+commandLine.getOptionValue('a')+"'"); } - + if (commandLine.hasOption('m')) { cxfEndpoint.getInInterceptors().add(new LoggingInInterceptor()); cxfEndpoint.getOutInterceptors().add(new LoggingOutInterceptor()); @@ -187,7 +187,7 @@ protected P createPort() throws Exception { return modelPort; } - + protected void printHelp() { final String commandLineSyntax = System.getProperty("sun.java.command"); final HelpFormatter helpFormatter = new HelpFormatter(); diff --git a/infra/ws-util/src/main/java/com/evolveum/midpoint/infra/wsutil/ClientPasswordHandler.java b/infra/ws-util/src/main/java/com/evolveum/midpoint/infra/wsutil/ClientPasswordHandler.java index 23c6e7fefc6..e21d7fa1979 100644 --- a/infra/ws-util/src/main/java/com/evolveum/midpoint/infra/wsutil/ClientPasswordHandler.java +++ b/infra/ws-util/src/main/java/com/evolveum/midpoint/infra/wsutil/ClientPasswordHandler.java @@ -28,13 +28,13 @@ * */ public class ClientPasswordHandler implements CallbackHandler { - + private static String password; public static void setPassword(String password) { ClientPasswordHandler.password = password; } - + @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { WSPasswordCallback pc = (WSPasswordCallback) callbacks[0]; diff --git a/infra/ws-util/src/test/java/com/evolveum/midpoint/infra/wsutil/DummyMain.java b/infra/ws-util/src/test/java/com/evolveum/midpoint/infra/wsutil/DummyMain.java index 9630c7ed7f9..d69e12e0a3d 100644 --- a/infra/ws-util/src/test/java/com/evolveum/midpoint/infra/wsutil/DummyMain.java +++ b/infra/ws-util/src/test/java/com/evolveum/midpoint/infra/wsutil/DummyMain.java @@ -17,9 +17,9 @@ /** * Run with: - * + * * mvn exec:java -Dexec.classpathScope=test -Dexec.mainClass="com.evolveum.midpoint.infra.wsutil.DummyMain" -Dexec.args="...." - * + * * @author semancik * */ diff --git a/infra/ws-util/src/test/java/com/evolveum/midpoint/infra/wsutil/DummyPort.java b/infra/ws-util/src/test/java/com/evolveum/midpoint/infra/wsutil/DummyPort.java index 6fd2e31a6e1..0fa13a941c8 100644 --- a/infra/ws-util/src/test/java/com/evolveum/midpoint/infra/wsutil/DummyPort.java +++ b/infra/ws-util/src/test/java/com/evolveum/midpoint/infra/wsutil/DummyPort.java @@ -23,7 +23,7 @@ */ @WebService(targetNamespace = "http://midpoint.evolveum.com/xml/ns/test/dummy-1", name = "dummyPort") public interface DummyPort { - + // Nothing here, really } diff --git a/infra/ws-util/src/test/java/com/evolveum/midpoint/infra/wsutil/DummyService.java b/infra/ws-util/src/test/java/com/evolveum/midpoint/infra/wsutil/DummyService.java index 15ea3363bb7..3d3ae61267f 100644 --- a/infra/ws-util/src/test/java/com/evolveum/midpoint/infra/wsutil/DummyService.java +++ b/infra/ws-util/src/test/java/com/evolveum/midpoint/infra/wsutil/DummyService.java @@ -28,7 +28,7 @@ * */ @WebServiceClient(name = "dumyService", - targetNamespace = "http://midpoint.evolveum.com/xml/ns/test/dummy-1") + targetNamespace = "http://midpoint.evolveum.com/xml/ns/test/dummy-1") public class DummyService extends Service { public final static QName SERVICE = new QName("http://midpoint.evolveum.com/xml/ns/test/dummy-1", "dumyService"); @@ -45,7 +45,7 @@ public DummyService(URL wsdlLocation, QName serviceName) { public DummyService() { super(null, SERVICE); } - + //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2 //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1 //compliant code instead. @@ -78,7 +78,7 @@ public DummyPort getModelPort() { } /** - * + * * @param features * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the features parameter will have their default values. * @return diff --git a/model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/AccessCertificationCampaignCreationTaskHandler.java b/model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/AccessCertificationCampaignCreationTaskHandler.java index 2efaf3b2f93..bd6662f63e8 100644 --- a/model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/AccessCertificationCampaignCreationTaskHandler.java +++ b/model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/AccessCertificationCampaignCreationTaskHandler.java @@ -37,7 +37,7 @@ /** * The task handler for automatic campaign start. - * + * * @author mederly */ @Component @@ -49,7 +49,7 @@ public class AccessCertificationCampaignCreationTaskHandler implements TaskHandl @Autowired private TaskManager taskManager; - + @Autowired private PrismContext prismContext; @@ -62,11 +62,11 @@ public class AccessCertificationCampaignCreationTaskHandler implements TaskHandl private void initialize() { taskManager.registerHandler(HANDLER_URI, this); } - + @Override public TaskRunResult run(Task task) { LOGGER.trace("Task run starting"); - + long progress = task.getProgress(); OperationResult opResult = new OperationResult(CLASS_DOT+"run"); opResult.setSummarizeSuccesses(true); @@ -130,7 +130,7 @@ public Long heartbeat(Task task) { @Override public void refreshStatus(Task task) { - // Do nothing. Everything is fresh already. + // Do nothing. Everything is fresh already. } @Override diff --git a/model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/AccessCertificationCloseStageApproachingTriggerHandler.java b/model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/AccessCertificationCloseStageApproachingTriggerHandler.java index e03135c944f..db0f7c48a15 100644 --- a/model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/AccessCertificationCloseStageApproachingTriggerHandler.java +++ b/model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/AccessCertificationCloseStageApproachingTriggerHandler.java @@ -41,9 +41,9 @@ */ @Component public class AccessCertificationCloseStageApproachingTriggerHandler implements TriggerHandler { - + public static final String HANDLER_URI = AccessCertificationConstants.NS_CERTIFICATION_TRIGGER_PREFIX + "/close-stage-approaching/handler-3"; - + private static final transient Trace LOGGER = TraceManager.getTrace(AccessCertificationCloseStageApproachingTriggerHandler.class); @Autowired private TriggerHandlerRegistry triggerHandlerRegistry; @@ -55,7 +55,7 @@ public class AccessCertificationCloseStageApproachingTriggerHandler implements T private void initialize() { triggerHandlerRegistry.register(HANDLER_URI, this); } - + @Override public void handle(PrismObject prismObject, TriggerType trigger, Task task, OperationResult result) { try { diff --git a/model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/AccessCertificationCloseStageTriggerHandler.java b/model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/AccessCertificationCloseStageTriggerHandler.java index 84b56aa25bf..05c7d042a94 100644 --- a/model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/AccessCertificationCloseStageTriggerHandler.java +++ b/model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/AccessCertificationCloseStageTriggerHandler.java @@ -46,22 +46,22 @@ */ @Component public class AccessCertificationCloseStageTriggerHandler implements TriggerHandler { - + public static final String HANDLER_URI = AccessCertificationConstants.NS_CERTIFICATION_TRIGGER_PREFIX + "/close-stage/handler-3"; - + private static final transient Trace LOGGER = TraceManager.getTrace(AccessCertificationCloseStageTriggerHandler.class); @Autowired private TriggerHandlerRegistry triggerHandlerRegistry; - + @Autowired private CertificationManager certificationManager; - + @PostConstruct private void initialize() { triggerHandlerRegistry.register(HANDLER_URI, this); } - + @Override public void handle(PrismObject prismObject, TriggerType trigger, Task task, OperationResult result) { try { diff --git a/model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/AccessCertificationRemediationTaskHandler.java b/model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/AccessCertificationRemediationTaskHandler.java index 2ae59dce032..b30b64d90d5 100644 --- a/model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/AccessCertificationRemediationTaskHandler.java +++ b/model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/AccessCertificationRemediationTaskHandler.java @@ -47,7 +47,7 @@ /** * The task hander for automatic remediation. - * + * * @author mederly */ @Component @@ -70,11 +70,11 @@ public class AccessCertificationRemediationTaskHandler implements TaskHandler { private void initialize() { taskManager.registerHandler(HANDLER_URI, this); } - + @Override public TaskRunResult run(Task task) { LOGGER.trace("Task run starting"); - + long progress = task.getProgress(); OperationResult opResult = new OperationResult(CLASS_DOT+"run"); opResult.setSummarizeSuccesses(true); @@ -157,7 +157,7 @@ public Long heartbeat(Task task) { @Override public void refreshStatus(Task task) { - // Do nothing. Everything is fresh already. + // Do nothing. Everything is fresh already. } @Override diff --git a/model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/CertificationHook.java b/model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/CertificationHook.java index 59d0d09904e..ef492257b74 100644 --- a/model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/CertificationHook.java +++ b/model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/CertificationHook.java @@ -48,16 +48,16 @@ /** * Starts ad-hoc certifications as prescribed by "certificate" policy action. - * + * * @author mederly */ @Component public class CertificationHook implements ChangeHook { - + private static final Trace LOGGER = TraceManager.getTrace(CertificationHook.class); - + private static final String HOOK_URI = SchemaConstants.NS_MODEL + "/certification-hook-3"; - + @Autowired private HookRegistry hookRegistry; @Autowired private CertificationManagerImpl certificationManager; @Autowired private AccCertUpdateHelper updateHelper; @@ -92,7 +92,7 @@ public HookOperationMode invoke(@NotNull ModelContext private Collection getFocusCertificationActions(ModelContext context) { return getCertificationActions(context.getFocusContext().getPolicyRules()); } - + private Collection getAssignmentCertificationActions(ModelContext context) { DeltaSetTriple> evaluatedAssignmentTriple = context.getEvaluatedAssignmentTriple(); if (evaluatedAssignmentTriple == null) { diff --git a/model/certification-impl/src/test/java/com/evolveum/midpoint/certification/test/AbstractCertificationTest.java b/model/certification-impl/src/test/java/com/evolveum/midpoint/certification/test/AbstractCertificationTest.java index 00d953e174e..5a53d7849a5 100644 --- a/model/certification-impl/src/test/java/com/evolveum/midpoint/certification/test/AbstractCertificationTest.java +++ b/model/certification-impl/src/test/java/com/evolveum/midpoint/certification/test/AbstractCertificationTest.java @@ -62,10 +62,10 @@ public class AbstractCertificationTest extends AbstractModelIntegrationTest { @Autowired private AccCertResponseComputationHelper computationHelper; - + 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 ORGS_AND_USERS_FILE = new File(COMMON_DIR, "orgs-and-users.xml"); protected static final File USER_BOB_FILE = new File(COMMON_DIR, "user-bob.xml"); protected static final File USER_BOB_DEPUTY_FULL_FILE = new File(COMMON_DIR, "user-bob-deputy-full.xml"); @@ -178,7 +178,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti super.initSystem(initTask, initResult); modelService.postInit(initResult); - + // System Configuration try { repoAddObjectFromFile(SYSTEM_CONFIGURATION_FILE, initResult); diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/AuthenticationEvaluator.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/AuthenticationEvaluator.java index 864504f3507..38b9cd390c9 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/AuthenticationEvaluator.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/AuthenticationEvaluator.java @@ -35,15 +35,15 @@ * */ public interface AuthenticationEvaluator { - - UsernamePasswordAuthenticationToken authenticate(ConnectionEnvironment connEnv, T authnCtx) - throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException, + + UsernamePasswordAuthenticationToken authenticate(ConnectionEnvironment connEnv, T authnCtx) + throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException, CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException; - - UserType checkCredentials(ConnectionEnvironment connEnv, T authnCtx) - throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException, + + UserType checkCredentials(ConnectionEnvironment connEnv, T authnCtx) + throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException, CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException; - + PreAuthenticatedAuthenticationToken authenticateUserPreAuthenticated(ConnectionEnvironment connEnv, String enteredUsername); } diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelAuditService.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelAuditService.java index b1c6f91de88..725313df498 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelAuditService.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelAuditService.java @@ -34,10 +34,10 @@ * */ public interface ModelAuditService { - - PrismObject reconstructObject(Class type, String oid, String eventIdentifier, + + PrismObject reconstructObject(Class type, String oid, String eventIdentifier, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException; - + void audit(AuditEventRecord record, Task task, OperationResult result) throws SecurityViolationException, SchemaException; @@ -54,13 +54,13 @@ void cleanupAudit(CleanupPolicyType policy, OperationResult parentResult) */ List listRecords(String query, Map params, OperationResult parentResult) throws SecurityViolationException, SchemaException; - + /** * @throws UnsupportedOperationException if object retrieval is not supported */ long countObjects(String query, Map params, OperationResult parentResult) throws SecurityViolationException, SchemaException; - + /** * Returns true if retrieval of objects from the audit trail is supported. * This applies to listRecords, countObjects, reconstructObject and similar diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelAuthorizationAction.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelAuthorizationAction.java index 386188d06d9..1fca0595d57 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelAuthorizationAction.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelAuthorizationAction.java @@ -28,21 +28,21 @@ public enum ModelAuthorizationAction implements DisplayableValue { DELETE("delete", "Delete", "DELETE_HELP"), RECOMPUTE("recompute", "Recompute", "RECOMPUTE_HELP"), TEST("test", "Test resource", "TEST_RESOURCE_HELP"), - + /** * Import objects from file or a stream. This means importing any type of * object (e.g. user, configuration, resource, object templates, ... */ IMPORT_OBJECTS("importObjects", "Import Objects", "IMPORT_OBJECTS_HELP"), - + /** * Import resource objects from resource. This means import of accounts, entitlements * or other objects from a resource. The import creates shadows. */ IMPORT_FROM_RESOURCE("importFromResource", "Import from Resource", "IMPORT_FROM_RESOURCE_HELP"), - - DISCOVER_CONNECTORS("discoverConnectors", "Discover Connectors", "DISCOVER_CONNECTORS_HELP"), - + + DISCOVER_CONNECTORS("discoverConnectors", "Discover Connectors", "DISCOVER_CONNECTORS_HELP"), + ASSIGN("assign", "Assign", "ASSIGN_HELP"), UNASSIGN("unassign", "Unassign", "UNASSIGN_HELP"), DELEGATE("delegate", "Delegate", "DELEGATE_HELP"), @@ -81,34 +81,34 @@ public enum ModelAuthorizationAction implements DisplayableValue { // Ability to manage the audit log, e.g. to clean it up (exprunge old records). AUDIT_MANAGE("auditManage", "Audit Manage", "AUDIT_MANAGE_HELP") ; - + private String url; private String label; private String description; - + private ModelAuthorizationAction(String urlLocalPart, String label, String desc) { this.url = QNameUtil.qNameToUri(new QName(ModelService.AUTZ_NAMESPACE, urlLocalPart)); this.label = label; this.description = desc; } - + public String getUrl() { return url; } - + @Override public String getValue() { return url; } - + @Override public String getLabel() { return label; } - + @Override public String getDescription() { return description; } - + } diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelCompareOptions.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelCompareOptions.java index 633b7443527..675457c9094 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelCompareOptions.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelCompareOptions.java @@ -29,7 +29,7 @@ * */ public class ModelCompareOptions implements Serializable, Cloneable { - + /** * Computes current-to-provided delta. ("Current" means the object that is currently available in the midPoint.) */ @@ -137,12 +137,12 @@ public static ModelCompareOptions fromModelCompareOptionsType(ModelCompareOption retval.setIgnoreOperationalItems(type.isIgnoreOperationalItems()); return retval; } - + public static ModelCompareOptions fromRestOptions(List options){ if (options == null || options.isEmpty()){ return null; } - + ModelCompareOptions rv = new ModelCompareOptions(); for (String option : options){ if (ModelCompareOptionsType.F_COMPUTE_CURRENT_TO_PROVIDED.getLocalPart().equals(option)){ @@ -178,7 +178,7 @@ public String toString() { sb.append(")"); return sb.toString(); } - + private void appendFlag(StringBuilder sb, String name, Boolean val) { if (val == null) { return; @@ -190,7 +190,7 @@ private void appendFlag(StringBuilder sb, String name, Boolean val) { sb.append("=false,"); } } - + public ModelCompareOptions clone() { // not much efficient, but... ModelCompareOptions clone = fromModelCompareOptionsType(toModelCompareOptionsType()); diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelDiagnosticService.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelDiagnosticService.java index 1147e12f5f0..3b62ba24076 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelDiagnosticService.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelDiagnosticService.java @@ -33,16 +33,16 @@ /** * A service provided by the IDM Model focused on system diagnostic. It allows to retrieve diagnostic data * that are not exactly part of system configuration (such as repository configuration). It can also be used - * to initiate self-tests and similar diagnostic routines. - * + * to initiate self-tests and similar diagnostic routines. + * * UNSTABLE: This is likely to change * PRIVATE: This interface is not supposed to be used outside of midPoint - * + * * @author Radovan Semancik * */ public interface ModelDiagnosticService { - + String CLASS_NAME_WITH_DOT = ModelDiagnosticService.class.getName() + "."; String REPOSITORY_SELF_TEST = CLASS_NAME_WITH_DOT + "repositorySelfTest"; String REPOSITORY_TEST_ORG_CLOSURE_CONSISTENCY = CLASS_NAME_WITH_DOT + "repositoryTestOrgClosureConsistency"; @@ -51,12 +51,12 @@ public interface ModelDiagnosticService { String PROVISIONING_SELF_TEST = CLASS_NAME_WITH_DOT + "provisioningSelfTest"; String GET_LOG_FILE_CONTENT = CLASS_NAME_WITH_DOT + "getLogFileContent"; String GET_LOG_FILE_SIZE = CLASS_NAME_WITH_DOT + "getLogFileSize"; - + /** * Provide repository run-time configuration and diagnostic information. */ RepositoryDiag getRepositoryDiag(Task task, OperationResult parentResult); - + /** * Runs a short, non-destructive repository self test. * This methods should never throw a (checked) exception. All the results diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelExecuteOptions.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelExecuteOptions.java index d43662380a4..07c46f4990a 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelExecuteOptions.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelExecuteOptions.java @@ -28,24 +28,24 @@ /** * Options for execution of Model operations. These options influence the way how the operations are executed. * The options are not mandatory. All options have reasonable default values. They may not be specified at all. - * + * * @author semancik */ public class ModelExecuteOptions extends AbstractOptions implements Serializable, Cloneable { - + /** * Force the operation even if it would otherwise fail due to external failure. E.g. attempt to delete an account * that no longer exists on resource may fail without a FORCE option. If FORCE option is used then the operation is * finished even if the account does not exist (e.g. at least shadow is removed from midPoint repository). */ private Boolean force; - + /** * Avoid any smart processing of the data except for schema application. Do not synchronize the data, do not apply * any expressions, etc. */ private Boolean raw; - + /** * Encrypt any cleartext data on write, decrypt any encrypted data on read. Applies only to the encrypted * data formats (ProtectedString, ProtectedByteArray). @@ -53,13 +53,13 @@ public class ModelExecuteOptions extends AbstractOptions implements Serializable * purposes to be used in development environments. */ private Boolean noCrypt; - + /** * Option to reconcile focus and all projections while executing changes. * (implies reconcileFocus) */ private Boolean reconcile; - + /** * Option to reconcile focus while executing changes. * If this option is set and the reconcile option is not set then the projections @@ -92,7 +92,7 @@ public class ModelExecuteOptions extends AbstractOptions implements Serializable * Option to user overwrite flag. It can be used from web service, if we want to re-import some object */ private Boolean overwrite; - + /** * Option to simulate import operation. E.g. search filters will be resolved. */ @@ -102,7 +102,7 @@ public class ModelExecuteOptions extends AbstractOptions implements Serializable * Causes reevaluation of search filters (producing partial errors on failure). */ private Boolean reevaluateSearchFilters; - + /** * Option to limit propagation only for the source resource */ @@ -113,12 +113,12 @@ public class ModelExecuteOptions extends AbstractOptions implements Serializable * EXPERIMENTAL. Currently supported only for raw executions. */ private Boolean preAuthorized; - + /** * Business context that describes this request. */ private OperationBusinessContextType requestBusinessContext; - + /** * Options that control selective execution of model logic. * Use with extreme care. Some combinations may be dangerous. @@ -142,7 +142,7 @@ public Boolean getForce() { public void setForce(Boolean force) { this.force = force; } - + public static boolean isForce(ModelExecuteOptions options) { if (options == null) { return false; @@ -152,7 +152,7 @@ public static boolean isForce(ModelExecuteOptions options) { } return options.force; } - + public static ModelExecuteOptions createForce() { ModelExecuteOptions opts = new ModelExecuteOptions(); opts.setForce(true); @@ -171,7 +171,7 @@ public Boolean getRaw() { public void setRaw(Boolean raw) { this.raw = raw; } - + public static boolean isRaw(ModelExecuteOptions options) { if (options == null) { return false; @@ -181,7 +181,7 @@ public static boolean isRaw(ModelExecuteOptions options) { } return options.raw; } - + public static ModelExecuteOptions createRaw() { ModelExecuteOptions opts = new ModelExecuteOptions(); opts.setRaw(true); @@ -200,7 +200,7 @@ public Boolean getNoCrypt() { public void setNoCrypt(Boolean noCrypt) { this.noCrypt = noCrypt; } - + public static boolean isNoCrypt(ModelExecuteOptions options) { if (options == null) { return false; @@ -225,11 +225,11 @@ public ModelExecuteOptions setNoCrypt() { public Boolean getReconcile() { return reconcile; } - + public void setReconcile(Boolean reconcile) { this.reconcile = reconcile; } - + public static boolean isReconcile(ModelExecuteOptions options) { if (options == null){ return false; @@ -239,7 +239,7 @@ public static boolean isReconcile(ModelExecuteOptions options) { } return options.reconcile; } - + public static ModelExecuteOptions createReconcile() { ModelExecuteOptions opts = new ModelExecuteOptions(); opts.setReconcile(true); @@ -256,7 +256,7 @@ public ModelExecuteOptions setReconcile() { setReconcile(true); return this; } - + public Boolean getReconcileFocus() { return reconcileFocus; } @@ -270,7 +270,7 @@ public static ModelExecuteOptions createReconcileFocus() { opts.setReconcileFocus(true); return opts; } - + public static boolean isReconcileFocus(ModelExecuteOptions options) { if (options == null){ return false; @@ -313,11 +313,11 @@ public ModelExecuteOptions setReconcileAffected() { public Boolean getOverwrite() { return overwrite; } - + public void setOverwrite(Boolean overwrite) { this.overwrite = overwrite; } - + public static boolean isOverwrite(ModelExecuteOptions options){ if (options == null){ return false; @@ -327,7 +327,7 @@ public static boolean isOverwrite(ModelExecuteOptions options){ } return options.overwrite; } - + public static ModelExecuteOptions createOverwrite(){ ModelExecuteOptions opts = new ModelExecuteOptions(); opts.setOverwrite(true); @@ -342,11 +342,11 @@ public ModelExecuteOptions setOverwrite() { public Boolean getIsImport() { return isImport; } - + public void setIsImport(Boolean isImport) { this.isImport = isImport; } - + public static boolean isIsImport(ModelExecuteOptions options){ if (options == null){ return false; @@ -356,7 +356,7 @@ public static boolean isIsImport(ModelExecuteOptions options){ } return options.isImport; } - + public static ModelExecuteOptions createIsImport(){ ModelExecuteOptions opts = new ModelExecuteOptions(); opts.setIsImport(true); @@ -367,7 +367,7 @@ public ModelExecuteOptions setIsImport(){ setIsImport(true); return this; } - + public void setExecuteImmediatelyAfterApproval(Boolean executeImmediatelyAfterApproval) { this.executeImmediatelyAfterApproval = executeImmediatelyAfterApproval; } @@ -391,7 +391,7 @@ public static ModelExecuteOptions createExecuteImmediatelyAfterApproval(){ public void setLimitPropagation(Boolean limitPropagation) { this.limitPropagation = limitPropagation; } - + public static boolean isLimitPropagation(ModelExecuteOptions options){ if (options == null){ return false; @@ -479,14 +479,14 @@ public OperationBusinessContextType getRequestBusinessContext() { public void setRequestBusinessContext(OperationBusinessContextType requestBusinessContext) { this.requestBusinessContext = requestBusinessContext; } - + public static OperationBusinessContextType getRequestBusinessContext(ModelExecuteOptions options) { if (options == null) { return null; } return options.getRequestBusinessContext(); } - + public static ModelExecuteOptions createRequestBusinessContext(OperationBusinessContextType requestBusinessContext) { ModelExecuteOptions opts = new ModelExecuteOptions(); opts.setRequestBusinessContext(requestBusinessContext); @@ -500,14 +500,14 @@ public PartialProcessingOptionsType getPartialProcessing() { public void setPartialProcessing(PartialProcessingOptionsType partialProcessing) { this.partialProcessing = partialProcessing; } - + public static PartialProcessingOptionsType getPartialProcessing(ModelExecuteOptions options) { if (options == null) { return null; } return options.getPartialProcessing(); } - + public static ModelExecuteOptions createPartialProcessing(PartialProcessingOptionsType partialProcessing) { ModelExecuteOptions opts = new ModelExecuteOptions(); opts.setPartialProcessing(partialProcessing); @@ -574,12 +574,12 @@ public static ModelExecuteOptions fromModelExecutionOptionsType(ModelExecuteOpti retval.setPartialProcessing(type.getPartialProcessing()); return retval; } - + public static ModelExecuteOptions fromRestOptions(List options){ if (options == null || options.isEmpty()){ return null; } - + ModelExecuteOptions retVal = new ModelExecuteOptions(); for (String option : options){ if (ModelExecuteOptionsType.F_RAW.getLocalPart().equals(option)){ @@ -611,10 +611,10 @@ public static ModelExecuteOptions fromRestOptions(List options){ } // preAuthorized is purposefully omitted (security reasons) } - + return retVal; } - + @Override public String toString() { StringBuilder sb = new StringBuilder("ModelExecuteOptions("); diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelInteractionService.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelInteractionService.java index 157b3035141..55dcd5de436 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelInteractionService.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelInteractionService.java @@ -43,16 +43,16 @@ * A service provided by the IDM Model that allows to improve the (user) interaction with the model. * It is supposed to provide services such as preview of changes, diagnostics and other informational * services. It should only provide access to read-only data or provide a temporary (throw-away) previews - * of data. It should not change the state of IDM repository, resources or tasks. - * + * of data. It should not change the state of IDM repository, resources or tasks. + * * UNSTABLE: This is likely to change * PRIVATE: This interface is not supposed to be used outside of midPoint - * + * * @author Radovan Semancik * */ public interface ModelInteractionService { - + String CLASS_NAME_WITH_DOT = ModelInteractionService.class.getName() + "."; String PREVIEW_CHANGES = CLASS_NAME_WITH_DOT + "previewChanges"; String GET_EDIT_OBJECT_DEFINITION = CLASS_NAME_WITH_DOT + "getEditObjectDefinition"; @@ -74,16 +74,16 @@ public interface ModelInteractionService { * add of a user or change of a shadow. The resulting context will sort that out to "focus" and "projection" as needed. * The supplied delta will be used as a primary change. The resulting context will reflect both this primary change and * any resulting secondary changes. - * - * The changes are only computed, NOT EXECUTED. It also does not change any state of any repository object or task. Therefore + * + * The changes are only computed, NOT EXECUTED. It also does not change any state of any repository object or task. Therefore * this method is safe to use anytime. However it is reading the data from the repository and possibly also from the resources * therefore there is still potential for communication (and other) errors and invocation of this method may not be cheap. * However, as no operations are really executed there may be issues with resource dependencies. E.g. identifier that are generated * by the resource are not taken into account while recomputing the values. This may also cause errors if some expressions depend - * on the generated values. + * on the generated values. */ ModelContext previewChanges( - Collection> deltas, ModelExecuteOptions options, Task task, OperationResult result) + Collection> deltas, ModelExecuteOptions options, Task task, OperationResult result) throws SchemaException, PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException, ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException; ModelContext previewChanges( @@ -112,15 +112,15 @@ ModelContext previewChanges( * e.g. to hide non-accessible fields from the form. The actual enforcement of the security is executed regardless of this * method. *

    - * + * * @param object object to edit * @return schema with correctly set constraint parts or null - * @throws SchemaException + * @throws SchemaException */ PrismObjectDefinition getEditObjectDefinition(PrismObject object, AuthorizationPhaseType phase, Task task, OperationResult result) throws SchemaException, ConfigurationException, ObjectNotFoundException; PrismObjectDefinition getEditShadowDefinition(ResourceShadowDiscriminator discr, AuthorizationPhaseType phase, Task task, OperationResult result) throws SchemaException, ConfigurationException, ObjectNotFoundException; - + RefinedObjectClassDefinition getEditObjectClassDefinition(PrismObject shadow, PrismObject resource, AuthorizationPhaseType phase) throws SchemaException; /** @@ -132,54 +132,54 @@ ModelContext previewChanges( * Note: this method returns only the list of authorization actions that are known to the IDM Model component and the components * below. It does not return a GUI-specific authorization actions. *

    - * + * * @return */ Collection> getActionUrls(); - + /** * Returns an object that defines which roles can be assigned by the currently logged-in user. - * + * * @param focus Object of the operation. The object (usually user) to whom the roles should be assigned. */ RoleSelectionSpecification getAssignableRoleSpecification(PrismObject focus, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ConfigurationException; /** * TODO - * + * * @param includeSpecial include special authorizations, such as "self". If set to false those authorizations * will be ignored. This is a good way to avoid interference of "self" when checking for * authorizations such as ability to display role members. */ boolean canSearch(Class resultType, Class objectType, String objectOid, boolean includeSpecial, ObjectQuery query, Task task, OperationResult result) throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException ; - + /** * Returns decisions for individual items for "assign" authorization. This is usually applicable to assignment parameters. * The decisions are evaluated using the security context of a currently logged-in user. - * + * * @param object object of the operation (user) * @param target target of the operation (role, org, service that is being assigned) */ ItemSecurityDecisions getAllowedRequestAssignmentItems(PrismObject object, PrismObject target) throws SchemaException, SecurityViolationException; - + SecurityPolicyType getSecurityPolicy(PrismObject user, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException; - + /** * Returns an authentications policies as defined in the system configuration security policy. This method is designed to be used - * during registration process or reset password process. + * during registration process or reset password process. * security questions, etc). - * - * + * + * * @param task *@param parentResult @return applicable credentials policy or null * @throws ObjectNotFoundException No system configuration or other major system inconsistency * @throws SchemaException Wrong schema or content of security policy */ AuthenticationsPolicyType getAuthenticationPolicy(PrismObject user, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException; - + /** * Returns a policy for registration, e.g. type of the supported registrations (self, social,...) - * + * * @param user user for who the policy should apply * @param task *@param parentResult @return applicable credentials policy or null @@ -187,12 +187,12 @@ ModelContext previewChanges( * @throws SchemaException Wrong schema or content of security policy */ RegistrationsPolicyType getRegistrationPolicy(PrismObject user, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException; - + /** * Returns a credential policy that applies to the specified user. This method is designed to be used * during credential reset so the GUI has enough information to set up the credential (e.g. password policies, * security questions, etc). - * + * * @param user user for who the policy should apply * @param task *@param parentResult @return applicable credentials policy or null @@ -200,7 +200,7 @@ ModelContext previewChanges( * @throws SchemaException Wrong schema or content of security policy */ CredentialsPolicyType getCredentialsPolicy(PrismObject user, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException; - + /** * Returns currently applicable admin GUI configuration. The implementation will do all steps necessary to construct * applicable configuration, e.g. reading from system configuration, merging with user preferences, etc. @@ -216,41 +216,41 @@ ModelContext previewChanges( AccessCertificationConfigurationType getCertificationConfiguration(OperationResult parentResult) throws ObjectNotFoundException, SchemaException; - + /** * Checks if the supplied password matches with current user password. This method is NOT subject to any * password expiration policies, it does not update failed login counters, it does not change any data or meta-data. - * This method is NOT SUPPOSED to be used to validate password on login. This method is supposed to check + * This method is NOT SUPPOSED to be used to validate password on login. This method is supposed to check * old password when the password is changed by the user. We assume that the user already passed normal * system authentication. - * + * * Note: no authorizations are checked in the implementation. It is assumed that authorizations will be * enforced at the page level. - * + * * @return true if the password matches, false otherwise */ boolean checkPassword(String userOid, ProtectedStringType password, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException; - + // TEMPORARY List visualizeDeltas(List> deltas, Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException; @NotNull Scene visualizeDelta(ObjectDelta delta, Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException; - + List getConnectorOperationalStatus(String resourceOid, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException; - - MergeDeltas mergeObjectsPreviewDeltas(Class type, - String leftOid, String rightOid, String mergeConfigurationName, Task task, OperationResult result) + + MergeDeltas mergeObjectsPreviewDeltas(Class type, + String leftOid, String rightOid, String mergeConfigurationName, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ConfigurationException, ExpressionEvaluationException, CommunicationException, SecurityViolationException ; - - PrismObject mergeObjectsPreviewObject(Class type, + + PrismObject mergeObjectsPreviewObject(Class type, String leftOid, String rightOid, String mergeConfigurationName, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ConfigurationException, ExpressionEvaluationException, CommunicationException, SecurityViolationException ; /** * TEMPORARY. Need to find out better way how to deal with generated values - * + * * @param policy * @param defaultLength * @param generateMinimalSize diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelPort.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelPort.java index 4a7ce60050c..df59aa7be80 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelPort.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelPort.java @@ -21,9 +21,9 @@ import javax.xml.namespace.QName; /** - * + * * @author lazyman - * + * */ public interface ModelPort { 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 f8371c9cbeb..2c07f6aabbe 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 @@ -24,7 +24,7 @@ * @author mederly */ public class ModelPublicConstants { - + public static final String NS_SYNCHRONIZATION_PREFIX = SchemaConstants.NS_MODEL +"/synchronization"; public static final String NS_SYNCHRONIZATION_TASK_PREFIX = NS_SYNCHRONIZATION_PREFIX + "/task"; diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelService.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelService.java index 4ee90152c25..fb7ee268d9c 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelService.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelService.java @@ -79,10 +79,10 @@ * attributes for objects. E.g. RBAC models may automatically derive resource * accounts attributes based on user role membership. *

    - * + * * @author lazyman * @author Radovan Semancik - * + * */ public interface ModelService { @@ -111,7 +111,7 @@ public interface ModelService { static final String MERGE_OBJECTS = CLASS_NAME_WITH_DOT + "mergeObjects"; static final String AUTZ_NAMESPACE = AuthorizationConstants.NS_AUTHORIZATION_MODEL; - + /** *

    * Returns object for provided OID. It retrieves the object from an appropriate source @@ -121,7 +121,7 @@ public interface ModelService { *

    * Fails if object with the OID does not exists. *

    - * + * * @param type * (class) of an object to get * @param oid @@ -135,7 +135,7 @@ public interface ModelService { * @return Retrieved object * @throws ObjectNotFoundException * requested object does not exist - * @throws SchemaException + * @throws SchemaException * the object is not schema compliant * @throw SecurityViolationException * Security violation during operation execution. May be caused either by midPoint internal @@ -154,7 +154,7 @@ public interface ModelService { * state */ PrismObject getObject(Class type, String oid, Collection> options, - Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, SecurityViolationException, + Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException; /** @@ -167,7 +167,7 @@ PrismObject getObject(Class type, String oid, Colle * also implicitly links the objects (mark them to be analogous) if such a link is part of the data model. * E.g. the implementation links all accounts to the user if they are passed in a single delta collection. * This is especially useful if the account deltas are ADD deltas without OID and therefore cannot be linked - * explicitly. + * explicitly. *

    *

    * There must be no more than one delta for each object. @@ -197,7 +197,7 @@ PrismObject getObject(Class type, String oid, Colle * The operation may fail if any of the objects to be created or modified does not conform to * the underlying schema of the storage system or the schema enforced by the implementation. *

    - * + * * @param deltas * Collection of object deltas to execute * @param options @@ -216,7 +216,7 @@ PrismObject getObject(Class type, String oid, Colle * @throws SchemaException * error dealing with resource schema, e.g. created object does * not conform to schema - * @throws ExpressionEvaluationException + * @throws ExpressionEvaluationException * evaluation of expression associated with the object has failed * @throws CommunicationException * Communication (network) error during retrieval. E.g. error communicating with the resource @@ -233,7 +233,7 @@ PrismObject getObject(Class type, String oid, Colle * unknown error from underlying layers or other unexpected state */ Collection> executeChanges(Collection> deltas, ModelExecuteOptions options, Task task, OperationResult parentResult) - throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, + throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException; Collection> executeChanges(Collection> deltas, ModelExecuteOptions options, Task task, Collection listeners, OperationResult parentResult) @@ -250,7 +250,7 @@ Collection> executeChanges(Collection * instead of this one. This method will assume the reconcile option to keep compatible behavior with * previous versions. *

    - * + * * @param type type (class) of an object to recompute * @param oid OID of the object to recompute * @param parentResult @@ -262,13 +262,13 @@ Collection> executeChanges(Collection @Deprecated void recompute(Class type, String oid, Task task, OperationResult parentResult) throws SchemaException, PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException, ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException; - + /** * Recomputes focal object with the specified OID. The operation considers all the applicable policies and * mapping and tries to re-apply them as necessary. - * + * * @since 3.6 - * + * * @param type type (class) of an object to recompute * @param oid OID of the object to recompute * @param options execute options @@ -280,7 +280,7 @@ void recompute(Class type, String oid, Task task, Oper */ void recompute(Class type, String oid, ModelExecuteOptions options, Task task, OperationResult parentResult) throws SchemaException, PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException, ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException; - + /** *

    * Returns the User object representing owner of specified account (account @@ -294,7 +294,7 @@ void recompute(Class type, String oid, ModelExecuteOpt * user. Forward association is implemented by property "account" of user * object. *

    - * + * * @param shadowOid * OID of the account to look for an owner * @param task @@ -314,7 +314,7 @@ void recompute(Class type, String oid, ModelExecuteOpt PrismObject findShadowOwner(String shadowOid, Task task, OperationResult parentResult) throws ObjectNotFoundException, SecurityViolationException, SchemaException, ConfigurationException; - + /** *

    * Returns the Focus object representing owner of specified shadow. @@ -327,7 +327,7 @@ PrismObject findShadowOwner(String shadowOid, Task task, OperationResu * user. Forward association is implemented by property "account" of user * object. *

    - * + * * @param shadowOid * OID of the shadow to look for an owner * @param task @@ -379,7 +379,7 @@ PrismObject searchShadowOwner(String shadowOid, Collection< * reference resolution or any other "smart" algorithm. *

    *

    - * + * * @param resourceOid * OID of the resource to fetch objects from * @param objectClass @@ -398,7 +398,7 @@ PrismObject searchShadowOwner(String shadowOid, Collection< */ @Deprecated List> listResourceObjects(String resourceOid, QName objectClass, ObjectPaging paging, - Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, + Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException; /** @@ -407,7 +407,7 @@ List> listResourceObjects(String resourceOid, *

    *

    * Searches through all object of a specified type. Returns a list of objects that match - * search criteria. + * search criteria. *

    *

    * Note that this method has a very limited scaling capability @@ -421,7 +421,7 @@ List> listResourceObjects(String resourceOid, * that type. Fails if object type is wrong. Should fail if unknown property is * specified in the query. *

    - * + * * @param type * (class) of an object to search * @param query @@ -434,12 +434,12 @@ List> listResourceObjects(String resourceOid, * parent OperationResult (in/out) * @return all objects of specified type that match search criteria (subject * to paging) - * + * * @throws SchemaException * unknown property used in search query * @throws ObjectNotFoundException * object required for a search was not found (e.g. resource definition) - * @throws CommunicationException + * @throws CommunicationException * Communication (network) error during retrieval. E.g. error communicating with the resource * @throw SecurityViolationException * Security violation during operation execution. May be caused either by midPoint internal @@ -486,7 +486,7 @@ Integer countContainers(Class type, ObjectQuery que * that type. Fails if object type is wrong. Should fail if unknown property is * specified in the query. *

    - * + * * @param type * (class) of an object to search * @param query @@ -503,7 +503,7 @@ Integer countContainers(Class type, ObjectQuery que * unknown property used in search query * @throws ObjectNotFoundException * object required for a search was not found (e.g. resource definition) - * @throws CommunicationException + * @throws CommunicationException * Communication (network) error during retrieval. E.g. error communicating with the resource * @throw SecurityViolationException * Security violation during operation execution. May be caused either by midPoint internal @@ -514,7 +514,7 @@ Integer countContainers(Class type, ObjectQuery que * wrong query format */ SearchResultMetadata searchObjectsIterative(Class type, ObjectQuery query, - ResultHandler handler, Collection> options, Task task, OperationResult parentResult) + ResultHandler handler, Collection> options, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException; /** @@ -524,9 +524,9 @@ SearchResultMetadata searchObjectsIterative(Class type *

    * Searches through all object of a specified type and returns a count of such objects. * This method is usually much more efficient than equivalent search method. It is used mostly for - * presentation purposes, e.g. displaying correct number of pages in the GUI listings. + * presentation purposes, e.g. displaying correct number of pages in the GUI listings. *

    - * + * * @param type * (class) of an object to search * @param query @@ -539,12 +539,12 @@ SearchResultMetadata searchObjectsIterative(Class type * parent OperationResult (in/out) * @return number of objects of specified type that match search criteria (subject * to paging). May return null if the number of objects is not known. - * + * * @throws SchemaException * unknown property used in search query * @throws ObjectNotFoundException * object required for a search was not found (e.g. resource definition) - * @throws CommunicationException + * @throws CommunicationException * Communication (network) error during retrieval. E.g. error communicating with the resource * @throw SecurityViolationException * Security violation during operation execution. May be caused either by midPoint internal @@ -555,7 +555,7 @@ SearchResultMetadata searchObjectsIterative(Class type * wrong query format */ Integer countObjects(Class type, ObjectQuery query, Collection> options, - Task task, OperationResult parentResult) + Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, SecurityViolationException, ConfigurationException, CommunicationException, ExpressionEvaluationException; /** @@ -575,7 +575,7 @@ Integer countObjects(Class type, ObjectQuery query, Co * using OperationResult to track its own execution but rather to track the * execution of resource tests (that in fact happen in provisioning). *

    - * + * * @param resourceOid * OID of resource to test * @return results of executed tests @@ -596,22 +596,22 @@ Integer countObjects(Class type, ObjectQuery query, Co * TODO: Better description */ void importFromResource(String resourceOid, QName objectClass, Task task, OperationResult parentResult) - throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException; - + throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException; + /** *

    * Import single account from resource. *

    - * TODO: Better description + * TODO: Better description */ void importFromResource(String shadowOid, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException; /** * Import objects from file. - * + * * Invocation of this method may be switched to background. - * + * * @param input * @param task */ @@ -619,12 +619,12 @@ void importFromResource(String shadowOid, Task task, OperationResult parentResul /** * Import objects from stream. - * + * * Invocation of this method will happen in foreground, as the stream cannot * be serialized. - * + * * The results will be provided in the task. - * + * * @param input * @param task */ @@ -646,14 +646,14 @@ void importFromResource(String shadowOid, Task task, OperationResult parentResul /** * Discovers local or remote connectors. - * + * * The operation will try to search for new connectors. It works either on * local host (hostType is null) or on a remote host (hostType is not null). * All discovered connectors are stored in the repository. - * + * * It returns connectors that were discovered: those that were not in the * repository before invocation of this operation. - * + * * @param hostType * definition of a connector host or null * @param parentResult @@ -661,13 +661,13 @@ void importFromResource(String shadowOid, Task task, OperationResult parentResul * @return discovered connectors * @throws CommunicationException error communicating with the connector host */ - public Set discoverConnectors(ConnectorHostType hostType, Task task, OperationResult parentResult) + public Set discoverConnectors(ConnectorHostType hostType, Task task, OperationResult parentResult) throws CommunicationException, SecurityViolationException, SchemaException, ConfigurationException, ObjectNotFoundException; /** * Finish initialization of the model and lower system components * (provisioning, repository, etc). - * + * * The implementation may execute resource-intensive tasks in this method. * All the dependencies should be already constructed, properly wired and * initialized. Also logging and other infrastructure should be already set @@ -697,22 +697,22 @@ CompareResultType compareObject(PrismObject object, @NotNull List ignoreItemPaths, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException; - + /** * Merge two objects into one. - * + * * EXPERIMENTAL feature. The method signature is likely to change in the future. - * + * * @param type object type * @param leftOid left-side object OID * @param rightOid right-side object OID * @param mergeConfigurationName name of the merge configuration to use * @param task * @param result - * @return + * @return */ - Collection> mergeObjects(Class type, String leftOid, String rightOid, - String mergeConfigurationName, Task task, OperationResult result) + Collection> mergeObjects(Class type, String leftOid, String rightOid, + String mergeConfigurationName, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ConfigurationException, ObjectAlreadyExistsException, ExpressionEvaluationException, CommunicationException, PolicyViolationException, SecurityViolationException; - + } diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/RoleSelectionSpecification.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/RoleSelectionSpecification.java index c64dfd96afa..0531d6e5015 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/RoleSelectionSpecification.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/RoleSelectionSpecification.java @@ -27,7 +27,7 @@ * */ public class RoleSelectionSpecification { - + private List> roleTypes = null; private ObjectFilter filter = null; @@ -42,21 +42,21 @@ public List> getRoleTypes() { public void setNoRoleTypes() { roleTypes = new ArrayList>(); } - + public void addRoleType(DisplayableValue roleType) { if (roleTypes == null) { roleTypes = new ArrayList>(); } ((Collection)roleTypes).add(roleType); } - + public void addRoleTypes(Collection> roleTypes) { if (this.roleTypes == null) { this.roleTypes = new ArrayList>(); } this.roleTypes.addAll((Collection)roleTypes); } - + /** * Returns "additional filter" that should be used to search for assignible roles. * This filter should be AND-ed with any application level filter. @@ -106,6 +106,6 @@ public boolean equals(Object obj) { public String toString() { return "RoleSelectionSpecification(" + roleTypes + ": "+filter+")"; } - - + + } diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/AbstractAuthenticationContext.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/AbstractAuthenticationContext.java index 45bb97f8a83..88fbd60c657 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/AbstractAuthenticationContext.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/AbstractAuthenticationContext.java @@ -3,15 +3,15 @@ public abstract class AbstractAuthenticationContext { private String username; - + public String getUsername() { return username; } - + public AbstractAuthenticationContext(String username) { this.username = username; } - + public abstract Object getEnteredCredential(); - + } diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/EvaluatedAssignment.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/EvaluatedAssignment.java index 0ac45f1d6e4..a99e19d33e4 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/EvaluatedAssignment.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/EvaluatedAssignment.java @@ -40,9 +40,9 @@ public interface EvaluatedAssignment extends DebugDumpable AssignmentType getAssignmentType(); Collection getAuthorizations(); - + Collection getAdminGuiConfigurations(); - + DeltaSetTriple getRoles(); DeltaSetTriple getEvaluatedConstructions(Task task, OperationResult result) throws SchemaException, ObjectNotFoundException; @@ -58,7 +58,7 @@ public interface EvaluatedAssignment extends DebugDumpable boolean isPresentInCurrentObject(); boolean isPresentInOldObject(); - + /** * Returns all policy rules that apply to the focal object and are derived from this assignment * - even those that were not triggered. The policy rules are compiled from all the applicable @@ -66,7 +66,7 @@ public interface EvaluatedAssignment extends DebugDumpable */ @NotNull Collection getFocusPolicyRules(); - + /** * Returns all policy rules that directly apply to the target object of this assignment * (and are derived from this assignment) - even those that were not triggered. The policy rules @@ -99,6 +99,6 @@ public interface EvaluatedAssignment extends DebugDumpable Collection getPolicySituations(); - + void triggerConstraint(@Nullable EvaluatedPolicyRule rule, EvaluatedPolicyRuleTrigger trigger) throws PolicyViolationException; } diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/EvaluatedAssignmentTarget.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/EvaluatedAssignmentTarget.java index 92fbf457f51..5e36b3c69ea 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/EvaluatedAssignmentTarget.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/EvaluatedAssignmentTarget.java @@ -26,7 +26,7 @@ * */ public interface EvaluatedAssignmentTarget extends DebugDumpable { - + PrismObject getTarget(); boolean isDirectlyAssigned(); diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/EvaluatedConstruction.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/EvaluatedConstruction.java index 751170e8e2a..21a75785233 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/EvaluatedConstruction.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/EvaluatedConstruction.java @@ -25,7 +25,7 @@ * */ public interface EvaluatedConstruction extends DebugDumpable { - + PrismObject getResource(); ShadowKindType getKind(); diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/EvaluatedPolicyRule.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/EvaluatedPolicyRule.java index c34d9d98f42..60f196e53a4 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/EvaluatedPolicyRule.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/EvaluatedPolicyRule.java @@ -39,7 +39,7 @@ public interface EvaluatedPolicyRule extends DebugDumpable, Serializable { Collection> getAllTriggers(); String getName(); - + PolicyRuleType getPolicyRule(); AssignmentPath getAssignmentPath(); @@ -52,11 +52,11 @@ public interface EvaluatedPolicyRule extends DebugDumpable, Serializable { ObjectType getDirectOwner(); PolicyConstraintsType getPolicyConstraints(); - + String getPolicySituation(); - + PolicyActionsType getActions(); - + Collection getPolicyExceptions(); EvaluatedPolicyRuleType toEvaluatedPolicyRuleType(); diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/EvaluatedPolicyRuleTrigger.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/EvaluatedPolicyRuleTrigger.java index 5fb3d64abb2..dadcf97f6b5 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/EvaluatedPolicyRuleTrigger.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/EvaluatedPolicyRuleTrigger.java @@ -29,11 +29,11 @@ /** * Description of a situation that caused a trigger of the policy rule. - * + * * @author semancik */ public class EvaluatedPolicyRuleTrigger implements DebugDumpable { - + @NotNull private final PolicyConstraintKindType constraintKind; @NotNull private final CT constraint; private final String message; diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/ModelContext.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/ModelContext.java index ce7f1dc510a..8947b5e5161 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/ModelContext.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/ModelContext.java @@ -41,11 +41,11 @@ public interface ModelContext extends Serializable, DebugDumpable { ModelState getState(); - + ModelElementContext getFocusContext(); - + Collection getProjectionContexts(); - + ModelProjectionContext findProjectionContext(ResourceShadowDiscriminator rat); ModelExecuteOptions getOptions(); @@ -56,7 +56,7 @@ public interface ModelContext extends Serializable, DebugD Class getFocusClass(); void reportProgress(ProgressInformation progress); - + DeltaSetTriple> getEvaluatedAssignmentTriple(); PrismContext getPrismContext(); // use with care diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/ModelElementContext.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/ModelElementContext.java index d369fc28e9d..8f1f3d78e88 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/ModelElementContext.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/ModelElementContext.java @@ -37,25 +37,25 @@ public interface ModelElementContext extends Serializable, PrismObject getObjectOld(); void setObjectOld(PrismObject objectOld); - + PrismObject getObjectNew(); - + void setObjectNew(PrismObject objectNew); - + ObjectDelta getPrimaryDelta(); - + void setPrimaryDelta(ObjectDelta primaryDelta); void addPrimaryDelta(ObjectDelta value) throws SchemaException; - + ObjectDelta getSecondaryDelta(); - + void setSecondaryDelta(ObjectDelta secondaryDelta); List getExecutedDeltas(); String getOid(); - + /** * Returns all policy rules that apply to this object - even those that were not triggered. * The policy rules are compiled from all the applicable sources (target, meta-roles, etc.) diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/ModelProjectionContext.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/ModelProjectionContext.java index ee8bdbab231..4015570eb74 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/ModelProjectionContext.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/ModelProjectionContext.java @@ -28,12 +28,12 @@ public interface ModelProjectionContext extends ModelElementContext /** * Returns synchronization delta. - * + * * Synchronization delta describes changes that have recently happened. MidPoint reacts to these * changes by "pulling them in" (e.g. using them in inbound mappings). */ public ObjectDelta getSyncDelta(); - + public void setSyncDelta(ObjectDelta syncDelta); ResourceShadowDiscriminator getResourceShadowDiscriminator(); @@ -41,9 +41,9 @@ public interface ModelProjectionContext extends ModelElementContext /** * Decision regarding the account. It describes the overall situation of the account e.g. whether account * is added, is to be deleted, unliked, etc. - * + * * If set to null no decision was made yet. Null is also a typical value when the context is created. - * + * * @see SynchronizationPolicyDecision */ public SynchronizationPolicyDecision getSynchronizationPolicyDecision(); diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/ModelState.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/ModelState.java index 32b71c597df..445ec716dfb 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/ModelState.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/ModelState.java @@ -22,17 +22,17 @@ * */ public enum ModelState { - + INITIAL, - + PRIMARY, - + SECONDARY, - + EXECUTION, - + POSTEXECUTION, - + FINAL; public ModelStateType toModelStateType() { diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/NonceAuthenticationContext.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/NonceAuthenticationContext.java index 8be8563f5ca..7597bf9d57c 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/NonceAuthenticationContext.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/NonceAuthenticationContext.java @@ -6,17 +6,17 @@ public class NonceAuthenticationContext extends AbstractAuthenticationContext { private String nonce; private NonceCredentialsPolicyType policy; - + public NonceAuthenticationContext(String username, String nonce, NonceCredentialsPolicyType policy) { super(username); this.nonce = nonce; this.policy = policy; } - + public String getNonce() { return nonce; } - + public NonceCredentialsPolicyType getPolicy() { return policy; } diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/PasswordAuthenticationContext.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/PasswordAuthenticationContext.java index 6c149ab8c06..8596369f5d0 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/PasswordAuthenticationContext.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/PasswordAuthenticationContext.java @@ -1,13 +1,13 @@ package com.evolveum.midpoint.model.api.context; public class PasswordAuthenticationContext extends AbstractAuthenticationContext { - + private String password; - + public String getPassword() { return password; } - + public PasswordAuthenticationContext(String username, String password) { super(username); this.password = password; @@ -17,5 +17,5 @@ public PasswordAuthenticationContext(String username, String password) { public Object getEnteredCredential() { return getPassword(); } - + } diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/PredefinedPolicySituation.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/PredefinedPolicySituation.java index 1e15ed566e7..ee36660f42f 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/PredefinedPolicySituation.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/PredefinedPolicySituation.java @@ -23,20 +23,20 @@ * */ public enum PredefinedPolicySituation { - + EXCLUSION_VIOLATION(SchemaConstants.MODEL_POLICY_SITUATION_EXCLUSION_VIOLATION, PolicyConstraintKindType.EXCLUSION), - + UNDERASSIGNED(SchemaConstants.MODEL_POLICY_SITUATION_UNDERASSIGNED, PolicyConstraintKindType.MIN_ASSIGNEES), - + OVERASSIGNED(SchemaConstants.MODEL_POLICY_SITUATION_OVERASSIGNED, PolicyConstraintKindType.MAX_ASSIGNEES), - + MODIFIED(SchemaConstants.MODEL_POLICY_SITUATION_MODIFIED, PolicyConstraintKindType.MODIFICATION), - + ASSIGNED(SchemaConstants.MODEL_POLICY_SITUATION_ASSIGNED, PolicyConstraintKindType.ASSIGNMENT); private String url; private PolicyConstraintKindType constraintKind; - + PredefinedPolicySituation(String url, PolicyConstraintKindType constraintKind) { this.url = url; this.constraintKind = constraintKind; diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/SecurityQuestionsAuthenticationContext.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/SecurityQuestionsAuthenticationContext.java index b13f72ddd5a..45c28a26869 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/SecurityQuestionsAuthenticationContext.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/SecurityQuestionsAuthenticationContext.java @@ -8,14 +8,14 @@ public class SecurityQuestionsAuthenticationContext extends AbstractAuthenticati private Map questionAnswerMap; private SecurityQuestionsCredentialsPolicyType policy; - - + + public SecurityQuestionsAuthenticationContext(String username, Map questionAnswerMap) { super(username); this.questionAnswerMap = questionAnswerMap; } - - + + public Map getQuestionAnswerMap() { return questionAnswerMap; } @@ -24,14 +24,14 @@ public Map getQuestionAnswerMap() { public Object getEnteredCredential() { return getQuestionAnswerMap(); } - + public SecurityQuestionsCredentialsPolicyType getPolicy() { return policy; } - + public void setPolicy(SecurityQuestionsCredentialsPolicyType policy) { this.policy = policy; } - - + + } diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/SynchronizationPolicyDecision.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/SynchronizationPolicyDecision.java index 8c5e2ca9d92..b76bf7e4cad 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/SynchronizationPolicyDecision.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/context/SynchronizationPolicyDecision.java @@ -19,33 +19,33 @@ /** * Describes what the policy "decides" about a specific account. - * + * * @author Radovan Semancik * */ public enum SynchronizationPolicyDecision { - + /** * New account that is going to be added (and linked) */ ADD, - + /** * Existing account that is going to be deleted (and unlinked) */ DELETE, - + /** * Existing account that is kept as it is (remains linked). * Note: there still may be attribute or entitlement changes. */ KEEP, - + /** * Existing account that is going to be unlinked (but NOT deleted) */ UNLINK, - + /** * The projection is broken. I.e. there is some (fixable) state that * prevents proper operations with the projection. This may be schema violation @@ -61,7 +61,7 @@ public enum SynchronizationPolicyDecision { * this is used only for evaluation assigment and the assigment policies */ IGNORE; - + public SynchronizationPolicyDecisionType toSynchronizationPolicyDecisionType() { switch (this) { case ADD: return SynchronizationPolicyDecisionType.ADD; diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/hooks/ChangeHook.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/hooks/ChangeHook.java index 94088433091..4d4b1065ccd 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/hooks/ChangeHook.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/hooks/ChangeHook.java @@ -24,10 +24,10 @@ /** * TODO - * + * * This applies to all changes, therefore it will "hook" into addObject, modifyObject * and also deleteObject. - * + * * @author semancik * */ diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/hooks/HookOperationMode.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/hooks/HookOperationMode.java index 900e27dc93b..2e5e27da4a5 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/hooks/HookOperationMode.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/hooks/HookOperationMode.java @@ -20,14 +20,14 @@ * */ public enum HookOperationMode { - + /** * The hook operates in background. If the hook returns then the hook operation is * completed. The caller reclaims ownership of the task. The thread may be used to * continue execution of the task and to complete the task. */ FOREGROUND, - + /** * The hook operates in background. The hook will use its own thread for execution. * After the hook is done with executing it will "return" control to the next handler diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/hooks/HookRegistry.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/hooks/HookRegistry.java index 81e48db667d..7bb4c6ee2ea 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/hooks/HookRegistry.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/hooks/HookRegistry.java @@ -23,7 +23,7 @@ * */ public interface HookRegistry { - + void registerChangeHook(String url, ChangeHook changeHook); List getAllChangeHooks(); 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 8228e23d571..b548c4259b2 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 @@ -32,7 +32,7 @@ public class MergeDeltas implements DebugDumpable, Seriali private ObjectDelta leftObjectDelta; private ObjectDelta leftLinkDelta; private ObjectDelta rightLinkDelta; - + public MergeDeltas(ObjectDelta leftObjectDelta, ObjectDelta leftLinkDelta, ObjectDelta rightLinkDelta) { super(); diff --git a/model/model-client/src/main/java/com/evolveum/midpoint/model/client/ModelClientUtil.java b/model/model-client/src/main/java/com/evolveum/midpoint/model/client/ModelClientUtil.java index bbcd1625238..ecaaa497910 100644 --- a/model/model-client/src/main/java/com/evolveum/midpoint/model/client/ModelClientUtil.java +++ b/model/model-client/src/main/java/com/evolveum/midpoint/model/client/ModelClientUtil.java @@ -70,24 +70,24 @@ * */ public class ModelClientUtil { - + // XML constants public static final String NS_COMMON = "http://midpoint.evolveum.com/xml/ns/public/common/common-3"; public static final String NS_TYPES = "http://prism.evolveum.com/xml/ns/public/types-3"; public static final String NS_RI = "http://midpoint.evolveum.com/xml/ns/public/resource/instance-3"; public static final String NS_ICFS = "http://midpoint.evolveum.com/xml/ns/public/resource/instance-3"; - + public static final QName COMMON_PATH = new QName(NS_COMMON, "path"); public static final QName COMMON_VALUE = new QName(NS_COMMON, "value"); public static final QName COMMON_GIVEN_NAME = new QName(NS_COMMON, "givenName"); public static final QName COMMON_ASSIGNMENT = new QName(NS_COMMON, "assignment"); - + private static final QName TYPES_POLYSTRING_ORIG = new QName(NS_TYPES, "orig"); public static final QName TYPES_CLEAR_VALUE = new QName(NS_TYPES, "clearValue"); private static final DocumentBuilder domDocumentBuilder; private static final JAXBContext jaxbContext; - + public static JAXBContext instantiateJaxbContext() throws JAXBException { return JAXBContext.newInstance("com.evolveum.midpoint.xml.ns._public.common.api_types_3:" + "com.evolveum.midpoint.xml.ns._public.common.common_3:" + @@ -99,7 +99,7 @@ public static JAXBContext instantiateJaxbContext() throws JAXBException { "com.evolveum.prism.xml.ns._public.query_3:" + "com.evolveum.prism.xml.ns._public.types_3"); } - + public static Element createPathElement(String stringPath, Document doc) { String pathDeclaration = "declare default namespace '" + NS_COMMON + "'; " + stringPath; return createTextElement(COMMON_PATH, pathDeclaration, doc); @@ -124,11 +124,11 @@ public static PolyStringType createPolyStringType(String string, Document doc) { polyStringType.getContent().add(string); return polyStringType; } - + public static PolyStringType createPolyStringType(String string) { return createPolyStringType(string, getDocumnent()); } - + public static String getOrig(PolyStringType polyStringType) { if (polyStringType == null) { return null; @@ -151,19 +151,19 @@ public static String getOrig(PolyStringType polyStringType) { } return sb.toString(); } - + public static Element createTextElement(QName qname, String value, Document doc) { Element element = doc.createElementNS(qname.getNamespaceURI(), qname.getLocalPart()); element.setTextContent(value); return element; } - + public static CredentialsType createPasswordCredentials(String password) { CredentialsType credentialsType = new CredentialsType(); credentialsType.setPassword(createPasswordType(password)); return credentialsType; } - + public static PasswordType createPasswordType(String password) { PasswordType passwordType = new PasswordType(); passwordType.setValue(createProtectedString(password)); @@ -189,7 +189,7 @@ public static String getTypeUri(Class type) { String typeUri = NS_COMMON + "#" + type.getSimpleName(); return typeUri; } - + public static QName getTypeQName(Class type) { QName typeQName = new QName(NS_COMMON, type.getSimpleName()); return typeQName; @@ -205,8 +205,8 @@ public static QName getElementName(Class type) { local = local.substring(0,1).toLowerCase() + local.substring(1); } return new QName(NS_COMMON, local); - } - + } + public static Element parseElement(String stringXml) throws SAXException, IOException { Document document = domDocumentBuilder.parse(IOUtils.toInputStream(stringXml, "utf-8")); return getFirstChildElement(document); @@ -263,8 +263,8 @@ public static ObjectDeltaOperationType findInDeltaOperationList(ObjectDeltaOpera } return null; } - - public static ObjectDeltaListType createModificationDeltaList(Class type, String oid, + + public static ObjectDeltaListType createModificationDeltaList(Class type, String oid, String path, ModificationTypeType modType, Object... values) { ObjectDeltaListType deltaList = new ObjectDeltaListType(); ObjectDeltaType delta = new ObjectDeltaType(); @@ -279,21 +279,21 @@ public static ObjectDeltaListType createModificationDelta deltaList.getDelta().add(delta); return deltaList; } - + @Deprecated - public static ObjectDeltaListType createAssignDeltaList(Class focusType, String focusOid, + public static ObjectDeltaListType createAssignDeltaList(Class focusType, String focusOid, Class targetType, String targetOid) { return createAssignmentDeltaList(focusType, focusOid, targetType, targetOid, ModificationTypeType.ADD); } @Deprecated - public static ObjectDeltaListType createUnassignDeltaList(Class focusType, String focusOid, + public static ObjectDeltaListType createUnassignDeltaList(Class focusType, String focusOid, Class targetType, String targetOid) { return createAssignmentDeltaList(focusType, focusOid, targetType, targetOid, ModificationTypeType.DELETE); } @Deprecated - private static ObjectDeltaListType createAssignmentDeltaList(Class focusType, String focusOid, + private static ObjectDeltaListType createAssignmentDeltaList(Class focusType, String focusOid, Class targetType, String targetOid, ModificationTypeType modificationType) { AssignmentType assignment = new AssignmentType(); ObjectReferenceType targetRef = new ObjectReferenceType(); @@ -302,10 +302,10 @@ private static ObjectDeltaListType assignment.setTargetRef(targetRef); return createModificationDeltaList(focusType, focusOid, "assignment", modificationType, assignment); } - + public static O unmarshallResource(String path) throws JAXBException, FileNotFoundException { - Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); - + Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); + InputStream is = null; JAXBElement element = null; try { @@ -326,8 +326,8 @@ public static O unmarshallResource(String path) throws JAXBException, FileNo } public static O unmarshallFile(File file) throws JAXBException, FileNotFoundException { - Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); - + Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); + InputStream is = null; JAXBElement element = null; try { @@ -343,11 +343,11 @@ public static O unmarshallFile(File file) throws JAXBException, FileNotFound } return element.getValue(); } - + public static String marshallToSting(O object) throws JAXBException { return marshallToSting(object, true); } - + public static String marshallToSting(O object, boolean formatted) throws JAXBException { Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); @@ -360,7 +360,7 @@ public static String marshallToSting(O object, boolean fo marshaller.marshal(element, sw); return sw.toString(); } - + public static String marshallToSting(QName elementName, T object, boolean formatted) throws JAXBException { Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); @@ -372,15 +372,15 @@ public static String marshallToSting(QName elementName, T object, boolean fo marshaller.marshal(element, sw); return sw.toString(); } - + public static ObjectDeltaType createRoleAssignDelta(Class focusType, String focusOid, String... roleOids) { return createRoleAssignmentDelta(focusType, focusOid, ModificationTypeType.ADD, roleOids); } - + public static ObjectDeltaType createRoleUnassignDelta(Class focusType, String focusOid, String... roleOids) { return createRoleAssignmentDelta(focusType, focusOid, ModificationTypeType.DELETE, roleOids); } - + public static ObjectDeltaType createRoleAssignmentDelta(Class focusType, String focusOid, ModificationTypeType modType, String... roleOids) { ItemDeltaType assignmentDelta = new ItemDeltaType(); assignmentDelta.setModificationType(modType); @@ -395,7 +395,7 @@ public static ObjectDeltaType createRoleAssignmentDelta(C deltaType.getItemDelta().add(assignmentDelta); return deltaType; } - + public static AssignmentType createRoleAssignment(String roleOid) { AssignmentType roleAssignment = new AssignmentType(); ObjectReferenceType roleRef = new ObjectReferenceType(); @@ -404,15 +404,15 @@ public static AssignmentType createRoleAssignment(String roleOid) { roleAssignment.setTargetRef(roleRef); return roleAssignment; } - + public static ObjectDeltaType createConstructionAssignDelta(Class focusType, String focusOid, String resourceOid) { return createConstructionAssignmentDelta(focusType, focusOid, ModificationTypeType.ADD, resourceOid, null, null); } - + public static ObjectDeltaType createConstructionAssignDelta(Class focusType, String focusOid, String resourceOid, ShadowKindType kind) { return createConstructionAssignmentDelta(focusType, focusOid, ModificationTypeType.ADD, resourceOid, kind, null); } - + public static ObjectDeltaType createConstructionAssignDelta(Class focusType, String focusOid, String resourceOid, ShadowKindType kind, String intent) { return createConstructionAssignmentDelta(focusType, focusOid, ModificationTypeType.ADD, resourceOid, kind, intent); } @@ -429,7 +429,7 @@ public static ObjectDeltaType createConstructionAssignmen deltaType.getItemDelta().add(assignmentDelta); return deltaType; } - + public static AssignmentType createConstructionAssignment(String resourceOid) { return createConstructionAssignment(resourceOid, null, null); } @@ -437,7 +437,7 @@ public static AssignmentType createConstructionAssignment(String resourceOid) { public static AssignmentType createConstructionAssignment(String resourceOid, ShadowKindType kind) { return createConstructionAssignment(resourceOid, kind, null); } - + public static AssignmentType createConstructionAssignment(String resourceOid, ShadowKindType kind, String intent) { AssignmentType assignment = new AssignmentType(); ConstructionType construction = new ConstructionType(); @@ -453,7 +453,7 @@ public static AssignmentType createConstructionAssignment(String resourceOid, Sh assignment.setConstruction(construction); return assignment; } - + public static ObjectDeltaListType createDeltaList(ObjectDeltaType... deltas) { ObjectDeltaListType list = new ObjectDeltaListType(); for (ObjectDeltaType delta: deltas) { @@ -461,7 +461,7 @@ public static ObjectDeltaListType createDeltaList(ObjectDeltaType... deltas) { } return list; } - + public static SelectorQualifiedGetOptionsType createRootGetOptions(GetOperationOptionsType opt) { SelectorQualifiedGetOptionsType rootOpts = new SelectorQualifiedGetOptionsType(); SelectorQualifiedGetOptionType selOpt = new SelectorQualifiedGetOptionType(); @@ -469,13 +469,13 @@ public static SelectorQualifiedGetOptionsType createRootGetOptions(GetOperationO rootOpts.getOption().add(selOpt); return rootOpts; } - + public static GetOperationOptionsType createRawGetOption() { GetOperationOptionsType opts = new GetOperationOptionsType(); opts.setRaw(Boolean.TRUE); return opts; } - + public static ModelExecuteOptionsType createRawExecuteOption() { ModelExecuteOptionsType opts = new ModelExecuteOptionsType(); opts.setRaw(Boolean.TRUE); @@ -499,7 +499,7 @@ public static String toString(O obj) { sb.append(")"); return sb.toString(); } - + public static String toString(PolyStringType poly) { if (poly == null) { return null; @@ -507,7 +507,7 @@ public static String toString(PolyStringType poly) { return getOrig(poly); } - + static { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); @@ -516,7 +516,7 @@ public static String toString(PolyStringType poly) { } catch (ParserConfigurationException e) { throw new IllegalStateException("Error creating XML document " + e.getMessage()); } - + try { jaxbContext = ModelClientUtil.instantiateJaxbContext(); } catch (JAXBException e) { @@ -524,5 +524,5 @@ public static String toString(PolyStringType poly) { } } - + } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/ConstantsManager.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/ConstantsManager.java index 41b4167afb7..7414b12db4c 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/ConstantsManager.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/ConstantsManager.java @@ -29,24 +29,24 @@ */ @Component public class ConstantsManager { - + public static final String SYSTEM_CONFIGURATION_SECTION = "midpoint.constants"; - + @Autowired private MidpointConfiguration midpointConfiguration; - + private Configuration constConfig; - + public ConstantsManager() { } - + /** * For testing. */ public ConstantsManager(Configuration config) { this.constConfig = config; } - + private Configuration getConstConfig() { if (constConfig == null) { constConfig = midpointConfiguration.getConfiguration(SYSTEM_CONFIGURATION_SECTION); diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/SystemObjectCache.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/SystemObjectCache.java index 16f873be6df..23b7e5aa479 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/SystemObjectCache.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/SystemObjectCache.java @@ -38,35 +38,35 @@ * independent of the request. It will store the system configuration in memory. * It will check for system configuration updates in regular interval using the * getVersion() method. - * + * * This supplements the RepositoryCache. RepositoryCache works on per-request * (per-operation) basis. The SystemObjectCache is global. Its goal is to reduce * the number of getObject(SystemConfiguration) and the getVersion(SystemConfiguration) * calls. - * + * * In the future: May be used for more objects that are often used and seldom * changed, e.g. object templates. - * + * * TODO: use real repo instead of repo cache - * + * * @author semancik */ @Component public class SystemObjectCache { - + private static final Trace LOGGER = TraceManager.getTrace(SystemObjectCache.class); - + @Autowired @Qualifier("cacheRepositoryService") private transient RepositoryService cacheRepositoryService; private PrismObject systemConfiguration; private Long systemConfigurationCheckTimestamp; - + private long getSystemConfigurationExpirationMillis() { return 1000; } - + public synchronized PrismObject getSystemConfiguration(OperationResult result) throws SchemaException { try { if (!hasValidSystemConfiguration(result)) { @@ -84,7 +84,7 @@ public synchronized PrismObject getSystemConfiguration( } return systemConfiguration; } - + private boolean hasValidSystemConfiguration(OperationResult result) throws ObjectNotFoundException, SchemaException { if (systemConfiguration == null) { return false; @@ -106,17 +106,17 @@ private boolean hasValidSystemConfiguration(OperationResult result) throws Objec } return false; } - + private void loadSystemConfiguration(OperationResult result) throws ObjectNotFoundException, SchemaException { Collection> options = SelectorOptions.createCollection(GetOperationOptions.createReadOnly()); - systemConfiguration = cacheRepositoryService.getObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), + systemConfiguration = cacheRepositoryService.getObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), options, result); systemConfigurationCheckTimestamp = System.currentTimeMillis(); if (systemConfiguration != null && systemConfiguration.getVersion() == null) { LOGGER.warn("Retrieved system configuration with null version"); } } - + public synchronized void invalidateCaches() { systemConfiguration = null; } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AbstractSearchExpressionEvaluator.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AbstractSearchExpressionEvaluator.java index 7db5b9efcbf..9146c7e470d 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AbstractSearchExpressionEvaluator.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AbstractSearchExpressionEvaluator.java @@ -82,11 +82,11 @@ /** * @author Radovan Semancik */ -public abstract class AbstractSearchExpressionEvaluator +public abstract class AbstractSearchExpressionEvaluator extends AbstractValueTransformationExpressionEvaluator { - + private static final Trace LOGGER = TraceManager.getTrace(AbstractSearchExpressionEvaluator.class); - + private PrismContext prismContext; private D outputDefinition; private Protector protector; @@ -103,7 +103,7 @@ protected AbstractSearchExpressionEvaluator(SearchObjectExpressionEvaluatorType this.objectResolver = objectResolver; this.modelService = modelService; } - + public PrismContext getPrismContext() { return prismContext; } @@ -128,12 +128,12 @@ public ModelService getModelService() { protected List transformSingleValue(ExpressionVariables variables, PlusMinusZero valueDestination, boolean useNew, ExpressionEvaluationContext context, String contextDescription, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException { - + // if (LOGGER.isTraceEnabled()) { // LOGGER.trace("transformSingleValue in {}\nvariables:\n{}\nvalueDestination: {}\nuseNew: {}", // new Object[]{contextDescription, variables.debugDump(1), valueDestination, useNew}); // } - + QName targetTypeQName = getExpressionEvaluatorType().getTargetType(); if (targetTypeQName == null) { targetTypeQName = getDefaultTargetType(); @@ -147,22 +147,22 @@ protected List transformSingleValue(ExpressionVariables variables, PlusMinusZ throw new SchemaException("Unknown target type "+targetTypeQName+" in "+shortDebugDump()); } Class targetTypeClass = targetType.getClassDefinition(); - + List resultValues = null; ObjectQuery query = null; - + List> additionalAttributeDeltas = null; PopulateType populateAssignmentType = getExpressionEvaluatorType().getPopulate(); if (populateAssignmentType != null) { additionalAttributeDeltas = collectAdditionalAttributes(populateAssignmentType, outputDefinition, variables, context, contextDescription, task, result); } - + if (getExpressionEvaluatorType().getOid() != null) { resultValues = new ArrayList<>(1); resultValues.add(createPrismValue(getExpressionEvaluatorType().getOid(), targetTypeQName, additionalAttributeDeltas, context)); } else { - + SearchFilterType filterType = getExpressionEvaluatorType().getFilter(); if (filterType == null) { throw new SchemaException("No filter in "+shortDebugDump()); @@ -177,14 +177,14 @@ protected List transformSingleValue(ExpressionVariables variables, PlusMinusZ LOGGER.trace("Expression in query evaluated to: {}", query.debugDump()); } query = extendQuery(query, context); - + if (LOGGER.isTraceEnabled()){ LOGGER.trace("Query after extension: {}", query.debugDump()); } - + resultValues = executeSearchUsingCache(targetTypeClass, targetTypeQName, query, additionalAttributeDeltas, context, contextDescription, task, context .getResult()); - + if (resultValues.isEmpty()) { ObjectReferenceType defaultTargetRef = getExpressionEvaluatorType().getDefaultTargetRef(); if (defaultTargetRef != null) { @@ -193,16 +193,16 @@ protected List transformSingleValue(ExpressionVariables variables, PlusMinusZ } } } - + if (resultValues.isEmpty() && getExpressionEvaluatorType().isCreateOnDemand() == Boolean.TRUE && (valueDestination == PlusMinusZero.PLUS || valueDestination == PlusMinusZero.ZERO || useNew)) { String createdObjectOid = createOnDemand(targetTypeClass, variables, context, context.getContextDescription(), task, context .getResult()); resultValues.add(createPrismValue(createdObjectOid, targetTypeQName, additionalAttributeDeltas, context)); } - + LOGGER.trace("Search expression got {} results for query {}", resultValues==null?"null":resultValues.size(), query); - + return (List) resultValues; } @@ -219,7 +219,7 @@ protected AbstractSearchExpressionEvaluatorCache getCache() { return null; } - private List executeSearchUsingCache(Class targetTypeClass, final QName targetTypeQName, ObjectQuery query, List> additionalAttributeDeltas, + private List executeSearchUsingCache(Class targetTypeClass, final QName targetTypeQName, ObjectQuery query, List> additionalAttributeDeltas, final ExpressionEvaluationContext params, String contextDescription, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException { ObjectSearchStrategyType searchStrategy = getSearchStrategy(); @@ -258,7 +258,7 @@ private ObjectSearchStrategyType getSearchStrategy() { private List executeSearch(List rawResult, Class targetTypeClass, final QName targetTypeQName, ObjectQuery query, ObjectSearchStrategyType searchStrategy, - List> additionalAttributeDeltas, + List> additionalAttributeDeltas, ExpressionEvaluationContext params, String contextDescription, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException { @@ -294,19 +294,19 @@ private List executeSearch(List rawResult private List executeSearchAttempt(final List rawResult, Class targetTypeClass, final QName targetTypeQName, ObjectQuery query, boolean searchOnResource, boolean tryAlsoRepository, - final List> additionalAttributeDeltas, + final List> additionalAttributeDeltas, final ExpressionEvaluationContext params, String contextDescription, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException { final List list = new ArrayList(); - + Collection> options = new ArrayList<>(); if (!searchOnResource) { options.add(SelectorOptions.create(GetOperationOptions.createNoFetch())); } extendOptions(options, searchOnResource); - + ResultHandler handler = new ResultHandler() { @Override public boolean handle(PrismObject object, OperationResult parentResult) { @@ -316,11 +316,11 @@ public boolean handle(PrismObject object, OperationResult parentResult) { list.add(createPrismValue(object.getOid(), targetTypeQName, additionalAttributeDeltas, params)); // TODO: we should count results and stop after some reasonably high number? - + return true; } }; - + try { objectResolver.searchIterative(targetTypeClass, query, options, handler, task, result); } catch (IllegalStateException e) { // this comes from checkConsistence methods @@ -329,7 +329,7 @@ public boolean handle(PrismObject object, OperationResult parentResult) { throw new SchemaException(e.getMessage()+" in "+contextDescription, e); } catch (SystemException e) { throw new SystemException(e.getMessage()+" in "+contextDescription, e); - } catch (CommunicationException | ConfigurationException + } catch (CommunicationException | ConfigurationException | SecurityViolationException e) { if (searchOnResource && tryAlsoRepository) { options = SelectorOptions.createCollection(GetOperationOptions.createNoFetch()); @@ -343,82 +343,82 @@ public boolean handle(PrismObject object, OperationResult parentResult) { // stop whole projection computation, but what to do if the // shadow for group doesn't exist? (MID-2107) throw new ExpressionEvaluationException("Unexpected expression exception "+e+": "+e.getMessage(), e); - } + } } else { throw new ExpressionEvaluationException("Unexpected expression exception "+e+": "+e.getMessage(), e); } } catch (ObjectNotFoundException e) { throw e; } - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Assignment expression resulted in {} objects, using query:\n{}", list.size(), query.debugDump()); } - + return list; } - + protected void extendOptions(Collection> options, boolean searchOnResource) { // Nothing to do. To be overridden by subclasses } - + // e.g parameters, activation for assignment etc. protected List> collectAdditionalAttributes(PopulateType fromPopulate, D outputDefinition, ExpressionVariables variables, ExpressionEvaluationContext params, String contextDescription, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException { - + if (!(outputDefinition instanceof PrismContainerDefinition)) { return null; } - + List> deltas = new ArrayList<>(); - + for (PopulateItemType populateItem: fromPopulate.getPopulateItem()) { - - ItemDelta itemDelta = evaluatePopulateExpression(populateItem, variables, params, + + ItemDelta itemDelta = evaluatePopulateExpression(populateItem, variables, params, (PrismContainerDefinition) outputDefinition, contextDescription, false, task, result); if (itemDelta != null) { deltas.add(itemDelta); } - + } - + return deltas; } protected abstract V createPrismValue(String oid, QName targetTypeQName, List> additionalAttributeDeltas, ExpressionEvaluationContext params); - - private String createOnDemand(Class targetTypeClass, ExpressionVariables variables, - ExpressionEvaluationContext params, String contextDescription, Task task, OperationResult result) + + private String createOnDemand(Class targetTypeClass, ExpressionVariables variables, + ExpressionEvaluationContext params, String contextDescription, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Going to create assignment targets on demand, variables:\n{}", variables.formatVariables()); } PrismObjectDefinition objectDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(targetTypeClass); PrismObject newObject = objectDefinition.instantiate(); - + PopulateType populateObject = getExpressionEvaluatorType().getPopulateObject(); - + if (populateObject == null) { LOGGER.warn("No populateObject in assignment expression in {}, " + "object created on demand will be empty. Subsequent operations will most likely fail", contextDescription); - } else { + } else { for (PopulateItemType populateItem: populateObject.getPopulateItem()) { - ItemDelta itemDelta = evaluatePopulateExpression(populateItem, variables, params, + ItemDelta itemDelta = evaluatePopulateExpression(populateItem, variables, params, objectDefinition, contextDescription, true, task, result); if (itemDelta != null) { itemDelta.applyTo(newObject); } } } - + LOGGER.debug("Creating object on demand from {}: {}", contextDescription, newObject); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Creating object on demand:\n{}", newObject.debugDump()); } - + ObjectDelta addDelta = newObject.createAddDelta(); Collection> deltas = MiscSchemaUtil.createCollection(addDelta); try { @@ -427,7 +427,7 @@ private String createOnDemand(Class targetTypeClass, E | PolicyViolationException | SecurityViolationException e) { throw new ExpressionEvaluationException(e.getMessage(), e); } - + return addDelta.getOid(); } @@ -440,7 +440,7 @@ private expression = expressionFactory.makeExpression(expressionType, propOutputDefinition, + Expression expression = expressionFactory.makeExpression(expressionType, propOutputDefinition, expressionDesc, task, result); ExpressionEvaluationContext context = new ExpressionEvaluationContext(null, variables, expressionDesc, task, result); @@ -472,21 +472,21 @@ private outputTriple = expression.evaluate(context); LOGGER.trace("output triple: {}", outputTriple.debugDump()); Collection pvalues = outputTriple.getNonNegativeValues(); - + // Maybe not really clean but it works. TODO: refactor later NameItemPathSegment first = (NameItemPathSegment)targetPath.first(); if (first.isVariable()) { targetPath = targetPath.rest(); } - + ItemDelta itemDelta = propOutputDefinition.createEmptyDelta(targetPath); itemDelta.addValuesToAdd(PrismValue.cloneCollection(pvalues)); - + LOGGER.trace("Item delta:\n{}", itemDelta.debugDump()); - + return itemDelta; } - + // Override the default in this case. It makes more sense like this. @Override protected Boolean isIncludeNullInputs() { diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AbstractValueTransformationExpressionEvaluator.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AbstractValueTransformationExpressionEvaluator.java index 4dbf1246aa5..799aaad1b7b 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AbstractValueTransformationExpressionEvaluator.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AbstractValueTransformationExpressionEvaluator.java @@ -63,7 +63,7 @@ public abstract class AbstractValueTransformationExpressionEvaluator evaluate(ExpressionEvaluationContext context) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException { - + PrismValueDeltaSetTriple outputTriple; if (expressionEvaluatorType.getRelativityMode() == TransformExpressionRelativityModeType.ABSOLUTE) { - + outputTriple = evaluateAbsoluteExpression(context.getSources(), context.getVariables(), context, context.getContextDescription(), context.getTask(), context.getResult()); - + } else if (expressionEvaluatorType.getRelativityMode() == null || expressionEvaluatorType.getRelativityMode() == TransformExpressionRelativityModeType.RELATIVE) { - + if (context.getSources() == null || context.getSources().isEmpty()) { // Special case. No sources, so there will be no input variables and no combinations. Everything goes to zero set. - outputTriple = evaluateAbsoluteExpression(null, context.getVariables(), context, + outputTriple = evaluateAbsoluteExpression(null, context.getVariables(), context, context.getContextDescription(), context.getTask(), context.getResult()); } else { List> sourceTriples = processSources(context.getSources(), isIncludeNullInputs(), context); - outputTriple = evaluateRelativeExpression(sourceTriples, context.getVariables(), context.isSkipEvaluationMinus(), context.isSkipEvaluationPlus(), + outputTriple = evaluateRelativeExpression(sourceTriples, context.getVariables(), context.isSkipEvaluationMinus(), context.isSkipEvaluationPlus(), isIncludeNullInputs(), context, context.getContextDescription(), context.getTask(), context.getResult()); } - + } else { throw new IllegalArgumentException("Unknown relativity mode "+expressionEvaluatorType.getRelativityMode()); } - - - return outputTriple; + + + return outputTriple; } - + protected Boolean isIncludeNullInputs() { return expressionEvaluatorType.isIncludeNullInputs(); } @@ -117,10 +117,10 @@ protected Boolean isIncludeNullInputs() { protected boolean isRelative() { return expressionEvaluatorType.getRelativityMode() != TransformExpressionRelativityModeType.ABSOLUTE; } - + private List> processSources(Collection> sources, Boolean includeNulls, ExpressionEvaluationContext params) { - List> sourceTriples = + List> sourceTriples = new ArrayList>(sources == null ? 0 : sources.size()); if (sources == null) { return sourceTriples; @@ -143,7 +143,7 @@ private List> processSources(Collection> sources, Item itemOld = source.getItemOld(); Item itemNew = source.getItemNew(); if (itemOld == null || itemOld.isEmpty()) { - if (!(itemNew == null || itemNew.isEmpty())) { + if (!(itemNew == null || itemNew.isEmpty())) { // change empty -> non-empty: we are removing "null" value sourceTriple.addToMinusSet(null); } else if (sourceTriple.hasMinusSet()) { @@ -171,11 +171,11 @@ private List> processSources(Collection> sources, private PrismValueDeltaSetTriple evaluateAbsoluteExpression(Collection> sources, ExpressionVariables variables, ExpressionEvaluationContext params, String contextDescription, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException { - + PrismValueDeltaSetTriple outputTriple; - + if (hasDeltas(sources) || hasDeltas(variables)) { - + Collection outputSetOld = null; if (!params.isSkipEvaluationMinus()) { outputSetOld = evaluateScriptExpression(sources, variables, contextDescription, false, params, task, result); @@ -184,19 +184,19 @@ private PrismValueDeltaSetTriple evaluateAbsoluteExpression(Collection outputSetNew = evaluateScriptExpression(sources, variables, contextDescription, true, params, task, result); outputTriple = new PrismValueDeltaSetTriple(); outputTriple.addAllToZeroSet(outputSetNew); } - + return outputTriple; } - + private boolean hasDeltas(Collection> sources) { if (sources == null) { return false; @@ -226,16 +226,16 @@ private boolean hasDeltas(ExpressionVariables variables) { } private Collection evaluateScriptExpression(Collection> sources, - ExpressionVariables variables, String contextDescription, boolean useNew, ExpressionEvaluationContext params, + ExpressionVariables variables, String contextDescription, boolean useNew, ExpressionEvaluationContext params, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException { - + ExpressionVariables scriptVariables = new ExpressionVariables(); if (useNew) { scriptVariables.addVariableDefinitionsNew(variables); } else { scriptVariables.addVariableDefinitionsOld(variables); } - + if (sources != null) { // Add sources to variables for (Source source: sources) { @@ -248,7 +248,7 @@ private Collection evaluateScriptExpression(Collection> sources, throw new ExpressionSyntaxException("No name definition for source in "+contextDescription); } } - + Object value = null; if (useNew) { value = getRealContent(source.getItemNew(), source.getResidualPath()); @@ -261,11 +261,11 @@ private Collection evaluateScriptExpression(Collection> sources, List scriptResults = transformSingleValue(scriptVariables, null, useNew, params, (useNew ? "(new) " : "(old) " ) + contextDescription, task, result); - + if (scriptResults == null || scriptResults.isEmpty()) { return null; } - + Collection outputSet = new ArrayList(scriptResults.size()); for (V pval: scriptResults) { if (pval instanceof PrismPropertyValue) { @@ -286,7 +286,7 @@ private Collection evaluateScriptExpression(Collection> sources, } outputSet.add(pval); } - + return outputSet; } @@ -303,7 +303,7 @@ private Object getRealContent(Item item, ItemPath residualPath) { } return item.find(residualPath); } - + private Object getRealContent(PrismValue pval, ItemPath residualPath) { if (residualPath == null || residualPath.isEmpty()) { return pval; @@ -315,11 +315,11 @@ private Object getRealContent(PrismValue pval, ItemPath residualPath) { } private PrismValueDeltaSetTriple evaluateRelativeExpression(final List> sourceTriples, - final ExpressionVariables variables, final boolean skipEvaluationMinus, final boolean skipEvaluationPlus, + final ExpressionVariables variables, final boolean skipEvaluationMinus, final boolean skipEvaluationPlus, final Boolean includeNulls, final ExpressionEvaluationContext evaluationContext, final String contextDescription, - final Task task, final OperationResult result) + final Task task, final OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException { - + List> valueCollections = new ArrayList<>(sourceTriples.size()); for (SourceTriple sourceTriple: sourceTriples) { Collection values = sourceTriple.union(); @@ -330,9 +330,9 @@ private PrismValueDeltaSetTriple evaluateRelativeExpression(final List outputTriple = new PrismValueDeltaSetTriple<>(); - + Processor> processor = pvalues -> { if (includeNulls != null && !includeNulls && MiscUtil.isAllNull(pvalues)) { // The case that all the sources are null. There is no point executing the expression. @@ -436,12 +436,12 @@ private PrismValueDeltaSetTriple evaluateRelativeExpression(final List triple) { if (triple == null) { return; @@ -475,11 +475,11 @@ private String dumpSourceValues(Map variables) { } return sb.toString(); } - + /* (non-Javadoc) * @see com.evolveum.midpoint.common.expression.ExpressionEvaluator#shortDebugDump() */ @Override public abstract String shortDebugDump(); - + } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssignmentTargetSearchExpressionEvaluator.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssignmentTargetSearchExpressionEvaluator.java index 584aec9177d..55c388caabc 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssignmentTargetSearchExpressionEvaluator.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssignmentTargetSearchExpressionEvaluator.java @@ -42,28 +42,28 @@ /** * @author Radovan Semancik */ -public class AssignmentTargetSearchExpressionEvaluator +public class AssignmentTargetSearchExpressionEvaluator extends AbstractSearchExpressionEvaluator, PrismContainerDefinition> { - + private static final Trace LOGGER = TraceManager.getTrace(AssignmentTargetSearchExpressionEvaluator.class); - - public AssignmentTargetSearchExpressionEvaluator(SearchObjectRefExpressionEvaluatorType expressionEvaluatorType, - PrismContainerDefinition outputDefinition, Protector protector, ObjectResolver objectResolver, + + public AssignmentTargetSearchExpressionEvaluator(SearchObjectRefExpressionEvaluatorType expressionEvaluatorType, + PrismContainerDefinition outputDefinition, Protector protector, ObjectResolver objectResolver, ModelService modelService, PrismContext prismContext, SecurityEnforcer securityEnforcer) { super(expressionEvaluatorType, outputDefinition, protector, objectResolver, modelService, prismContext, securityEnforcer); } - + protected PrismContainerValue createPrismValue(String oid, QName targetTypeQName, List, PrismContainerDefinition>> additionalAttributeDeltas, ExpressionEvaluationContext params) { AssignmentType assignmentType = new AssignmentType(); PrismContainerValue assignmentCVal = assignmentType.asPrismContainerValue(); - + ObjectReferenceType targetRef = new ObjectReferenceType(); targetRef.setOid(oid); targetRef.setType(targetTypeQName); targetRef.setRelation(((SearchObjectRefExpressionEvaluatorType)getExpressionEvaluatorType()).getRelation()); assignmentType.setTargetRef(targetRef); - + try { if (additionalAttributeDeltas != null) { ItemDelta.applyTo(additionalAttributeDeltas, assignmentCVal); @@ -76,7 +76,7 @@ protected PrismContainerValue createPrismValue(String oid, QName // Should not happen throw new SystemException(e); } - + return assignmentCVal; } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssignmentTargetSearchExpressionEvaluatorFactory.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssignmentTargetSearchExpressionEvaluatorFactory.java index 35392244cf9..8377b05d8d3 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssignmentTargetSearchExpressionEvaluatorFactory.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssignmentTargetSearchExpressionEvaluatorFactory.java @@ -44,7 +44,7 @@ * */ public class AssignmentTargetSearchExpressionEvaluatorFactory implements ExpressionEvaluatorFactory { - + private PrismContext prismContext; private Protector protector; private ObjectResolver objectResolver; @@ -87,7 +87,7 @@ public ExpressionEvaluator } evaluatorElement = evaluatorElements.iterator().next(); } - + Object evaluatorTypeObject = null; if (evaluatorElement != null) { evaluatorTypeObject = evaluatorElement.getValue(); @@ -95,7 +95,7 @@ public ExpressionEvaluator if (evaluatorTypeObject != null && !(evaluatorTypeObject instanceof SearchObjectRefExpressionEvaluatorType)) { throw new SchemaException("assignment expression evaluator cannot handle elements of type " + evaluatorTypeObject.getClass().getName()+" in "+contextDescription); } - AssignmentTargetSearchExpressionEvaluator expressionEvaluator = new AssignmentTargetSearchExpressionEvaluator((SearchObjectRefExpressionEvaluatorType)evaluatorTypeObject, + AssignmentTargetSearchExpressionEvaluator expressionEvaluator = new AssignmentTargetSearchExpressionEvaluator((SearchObjectRefExpressionEvaluatorType)evaluatorTypeObject, (PrismContainerDefinition) outputDefinition, protector, objectResolver, modelService, prismContext, securityEnforcer); return (ExpressionEvaluator) expressionEvaluator; } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssociationFromLinkExpressionEvaluator.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssociationFromLinkExpressionEvaluator.java index 4d5fea4b8b8..fdc62bf87d3 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssociationFromLinkExpressionEvaluator.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssociationFromLinkExpressionEvaluator.java @@ -51,10 +51,10 @@ * @author Radovan Semancik * */ -public class AssociationFromLinkExpressionEvaluator +public class AssociationFromLinkExpressionEvaluator implements ExpressionEvaluator, PrismContainerDefinition> { - + private static final Trace LOGGER = TraceManager.getTrace(AssociationFromLinkExpressionEvaluator.class); private AssociationFromLinkExpressionEvaluatorType evaluatorType; @@ -62,7 +62,7 @@ public class AssociationFromLinkExpressionEvaluator private ObjectResolver objectResolver; private PrismContext prismContext; - AssociationFromLinkExpressionEvaluator(AssociationFromLinkExpressionEvaluatorType evaluatorType, + AssociationFromLinkExpressionEvaluator(AssociationFromLinkExpressionEvaluatorType evaluatorType, PrismContainerDefinition outputDefinition, ObjectResolver objectResolver, PrismContext prismContext) { this.evaluatorType = evaluatorType; this.outputDefinition = outputDefinition; @@ -76,7 +76,7 @@ public class AssociationFromLinkExpressionEvaluator @Override public PrismValueDeltaSetTriple> evaluate(ExpressionEvaluationContext context) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException { - + String desc = context.getContextDescription(); Object orderOneObject = context.getVariables().get(ExpressionConstants.VAR_ORDER_ONE_OBJECT); if (orderOneObject == null) { @@ -87,14 +87,14 @@ public PrismValueDeltaSetTriple> eval +"; the expression may be used in a wrong place. It is only supposed to work in a role."); } AbstractRoleType thisRole = (AbstractRoleType)orderOneObject; - - LOGGER.trace("Evaluating association from link on: {}", thisRole); - + + LOGGER.trace("Evaluating association from link on: {}", thisRole); + RefinedObjectClassDefinition rAssocTargetDef = (RefinedObjectClassDefinition) context.getVariables().get(ExpressionConstants.VAR_ASSOCIATION_TARGET_OBJECT_CLASS_DEFINITION); if (rAssocTargetDef == null) { throw new ExpressionEvaluationException("No association target object class definition variable in "+desc+"; the expression may be used in a wrong place. It is only supposed to create an association."); - } - + } + ShadowDiscriminatorType projectionDiscriminator = evaluatorType.getProjectionDiscriminator(); if (projectionDiscriminator == null) { throw new ExpressionEvaluationException("No projectionDiscriminator in "+desc); @@ -104,21 +104,21 @@ public PrismValueDeltaSetTriple> eval throw new ExpressionEvaluationException("No kind in projectionDiscriminator in "+desc); } String intent = projectionDiscriminator.getIntent(); - + PrismContainer output = outputDefinition.instantiate(); - + QName assocName = context.getMappingQName(); String resourceOid = rAssocTargetDef.getResourceOid(); Collection> options = null; - + // Always process the first role (myself) regardless of recursion setting gatherAssociationsFromAbstractRole(thisRole, output, resourceOid, kind, intent, assocName, options, desc, context); - + if (thisRole instanceof OrgType && matchesForRecursion((OrgType)thisRole)) { gatherAssociationsFromAbstractRoleRecurse((OrgType)thisRole, output, resourceOid, kind, intent, assocName, options, desc, context); } - + return ItemDelta.toDeltaSetTriple(output, null); } @@ -146,14 +146,14 @@ private void gatherAssociationsFromAbstractRole(AbstractRoleType thisRole, } } } - + private void gatherAssociationsFromAbstractRoleRecurse(OrgType thisOrg, PrismContainer output, String resourceOid, ShadowKindType kind, String intent, QName assocName, Collection> options, String desc, ExpressionEvaluationContext params) throws SchemaException, ObjectNotFoundException { - + gatherAssociationsFromAbstractRole(thisOrg, output, resourceOid, kind, intent, assocName, options, desc, params); - + for (ObjectReferenceType parentOrgRef: thisOrg.getParentOrgRef()) { OrgType parent = objectResolver.resolve(parentOrgRef, OrgType.class, options, desc, params.getTask(), params.getResult()); if (matchesForRecursion(parent)) { @@ -161,7 +161,7 @@ private void gatherAssociationsFromAbstractRoleRecurse(OrgType thisOrg, } } } - + private boolean matchesForRecursion(OrgType thisOrg) { for (String recurseUpOrgType: evaluatorType.getRecurseUpOrgType()) { thisOrg.getOrgType().contains(recurseUpOrgType); diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssociationFromLinkExpressionEvaluatorFactory.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssociationFromLinkExpressionEvaluatorFactory.java index 03bb90bd9d2..94258c55432 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssociationFromLinkExpressionEvaluatorFactory.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssociationFromLinkExpressionEvaluatorFactory.java @@ -42,7 +42,7 @@ * */ public class AssociationFromLinkExpressionEvaluatorFactory implements ExpressionEvaluatorFactory { - + private PrismContext prismContext; private Protector protector; private ObjectResolver objectResolver; @@ -75,7 +75,7 @@ public ExpressionEvaluator D outputDefinition, String contextDescription, Task task, OperationResult result) throws SchemaException { Validate.notNull(outputDefinition, "output definition must be specified for associationFromLink expression evaluator"); - + JAXBElement evaluatorElement = null; if (evaluatorElements != null) { if (evaluatorElements.size() > 1) { @@ -83,7 +83,7 @@ public ExpressionEvaluator } evaluatorElement = evaluatorElements.iterator().next(); } - + Object evaluatorTypeObject = null; if (evaluatorElement != null) { evaluatorTypeObject = evaluatorElement.getValue(); @@ -92,7 +92,7 @@ public ExpressionEvaluator throw new SchemaException("Association expression evaluator cannot handle elements of type " + evaluatorTypeObject.getClass().getName()+" in "+contextDescription); } AssociationFromLinkExpressionEvaluator evaluator = new AssociationFromLinkExpressionEvaluator( - (AssociationFromLinkExpressionEvaluatorType)evaluatorTypeObject, + (AssociationFromLinkExpressionEvaluatorType)evaluatorTypeObject, (PrismContainerDefinition) outputDefinition, objectResolver, prismContext); return (ExpressionEvaluator) evaluator; } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssociationTargetSearchExpressionEvaluator.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssociationTargetSearchExpressionEvaluator.java index dfdfd02a2ac..7c41fd15927 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssociationTargetSearchExpressionEvaluator.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssociationTargetSearchExpressionEvaluator.java @@ -54,14 +54,14 @@ /** * @author Radovan Semancik */ -public class AssociationTargetSearchExpressionEvaluator +public class AssociationTargetSearchExpressionEvaluator extends AbstractSearchExpressionEvaluator, PrismContainerDefinition> { - + private static final Trace LOGGER = TraceManager.getTrace(AssociationTargetSearchExpressionEvaluator.class); - - public AssociationTargetSearchExpressionEvaluator(SearchObjectExpressionEvaluatorType expressionEvaluatorType, - PrismContainerDefinition outputDefinition, Protector protector, ObjectResolver objectResolver, + + public AssociationTargetSearchExpressionEvaluator(SearchObjectExpressionEvaluatorType expressionEvaluatorType, + PrismContainerDefinition outputDefinition, Protector protector, ObjectResolver objectResolver, ModelService modelService, PrismContext prismContext, SecurityEnforcer securityEnforcer) { super(expressionEvaluatorType, outputDefinition, protector, objectResolver, modelService, prismContext, securityEnforcer); } @@ -77,7 +77,7 @@ protected ObjectQuery extendQuery(ObjectQuery query, ExpressionEvaluationContext if (rAssocTargetDef == null) { throw new ExpressionEvaluationException("No association target object class definition variable in "+ params.getContextDescription()+"; the expression may be used in a wrong place. It is only supposed to create an association."); - } + } ObjectFilter resourceFilter = ObjectQueryUtil.createResourceFilter(rAssocTargetDef.getResourceOid(), getPrismContext()); ObjectFilter objectClassFilter = ObjectQueryUtil.createObjectClassFilter(rAssocTargetDef.getObjectClassDefinition().getTypeName(), getPrismContext()); @@ -85,7 +85,7 @@ protected ObjectQuery extendQuery(ObjectQuery query, ExpressionEvaluationContext query.setFilter(extendedFilter); return query; } - + @Override protected void extendOptions(Collection> options, boolean searchOnResource) { @@ -103,13 +103,13 @@ protected PrismContainerValue createPrismValue(String oid targetRef.setOid(oid); targetRef.setType(targetTypeQName); associationType.setShadowRef(targetRef); - + try { - + if (additionalAttributeDeltas != null) { ItemDelta.applyTo(additionalAttributeDeltas, associationCVal); } - + getPrismContext().adopt(associationCVal, ShadowType.COMPLEX_TYPE, new ItemPath(ShadowType.F_ASSOCIATION)); if (InternalsConfig.consistencyChecks) { associationCVal.assertDefinitions("associationCVal in assignment expression in "+params.getContextDescription()); @@ -118,10 +118,10 @@ protected PrismContainerValue createPrismValue(String oid // Should not happen throw new SystemException(e); } - + return associationCVal; } - + @Override protected QName getDefaultTargetType() { return ShadowType.COMPLEX_TYPE; diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssociationTargetSearchExpressionEvaluatorFactory.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssociationTargetSearchExpressionEvaluatorFactory.java index 68a0c955277..64d82bde1a8 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssociationTargetSearchExpressionEvaluatorFactory.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/AssociationTargetSearchExpressionEvaluatorFactory.java @@ -44,7 +44,7 @@ * */ public class AssociationTargetSearchExpressionEvaluatorFactory implements ExpressionEvaluatorFactory { - + private PrismContext prismContext; private Protector protector; private ObjectResolver objectResolver; @@ -79,7 +79,7 @@ public ExpressionEvaluator D outputDefinition, String contextDescription, Task task, OperationResult result) throws SchemaException { Validate.notNull(outputDefinition, "output definition must be specified for associationTargetSearch expression evaluator"); - + JAXBElement evaluatorElement = null; if (evaluatorElements != null) { if (evaluatorElements.size() > 1) { @@ -87,7 +87,7 @@ public ExpressionEvaluator } evaluatorElement = evaluatorElements.iterator().next(); } - + Object evaluatorTypeObject = null; if (evaluatorElement != null) { evaluatorTypeObject = evaluatorElement.getValue(); @@ -95,7 +95,7 @@ public ExpressionEvaluator if (evaluatorTypeObject != null && !(evaluatorTypeObject instanceof SearchObjectExpressionEvaluatorType)) { throw new SchemaException("Association expression evaluator cannot handle elements of type " + evaluatorTypeObject.getClass().getName()+" in "+contextDescription); } - AssociationTargetSearchExpressionEvaluator evaluator = new AssociationTargetSearchExpressionEvaluator((SearchObjectExpressionEvaluatorType)evaluatorTypeObject, + AssociationTargetSearchExpressionEvaluator evaluator = new AssociationTargetSearchExpressionEvaluator((SearchObjectExpressionEvaluatorType)evaluatorTypeObject, (PrismContainerDefinition) outputDefinition, protector, objectResolver, modelService, prismContext, securityEnforcer); return (ExpressionEvaluator) evaluator; } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/ConstExpressionEvaluator.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/ConstExpressionEvaluator.java index 937999cf023..bff95461514 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/ConstExpressionEvaluator.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/ConstExpressionEvaluator.java @@ -57,7 +57,7 @@ public class ConstExpressionEvaluator evaluate(ExpressionEvaluationContext context) String constName = constEvaluatorType.getValue(); String stringValue = constantsManager.getConstantValue(constName); - + Item output = outputDefinition.instantiate(); Object value = ExpressionUtil.convertToOutputValue(stringValue, outputDefinition, protector); - + if (output instanceof PrismProperty) { PrismPropertyValue pValue = new PrismPropertyValue(value); ((PrismProperty) output).add(pValue); @@ -87,7 +87,7 @@ public PrismValueDeltaSetTriple evaluate(ExpressionEvaluationContext context) /* * (non-Javadoc) - * + * * @see com.evolveum.midpoint.common.expression.ExpressionEvaluator# * shortDebugDump() */ diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/ConstExpressionEvaluatorFactory.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/ConstExpressionEvaluatorFactory.java index b70d111d3fc..e80d26095c2 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/ConstExpressionEvaluatorFactory.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/ConstExpressionEvaluatorFactory.java @@ -41,7 +41,7 @@ * */ public class ConstExpressionEvaluatorFactory implements ExpressionEvaluatorFactory { - + private Protector protector; private ConstantsManager constantsManager; private PrismContext prismContext; @@ -67,20 +67,20 @@ public ExpressionEvaluator throws SchemaException, ObjectNotFoundException { Validate.notNull(outputDefinition, "output definition must be specified for 'generate' expression evaluator"); - + Validate.notNull(outputDefinition, "output definition must be specified for path expression evaluator"); - + if (evaluatorElements.size() > 1) { throw new SchemaException("More than one evaluator specified in "+contextDescription); } JAXBElement evaluatorElement = evaluatorElements.iterator().next(); - + Object evaluatorElementObject = evaluatorElement.getValue(); if (!(evaluatorElementObject instanceof ConstExpressionEvaluatorType)) { - throw new IllegalArgumentException("Const expression cannot handle elements of type " + throw new IllegalArgumentException("Const expression cannot handle elements of type " + evaluatorElementObject.getClass().getName()+" in "+contextDescription); } - + return new ConstExpressionEvaluator((ConstExpressionEvaluatorType)evaluatorElementObject, outputDefinition, protector, constantsManager, prismContext); } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/GenerateExpressionEvaluator.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/GenerateExpressionEvaluator.java index c9f20092510..d1130a851b2 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/GenerateExpressionEvaluator.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/GenerateExpressionEvaluator.java @@ -88,7 +88,7 @@ private boolean isNotEmptyMinLength(StringPolicyType policy) { /* * (non-Javadoc) - * + * * @see * com.evolveum.midpoint.common.expression.ExpressionEvaluator#evaluate(java * .util.Collection, java.util.Map, boolean, java.lang.String, @@ -100,7 +100,7 @@ public PrismValueDeltaSetTriple evaluate(ExpressionEvaluationContext context) StringPolicyType stringPolicyType = null; - + ObjectReferenceType generateEvaluatorValuePolicyRef = generateEvaluatorType.getValuePolicyRef(); if (generateEvaluatorValuePolicyRef != null) { if (generateEvaluatorType.getValuePolicyRef() != null) { @@ -108,7 +108,7 @@ public PrismValueDeltaSetTriple evaluate(ExpressionEvaluationContext context) null, "resolving value policy reference in generateExpressionEvaluator", context.getTask(), context.getResult()); stringPolicyType = valuePolicyType.getStringPolicy(); } - + } // if (elementStringPolicy == null) { @@ -122,7 +122,7 @@ public PrismValueDeltaSetTriple evaluate(ExpressionEvaluationContext context) stringPolicyType = stringPolicyResolver.resolve(); } } - + elementStringPolicy = stringPolicyType; // } else { // stringPolicyType = elementStringPolicy; @@ -168,7 +168,7 @@ public PrismValueDeltaSetTriple evaluate(ExpressionEvaluationContext context) Object value = ExpressionUtil.convertToOutputValue(stringValue, outputDefinition, protector); - + if (output instanceof PrismProperty) { PrismPropertyValue pValue = new PrismPropertyValue(value); ((PrismProperty) output).add(pValue); @@ -197,7 +197,7 @@ private PrismObject getObject(ExpressionEvaluationCont /* * (non-Javadoc) - * + * * @see com.evolveum.midpoint.common.expression.ExpressionEvaluator# * shortDebugDump() */ diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/GenerateExpressionEvaluatorFactory.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/GenerateExpressionEvaluatorFactory.java index 74a84f22470..2830b942955 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/GenerateExpressionEvaluatorFactory.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/GenerateExpressionEvaluatorFactory.java @@ -42,7 +42,7 @@ * */ public class GenerateExpressionEvaluatorFactory implements ExpressionEvaluatorFactory { - + private Protector protector; private PrismContext prismContext; private ObjectResolver objectResolver; @@ -73,12 +73,12 @@ public ExpressionEvaluator throws SchemaException, ObjectNotFoundException { Validate.notNull(outputDefinition, "output definition must be specified for 'generate' expression evaluator"); - + if (evaluatorElements.size() > 1) { throw new SchemaException("More than one evaluator specified in "+contextDescription); } JAXBElement evaluatorElement = evaluatorElements.iterator().next(); - + Object evaluatorTypeObject = null; if (evaluatorElement != null) { evaluatorTypeObject = evaluatorElement.getValue(); @@ -86,9 +86,9 @@ public ExpressionEvaluator if (evaluatorTypeObject != null && !(evaluatorTypeObject instanceof GenerateExpressionEvaluatorType)) { throw new SchemaException("Generate expression evaluator cannot handle elements of type " + evaluatorTypeObject.getClass().getName()+" in "+contextDescription); } - + GenerateExpressionEvaluatorType generateEvaluatorType = (GenerateExpressionEvaluatorType)evaluatorTypeObject; - + return new GenerateExpressionEvaluator(generateEvaluatorType, outputDefinition, protector, objectResolver, valuePolicyGenerator, prismContext); } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/PathExpressionEvaluator.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/PathExpressionEvaluator.java index 1e868fbb649..cd66ce2ffc2 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/PathExpressionEvaluator.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/PathExpressionEvaluator.java @@ -46,14 +46,14 @@ * @author Radovan Semancik */ public class PathExpressionEvaluator implements ExpressionEvaluator { - + private ItemPath path; private ObjectResolver objectResolver; private PrismContext prismContext; private D outputDefinition; private Protector protector; - - public PathExpressionEvaluator(ItemPath path, ObjectResolver objectResolver, + + public PathExpressionEvaluator(ItemPath path, ObjectResolver objectResolver, D outputDefinition, Protector protector, PrismContext prismContext) { this.path = path; this.objectResolver = objectResolver; @@ -70,7 +70,7 @@ public PrismValueDeltaSetTriple evaluate(ExpressionEvaluationContext context) ExpressionEvaluationException, ObjectNotFoundException { ItemDeltaItem resolveContext = null; - + if (context.getSources() != null && context.getSources().size() == 1) { Source source = context.getSources().iterator().next(); if (path.isEmpty()) { @@ -79,7 +79,7 @@ public PrismValueDeltaSetTriple evaluate(ExpressionEvaluationContext context) } resolveContext = source; } - + Map variablesAndSources = ExpressionUtil.compileVariablesAndSources(context); ItemPath resolvePath = path; @@ -95,12 +95,12 @@ public PrismValueDeltaSetTriple evaluate(ExpressionEvaluationContext context) } else { throw new ExpressionEvaluationException("No variable with name "+variableName+" in "+ context.getContextDescription()); } - + if (variableValue == null) { return null; } if (variableValue instanceof Item || variableValue instanceof ItemDeltaItem) { - resolveContext = ExpressionUtil.toItemDeltaItem(variableValue, objectResolver, + resolveContext = ExpressionUtil.toItemDeltaItem(variableValue, objectResolver, "path expression in "+ context.getContextDescription(), context.getResult()); } else if (variableValue instanceof PrismPropertyValue){ PrismValueDeltaSetTriple outputTriple = new PrismValueDeltaSetTriple<>(); @@ -109,14 +109,14 @@ public PrismValueDeltaSetTriple evaluate(ExpressionEvaluationContext context) } else { throw new ExpressionEvaluationException("Unexpected variable value "+variableValue+" ("+variableValue.getClass()+")"); } - + resolvePath = path.rest(); } - + if (resolveContext == null) { return null; } - + while (!resolvePath.isEmpty()) { if (resolveContext.isContainer()) { resolveContext = resolveContext.findIdi(resolvePath.head()); @@ -136,14 +136,14 @@ public PrismValueDeltaSetTriple evaluate(ExpressionEvaluationContext context) throw new ExpressionEvaluationException("Cannot resolve path "+resolvePath+" on "+resolveContext+" in "+ context.getContextDescription()); } } - - PrismValueDeltaSetTriple outputTriple = ItemDelta.toDeltaSetTriple((Item)resolveContext.getItemOld(), + + PrismValueDeltaSetTriple outputTriple = ItemDelta.toDeltaSetTriple((Item)resolveContext.getItemOld(), (ItemDelta)resolveContext.getDelta()); - + if (outputTriple == null) { return null; } - + return ExpressionUtil.toOutputTriple(outputTriple, outputDefinition, context.getAdditionalConvertor(), null, protector, prismContext); } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/PathExpressionEvaluatorFactory.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/PathExpressionEvaluatorFactory.java index 5a3a02a8e05..d88db5afa23 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/PathExpressionEvaluatorFactory.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/PathExpressionEvaluatorFactory.java @@ -41,7 +41,7 @@ * */ public class PathExpressionEvaluatorFactory implements ExpressionEvaluatorFactory { - + private PrismContext prismContext; private ObjectResolver objectResolver; private Protector protector; @@ -69,21 +69,21 @@ public ExpressionEvaluator D outputDefinition, String contextDescription, Task task, OperationResult result) throws SchemaException { Validate.notNull(outputDefinition, "output definition must be specified for path expression evaluator"); - + if (evaluatorElements.size() > 1) { throw new SchemaException("More than one evaluator specified in "+contextDescription); } JAXBElement evaluatorElement = evaluatorElements.iterator().next(); - + Object evaluatorElementObject = evaluatorElement.getValue(); if (!(evaluatorElementObject instanceof ItemPathType)) { - throw new IllegalArgumentException("Path expression cannot handle elements of type " + throw new IllegalArgumentException("Path expression cannot handle elements of type " + evaluatorElementObject.getClass().getName()+" in "+contextDescription); } ItemPath path = ((ItemPathType)evaluatorElementObject).getItemPath(); - + return new PathExpressionEvaluator<>(path, objectResolver, outputDefinition, protector, prismContext); - + } } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/ReferenceSearchExpressionEvaluator.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/ReferenceSearchExpressionEvaluator.java index 77aadb05012..c345bf5f355 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/ReferenceSearchExpressionEvaluator.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/ReferenceSearchExpressionEvaluator.java @@ -35,24 +35,24 @@ /** * @author Radovan Semancik */ -public class ReferenceSearchExpressionEvaluator +public class ReferenceSearchExpressionEvaluator extends AbstractSearchExpressionEvaluator { - + private static final Trace LOGGER = TraceManager.getTrace(ReferenceSearchExpressionEvaluator.class); - - public ReferenceSearchExpressionEvaluator(SearchObjectRefExpressionEvaluatorType expressionEvaluatorType, - PrismReferenceDefinition outputDefinition, Protector protector, ObjectResolver objectResolver, + + public ReferenceSearchExpressionEvaluator(SearchObjectRefExpressionEvaluatorType expressionEvaluatorType, + PrismReferenceDefinition outputDefinition, Protector protector, ObjectResolver objectResolver, ModelService modelService, PrismContext prismContext, SecurityEnforcer securityEnforcer) { super(expressionEvaluatorType, outputDefinition, protector, objectResolver, modelService, prismContext, securityEnforcer); } - + protected PrismReferenceValue createPrismValue(String oid, QName targetTypeQName, List> additionalAttributeValues, ExpressionEvaluationContext params) { PrismReferenceValue refVal = new PrismReferenceValue(); - + refVal.setOid(oid); refVal.setTargetType(targetTypeQName); refVal.setRelation(((SearchObjectRefExpressionEvaluatorType)getExpressionEvaluatorType()).getRelation()); - + return refVal; } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/ReferenceSearchExpressionEvaluatorFactory.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/ReferenceSearchExpressionEvaluatorFactory.java index 439b767597b..622327abcb3 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/ReferenceSearchExpressionEvaluatorFactory.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/evaluator/ReferenceSearchExpressionEvaluatorFactory.java @@ -43,7 +43,7 @@ * */ public class ReferenceSearchExpressionEvaluatorFactory implements ExpressionEvaluatorFactory { - + private PrismContext prismContext; private Protector protector; private ObjectResolver objectResolver; @@ -86,7 +86,7 @@ public ExpressionEvaluator } evaluatorElement = evaluatorElements.iterator().next(); } - + Object evaluatorTypeObject = null; if (evaluatorElement != null) { evaluatorTypeObject = evaluatorElement.getValue(); @@ -94,7 +94,7 @@ public ExpressionEvaluator if (evaluatorTypeObject != null && !(evaluatorTypeObject instanceof SearchObjectRefExpressionEvaluatorType)) { throw new SchemaException("reference search expression evaluator cannot handle elements of type " + evaluatorTypeObject.getClass().getName()+" in "+contextDescription); } - ReferenceSearchExpressionEvaluator expressionEvaluator = new ReferenceSearchExpressionEvaluator((SearchObjectRefExpressionEvaluatorType)evaluatorTypeObject, + ReferenceSearchExpressionEvaluator expressionEvaluator = new ReferenceSearchExpressionEvaluator((SearchObjectRefExpressionEvaluatorType)evaluatorTypeObject, (PrismReferenceDefinition) outputDefinition, protector, objectResolver, modelService, prismContext, securityEnforcer); return (ExpressionEvaluator) expressionEvaluator; } 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 41aa2a2a5d0..832f5fc8970 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 @@ -71,23 +71,23 @@ /** * Library of standard midPoint functions. These functions are made available to all * midPoint expressions. - * + * * The functions should be written to support scripting-like comfort. It means that they all needs * to be null-safe, automatically convert data types as necessary and so on. - * + * * @author Radovan Semancik * */ public class BasicExpressionFunctions { - + public static final String NAME_SEPARATOR = " "; - + public static final Trace LOGGER = TraceManager.getTrace(BasicExpressionFunctions.class); - + private static String STRING_PATTERN_WHITESPACE = "\\s+"; private static String STRING_PATTERN_HONORIFIC_PREFIX_ENDS_WITH_DOT = "^(\\S+\\.)$"; private static Pattern PATTERN_NICK_NAME = Pattern.compile("^([^\"]*)\"([^\"]+)\"([^\"]*)$"); - + private PrismContext prismContext; private Protector protector; @@ -96,7 +96,7 @@ public BasicExpressionFunctions(PrismContext prismContext, Protector protector) this.prismContext = prismContext; this.protector = protector; } - + /** * Convert string to lower case. */ @@ -110,7 +110,7 @@ public static String lc(String orig) { public static String uc(String orig) { return StringUtils.upperCase(orig); } - + public boolean contains(Object object, Object search) { String objectStr = stringify(object); if (StringUtils.isEmpty(objectStr)) { @@ -122,7 +122,7 @@ public boolean contains(Object object, Object search) { } return objectStr.contains(searchStr); } - + public boolean containsIgnoreCase(Object object, Object search) { String objectStr = stringify(object); if (StringUtils.isEmpty(objectStr)) { @@ -134,7 +134,7 @@ public boolean containsIgnoreCase(Object object, Object search) { } return StringUtils.containsIgnoreCase(objectStr, searchStr); } - + /** * Remove whitespaces at the beginning and at the end of the string. */ @@ -182,7 +182,7 @@ public String concatName(Object... components) { /** * Normalize a string value. It follows the default normalization algorithm * used for PolyString values. - * + * * @param orig original value to normalize * @return normalized value */ @@ -194,10 +194,10 @@ public String norm(String orig) { polyString.recompute(prismContext.getDefaultPolyStringNormalizer()); return polyString.getNorm(); } - + /** * Normalize a PolyString value. - * + * * @param orig original value to normalize * @return normalized value */ @@ -214,7 +214,7 @@ public String norm(PolyString orig) { /** * Normalize a PolyStringType value. - * + * * @param orig original value to normalize * @return normalized value */ @@ -234,22 +234,22 @@ public String toAscii(Object input) { String decomposed = Normalizer.normalize(inputString, Normalizer.Form.NFKD); return decomposed.replaceAll("\\p{M}", ""); } - + /** * Converts whatever it gets to a string. But it does it in a sensitive way. - * E.g. it tries to detect collections and returns the first element (if there is only one). - * Never returns null. Returns empty string instead. + * E.g. it tries to detect collections and returns the first element (if there is only one). + * Never returns null. Returns empty string instead. */ public String stringify(Object whatever) { - + if (whatever == null) { return ""; } - + if (whatever instanceof String) { return (String)whatever; } - + if (whatever instanceof PolyString) { return ((PolyString)whatever).getOrig(); } @@ -257,7 +257,7 @@ public String stringify(Object whatever) { if (whatever instanceof PolyStringType) { return ((PolyStringType)whatever).getOrig(); } - + if (whatever instanceof Collection) { Collection collection = (Collection)whatever; if (collection.isEmpty()) { @@ -268,7 +268,7 @@ public String stringify(Object whatever) { } whatever = collection.iterator().next(); } - + Class whateverClass = whatever.getClass(); if (whateverClass.isArray()) { Object[] array = (Object[])whatever; @@ -280,15 +280,15 @@ public String stringify(Object whatever) { } whatever = array[0]; } - + if (whatever == null) { return ""; } - + if (whatever instanceof String) { return (String)whatever; } - + if (whatever instanceof PolyString) { return ((PolyString)whatever).getOrig(); } @@ -296,7 +296,7 @@ public String stringify(Object whatever) { if (whatever instanceof PolyStringType) { return ((PolyStringType)whatever).getOrig(); } - + if (whatever instanceof Element) { Element element = (Element)whatever; Element origElement = DOMUtil.getChildElement(element, PolyString.F_ORIG); @@ -307,19 +307,19 @@ public String stringify(Object whatever) { return element.getTextContent(); } } - + if (whatever instanceof Node) { return ((Node)whatever).getTextContent(); } return whatever.toString(); } - + public Collection getOids(Collection refs){ if (refs == null){ return null; } - + Collection oids = new ArrayList(); for (ObjectReferenceType ort : refs){ if (StringUtils.isNotBlank(ort.getOid())){ @@ -328,24 +328,24 @@ public Collection getOids(Collection refs){ oids.add(ort.asReferenceValue().getObject().getOid()); } } - + return oids; - + } - + public Collection getOids(ObjectReferenceType refs){ List refList = new ArrayList<>(); refList.add(refs); return getOids(refList); } - + public Collection getOids(ObjectType refs){ List oid = new ArrayList<>(); oid.add(refs.getOid()); return oid; - + } - + public boolean isEmpty(Object whatever) { if (whatever == null) { return true; @@ -362,32 +362,32 @@ public boolean isEmpty(Object whatever) { } return whateverString.isEmpty(); } - + public Collection getExtensionPropertyValues(ObjectType object, String namespace, String localPart) { return getExtensionPropertyValues(object, new javax.xml.namespace.QName(namespace, localPart)); } - + public Collection getExtensionPropertyValues(ObjectType object, groovy.xml.QName propertyQname) { return getExtensionPropertyValues(object, propertyQname.getNamespaceURI(), propertyQname.getLocalPart()); } - + public Collection getExtensionPropertyValues(ObjectType object, javax.xml.namespace.QName propertyQname) { return ObjectTypeUtil.getExtensionPropertyValuesNotNull(object, propertyQname); } - + public T getExtensionPropertyValue(ObjectType object, String namespace, String localPart) throws SchemaException { return getExtensionPropertyValue(object, new javax.xml.namespace.QName(namespace, localPart)); } - + public Referencable getExtensionReferenceValue(ObjectType object, String namespace, String localPart) throws SchemaException { return getExtensionReferenceValue(object, new javax.xml.namespace.QName(namespace, localPart)); } - + public T getExtensionPropertyValue(ObjectType object, groovy.xml.QName propertyQname) throws SchemaException { return getExtensionPropertyValue(object, propertyQname.getNamespaceURI(), propertyQname.getLocalPart()); } - + public T getExtensionPropertyValue(ObjectType object, javax.xml.namespace.QName propertyQname) throws SchemaException { if (object == null) { return null; @@ -395,7 +395,7 @@ public T getExtensionPropertyValue(ObjectType object, javax.xml.namespace.QN Collection values = ObjectTypeUtil.getExtensionPropertyValues(object, propertyQname); return toSingle(values, "a multi-valued extension property "+propertyQname); } - + public Referencable getExtensionReferenceValue(ObjectType object, javax.xml.namespace.QName propertyQname) throws SchemaException { if (object == null) { return null; @@ -403,12 +403,12 @@ public Referencable getExtensionReferenceValue(ObjectType object, javax.xml.name Collection values = ObjectTypeUtil.getExtensionReferenceValues(object, propertyQname); return toSingle(values, "a multi-valued extension property "+propertyQname); } - + public T getPropertyValue(ObjectType object, String path) throws SchemaException { Collection values = getPropertyValues(object, path); return toSingle(values, "a multi-valued property "+path); } - + public Collection getPropertyValues(ObjectType object, String path) { if (object == null) { return null; @@ -422,20 +422,20 @@ public Collection getPropertyValues(ObjectType object, String path) { } return property.getRealValues(); } - - + + public Collection getAttributeValues(ShadowType shadow, String attributeNamespace, String attributeLocalPart) { return getAttributeValues(shadow, new javax.xml.namespace.QName(attributeNamespace, attributeLocalPart)); } - + public Collection getAttributeValues(ShadowType shadow, String attributeLocalPart) { return getAttributeValues(shadow, new javax.xml.namespace.QName(MidPointConstants.NS_RI, attributeLocalPart)); } - + public Collection getAttributeValues(ShadowType shadow, groovy.xml.QName attributeQname) { return getAttributeValues(shadow, attributeQname.getNamespaceURI(), attributeQname.getLocalPart()); } - + public Collection getAttributeValues(ShadowType shadow, javax.xml.namespace.QName attributeQname) { return ShadowUtil.getAttributeValues(shadow, attributeQname); } @@ -451,23 +451,23 @@ public T getAttributeValue(ShadowType shadow, String attributeLocalPart) thr public T getAttributeValue(ShadowType shadow, groovy.xml.QName attributeQname) throws SchemaException { return getAttributeValue(shadow, attributeQname.getNamespaceURI(), attributeQname.getLocalPart()); } - + public T getAttributeValue(ShadowType shadow, javax.xml.namespace.QName attributeQname) throws SchemaException { return ShadowUtil.getAttributeValue(shadow, attributeQname); } - + public Collection getAttributeStringValues(ShadowType shadow, String attributeNamespace, String attributeLocalPart) { return getAttributeStringValues(shadow, new javax.xml.namespace.QName(attributeNamespace, attributeLocalPart)); } - + public Collection getAttributeStringValues(ShadowType shadow, groovy.xml.QName attributeQname) { return getAttributeStringValues(shadow, attributeQname.getNamespaceURI(), attributeQname.getLocalPart()); } - + public Collection getAttributeStringValues(ShadowType shadow, javax.xml.namespace.QName attributeQname) { return ShadowUtil.getAttributeValues(shadow, attributeQname, String.class); } - + public T getIdentifierValue(ShadowType shadow) throws SchemaException { if (shadow == null) { return null; @@ -513,7 +513,7 @@ public T getSecondaryIdentifierValue(ShadowType shadow) throws SchemaExcepti public String determineLdapSingleAttributeValue(Collection dns, String attributeName, PrismProperty attribute) throws NamingException { return determineLdapSingleAttributeValue(dns, attributeName, attribute.getRealValues()); } - + public T getResourceIcfConfigurationPropertyValue(ResourceType resource, javax.xml.namespace.QName propertyQname) throws SchemaException { if (propertyQname == null) { return null; @@ -528,7 +528,7 @@ public T getResourceIcfConfigurationPropertyValue(ResourceType resource, jav } return property.getRealValue(); } - + public T getResourceIcfConfigurationPropertyValue(ResourceType resource, String propertyLocalPart) throws SchemaException { if (propertyLocalPart == null) { return null; @@ -544,7 +544,7 @@ public T getResourceIcfConfigurationPropertyValue(ResourceType resource, Str } return null; } - + private PrismContainer getIcfConfigurationProperties(ResourceType resource) { if (resource == null) { return null; @@ -555,7 +555,7 @@ private PrismContainer getIcfConfigurationProperties(ResourceType resource) { } return connectorConfiguration.findContainer(SchemaConstants.ICF_CONFIGURATION_PROPERTIES); } - + public String determineLdapSingleAttributeValue(Collection dns, String attributeName, Collection values) throws NamingException { if (values == null || values.isEmpty()) { // Shortcut. This is maybe the most common case. We want to return quickly and we also need to avoid more checks later. @@ -569,14 +569,14 @@ public String determineLdapSingleAttributeValue(Collection dns, String a } return determineLdapSingleAttributeValue(dns.iterator().next(), attributeName, values); } - + // We cannot have Collection here. The generic type information will disappear at runtime and the scripts can pass // anything that they find suitable. E.g. XPath is passing elements public String determineLdapSingleAttributeValue(String dn, String attributeName, Collection values) throws NamingException { if (values == null || values.isEmpty()) { return null; } - + Collection stringValues = null; // Determine item type, try to convert to strings Object firstElement = values.iterator().next(); @@ -591,15 +591,15 @@ public String determineLdapSingleAttributeValue(String dn, String attributeName, } else { throw new IllegalArgumentException("Unexpected value type "+firstElement.getClass()); } - + if (stringValues.size() == 1) { return stringValues.iterator().next(); } - + if (StringUtils.isBlank(dn)) { throw new IllegalArgumentException("No dn argument specified, cannot determine which of "+values.size()+" values to use"); } - + LdapName parsedDn = new LdapName(dn); for (int i=0; i < parsedDn.size(); i++) { Rdn rdn = parsedDn.getRdn(i); @@ -618,11 +618,11 @@ public String determineLdapSingleAttributeValue(String dn, String attributeName, } } } - + // Fallback. No values in DN. Just return the first alphabetically-wise value. return Collections.min(stringValues); } - + public T toSingle(Collection values) throws SchemaException { if (values == null || values.isEmpty()) { return null; @@ -632,7 +632,7 @@ public T toSingle(Collection values) throws SchemaException { return values.iterator().next(); } } - + private T toSingle(Collection values, String contextDesc) throws SchemaException { if (values == null || values.isEmpty()) { return null; @@ -646,7 +646,7 @@ private T toSingle(Collection values, String contextDesc) throws SchemaEx public static String readFile(String filename) throws IOException { return FileUtils.readFileToString(new File(filename)); } - + public String formatDateTime(String format, XMLGregorianCalendar xmlCal) { if (xmlCal == null || format == null) { return null; @@ -655,7 +655,7 @@ public String formatDateTime(String format, XMLGregorianCalendar xmlCal) { Date date = XmlTypeConverter.toDate(xmlCal); return sdf.format(date); } - + public String formatDateTime(String format, Long millis) { if (millis == null || format == null) { return null; @@ -663,7 +663,7 @@ public String formatDateTime(String format, Long millis) { SimpleDateFormat sdf = new SimpleDateFormat(format); return sdf.format(millis); } - + public XMLGregorianCalendar parseDateTime(String format, String stringDate) throws ParseException { if (format == null || stringDate == null) { return null; @@ -675,20 +675,20 @@ public XMLGregorianCalendar parseDateTime(String format, String stringDate) thro } return XmlTypeConverter.createXMLGregorianCalendar(date); } - + public XMLGregorianCalendar currentDateTime() { return XmlTypeConverter.createXMLGregorianCalendar(System.currentTimeMillis()); } - + private ParsedFullName parseFullName(String fullName) { if (StringUtils.isBlank(fullName)) { return null; } String root = fullName.trim(); ParsedFullName p = new ParsedFullName(); - + // LOGGER.trace("(1) root=", root); - + Matcher m = PATTERN_NICK_NAME.matcher(root); if (m.matches()) { String nickName = m.group(2).trim(); @@ -696,12 +696,12 @@ private ParsedFullName parseFullName(String fullName) { root = m.group(1) + " " + m.group(3); // LOGGER.trace("nick={}, root={}", nickName, root); } - + String[] words = root.split(STRING_PATTERN_WHITESPACE); int i = 0; - + // LOGGER.trace("(2) i={}, words={}", i, Arrays.toString(words)); - + StringBuilder honorificPrefixBuilder = new StringBuilder(); while (i < words.length && words[i].matches(STRING_PATTERN_HONORIFIC_PREFIX_ENDS_WITH_DOT)) { honorificPrefixBuilder.append(words[i]); @@ -712,15 +712,15 @@ private ParsedFullName parseFullName(String fullName) { honorificPrefixBuilder.setLength(honorificPrefixBuilder.length() - 1); p.setHonorificPrefix(honorificPrefixBuilder.toString()); } - + // LOGGER.trace("(3) i={}, words={}", i, Arrays.toString(words)); - + List rootNameWords = new ArrayList<>(); while (i < words.length && !words[i].endsWith(",")) { rootNameWords.add(words[i]); i++; } - + if (i < words.length && words[i].endsWith(",")) { String word = words[i]; i++; @@ -729,20 +729,20 @@ private ParsedFullName parseFullName(String fullName) { rootNameWords.add(word); } } - + // LOGGER.trace("(4) i={}, words={}", i, Arrays.toString(words)); // LOGGER.trace("(4) rootNameWords={}", rootNameWords); - + if (rootNameWords.size() > 1) { - p.setFamilyName(rootNameWords.get(rootNameWords.size() - 1)); + p.setFamilyName(rootNameWords.get(rootNameWords.size() - 1)); rootNameWords.remove(rootNameWords.size() - 1); p.setGivenName(rootNameWords.get(0)); rootNameWords.remove(0); p.setAdditionalName(StringUtils.join(rootNameWords, " ")); } else if (rootNameWords.size() == 1) { - p.setFamilyName(rootNameWords.get(0)); + p.setFamilyName(rootNameWords.get(0)); } - + StringBuilder honorificSuffixBuilder = new StringBuilder(); while (i < words.length) { honorificSuffixBuilder.append(words[i]); @@ -755,10 +755,10 @@ private ParsedFullName parseFullName(String fullName) { } LOGGER.trace("Parsed full name '{}' as {}", fullName, p); - + return p; } - + public String parseGivenName(Object fullName) { ParsedFullName p = parseFullName(stringify(fullName)); if (p == null) { @@ -767,7 +767,7 @@ public String parseGivenName(Object fullName) { return p.getGivenName(); } } - + public String parseFamilyName(Object fullName) { ParsedFullName p = parseFullName(stringify(fullName)); if (p == null) { @@ -776,7 +776,7 @@ public String parseFamilyName(Object fullName) { return p.getFamilyName(); } } - + public String parseAdditionalName(Object fullName) { ParsedFullName p = parseFullName(stringify(fullName)); if (p == null) { @@ -785,7 +785,7 @@ public String parseAdditionalName(Object fullName) { return p.getAdditionalName(); } } - + public String parseNickName(Object fullName) { ParsedFullName p = parseFullName(stringify(fullName)); if (p == null) { @@ -794,7 +794,7 @@ public String parseNickName(Object fullName) { return p.getNickName(); } } - + public String parseHonorificPrefix(Object fullName) { ParsedFullName p = parseFullName(stringify(fullName)); if (p == null) { @@ -803,7 +803,7 @@ public String parseHonorificPrefix(Object fullName) { return p.getHonorificPrefix(); } } - + public String parseHonorificSuffix(Object fullName) { ParsedFullName p = parseFullName(stringify(fullName)); if (p == null) { @@ -812,7 +812,7 @@ public String parseHonorificSuffix(Object fullName) { return p.getHonorificSuffix(); } } - + public String decrypt(ProtectedStringType protectedString) { try { return protector.decryptString(protectedString); @@ -820,7 +820,7 @@ public String decrypt(ProtectedStringType protectedString) { throw new SystemException(e.getMessage(), e); } } - + public ProtectedStringType encrypt(String string) { try { return protector.encryptString(string); @@ -828,18 +828,18 @@ public ProtectedStringType encrypt(String string) { throw new SystemException(e.getMessage(), e); } } - + /** * Creates a valid LDAP distinguished name from the wide range of components. The method * can be invoked in many ways, e.g.: - * + * * composeDn("cn","foo","o","bar") * composeDn("cn","foo",new Rdn("o","bar")) * composeDn(new Rdn("cn","foo"),"ou","baz",new Rdn("o","bar")) * composeDn(new Rdn("cn","foo"),"ou","baz","o","bar") * composeDn(new Rdn("cn","foo"),new LdapName("ou=baz,o=bar")) * composeDn("cn","foo",new LdapName("ou=baz,o=bar")) - * + * * Note: the DN is not normalized. The case of the attribute names and white spaces are * preserved. */ @@ -876,7 +876,7 @@ public static String composeDn(Object... components) throws InvalidNameException rdns.addFirst(new Rdn(attrName, (String)component)); attrName = null; } - } + } if (component instanceof LdapName) { rdns.addAll(0,((LdapName)component).getRdns()); } @@ -884,18 +884,18 @@ public static String composeDn(Object... components) throws InvalidNameException LdapName dn = new LdapName(rdns); return dn.toString(); } - + /** * Creates a valid LDAP distinguished name from the wide range of components assuming that * the last component is a suffix. The method can be invoked in many ways, e.g.: - * + * * composeDn("cn","foo","o=bar") * composeDn(new Rdn("cn","foo"),"ou=baz,o=bar") * composeDn(new Rdn("cn","foo"),new LdapName("ou=baz,o=bar")) * composeDn("cn","foo",new LdapName("ou=baz,o=bar")) - * + * * The last element is a complete suffix represented either as String or LdapName. - * + * * Note: the DN is not normalized. The case of the attribute names and white spaces are * preserved. */ @@ -932,7 +932,7 @@ public static String composeDnWithSuffix(Object... components) throws InvalidNam components[components.length - 1] = suffix; return composeDn(components); } - + public static String debugDump(Object o) { if (o == null) { return "null"; @@ -942,7 +942,7 @@ public static String debugDump(Object o) { } return DebugUtil.debugDump(o, 0); } - + public static String debugDump(Object o, int indent) { if (o == null) { return "null"; @@ -952,5 +952,5 @@ public static String debugDump(Object o, int indent) { } return DebugUtil.debugDump(o, indent); } - + } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/BasicExpressionFunctionsXPath.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/BasicExpressionFunctionsXPath.java index 30bf6a76d23..a300859bc61 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/BasicExpressionFunctionsXPath.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/BasicExpressionFunctionsXPath.java @@ -27,21 +27,21 @@ /** * Library of standard midPoint functions. These functions are made available to all * midPoint expressions. - * + * * @author Radovan Semancik * */ public class BasicExpressionFunctionsXPath { - + public static final Trace LOGGER = TraceManager.getTrace(BasicExpressionFunctionsXPath.class); - + private BasicExpressionFunctions functions; public BasicExpressionFunctionsXPath(BasicExpressionFunctions functions) { super(); this.functions = functions; } - + /** * Convert string to lower case. */ @@ -55,7 +55,7 @@ public static String lc(String orig) { public static String uc(String orig) { return BasicExpressionFunctions.uc(orig); } - + /** * Remove whitespaces at the beginning and at the end of the string. */ @@ -74,28 +74,28 @@ public String concatName(String... components) { /** * Normalize a string value. It follows the default normalization algorithm * used for PolyString values. - * + * * @param orig original value to normalize * @return normalized value */ public String norm(String orig) { return functions.norm(orig); } - + public String stringify(Object whatever) { return functions.stringify(whatever); } - + public String determineLdapSingleAttributeValue(Element dn, String attributeName, Element valueElement) throws NamingException { // Trivial case: the value is a single element therefore it has a single value. return valueElement.getTextContent(); } - + public String determineLdapSingleAttributeValue(Collection dns, String attributeName, Element valueElement) throws NamingException { // Trivial case: the value is a single element therefore it has a single value. return valueElement.getTextContent(); } - + public String determineLdapSingleAttributeValue(Element dnElement, String attributeName, Collection values) throws NamingException { if (values == null || values.isEmpty()) { // Shortcut. This is maybe the most common case. We want to return quickly and we also need to avoid more checks later. @@ -106,9 +106,9 @@ public String determineLdapSingleAttributeValue(Element dnElement, String attrib } return functions.determineLdapSingleAttributeValue(dnElement.getTextContent(), attributeName, values); } - + public String determineLdapSingleAttributeValue(Collection dns, String attributeName, Collection values) throws NamingException { return functions.determineLdapSingleAttributeValue(dns, attributeName, values); } - + } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/FunctionLibrary.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/FunctionLibrary.java index ea328d45c0f..70c81e0195c 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/FunctionLibrary.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/FunctionLibrary.java @@ -20,43 +20,43 @@ * */ public class FunctionLibrary { - + private String variableName; private String namespace; private Object genericFunctions; private Object xmlFunctions; - + public String getVariableName() { return variableName; } - + public void setVariableName(String variableName) { this.variableName = variableName; } - + public String getNamespace() { return namespace; } - + public void setNamespace(String namespace) { this.namespace = namespace; } - + public Object getGenericFunctions() { return genericFunctions; } - + public void setGenericFunctions(Object genericFunctions) { this.genericFunctions = genericFunctions; } - + public Object getXmlFunctions() { return xmlFunctions; } - + public void setXmlFunctions(Object xmlFunctions) { this.xmlFunctions = xmlFunctions; } - + } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/FunctionLibraryUtil.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/FunctionLibraryUtil.java index 244c0f132b6..8a7a76ba9f6 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/FunctionLibraryUtil.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/FunctionLibraryUtil.java @@ -24,7 +24,7 @@ * */ public class FunctionLibraryUtil { - + public static FunctionLibrary createBasicFunctionLibrary(PrismContext prismContext, Protector protector) { FunctionLibrary lib = new FunctionLibrary(); lib.setVariableName(MidPointConstants.FUNCTION_LIBRARY_BASIC_VARIABLE_NAME); diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/LogExpressionFunctions.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/LogExpressionFunctions.java index c40b4015ca7..e275175012c 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/LogExpressionFunctions.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/LogExpressionFunctions.java @@ -24,22 +24,22 @@ * */ public class LogExpressionFunctions { - + public static String EXPRESSION_LOGGER_NAME = "com.evolveum.midpoint.expression"; - + public static final Trace LOGGER = TraceManager.getTrace(EXPRESSION_LOGGER_NAME); - + private PrismContext prismContext; public LogExpressionFunctions(PrismContext prismContext) { super(); this.prismContext = prismContext; } - + public void error(String format, Object... args) { LOGGER.error(format, args); } - + public void warn(String format, Object... args) { LOGGER.warn(format, args); } @@ -47,7 +47,7 @@ public void warn(String format, Object... args) { public void info(String format, Object... args) { LOGGER.info(format, args); } - + public void debug(String format, Object... args) { LOGGER.debug(format, args); } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/ParsedFullName.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/ParsedFullName.java index 4a196239568..3f7d6f75770 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/ParsedFullName.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/ParsedFullName.java @@ -20,42 +20,42 @@ * */ public class ParsedFullName { - + private String givenName; private String familyName; private String nickName; private String additionalName; private String honorificPrefix; private String honorificSuffix; - + public String getGivenName() { return givenName; } - + public void setGivenName(String givenName) { this.givenName = givenName; } - + public String getFamilyName() { return familyName; } - + public void setFamilyName(String familyName) { this.familyName = familyName; } - + public String getNickName() { return nickName; } - + public void setNickName(String nickName) { this.nickName = nickName; } - + public String getAdditionalName() { return additionalName; } - + public void setAdditionalName(String additionalName) { this.additionalName = additionalName; } @@ -83,6 +83,6 @@ public String toString() { + ", honorificSuffix=" + honorificSuffix + ")"; } - - + + } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptEvaluator.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptEvaluator.java index 54688878449..f4ea2b80c7a 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptEvaluator.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptEvaluator.java @@ -36,7 +36,7 @@ * @author Radovan Semancik */ public interface ScriptEvaluator { - + List evaluate(ScriptExpressionEvaluatorType expressionType, ExpressionVariables variables, ItemDefinition outputDefinition, Function additionalConvertor, ScriptExpressionReturnTypeType suggestedReturnType, ObjectResolver objectResolver, diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptExpression.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptExpression.java index a3fa5c31584..f16f4e029e2 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptExpression.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptExpression.java @@ -76,7 +76,7 @@ public ObjectResolver getObjectResolver() { public void setObjectResolver(ObjectResolver objectResolver) { this.objectResolver = objectResolver; } - + public Collection getFunctions() { return functions; } @@ -99,12 +99,12 @@ public List evaluate(ExpressionVariables variables, Sc ScriptExpressionEvaluationContext context = new ScriptExpressionEvaluationContext(variables, contextDescription, result, task, this); context.setEvaluateNew(useNew); - + try { context.setupThreadLocal(); - + List expressionResult = evaluator.evaluate(scriptType, variables, outputDefinition, additionalConvertor, suggestedReturnType, objectResolver, functions, contextDescription, task, result); - + traceExpressionSuccess(variables, contextDescription, expressionResult); return expressionResult; @@ -144,11 +144,11 @@ private void traceExpressionFailure(ExpressionVariables variables, String shortD "Error: {}", shortDesc, evaluator.getLanguageName(), scriptType.getRelativityMode(), formatVariables(variables), formatCode(), SchemaDebugUtil.prettyPrint(exception)); } - + private boolean isTrace() { - return LOGGER.isTraceEnabled() || (scriptType != null && scriptType.isTrace() == Boolean.TRUE); + return LOGGER.isTraceEnabled() || (scriptType != null && scriptType.isTrace() == Boolean.TRUE); } - + private void trace(String msg, Object... args) { if (scriptType != null && scriptType.isTrace() == Boolean.TRUE) { LOGGER.info(msg, args); @@ -167,7 +167,7 @@ private String formatVariables(ExpressionVariables variables) { private String formatCode() { return DebugUtil.excerpt(scriptType.getCode().replaceAll("[\\s\\r\\n]+", " "), MAX_CODE_CHARS); } - + public ItemPath parsePath(String path) { if (path == null) { return null; diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptExpressionEvaluator.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptExpressionEvaluator.java index 765bb598d8b..e3387796912 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptExpressionEvaluator.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptExpressionEvaluator.java @@ -37,20 +37,20 @@ /** * @author Radovan Semancik */ -public class ScriptExpressionEvaluator +public class ScriptExpressionEvaluator extends AbstractValueTransformationExpressionEvaluator { private ScriptExpression scriptExpression; - + private static final Trace LOGGER = TraceManager.getTrace(ScriptExpressionEvaluator.class); ScriptExpressionEvaluator(ScriptExpressionEvaluatorType scriptType, ScriptExpression scriptExpression, SecurityEnforcer securityEnforcer) { super(scriptType, securityEnforcer); this.scriptExpression = scriptExpression; } - + @Override - protected List transformSingleValue(ExpressionVariables variables, PlusMinusZero valueDestination, boolean useNew, + protected List transformSingleValue(ExpressionVariables variables, PlusMinusZero valueDestination, boolean useNew, ExpressionEvaluationContext context, String contextDescription, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException { ScriptExpressionReturnTypeType returnType = getExpressionEvaluatorType().getReturnType(); @@ -60,7 +60,7 @@ protected List transformSingleValue(ExpressionVariables variables, PlusMinusZ scriptExpression.setAdditionalConvertor(context.getAdditionalConvertor()); return (List) scriptExpression.evaluate(variables, returnType, useNew, contextDescription, task, result); } - + /* (non-Javadoc) * @see com.evolveum.midpoint.common.expression.ExpressionEvaluator#shortDebugDump() */ diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptExpressionEvaluatorFactory.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptExpressionEvaluatorFactory.java index 8e3f887a23c..40afe5a8808 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptExpressionEvaluatorFactory.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptExpressionEvaluatorFactory.java @@ -36,7 +36,7 @@ * */ public class ScriptExpressionEvaluatorFactory implements ExpressionEvaluatorFactory { - + private ScriptExpressionFactory scriptExpressionFactory; private SecurityEnforcer securityEnforcer; @@ -56,22 +56,22 @@ public QName getElementName() { @Override public ExpressionEvaluator createEvaluator(Collection> evaluatorElements, D outputDefinition, String contextDescription, Task task, OperationResult result) throws SchemaException { - + if (evaluatorElements.size() > 1) { throw new SchemaException("More than one evaluator specified in "+contextDescription); } JAXBElement evaluatorElement = evaluatorElements.iterator().next(); - + Object evaluatorElementObject = evaluatorElement.getValue(); if (!(evaluatorElementObject instanceof ScriptExpressionEvaluatorType)) { throw new IllegalArgumentException("Script expression cannot handle elements of type " + evaluatorElementObject.getClass().getName()); } ScriptExpressionEvaluatorType scriptType = (ScriptExpressionEvaluatorType) evaluatorElementObject; - + ScriptExpression scriptExpression = scriptExpressionFactory.createScriptExpression(scriptType, outputDefinition, contextDescription); - + return new ScriptExpressionEvaluator<>(scriptType, scriptExpression, securityEnforcer); - + } } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptExpressionFactory.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptExpressionFactory.java index 7eb8bdb0c36..709b7edfb70 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptExpressionFactory.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptExpressionFactory.java @@ -28,20 +28,20 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ScriptExpressionEvaluatorType; /** - * + * * @author Radovan Semancik * */ public class ScriptExpressionFactory { - + public static String DEFAULT_LANGUAGE = "http://midpoint.evolveum.com/xml/ns/public/expression/language#Groovy"; - + private Map evaluatorMap = new HashMap(); private ObjectResolver objectResolver; private PrismContext prismContext; private Collection functions; private Protector protector; - + public ScriptExpressionFactory(PrismContext prismContext, Protector protector) { this.prismContext = prismContext; this.protector = protector; @@ -54,7 +54,7 @@ public ObjectResolver getObjectResolver() { public void setObjectResolver(ObjectResolver objectResolver) { this.objectResolver = objectResolver; } - + public void setEvaluators(Collection evaluators) { for (ScriptEvaluator evaluator: evaluators) { registerEvaluator(evaluator.getLanguageUrl(), evaluator); @@ -80,14 +80,14 @@ public ScriptExpression createScriptExpression(ScriptExpressionEvaluatorType exp expression.setFunctions(functions); return expression; } - + public void registerEvaluator(String language, ScriptEvaluator evaluator) { if (evaluatorMap.containsKey(language)) { throw new IllegalArgumentException("Evaluator for language "+language+" already registered"); } evaluatorMap.put(language,evaluator); } - + private ScriptEvaluator getEvaluator(String language, String shortDesc) throws ExpressionSyntaxException { ScriptEvaluator evaluator = evaluatorMap.get(language); if (evaluator == null) { @@ -102,6 +102,6 @@ private String getLanguage(ScriptExpressionEvaluatorType expressionType) { } return DEFAULT_LANGUAGE; } - + } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptExpressionUtil.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptExpressionUtil.java index cbe3e7233b6..ffadb4f014d 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptExpressionUtil.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptExpressionUtil.java @@ -37,7 +37,7 @@ * */ public class ScriptExpressionUtil { - + public static Map prepareScriptVariables(ExpressionVariables variables, ObjectResolver objectResolver, Collection functions, String contextDescription, PrismContext prismContext, Task task, OperationResult result) throws ExpressionSyntaxException, ObjectNotFoundException { diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/jsr223/Jsr223ScriptEvaluator.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/jsr223/Jsr223ScriptEvaluator.java index 01380383bb7..3357a8f68db 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/jsr223/Jsr223ScriptEvaluator.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/jsr223/Jsr223ScriptEvaluator.java @@ -60,7 +60,7 @@ /** * Expression evaluator that is using javax.script (JSR-223) engine. - * + * * @author Radovan Semancik * */ @@ -71,9 +71,9 @@ public class Jsr223ScriptEvaluator implements ScriptEvaluator { private ScriptEngine scriptEngine; private PrismContext prismContext; private Protector protector; - + private Map scriptCache; - + public Jsr223ScriptEvaluator(String engineName, PrismContext prismContext, Protector protector) { ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); scriptEngine = scriptEngineManager.getEngineByName(engineName); @@ -84,7 +84,7 @@ public Jsr223ScriptEvaluator(String engineName, PrismContext prismContext, Prote this.protector = protector; this.scriptCache = new ConcurrentHashMap<>(); } - + @Override public List evaluate(ScriptExpressionEvaluatorType expressionType, ExpressionVariables variables, ItemDefinition outputDefinition, @@ -93,9 +93,9 @@ public List evaluate(ScriptExpressionEvaluatorType ObjectResolver objectResolver, Collection functions, String contextDescription, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, ExpressionSyntaxException { - + Bindings bindings = convertToBindings(variables, objectResolver, functions, contextDescription, task, result); - + String codeString = expressionType.getCode(); if (codeString == null) { throw new ExpressionEvaluationException("No script code in " + contextDescription); @@ -105,25 +105,25 @@ public List evaluate(ScriptExpressionEvaluatorType if (expressionType.isAllowEmptyValues() != null) { allowEmptyValues = expressionType.isAllowEmptyValues(); } - + CompiledScript compiledScript = createCompiledScript(codeString, contextDescription); - + Object evalRawResult; try { InternalMonitor.recordCount(InternalCounters.SCRIPT_EXECUTION_COUNT); evalRawResult = compiledScript.eval(bindings); } catch (Throwable e) { - throw new ExpressionEvaluationException(e.getMessage() + " in " + contextDescription, e, + throw new ExpressionEvaluationException(e.getMessage() + " in " + contextDescription, e, ExceptionUtil.getUserFriendlyMessage(e)); } - + if (outputDefinition == null) { // No outputDefinition means "void" return type, we can return right now return null; } - + QName xsdReturnType = outputDefinition.getTypeName(); - + Class javaReturnType = XsdTypeMapper.toJavaType(xsdReturnType); if (javaReturnType == null) { javaReturnType = prismContext.getSchemaRegistry().getCompileTimeClass(xsdReturnType); @@ -134,9 +134,9 @@ public List evaluate(ScriptExpressionEvaluatorType // ...and enums (xsd:simpleType) are not parsed into ComplexTypeDefinitions javaReturnType = (Class) String.class; } - + List pvals = new ArrayList(); - + // TODO: what about PrismContainer and // PrismReference? Shouldn't they be processed in the same way as // PrismProperty? @@ -155,16 +155,16 @@ public List evaluate(ScriptExpressionEvaluatorType pvals.add((V) ExpressionUtil.convertToPrismValue(evalResult, outputDefinition, contextDescription, prismContext)); } } - + return pvals; } public Object evaluateReportScript(String codeString, ExpressionVariables variables, ObjectResolver objectResolver, Collection functions, String contextDescription, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, ExpressionSyntaxException { - + Bindings bindings = convertToBindings(variables, objectResolver, functions, contextDescription, (Task) null, result); - + // String codeString = code; if (codeString == null) { throw new ExpressionEvaluationException("No script code in " + contextDescription); @@ -174,9 +174,9 @@ public Object evaluateReportScript(String codeString, ExpressionVariables va // if (expressionType.isAllowEmptyValues() != null) { // allowEmptyValues = expressionType.isAllowEmptyValues(); // } - + CompiledScript compiledScript = createCompiledScript(codeString, contextDescription); - + Object evalRawResult; try { InternalMonitor.recordCount(InternalCounters.SCRIPT_EXECUTION_COUNT); @@ -184,12 +184,12 @@ public Object evaluateReportScript(String codeString, ExpressionVariables va } catch (Throwable e) { throw new ExpressionEvaluationException(e.getMessage() + " in " + contextDescription, e); } - - - + + + return evalRawResult; } - + private CompiledScript createCompiledScript(String codeString, String contextDescription) throws ExpressionEvaluationException { CompiledScript compiledScript = scriptCache.get(codeString); if (compiledScript != null) { @@ -213,7 +213,7 @@ private T convertScalarResult(Class expectedType, Function functions, String contextDescription, Task task, OperationResult result) throws ExpressionSyntaxException, ObjectNotFoundException { diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/velocity/VelocityScriptEvaluator.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/velocity/VelocityScriptEvaluator.java index 18cc4923bbf..ed08180f6dc 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/velocity/VelocityScriptEvaluator.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/velocity/VelocityScriptEvaluator.java @@ -46,7 +46,7 @@ /** * Expression evaluator that is using Apache Velocity engine. - * + * * @author mederly * */ @@ -64,7 +64,7 @@ public VelocityScriptEvaluator(PrismContext prismContext, Protector protector) { // properties.put("runtime.references.strict", "true"); Velocity.init(properties); } - + @Override public List evaluate(ScriptExpressionEvaluatorType expressionType, ExpressionVariables variables, ItemDefinition outputDefinition, @@ -73,9 +73,9 @@ public List evaluate(ScriptExpressionEvaluatorType ObjectResolver objectResolver, Collection functions, String contextDescription, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, ExpressionSyntaxException { - + VelocityContext context = createVelocityContext(variables, objectResolver, functions, contextDescription, task, result); - + String codeString = expressionType.getCode(); if (codeString == null) { throw new ExpressionEvaluationException("No script code in " + contextDescription); @@ -85,7 +85,7 @@ public List evaluate(ScriptExpressionEvaluatorType if (expressionType.isAllowEmptyValues() != null) { allowEmptyValues = expressionType.isAllowEmptyValues(); } - + StringWriter resultWriter = new StringWriter(); try { InternalMonitor.recordCount(InternalCounters.SCRIPT_EXECUTION_COUNT); @@ -93,14 +93,14 @@ public List evaluate(ScriptExpressionEvaluatorType } catch (RuntimeException e) { throw new ExpressionEvaluationException(e.getMessage() + " in " + contextDescription, e); } - + if (outputDefinition == null) { // No outputDefinition means "void" return type, we can return right now return null; } - + QName xsdReturnType = outputDefinition.getTypeName(); - + Class javaReturnType = XsdTypeMapper.toJavaType(xsdReturnType); if (javaReturnType == null) { javaReturnType = prismContext.getSchemaRegistry().getCompileTimeClass(xsdReturnType); @@ -111,7 +111,7 @@ public List evaluate(ScriptExpressionEvaluatorType // ...and enums (xsd:simpleType) are not parsed into ComplexTypeDefinitions javaReturnType = (Class) String.class; } - + T evalResult; try { evalResult = ExpressionUtil.convertValue(javaReturnType, additionalConvertor, resultWriter.toString(), protector, prismContext); diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/LazyXPathVariableResolver.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/LazyXPathVariableResolver.java index e3f6c3c2229..c6578eee41e 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/LazyXPathVariableResolver.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/LazyXPathVariableResolver.java @@ -60,16 +60,16 @@ public class LazyXPathVariableResolver implements XPathVariableResolver { private static final QName FAKE_VARIABLE_QNAME = new QName(SchemaConstants.NS_C, "fakeVar"); - + private ExpressionVariables variables; private ObjectResolver objectResolver; private String contextDescription; private OperationResult result; private PrismContext prismContext; - + private static final Trace LOGGER = TraceManager.getTrace(LazyXPathVariableResolver.class); - public LazyXPathVariableResolver(ExpressionVariables variables, ObjectResolver objectResolver, + public LazyXPathVariableResolver(ExpressionVariables variables, ObjectResolver objectResolver, String contextDescription, PrismContext prismContext, OperationResult result) { this.variables = variables; this.objectResolver = objectResolver; @@ -83,21 +83,21 @@ public Object resolveVariable(QName name) { if (variables == null) { return null; } - + if (name != null && (name.getNamespaceURI() == null || name.getNamespaceURI().isEmpty())) { LOGGER.warn("Using variable without a namespace ("+name+"), possible namespace problem (e.g. missing namespace prefix declaration) in "+contextDescription); } - + // Note: null is a legal variable name here. It corresponds to the root node Object variableValue = variables.get(name); - + if (variableValue == null) { // TODO: warning ??? return null; } - + QName type = null; - + // Attempt to resolve object reference if (objectResolver != null && variableValue instanceof ObjectReferenceType) { ObjectReferenceType ref = (ObjectReferenceType)variableValue; @@ -107,9 +107,9 @@ public Object resolveVariable(QName name) { } else { type = ref.getType(); try { - + variableValue = objectResolver.resolve(ref, ObjectType.class, null, contextDescription, null, result); // TODO task - + } catch (ObjectNotFoundException e) { ObjectNotFoundException newEx = new ObjectNotFoundException("Object not found during variable "+name+" resolution in "+contextDescription+": "+e.getMessage(),e, ref.getOid()); // We have no other practical way how to handle the error @@ -120,22 +120,22 @@ public Object resolveVariable(QName name) { } } } - + try { return convertToXml(variableValue, name, prismContext, contextDescription); } catch (SchemaException e) { throw new TunnelException(e); } } - + // May return primitive types or DOM Node public static Object convertToXml(Object variableValue, QName variableName, final PrismContext prismContext, String contextDescription) throws SchemaException { - + try { if (variableValue instanceof Objectable) { variableValue = ((Objectable)variableValue).asPrismObject(); } - + if (variableValue instanceof PrismObject) { PrismObject prismObject = (PrismObject)variableValue; variableValue = prismObject.getPrismContext().domSerializer().serialize(prismObject); @@ -149,7 +149,7 @@ public static Object convertToXml(Object variableValue, QName variableName, fina } NodeList nodeList = new AdHocNodeList(elementList); variableValue = nodeList; - + } else if (variableValue instanceof PrismValue) { PrismValue pval = (PrismValue)variableValue; if (pval.getParent() == null) { @@ -158,12 +158,12 @@ public static Object convertToXml(Object variableValue, QName variableName, fina } variableValue = prismContext.domSerializer().serialize(pval, variableName); } - - if (!((variableValue instanceof Node)||variableValue instanceof NodeList) + + if (!((variableValue instanceof Node)||variableValue instanceof NodeList) && !(variableValue.getClass().getPackage().getName().startsWith("java."))) { throw new SchemaException("Unable to convert value of variable "+variableName+" to XML, still got "+variableValue.getClass().getName()+":"+variableValue+" value at the end"); } - + // DEBUG hack // if (LOGGER.isDebugEnabled()) { // LOGGER.trace("VAR "+variableName+" - "+variableValue.getClass().getName()+":"); @@ -173,9 +173,9 @@ public static Object convertToXml(Object variableValue, QName variableName, fina // LOGGER.trace(PrettyPrinter.prettyPrint(variableValue)); // } // } - + return variableValue; - + } catch (SchemaException e) { if (variableValue != null && variableValue instanceof DebugDumpable) { LOGGER.trace("Value of variable {}:\n{}", variableName, ((DebugDumpable)variableValue).debugDump()); diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/MidPointNamespaceContext.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/MidPointNamespaceContext.java index c1008d54668..4439bc30881 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/MidPointNamespaceContext.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/MidPointNamespaceContext.java @@ -24,9 +24,9 @@ /** * Used to register namespaces for prefixes for JAXP - * + * * @see NamespaceContext - * + * * @author Igor Farinic */ diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/ReflectionXPathFunctionResolver.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/ReflectionXPathFunctionResolver.java index 98d44c31d87..0e538669efa 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/ReflectionXPathFunctionResolver.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/ReflectionXPathFunctionResolver.java @@ -34,11 +34,11 @@ public class ReflectionXPathFunctionResolver implements XPathFunctionResolver { private static final Object LOG_FUNCTION_NAME = "logDebug"; - + public static final Trace LOGGER = TraceManager.getTrace(ReflectionXPathFunctionResolver.class); - + private Collection functions; - + public ReflectionXPathFunctionResolver(Collection functions) { super(); this.functions = functions; @@ -57,24 +57,24 @@ public XPathFunction resolveFunction(QName functionQName, int arity) { } else if (namespace.equals(MidPointConstants.NS_FUNC_BASIC)) { enableDebug = true; } - + FunctionLibrary lib = findLibrary(namespace); if (lib == null) { LOGGER.trace("Unknown namespace for function {} function with {} arguments", functionQName, arity); return null; } - + Object functionObject = null; if (lib.getXmlFunctions() != null) { functionObject = lib.getXmlFunctions(); } else { functionObject = lib.getGenericFunctions(); } - + String functionName = functionQName.getLocalPart(); - + LOGGER.trace("Resolving to {} function with {} arguments", functionName, arity); - ReflectionXPathFunctionWrapper xPathFunction = new ReflectionXPathFunctionWrapper(functionObject, functionName, + ReflectionXPathFunctionWrapper xPathFunction = new ReflectionXPathFunctionWrapper(functionObject, functionName, arity, enableDebug); return xPathFunction; } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/ReflectionXPathFunctionWrapper.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/ReflectionXPathFunctionWrapper.java index 210ed340aa1..6ad647812ac 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/ReflectionXPathFunctionWrapper.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/ReflectionXPathFunctionWrapper.java @@ -31,12 +31,12 @@ * */ public class ReflectionXPathFunctionWrapper implements XPathFunction { - + private static final Object LOG_FUNCTION_NAME = "logDebug"; - + public static final Trace LOGGER = TraceManager.getTrace(ReflectionXPathFunctionWrapper.class); - - private Object functionObject; + + private Object functionObject; private String functionName; private int arity; private boolean enableDebug; @@ -58,7 +58,7 @@ public Object evaluate(List argList) throws XPathFunctionException { LogExpressionFunctions.LOGGER.debug("{}", ReflectionUtil.debugDumpArgList(argList)); return null; } - + try { return ReflectionUtil.invokeMethod(functionObject, functionName, argList); } catch (IllegalArgumentException e) { diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/XPathExpressionCodeHolder.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/XPathExpressionCodeHolder.java index 7316c976463..8ca67d9c134 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/XPathExpressionCodeHolder.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/XPathExpressionCodeHolder.java @@ -24,16 +24,16 @@ * */ public class XPathExpressionCodeHolder { - + private String expression; // TODO think about this one! (there's a problem with namespaces now) - + public XPathExpressionCodeHolder(String expression) { if (expression == null) { throw new IllegalArgumentException("Attempt to create "+XPathExpressionCodeHolder.class.getSimpleName()+" with null DOM element"); } this.expression = expression; } - + // public NodeList getExpression() { // return dom.getChildNodes(); // } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/XPathScriptEvaluator.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/XPathScriptEvaluator.java index 5a9197e4ece..bc01bd7dfdb 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/XPathScriptEvaluator.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/xpath/XPathScriptEvaluator.java @@ -61,7 +61,7 @@ public class XPathScriptEvaluator implements ScriptEvaluator { public static String XPATH_LANGUAGE_URL = "http://www.w3.org/TR/xpath/"; private XPathFactory factory = XPathFactory.newInstance(); - + private PrismContext prismContext; public XPathScriptEvaluator(PrismContext prismContext) { @@ -91,21 +91,21 @@ public List evaluate(ScriptExpressionEvaluatorType if (type == null) { type = (Class) Element.class; // actually, if outputDefinition is null, the return value is of no interest for us } - + QName returnType = determineRerturnType(type, expressionType, outputDefinition, suggestedReturnType); Object evaluatedExpression = evaluate(returnType, codeString, variables, objectResolver, functions, contextDescription, result); List propertyValues; - + boolean scalar = !outputDefinition.isMultiValue(); if (expressionType.getReturnType() != null) { scalar = isScalar(expressionType.getReturnType()); } else if (suggestedReturnType != null) { scalar = isScalar(suggestedReturnType); } - + if (scalar) { if (evaluatedExpression instanceof NodeList) { NodeList evaluatedExpressionNodeList = (NodeList)evaluatedExpression; @@ -129,7 +129,7 @@ public List evaluate(ScriptExpressionEvaluatorType } propertyValues = convertList(type, (NodeList) evaluatedExpression, contextDescription); } - + return (List) PrismValue.cloneCollection(propertyValues); } @@ -142,14 +142,14 @@ private boolean isScalar(ScriptExpressionReturnTypeType returnType) { } private Object evaluate(QName returnType, String code, ExpressionVariables variables, ObjectResolver objectResolver, - Collection functions, + Collection functions, String contextDescription, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, ExpressionSyntaxException { XPathExpressionCodeHolder codeHolder = new XPathExpressionCodeHolder(code); //System.out.println("code " + code); XPath xpath = factory.newXPath(); - XPathVariableResolver variableResolver = new LazyXPathVariableResolver(variables, objectResolver, + XPathVariableResolver variableResolver = new LazyXPathVariableResolver(variables, objectResolver, contextDescription, prismContext, result); xpath.setXPathVariableResolver(variableResolver); xpath.setNamespaceContext(new MidPointNamespaceContext(codeHolder.getNamespaceMap())); @@ -217,7 +217,7 @@ private Object evaluate(QName returnType, String code, ExpressionVariables varia private ExpressionEvaluationException createExpressionEvaluationException(Exception e, String contextDescription) { return new ExpressionEvaluationException(lookForMessage(e) + " in " + contextDescription, e); } - + public static String lookForMessage(Throwable e) { // the net.sf.saxon.trans.XPathException lies. It has meaningless message. skip it. if (e instanceof net.sf.saxon.trans.XPathException && e.getCause() != null) { @@ -253,19 +253,19 @@ private QName determineRerturnType(Class type, ScriptExpressionEvaluatorT if (expressionType.getReturnType() == ScriptExpressionReturnTypeType.LIST || suggestedReturnType == ScriptExpressionReturnTypeType.LIST) { return XPathConstants.NODESET; } - + if (expressionType.getReturnType() == ScriptExpressionReturnTypeType.SCALAR) { return toXPathReturnType(outputDefinition.getTypeName()); } - + if (suggestedReturnType == ScriptExpressionReturnTypeType.LIST) { return XPathConstants.NODESET; } - + if (suggestedReturnType == ScriptExpressionReturnTypeType.SCALAR) { return toXPathReturnType(outputDefinition.getTypeName()); } - + if (outputDefinition.isMultiValue()) { return XPathConstants.NODESET; } else { @@ -344,7 +344,7 @@ private V convertScalar(Class type, QName returnTyp if (value instanceof ObjectReferenceType){ return (V) ((ObjectReferenceType) value).asReferenceValue(); } - + if (type.isAssignableFrom(value.getClass())) { return (V) new PrismPropertyValue((T) value); } @@ -363,7 +363,7 @@ private V convertScalar(Class type, QName returnTyp resultValue = (T) new PolyString((String)resultValue); } PrismUtil.recomputeRealValue(resultValue, prismContext); - + return (V) new PrismPropertyValue(resultValue); } catch (SchemaException e) { throw new ExpressionEvaluationException("Error converting result of " @@ -399,7 +399,7 @@ private List convertList(Class type, NodeList va throw new ExpressionEvaluationException("Error converting return value of " + contextDescription + ": " + e.getMessage(), e); } } - + private boolean isNothing(T value) { return value == null || ((value instanceof String) && ((String) value).isEmpty()); } @@ -412,7 +412,7 @@ private XPathFunctionResolver getFunctionResolver(Collection fu public String getLanguageName() { return "XPath 2.0"; } - + @Override public String getLanguageUrl() { return XPATH_LANGUAGE_URL; diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/mapping/Mapping.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/mapping/Mapping.java index 14c4e3d6f65..ad88bdb2006 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/mapping/Mapping.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/mapping/Mapping.java @@ -68,17 +68,17 @@ import com.evolveum.midpoint.util.logging.TraceManager; /** - * + * * Mapping is non-recyclable single-use object. Once evaluated it should not be evaluated again. It will retain its original * inputs and outputs that can be read again and again. But these should not be changed after evaluation. * * Configuration properties are unmodifiable. They are to be set via Mapping.Builder. - * + * * @author Radovan Semancik * */ public class Mapping implements DebugDumpable, PrismValueDeltaSetTripleProducer { - + // configuration properties (unmodifiable) private final MappingType mappingType; private final ExpressionFactory expressionFactory; @@ -127,7 +127,7 @@ public class Mapping implements D // This is single-use only. Once evaluated it is not used any more // it is remembered only for tracing purposes. private Expression expression; - + private static final Trace LOGGER = TraceManager.getTrace(Mapping.class); private Mapping(Builder builder) { @@ -167,7 +167,7 @@ public QName getItemName() { } return null; } - + public OriginType getOriginType() { return originType; } @@ -216,7 +216,7 @@ public String getMappingContextDescription() { public MappingType getMappingType() { return mappingType; } - + @Override public boolean isSourceless() { return sources.isEmpty(); @@ -258,14 +258,14 @@ public boolean isExclusive() { } return value; } - + public Boolean isTolerant() { if (mappingType == null) { return null; } return mappingType.isTolerant(); } - + public boolean isConditionMaskOld() { return conditionMaskOld; } @@ -325,7 +325,7 @@ public Long getEvaluationStartTime() { public Long getEvaluationEndTime() { return evaluationEndTime; } - + public Long getEtime() { if (evaluationStartTime == null || evaluationEndTime == null) { return null; @@ -368,59 +368,59 @@ public void prepare(Task task, OperationResult parentResult) throws SchemaExcept OperationResult result = parentResult.createMinorSubresult(Mapping.class.getName()+".prepare"); assertState(MappingEvaluationState.UNINITIALIZED); try { - + parseSources(task, result); - + parseTarget(); if (outputPath != null && outputDefinition == null) { throw new IllegalArgumentException("No output definition, cannot evaluate "+getMappingContextDescription()); } - + } catch (ExpressionEvaluationException | ObjectNotFoundException | RuntimeException | SchemaException | Error e) { result.recordFatalError(e); throw e; } - + transitionState(MappingEvaluationState.PREPARED); result.recordSuccess(); } - + public boolean isActivated() { // TODO // return isActivated; return sourcesChanged(); } - + // TODO: rename to evaluate public void evaluateBody(Task task, OperationResult parentResult) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException { - + assertState(MappingEvaluationState.PREPARED); - + OperationResult result = parentResult.createMinorSubresult(Mapping.class.getName()+".evaluate"); traceEvaluationStart(); - + try { - + // We may need to re-parse the sources here - + evaluateTimeConstraintValid(task, result); - + if (!timeConstraintValid) { outputTriple = null; result.recordNotApplicableIfUnknown(); traceDeferred(); return; } - + evaluateCondition(task, result); - + boolean conditionOutputOld = computeConditionResult(conditionOutputTriple.getNonPositiveValues()); boolean conditionResultOld = conditionOutputOld && conditionMaskOld; - + boolean conditionOutputNew = computeConditionResult(conditionOutputTriple.getNonNegativeValues()); boolean conditionResultNew = conditionOutputNew && conditionMaskNew; - + if (!conditionResultOld && !conditionResultNew) { outputTriple = null; transitionState(MappingEvaluationState.EVALUATED); @@ -428,7 +428,7 @@ public void evaluateBody(Task task, OperationResult parentResult) throws Express traceNotApplicable("condition is false"); return; } - + // TODO: input filter evaluateExpression(task, result, conditionResultOld, conditionResultNew); fixDefinition(); @@ -441,7 +441,7 @@ public void evaluateBody(Task task, OperationResult parentResult) throws Express transitionState(MappingEvaluationState.EVALUATED); result.recordSuccess(); traceSuccess(conditionResultOld, conditionResultNew); - + } catch (ExpressionEvaluationException | ObjectNotFoundException | RuntimeException | SchemaException | Error e) { result.recordFatalError(e); traceFailure(e); @@ -531,7 +531,7 @@ private boolean isInRange(V value, Task task, OperationResult result) throws Exp public boolean isSatisfyCondition() { boolean conditionOutputOld = computeConditionResult(conditionOutputTriple.getNonPositiveValues()); boolean conditionResultOld = conditionOutputOld && conditionMaskOld; - + boolean conditionOutputNew = computeConditionResult(conditionOutputTriple.getNonNegativeValues()); boolean conditionResultNew = conditionOutputNew && conditionMaskNew; return (conditionResultOld || conditionResultNew); @@ -546,7 +546,7 @@ private void traceEvaluationStart() { evaluationStartTime = System.currentTimeMillis(); } } - + private void traceEvaluationEnd() { if (profiling) { evaluationEndTime = System.currentTimeMillis(); @@ -580,7 +580,7 @@ private void traceSuccess(boolean conditionResultOld, boolean conditionResultNew appendTraceFooter(sb); trace(sb.toString()); } - + private void traceDeferred() { traceEvaluationEnd(); if (!isTrace()) { @@ -603,7 +603,7 @@ private void traceDeferred() { appendTraceFooter(sb); trace(sb.toString()); } - + private void traceNotApplicable(String reason) { traceEvaluationEnd(); if (!isTrace()) { @@ -621,7 +621,7 @@ private void traceNotApplicable(String reason) { appendTraceFooter(sb); trace(sb.toString()); } - + private void traceFailure(Throwable e) { LOGGER.error("Error evaluating {}: {}", new Object[]{getMappingContextDescription(), e.getMessage(), e}); traceEvaluationEnd(); @@ -640,11 +640,11 @@ private void traceFailure(Throwable e) { appendTraceFooter(sb); trace(sb.toString()); } - + private boolean isTrace() { - return LOGGER.isTraceEnabled() || (mappingType != null && mappingType.isTrace() == Boolean.TRUE); + return LOGGER.isTraceEnabled() || (mappingType != null && mappingType.isTrace() == Boolean.TRUE); } - + private void trace(String msg) { if (mappingType != null && mappingType.isTrace() == Boolean.TRUE) { LOGGER.info(msg); @@ -681,7 +681,7 @@ private void appendTraceHeader(StringBuilder sb) { private void appendTraceFooter(StringBuilder sb) { sb.append("\n------------------------------------------------------"); } - + private boolean computeConditionResult(Collection> booleanPropertyValues) { if (mappingType.getCondition() == null) { // If condition is not present at all consider it to be true @@ -704,32 +704,32 @@ private void parseTimeConstraints(Task task, OperationResult result) throws Sche timeConstraintValid = true; return; } - + XMLGregorianCalendar timeFrom = parseTime(timeFromType, task, result); if (timeFrom == null && timeFromType != null) { // Time is specified but there is no value for it. // This means that event that should start validity haven't happened yet - // therefore the mapping is not yet valid. + // therefore the mapping is not yet valid. timeConstraintValid = false; return; } XMLGregorianCalendar timeTo = parseTime(timeToType, task, result); - + if (timeFrom != null && timeFrom.compare(now) == DatatypeConstants.GREATER) { // before timeFrom nextRecomputeTime = timeFrom; timeConstraintValid = false; return; } - + if (timeTo == null && timeToType != null) { // Time is specified but there is no value for it. // This means that event that should stop validity haven't happened yet - // therefore the mapping is still valid. + // therefore the mapping is still valid. timeConstraintValid = true; return; } - + if (timeTo != null && timeTo.compare(now) == DatatypeConstants.GREATER) { // between timeFrom and timeTo (also no timeFrom and before timeTo) nextRecomputeTime = timeTo; @@ -742,16 +742,16 @@ private void parseTimeConstraints(Task task, OperationResult result) throws Sche // no nextRecomputeTime set, there is nothing to recompute in the future timeConstraintValid = true; return; - + } else { // after timeTo // no nextRecomputeTime set, there is nothing to recompute in the future timeConstraintValid = false; return; } - + } - + private XMLGregorianCalendar parseTime(MappingTimeDeclarationType timeType, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException { if (timeType == null) { return null; @@ -788,7 +788,7 @@ private XMLGregorianCalendar parseTimeSource(VariableBindingDefinitionType sourc if (path.isEmpty()) { throw new SchemaException("Empty source path in "+getMappingContextDescription()); } - + Object sourceObject = ExpressionUtil.resolvePath(path, variables, sourceContext, objectResolver, "reference time definition in "+getMappingContextDescription(), task, result); if (sourceObject == null) { return null; @@ -818,7 +818,7 @@ private Collection> parseSources(Task task, OperationResult result) for (VariableBindingDefinitionType sourceType: sourceTypes) { Source source = parseSource(sourceType, task, result); source.recompute(); - + // Override existing sources (e.g. default source) Iterator> iterator = sources.iterator(); while (iterator.hasNext()) { @@ -827,7 +827,7 @@ private Collection> parseSources(Task task, OperationResult result) iterator.remove(); } } - + sources.add(source); } } @@ -869,29 +869,29 @@ private Source parseSo throw new IllegalStateException("Unknown resolve result "+sourceObject); } } - + // apply domain ValueSetDefinitionType domainSetType = sourceType.getSet(); if (domainSetType != null) { ValueSetDefinition setDef = new ValueSetDefinition(domainSetType, name, "domain of "+name.getLocalPart()+" in "+getMappingContextDescription(), task, result); setDef.init(expressionFactory); try { - + if (itemOld != null) { itemOld = itemOld.clone(); itemOld.filterValues(val -> setDef.containsTunnel(val)); } - + if (itemNew != null) { itemNew = itemNew.clone(); itemNew.filterValues(val -> setDef.containsTunnel(val)); } - + if (delta != null) { delta = delta.clone(); delta.filterValues(val -> setDef.containsTunnel(val)); } - + } catch (TunnelException te) { Throwable cause = te.getCause(); if (cause instanceof SchemaException) { @@ -903,14 +903,14 @@ private Source parseSo } } } - + Source source = new Source<>(itemOld, delta, itemNew, name); source.setResidualPath(residualPath); source.setResolvePath(resolvePath); source.setSubItemDeltas(subItemDeltas); return source; } - + private boolean sourcesChanged() { for (Source source: sources) { if (source.getDelta() != null) { @@ -919,7 +919,7 @@ private boolean sourcesChanged() { } return false; } - + private void parseTarget() throws SchemaException { VariableBindingDefinitionType targetType = mappingType.getTarget(); if (targetType == null) { @@ -944,14 +944,14 @@ private void parseTarget() throws SchemaException { stringPolicyResolver.setOutputPath(outputPath); } } - + public D getOutputDefinition() throws SchemaException { if (outputDefinition == null) { parseTarget(); } return outputDefinition; } - + public ItemPath getOutputPath() throws SchemaException { if (outputDefinition == null) { parseTarget(); @@ -970,7 +970,7 @@ private void fixDefinition() throws SchemaException { outputTriple.applyDefinition(outputDefinition); } } - + private void recomputeValues() { if (outputTriple == null) { return; @@ -997,7 +997,7 @@ private void setOrigin() { outputTriple.setOriginObject(originObject); } } - + private void evaluateCondition(Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException { ExpressionType conditionExpressionType = mappingType.getCondition(); if (conditionExpressionType == null) { @@ -1006,8 +1006,8 @@ private void evaluateCondition(Task task, OperationResult result) throws SchemaE conditionOutputTriple.addToZeroSet(new PrismPropertyValue(Boolean.TRUE)); return; } - Expression,PrismPropertyDefinition> expression = - ExpressionUtil.createCondition(conditionExpressionType, expressionFactory, + Expression,PrismPropertyDefinition> expression = + ExpressionUtil.createCondition(conditionExpressionType, expressionFactory, "condition in "+getMappingContextDescription(), task, result); ExpressionEvaluationContext context = new ExpressionEvaluationContext(sources, variables, "condition in "+getMappingContextDescription(), task, result); @@ -1020,13 +1020,13 @@ private void evaluateCondition(Task task, OperationResult result) throws SchemaE conditionOutputTriple = expression.evaluate(context); } - + private void evaluateExpression(Task task, OperationResult result, boolean conditionResultOld, boolean conditionResultNew) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException { ExpressionType expressionType = null; if (mappingType != null) { expressionType = mappingType.getExpression(); } - expression = expressionFactory.makeExpression(expressionType, outputDefinition, + expression = expressionFactory.makeExpression(expressionType, outputDefinition, "expression in "+getMappingContextDescription(), task, result); ExpressionEvaluationContext context = new ExpressionEvaluationContext(sources, variables, "expression in "+getMappingContextDescription(), task, result); @@ -1041,7 +1041,7 @@ private void evaluateExpression(Task task, OperationResult result, boolean condi outputTriple = expression.evaluate(context); if (outputTriple == null) { - + if (conditionResultNew) { // We need to return empty triple instead of null. // The condition was true (or there was not condition at all) @@ -1050,9 +1050,9 @@ private void evaluateExpression(Task task, OperationResult result, boolean condi // at all. outputTriple = new PrismValueDeltaSetTriple<>(); } - + } else { - + // reflect condition change if (!conditionResultOld && conditionResultNew) { // Condition change false -> true @@ -1068,7 +1068,7 @@ private void evaluateExpression(Task task, OperationResult result, boolean condi } } } - + /* (non-Javadoc) * @see com.evolveum.midpoint.model.common.mapping.PrismValueDeltaSetTripleProducer#getOutputTriple() */ @@ -1092,11 +1092,11 @@ public Item getOutput() throws SchemaException { output.addAll(PrismValue.cloneCollection(outputTriple.getNonNegativeValues())); return output; } - + public ItemDelta createEmptyDelta(ItemPath path) { return outputDefinition.createEmptyDelta(path); } - + private PrismPropertyValue filterValue(PrismPropertyValue propertyValue, List filters) { PrismPropertyValue filteredValue = propertyValue.clone(); filteredValue.setOriginType(OriginType.INBOUND); @@ -1112,17 +1112,17 @@ private PrismPropertyValue filterValue(PrismPropertyValue propertyValu return filteredValue; } - + private void transitionState(MappingEvaluationState newState) { state = newState; } - + private void assertState(MappingEvaluationState expecetdState) { if (state != expecetdState) { throw new IllegalArgumentException("Expected mapping state "+expecetdState+", but was "+state); } } - + /** * Shallow clone. Only the output is cloned deeply. */ diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/mapping/MappingEvaluationState.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/mapping/MappingEvaluationState.java index a43412e3401..8118c9c5c57 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/mapping/MappingEvaluationState.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/mapping/MappingEvaluationState.java @@ -24,16 +24,16 @@ public enum MappingEvaluationState { * Nothing is initialized, we are just preparing the mapping. */ UNINITIALIZED, - + /** * Prepared for evaluation. Declarative part of mapping is - * set and parsed. Variables are set. Source are set, but they can still change. + * set and parsed. Variables are set. Source are set, but they can still change. * The purpose of this state is that we can check if a mapping is activated * (i.e. if the input changes will "trigger" the mapping). And we can sort * mapping evaluation according to their dependencies. */ PREPARED, - + /** * Mapping was evaluated, results are produced. */ diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/mapping/MappingFactory.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/mapping/MappingFactory.java index f8dacbb3cd1..c45d5d3e887 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/mapping/MappingFactory.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/mapping/MappingFactory.java @@ -35,7 +35,7 @@ public class MappingFactory { // ObjectFactory objectFactory = new ObjectFactory(); - + private ExpressionFactory expressionFactory; private ObjectResolver objectResolver; private Protector protector; // not used for now @@ -43,7 +43,7 @@ public class MappingFactory { private FilterManager filterManager; private SecurityEnforcer securityEnforcer; private boolean profiling = false; - + public ExpressionFactory getExpressionFactory() { return expressionFactory; } @@ -51,7 +51,7 @@ public ExpressionFactory getExpressionFactory() { public void setExpressionFactory(ExpressionFactory expressionFactory) { this.expressionFactory = expressionFactory; } - + public void setProtector(Protector protector) { this.protector = protector; } diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/mapping/PrismValueDeltaSetTripleProducer.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/mapping/PrismValueDeltaSetTripleProducer.java index 6be7397ff12..20f8f186f04 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/mapping/PrismValueDeltaSetTripleProducer.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/mapping/PrismValueDeltaSetTripleProducer.java @@ -32,7 +32,7 @@ public interface PrismValueDeltaSetTripleProducer getOutputTriple(); - + MappingStrengthType getStrength(); PrismValueDeltaSetTripleProducer clone(); @@ -46,6 +46,6 @@ public interface PrismValueDeltaSetTripleProducer object; - + // We need to get old credential as a configuration. We cannot determine it // from the "object". E.g. in case of addition the object is the new object that // is just being added. The password will conflict with itself. private AbstractCredentialType oldCredentialType; - + private String shortDesc; - + private Task task; - + // state - + private boolean prepared = false; private QName credentialQName = null; private CredentialPolicyType credentialPolicy; private ValuePolicyType valuePolicy; - - + + public Protector getProtector() { return protector; } @@ -187,19 +187,19 @@ public OperationResult validateProtectedStringValue(ProtectedStringType value) t String clearValue = getClearValue(value); return validateStringValue(clearValue); } - + public OperationResult validateStringValue(String clearValue) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException { OperationResult result = new OperationResult(OPERATION_VALIDATE_VALUE); // TODO: later we need to replace the string message with something more structured. // something that can be localized StringBuilder messageBuilder = new StringBuilder(); - + prepare(); - + validateMinAge(messageBuilder, result); validateHistory(clearValue, messageBuilder, result); validateStringPolicy(clearValue, messageBuilder, result); - + String message = messageBuilder.toString(); if (message.isEmpty()) { result.computeStatus(); @@ -208,7 +208,7 @@ public OperationResult validateStringValue(String clearValue) throws SchemaExcep } return result; } - + private void prepare() throws SchemaException { if (!prepared) { preparePassword(); @@ -217,7 +217,7 @@ private void prepare() throws SchemaException { prepared = true; } } - + private void prepareValuePolicy() { if (credentialPolicy != null) { ObjectReferenceType valuePolicyRef = credentialPolicy.getValuePolicyRef(); @@ -243,15 +243,15 @@ private void preparePassword() { if (!QNameUtil.match(CredentialsType.F_PASSWORD, credentialQName)) { return; } - + credentialPolicy = SecurityUtil.getEffectivePasswordCredentialsPolicy(securityPolicy); } - + private void prepareNonce() throws SchemaException { if (!QNameUtil.match(CredentialsType.F_NONCE, credentialQName)) { return; } - + credentialPolicy = SecurityUtil.getEffectiveNonceCredentialsPolicy(securityPolicy); } @@ -274,7 +274,7 @@ private void validateMinAge(StringBuilder messageBuilder, OperationResult result if (lastChangeTimestamp == null) { return; } - + XMLGregorianCalendar changeAllowedTimestamp = XmlTypeConverter.addDuration(lastChangeTimestamp, minAge); if (changeAllowedTimestamp.compare(now) == DatatypeConstants.GREATER) { LOGGER.trace("Password minAge violated. lastChange={}, minAge={}, now={}", lastChangeTimestamp, minAge, now); @@ -287,7 +287,7 @@ private void validateMinAge(StringBuilder messageBuilder, OperationResult result } private void validateStringPolicy(String clearValue, StringBuilder messageBuilder, OperationResult result) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException { - + if (clearValue == null) { int minOccurs = getMinOccurs(); if (minOccurs == 0) { @@ -300,44 +300,44 @@ private void validateStringPolicy(String clearValue, StringBuilder messageBuilde return; } } - + if (valuePolicy == null) { LOGGER.trace("Skipping validating {} value. Value policy not specified.", shortDesc); return; } - - valuePolicyProcessor.validateValue(clearValue, valuePolicy, object, messageBuilder, + + valuePolicyProcessor.validateValue(clearValue, valuePolicy, object, messageBuilder, "user " + shortDesc + " value policy validation", task, result); } - + private void validateHistory(String clearValue, StringBuilder messageBuilder, OperationResult result) throws SchemaException { - + if (!QNameUtil.match(CredentialsType.F_PASSWORD, credentialQName)) { LOGGER.trace("Skipping validating {} history, only passowrd history is supported", shortDesc); return; } - + int historyLegth = getHistoryLength(); if (historyLegth == 0) { LOGGER.trace("Skipping validating {} history, because history length is set to zero", shortDesc); return; } - + PasswordType currentPasswordType = (PasswordType)oldCredentialType; if (currentPasswordType == null) { LOGGER.trace("Skipping validating {} history, because it is empty", shortDesc); return; } - + ProtectedStringType newPasswordPs = new ProtectedStringType(); newPasswordPs.setClearValue(clearValue); - + if (passwordEquals(newPasswordPs, currentPasswordType.getValue())) { LOGGER.trace("{} matched current value", shortDesc); appendHistoryViolationMessage(messageBuilder, result); return; } - + List sortedHistoryList = getSortedHistoryList( currentPasswordType.asPrismContainerValue().findContainer(PasswordType.F_HISTORY_ENTRY), false); int i = 1; @@ -352,20 +352,20 @@ private void validateHistory(String clearValue, StringBuilder messageBuilder, Op return; } i++; - } + } } - + private int getHistoryLength() { return SecurityUtil.getCredentialHistoryLength(credentialPolicy); } - + private Duration getMinAge() { if (credentialPolicy == null) { return null; } return credentialPolicy.getMinAge(); } - + private int getMinOccurs() { if (credentialPolicy == null) { return 0; @@ -395,14 +395,14 @@ private List getSortedHistoryList(PrismContainer,PrismPropertyDefinition> expression = expressionFactory.makeExpression(expressionType, outputDefinition , TEST_NAME, null, result); - + ExpressionVariables variables = new ExpressionVariables(); PrismObject user = PrismTestUtil.parseObject(USER_JACK_FILE); variables.addVariableDefinition(ExpressionConstants.VAR_FOCUS, user); @@ -106,20 +106,20 @@ public void testIterationCondition() throws Exception { variables.addVariableDefinition(ExpressionConstants.VAR_SHADOW, account); variables.addVariableDefinition(ExpressionConstants.VAR_ITERATION, 1); variables.addVariableDefinition(ExpressionConstants.VAR_ITERATION_TOKEN, "001"); - + ExpressionEvaluationContext expressionContext = new ExpressionEvaluationContext(null , variables, TEST_NAME, null, result); - + // WHEN PrismValueDeltaSetTriple> outputTriple = expression.evaluate(expressionContext); - + // THEN assertNotNull(outputTriple); outputTriple.checkConsistence(); - + // Make sure that the script is executed only once. There is no delta in the variables, no need to do it twice. assertScriptExecutionIncrement(1); } - + protected void rememberScriptExecutionCount() { lastScriptExecutionCount = InternalMonitor.getCount(InternalCounters.SCRIPT_EXECUTION_COUNT); } @@ -130,5 +130,5 @@ protected void assertScriptExecutionIncrement(int expectedIncrement) { assertEquals("Unexpected increment in script execution count", (long)expectedIncrement, actualIncrement); lastScriptExecutionCount = currentScriptExecutionCount; } - + } 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 cf9208482b8..0ab0cba0c7a 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 @@ -60,7 +60,7 @@ * */ public class TestExpressionUtil { - + public static final String USER_JACK_OID = "c0c010c0-d34d-b33f-f00d-111111111111"; public static final File USER_JACK_FILE = new File(MidPointTestConstants.OBJECTS_DIR, USER_JACK_OID + ".xml"); @@ -74,140 +74,140 @@ public void setup() throws SchemaException, SAXException, IOException { public void testResolvePathStringProperty() throws Exception { final String TEST_NAME = "testResolvePathStringProperty"; System.out.println("\n===[ "+TEST_NAME+" ]===\n"); - + // GIVEN // WHEN PrismProperty resolvedProperty = resolvePath("$user/description", TEST_NAME); - + // THEN assertEquals("Wrong resolved property value", "jack", resolvedProperty.getRealValue()); } - + @Test public void testResolvePathPolyStringProperty() throws Exception { final String TEST_NAME = "testResolvePathPolyStringProperty"; System.out.println("\n===[ "+TEST_NAME+" ]===\n"); - + // GIVEN // WHEN PrismProperty resolvedProperty = resolvePath("$user/fullName", TEST_NAME); - + // THEN assertEquals("Wrong resolved property value", PrismTestUtil.createPolyString("Jack Sparrow"), resolvedProperty.getRealValue()); } - + @Test public void testResolvePathPolyStringOrig() throws Exception { final String TEST_NAME = "testResolvePathPolyStringOrig"; System.out.println("\n===[ "+TEST_NAME+" ]===\n"); - + // GIVEN // WHEN String resolved = resolvePath("$user/fullName/t:orig", TEST_NAME); - + // THEN assertEquals("Wrong resolved property value", "Jack Sparrow", resolved); } - + @Test public void testResolvePathPolyStringNorm() throws Exception { final String TEST_NAME = "testResolvePathPolyStringNorm"; System.out.println("\n===[ "+TEST_NAME+" ]===\n"); - + // GIVEN // WHEN String resolved = resolvePath("$user/fullName/t:norm", TEST_NAME); - + // THEN assertEquals("Wrong resolved property value", "jack sparrow", resolved); } - + @Test public void testResolvePathPolyStringOdo() throws Exception { final String TEST_NAME = "testResolvePathPolyStringOdo"; System.out.println("\n===[ "+TEST_NAME+" ]===\n"); - + // GIVEN // WHEN ItemDeltaItem,PrismPropertyDefinition> idi = resolvePathOdo("$user/fullName", TEST_NAME); - + // THEN - assertEquals("Wrong resolved idi old value", PrismTestUtil.createPolyString("Jack Sparrow"), + assertEquals("Wrong resolved idi old value", PrismTestUtil.createPolyString("Jack Sparrow"), ((PrismProperty)idi.getItemOld()).getRealValue()); - assertEquals("Wrong resolved idi new value", PrismTestUtil.createPolyString("Captain Jack Sparrow"), + assertEquals("Wrong resolved idi new value", PrismTestUtil.createPolyString("Captain Jack Sparrow"), ((PrismProperty)idi.getItemNew()).getRealValue()); - - assertTrue("Wrong residual path: "+idi.getResidualPath(), + + assertTrue("Wrong residual path: "+idi.getResidualPath(), idi.getResidualPath() == null || idi.getResidualPath().isEmpty()); - + } @Test public void testResolvePathPolyStringOdoOrig() throws Exception { final String TEST_NAME = "testResolvePathPolyStringOdoOrig"; System.out.println("\n===[ "+TEST_NAME+" ]===\n"); - + // GIVEN // WHEN ItemDeltaItem,PrismPropertyDefinition> idi = resolvePathOdo("$user/fullName/t:orig", TEST_NAME); - + // THEN - assertEquals("Wrong resolved idi old value", PrismTestUtil.createPolyString("Jack Sparrow"), + assertEquals("Wrong resolved idi old value", PrismTestUtil.createPolyString("Jack Sparrow"), ((PrismProperty)idi.getItemOld()).getRealValue()); - assertEquals("Wrong resolved idi new value", PrismTestUtil.createPolyString("Captain Jack Sparrow"), + assertEquals("Wrong resolved idi new value", PrismTestUtil.createPolyString("Captain Jack Sparrow"), ((PrismProperty)idi.getItemNew()).getRealValue()); - + PrismAsserts.assertPathEquivalent("Wrong residual path", new ItemPath(PolyString.F_ORIG), idi.getResidualPath()); } - + @Test public void testResolvePathPolyStringOdoNorm() throws Exception { final String TEST_NAME = "testResolvePathPolyStringOdoNorm"; System.out.println("\n===[ "+TEST_NAME+" ]===\n"); - + // GIVEN // WHEN ItemDeltaItem,PrismPropertyDefinition> idi = resolvePathOdo("$user/fullName/t:norm", TEST_NAME); - + // THEN - assertEquals("Wrong resolved idi old value", PrismTestUtil.createPolyString("Jack Sparrow"), + assertEquals("Wrong resolved idi old value", PrismTestUtil.createPolyString("Jack Sparrow"), ((PrismProperty)idi.getItemOld()).getRealValue()); - assertEquals("Wrong resolved idi new value", PrismTestUtil.createPolyString("Captain Jack Sparrow"), + assertEquals("Wrong resolved idi new value", PrismTestUtil.createPolyString("Captain Jack Sparrow"), ((PrismProperty)idi.getItemNew()).getRealValue()); PrismAsserts.assertPathEquivalent("Wrong residual path", new ItemPath(PolyString.F_NORM), idi.getResidualPath()); - + } private T resolvePath(String path, final String TEST_NAME) throws SchemaException, ObjectNotFoundException, IOException { ExpressionVariables variables = createVariables(); return resolvePath(path, variables, TEST_NAME); } - + private T resolvePathOdo(String path, final String TEST_NAME) throws SchemaException, ObjectNotFoundException, IOException { ExpressionVariables variables = createVariablesOdo(); return resolvePath(path, variables, TEST_NAME); } - + private T resolvePath(String path, ExpressionVariables variables, final String TEST_NAME) throws SchemaException, ObjectNotFoundException { OperationResult result = new OperationResult(TestExpressionUtil.class.getName() + "." + TEST_NAME); ItemPath itemPath = toItemPath(path); - + // WHEN Object resolved = ExpressionUtil.resolvePath(itemPath, variables, null, null, TEST_NAME, null, result); - + // THEN System.out.println("Resolved:"); System.out.println(resolved); - + return (T) resolved; } @@ -216,7 +216,7 @@ private ExpressionVariables createVariables() throws SchemaException, IOExceptio variables.addVariableDefinition(ExpressionConstants.VAR_USER, createUser()); return variables; } - + private ExpressionVariables createVariablesOdo() throws SchemaException, IOException { ExpressionVariables variables = new ExpressionVariables(); PrismObject userOld = createUser(); @@ -236,12 +236,12 @@ private PrismObject createUser() throws SchemaException, IOException { private ItemPath toItemPath(String stringPath) { String xml = "" + + "xmlns:t='"+SchemaConstants.NS_TYPES+"'>" + stringPath + ""; Document doc = DOMUtil.parseDocument(xml); Element element = DOMUtil.getFirstChildElement(doc); return new ItemPathHolder(element).toItemPath(); - + } } diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/AbstractScriptTest.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/AbstractScriptTest.java index db2222fb8b2..feb1295033b 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/AbstractScriptTest.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/AbstractScriptTest.java @@ -73,12 +73,12 @@ public abstract class AbstractScriptTest { protected static File BASE_TEST_DIR = new File("src/test/resources/expression"); protected static File OBJECTS_DIR = new File("src/test/resources/objects"); protected static final String USER_OID = "c0c010c0-d34d-b33f-f00d-111111111111"; - + public static final Trace LOGGER = TraceManager.getTrace(AbstractScriptTest.class); protected ScriptExpressionFactory scriptExpressionfactory; protected ScriptEvaluator evaluator; - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); @@ -102,16 +102,16 @@ public void setupFactory() { } protected abstract ScriptEvaluator createEvaluator(PrismContext prismContext, Protector protector); - + protected abstract File getTestDir(); - + protected boolean supportsRootNode() { return false; } - + @Test public void testExpressionSimple() throws Exception { - evaluateAndAssertStringScalarExpresssion("expression-simple.xml", + evaluateAndAssertStringScalarExpresssion("expression-simple.xml", "testExpressionSimple", null, "foobar"); } @@ -119,8 +119,8 @@ public void testExpressionSimple() throws Exception { @Test public void testExpressionStringVariables() throws Exception { evaluateAndAssertStringScalarExpresssion( - "expression-string-variables.xml", - "testExpressionStringVariables", + "expression-string-variables.xml", + "testExpressionStringVariables", ExpressionVariables.create( new QName(NS_X, "foo"), "FOO", new QName(NS_Y, "bar"), "BAR" @@ -132,63 +132,63 @@ public void testExpressionStringVariables() throws Exception { @Test public void testExpressionObjectRefVariables() throws Exception { evaluateAndAssertStringScalarExpresssion( - "expression-objectref-variables.xml", - "testExpressionObjectRefVariables", + "expression-objectref-variables.xml", + "testExpressionObjectRefVariables", ExpressionVariables.create( new QName(NS_X, "foo"), "Captain", - new QName(NS_Y, "jack"), + new QName(NS_Y, "jack"), MiscSchemaUtil.createObjectReference(USER_OID, UserType.COMPLEX_TYPE) - ), + ), "Captain emp1234"); } @Test public void testExpressionObjectRefVariablesPolyString() throws Exception { evaluateAndAssertStringScalarExpresssion( - "expression-objectref-variables-polystring.xml", + "expression-objectref-variables-polystring.xml", "testExpressionObjectRefVariablesPolyString", ExpressionVariables.create( new QName(NS_X, "foo"), "Captain", - new QName(NS_Y, "jack"), + new QName(NS_Y, "jack"), MiscSchemaUtil.createObjectReference(USER_OID, UserType.COMPLEX_TYPE) ), "Captain Jack Sparrow"); } // Using similar settings that will be used with mapping and SYSTEM VARIABLES - + @Test public void testUserGivenName() throws Exception { evaluateAndAssertStringScalarExpresssion( - "expression-user-given-name.xml", - "testUserGivenName", + "expression-user-given-name.xml", + "testUserGivenName", createUserScriptVariables(), "Jack"); } - + @Test public void testUserExtensionShip() throws Exception { evaluateAndAssertStringScalarExpresssion( - "expression-user-extension-ship.xml", - "testUserExtensionShip", + "expression-user-extension-ship.xml", + "testUserExtensionShip", createUserScriptVariables(), "Black Pearl"); } - + @Test public void testUserExtensionShipPath() throws Exception { evaluateAndAssertStringScalarExpresssion( - "expression-user-extension-ship-path.xml", - "testUserExtensionShipPath", + "expression-user-extension-ship-path.xml", + "testUserExtensionShipPath", createUserScriptVariables(), "Black Pearl"); } - + @Test public void testUserExtensionStringifyFullName() throws Exception { evaluateAndAssertStringScalarExpresssion( - "expression-user-stringify-full-name.xml", - "testUserExtensionStringifyFullName", + "expression-user-stringify-full-name.xml", + "testUserExtensionStringifyFullName", createUserScriptVariables(), "Jack Sparrow"); } @@ -197,12 +197,12 @@ public void testUserExtensionStringifyFullName() throws Exception { // TODO: user + polystring // TODO: user + numeric // TODO: user + no property value - + private ExpressionVariables createUserScriptVariables() { - return ExpressionVariables.create(SchemaConstants.C_USER, + return ExpressionVariables.create(SchemaConstants.C_USER, MiscSchemaUtil.createObjectReference(USER_OID, UserType.COMPLEX_TYPE)); } - + // TODO: shadow + attributes @Test @@ -210,11 +210,11 @@ public void testRootNode() throws Exception { if (!supportsRootNode()) { return; } - + evaluateAndAssertStringScalarExpresssion( - "expression-root-node.xml", - "testRootNode", - ExpressionVariables.create(null, + "expression-root-node.xml", + "testRootNode", + ExpressionVariables.create(null, MiscSchemaUtil.createObjectReference(USER_OID, UserType.COMPLEX_TYPE)), "Black Pearl"); } @@ -222,35 +222,35 @@ public void testRootNode() throws Exception { @Test public void testExpressionList() throws Exception { evaluateAndAssertStringListExpresssion( - "expression-list.xml", - "testExpressionList", + "expression-list.xml", + "testExpressionList", ExpressionVariables.create( - new QName(NS_Y, "jack"), + new QName(NS_Y, "jack"), MiscSchemaUtil.createObjectReference(USER_OID, UserType.COMPLEX_TYPE) ), - "Leaders", "Followers"); + "Leaders", "Followers"); } - + @Test public void testExpressionFunc() throws Exception { - evaluateAndAssertStringScalarExpresssion("expression-func.xml", + evaluateAndAssertStringScalarExpresssion("expression-func.xml", "testExpressionFunc", null, "gulocka v jamocke"); } - + @Test public void testExpressionFuncConcatName() throws Exception { - evaluateAndAssertStringScalarExpresssion("expression-func-concatname.xml", + evaluateAndAssertStringScalarExpresssion("expression-func-concatname.xml", "testExpressionFuncConcatName", null, "Horatio Torquemada Marley"); } - + private ScriptExpressionEvaluatorType parseScriptType(String fileName) throws SchemaException, IOException, JAXBException { ScriptExpressionEvaluatorType expressionType = PrismTestUtil.parseAtomicValue( new File(getTestDir(), fileName), ScriptExpressionEvaluatorType.COMPLEX_TYPE); return expressionType; } - - private List> evaluateExpression(ScriptExpressionEvaluatorType scriptType, ItemDefinition outputDefinition, + + private List> evaluateExpression(ScriptExpressionEvaluatorType scriptType, ItemDefinition outputDefinition, ExpressionVariables variables, String shortDesc, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException { ScriptExpression scriptExpression = scriptExpressionfactory.createScriptExpression(scriptType, outputDefinition, shortDesc); List> resultValues = scriptExpression.evaluate(variables, null, false, shortDesc, null, result); @@ -263,8 +263,8 @@ private List> evaluateExpression(ScriptExpressionEvalu } return resultValues; } - - private List> evaluateExpression(ScriptExpressionEvaluatorType scriptType, QName typeName, boolean scalar, + + private List> evaluateExpression(ScriptExpressionEvaluatorType scriptType, QName typeName, boolean scalar, ExpressionVariables variables, String shortDesc, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException { ItemDefinition outputDefinition = new PrismPropertyDefinitionImpl(PROPERTY_NAME, typeName, PrismTestUtil.getPrismContext()); if (!scalar) { @@ -272,13 +272,13 @@ private List> evaluateExpression(ScriptExpressionEvalu } return evaluateExpression(scriptType, outputDefinition, variables, shortDesc, result); } - - private PrismPropertyValue evaluateExpressionScalar(ScriptExpressionEvaluatorType scriptType, QName typeName, + + private PrismPropertyValue evaluateExpressionScalar(ScriptExpressionEvaluatorType scriptType, QName typeName, ExpressionVariables variables, String shortDesc, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException { List> expressionResultList = evaluateExpression(scriptType, typeName, true, variables, shortDesc, result); return asScalar(expressionResultList, shortDesc); } - + private PrismPropertyValue asScalar(List> expressionResultList, String shortDesc) { if (expressionResultList.size() > 1) { AssertJUnit.fail("Expression "+shortDesc+" produces a list of "+expressionResultList.size()+" while only expected a single value: "+expressionResultList); @@ -288,7 +288,7 @@ private PrismPropertyValue asScalar(List> expressio } return expressionResultList.iterator().next(); } - + protected void evaluateAndAssertStringScalarExpresssion(String fileName, String testName, ExpressionVariables variables, String expectedValue) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException { List> expressionResultList = evaluateStringExpresssion(fileName, testName, variables, true); PrismPropertyValue expressionResult = asScalar(expressionResultList, testName); @@ -312,18 +312,18 @@ private List> evaluateStringExpresssion(String fileNa ScriptExpressionEvaluatorType scriptType = parseScriptType(fileName); OperationResult opResult = new OperationResult(testName); - return evaluateExpression(scriptType, DOMUtil.XSD_STRING, true, variables, testName, opResult); + return evaluateExpression(scriptType, DOMUtil.XSD_STRING, true, variables, testName, opResult); } - + private List> evaluateBooleanExpresssion(String fileName, String testName, ExpressionVariables variables, boolean scalar) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException { displayTestTitle(testName); ScriptExpressionEvaluatorType scriptType = parseScriptType(fileName); OperationResult opResult = new OperationResult(testName); - return evaluateExpression(scriptType, DOMUtil.XSD_BOOLEAN, true, variables, testName, opResult); + return evaluateExpression(scriptType, DOMUtil.XSD_BOOLEAN, true, variables, testName, opResult); } - - + + private void displayTestTitle(String testName) { System.out.println("===[ "+evaluator.getLanguageName()+": "+testName+" ]==========================="); LOGGER.info("===[ "+evaluator.getLanguageName()+": "+testName+" ]==========================="); diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestExpressionFunctions.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestExpressionFunctions.java index 9ccb065b3e5..e62450f213d 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestExpressionFunctions.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestExpressionFunctions.java @@ -54,14 +54,14 @@ * @author semancik */ public class TestExpressionFunctions { - + public static final File TEST_DIR = new File("src/test/resources/expression/functions"); public static final File USER_JACK_FILE = new File(TEST_DIR, "user-jack.xml"); public static final File ACCOUNT_JACK_FILE = new File(TEST_DIR, "account-jack.xml"); public static final File RESOURCE_OPENDJ_FILE = new File(TEST_DIR, "resource-opendj.xml"); private static final String ATTR_FULLNAME_LOCAL_PART = "fullname"; private static final String ATTR_WEAPON_LOCAL_PART = "weapon"; - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); @@ -72,30 +72,30 @@ public void setup() throws SchemaException, SAXException, IOException { public void testGetExtensionPropertyValue() throws Exception { final String TEST_NAME = "testGetExtensionPropertyValue"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN BasicExpressionFunctions f = createBasicFunctions(); PrismObject userJack = PrismTestUtil.parseObject(USER_JACK_FILE); // WHEN - String shipExtension = f.getExtensionPropertyValue(userJack.asObjectable(), + String shipExtension = f.getExtensionPropertyValue(userJack.asObjectable(), SchemaTestConstants.EXTENSION_SHIP_ELEMENT); // THEN assertEquals("Wrong value for extension "+SchemaTestConstants.EXTENSION_SHIP_ELEMENT, "Black Pearl", shipExtension); } - + @Test public void testGetExtensionPropertyValueParts() throws Exception { final String TEST_NAME = "testGetExtensionPropertyValueParts"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN BasicExpressionFunctions f = createBasicFunctions(); PrismObject userJack = PrismTestUtil.parseObject(USER_JACK_FILE); // WHEN - String shipExtension = f.getExtensionPropertyValue(userJack.asObjectable(), + String shipExtension = f.getExtensionPropertyValue(userJack.asObjectable(), SchemaTestConstants.EXTENSION_SHIP_ELEMENT.getNamespaceURI(), SchemaTestConstants.EXTENSION_SHIP_ELEMENT.getLocalPart()); @@ -107,40 +107,40 @@ public void testGetExtensionPropertyValueParts() throws Exception { public void testGetExtensionPropertyValueNotPresent() throws Exception { final String TEST_NAME = "testGetExtensionPropertyValueNotPresent"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN BasicExpressionFunctions f = createBasicFunctions(); PrismObject userJack = PrismTestUtil.parseObject(USER_JACK_FILE); // WHEN - String extensionVal = f.getExtensionPropertyValue(userJack.asObjectable(), + String extensionVal = f.getExtensionPropertyValue(userJack.asObjectable(), new QName(SchemaTestConstants.NS_EXTENSION, "kajdsfhklfdsjh")); // THEN assertNull("Unexpected value for extension "+SchemaTestConstants.EXTENSION_SHIP_ELEMENT+": "+extensionVal, extensionVal); } - + @Test public void testGetExtensionPropertyValueNullObject() throws Exception { final String TEST_NAME = "testGetExtensionPropertyValueNullObject"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN BasicExpressionFunctions f = createBasicFunctions(); // WHEN - String shipExtension = f.getExtensionPropertyValue(null, + String shipExtension = f.getExtensionPropertyValue(null, SchemaTestConstants.EXTENSION_SHIP_ELEMENT); // THEN assertNull("Unexpected value for extension "+SchemaTestConstants.EXTENSION_SHIP_ELEMENT+": "+shipExtension, shipExtension); } - + @Test public void testGetAttributeValueParts() throws Exception { final String TEST_NAME = "testGetAttributeValueParts"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN BasicExpressionFunctions f = createBasicFunctions(); PrismObject accountJack = PrismTestUtil.parseObject(ACCOUNT_JACK_FILE); @@ -158,7 +158,7 @@ public void testGetAttributeValueParts() throws Exception { public void testGetAttributeValueDefaultRi() throws Exception { final String TEST_NAME = "testGetAttributeValueDefaultRi"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN BasicExpressionFunctions f = createBasicFunctions(); PrismObject accountJack = PrismTestUtil.parseObject(ACCOUNT_JACK_FILE); @@ -175,7 +175,7 @@ public void testGetAttributeValueDefaultRi() throws Exception { public void testGetAttributeValuesParts() throws Exception { final String TEST_NAME = "testGetAttributeValuesParts"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN BasicExpressionFunctions f = createBasicFunctions(); PrismObject accountJack = PrismTestUtil.parseObject(ACCOUNT_JACK_FILE); @@ -193,7 +193,7 @@ public void testGetAttributeValuesParts() throws Exception { public void testGetAttributeValuesDefaultRi() throws Exception { final String TEST_NAME = "testGetAttributeValuesDefaultRi"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN BasicExpressionFunctions f = createBasicFunctions(); PrismObject accountJack = PrismTestUtil.parseObject(ACCOUNT_JACK_FILE); @@ -205,12 +205,12 @@ public void testGetAttributeValuesDefaultRi() throws Exception { // THEN TestUtil.assertSetEquals("Wrong value for attribute "+ATTR_WEAPON_LOCAL_PART, attrVals, "rum", "smell"); } - + @Test public void testgetResourceIcfConfigurationPropertyValueStringHost() throws Exception { final String TEST_NAME = "testgetResourceIcfConfigurationPropertyValueStringHost"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN BasicExpressionFunctions f = createBasicFunctions(); PrismObject resource = PrismTestUtil.parseObject(RESOURCE_OPENDJ_FILE); @@ -221,12 +221,12 @@ public void testgetResourceIcfConfigurationPropertyValueStringHost() throws Exce // THEN assertEquals("Wrong value of ICF configuration property", "localhost", val); } - + @Test public void testgetResourceIcfConfigurationPropertyValueStringPort() throws Exception { final String TEST_NAME = "testgetResourceIcfConfigurationPropertyValueStringPort"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN BasicExpressionFunctions f = createBasicFunctions(); PrismObject resource = PrismTestUtil.parseObject(RESOURCE_OPENDJ_FILE); @@ -242,7 +242,7 @@ public void testgetResourceIcfConfigurationPropertyValueStringPort() throws Exce public void testDetermineLdapSingleAttributeValue01() throws Exception { final String TEST_NAME = "testDetermineLdapSingleAttributeValue01"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN BasicExpressionFunctions f = createBasicFunctions(); String dn = "uid=foo, ou=People, dc=example,dc=com"; @@ -262,7 +262,7 @@ public void testDetermineLdapSingleAttributeValue01() throws Exception { @Test public void testDetermineLdapSingleAttributeValue02() throws Exception { System.out.println("\n===[ testDetermineLdapSingleAttributeValue02 ]===\n"); - + // GIVEN BasicExpressionFunctions f = createBasicFunctions(); String dn = "cn=jack+uid=FooBAR, ou=People, dc=example,dc=com"; @@ -285,7 +285,7 @@ public void testDetermineLdapSingleAttributeValue02() throws Exception { @Test public void testDetermineLdapSingleAttributeValueSingle() throws Exception { System.out.println("\n===[ testDetermineLdapSingleAttributeValueSingle ]===\n"); - + // GIVEN BasicExpressionFunctions f = createBasicFunctions(); String dn = "cn=jack+uid=FooBar, ou=People, dc=example,dc=com"; @@ -305,7 +305,7 @@ public void testDetermineLdapSingleAttributeValueSingle() throws Exception { @Test public void testDetermineLdapSingleAttributeValueNull() throws Exception { System.out.println("\n===[ testDetermineLdapSingleAttributeValueNull ]===\n"); - + // GIVEN BasicExpressionFunctions f = createBasicFunctions(); String dn = "cn=jack+uid=FooBar, ou=People, dc=example,dc=com"; @@ -319,11 +319,11 @@ public void testDetermineLdapSingleAttributeValueNull() throws Exception { System.out.println("Resulting value: "+resultValue); assertNull("Result value is not null", resultValue); } - + @Test public void testDetermineLdapSingleAttributeValueFallback() throws Exception { System.out.println("\n===[ testDetermineLdapSingleAttributeValueFallback ]===\n"); - + // GIVEN BasicExpressionFunctions f = createBasicFunctions(); String dn = "cn=jack, ou=People, dc=example,dc=com"; @@ -343,11 +343,11 @@ public void testDetermineLdapSingleAttributeValueFallback() throws Exception { @Test public void testFormatDateTime() throws Exception { System.out.println("\n===[ testFormatDateTime ]===\n"); - + // GIVEN BasicExpressionFunctions f = createBasicFunctions(); XMLGregorianCalendar xmlCal = XmlTypeConverter.createXMLGregorianCalendar(1975, 5, 30, 22, 30, 0, 0, DatatypeConstants.FIELD_UNDEFINED); // don't use GMT (offset 0) because serialized value is then in local time - + // WHEN String resultValue = f.formatDateTime("yyyy MM dd HH:mm:ss.SSS", xmlCal); // don't include timezone in the format string, it is hard to check then @@ -362,10 +362,10 @@ public void testFormatDateTime() throws Exception { public void testParseDateTime() throws Exception { final String TEST_NAME = "testParseDateTime"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN BasicExpressionFunctions f = createBasicFunctions(); - + // WHEN XMLGregorianCalendar resultValue = f.parseDateTime("yyyy MM dd HH:mm:ss.SSS zzzz", "1975 05 30 22:30:00.000 Central European Time"); @@ -378,13 +378,13 @@ public void testParseDateTime() throws Exception { assertEquals("Wrong result value", xmlCal, resultValue); } - + private BasicExpressionFunctions createBasicFunctions() throws SchemaException, SAXException, IOException { PrismContext prismContext = PrismTestUtil.createInitializedPrismContext(); Protector protector = new ProtectorImpl(); return new BasicExpressionFunctions(prismContext, protector); } - + @Test public void testStringify() throws Exception { final String TEST_NAME = "testStringifyString"; @@ -397,7 +397,7 @@ public void testStringify() throws Exception { assertEquals("", basic.stringify(null)); assertEquals("", basic.stringify("")); } - + @Test public void testConcatName() throws Exception { final String TEST_NAME = "testConcatName"; @@ -416,7 +416,7 @@ public void testConcatName() throws Exception { assertEquals("foo bar", basic.concatName(" foo ",null," bar ")); assertEquals("foo bar", basic.concatName(" foo "," "," bar ")); } - + private PolyString poly(String s) { return PrismTestUtil.createPolyString(s); } @@ -435,13 +435,13 @@ public void testToAscii() throws Exception { assertEquals(null, basic.toAscii(null)); assertEquals("", basic.toAscii("")); } - + @Test public void testComposeDn() throws Exception { final String TEST_NAME = "testComposeDn"; TestUtil.displayTestTitle(TEST_NAME); BasicExpressionFunctions basic = createBasicFunctions(); - + assertEquals("cn=foo,o=bar", basic.composeDn("cn","foo","o","bar")); assertEquals("cn=foo,o=bar", basic.composeDn("cn",PrismTestUtil.createPolyString("foo"),"o","bar")); assertEquals("cn=foo,o=bar", basic.composeDn("cn",PrismTestUtil.createPolyStringType("foo"),"o","bar")); @@ -457,13 +457,13 @@ public void testComposeDn() throws Exception { assertEquals(null, basic.composeDn("")); assertEquals(null, basic.composeDn(" ")); } - + @Test public void testComposeDnWithSuffix() throws Exception { final String TEST_NAME = "testComposeDnWithSuffix"; TestUtil.displayTestTitle(TEST_NAME); BasicExpressionFunctions basic = createBasicFunctions(); - + assertEquals("cn=foo,ou=baz,o=bar", basic.composeDnWithSuffix(new Rdn("cn","foo"),"ou=baz,o=bar")); assertEquals("cn=foo,ou=baz,o=bar", basic.composeDnWithSuffix(new Rdn("cn","foo"),new LdapName("ou=baz,o=bar"))); assertEquals("cn=foo,ou=baz,o=bar", basic.composeDnWithSuffix("cn","foo","ou=baz,o=bar")); @@ -485,35 +485,35 @@ public void testComposeDnWithSuffix() throws Exception { assertEquals(null, basic.composeDnWithSuffix("")); assertEquals(null, basic.composeDnWithSuffix(" ")); } - + @Test public void testParseFullName() throws Exception { final String TEST_NAME = "testParseFullName"; TestUtil.displayTestTitle(TEST_NAME); BasicExpressionFunctions basic = createBasicFunctions(); - + assertEquals(null, basic.parseGivenName(null)); assertEquals(null, basic.parseGivenName(" ")); - + assertEquals("Jack", basic.parseGivenName("Jack Sparrow")); assertEquals("Jack", basic.parseGivenName(" Jack Sparrow ")); assertEquals("Jack", basic.parseGivenName(new PolyString("Jack Sparrow"))); assertEquals("Sparrow", basic.parseFamilyName("Jack Sparrow")); assertEquals("Sparrow", basic.parseFamilyName(" Jack Sparrow ")); - + assertEquals("Tim", basic.parseGivenName("Tim Berners-Lee")); assertEquals("Berners-Lee", basic.parseFamilyName("Tim Berners-Lee")); - + assertEquals("Cassius", basic.parseGivenName("Cassius Marcellus \"Muhammad Ali\" Clay, Jr.")); assertEquals("Marcellus", basic.parseAdditionalName("Cassius Marcellus \"Muhammad Ali\" Clay, Jr.")); assertEquals("Clay", basic.parseFamilyName("Cassius Marcellus \"Muhammad Ali\" Clay, Jr.")); assertEquals("Muhammad Ali", basic.parseNickName("Cassius Marcellus \"Muhammad Ali\" Clay, Jr.")); assertEquals("Jr.", basic.parseHonorificSuffix("Cassius Marcellus \"Muhammad Ali\" Clay, Jr.")); - + assertEquals("Radovan", basic.parseGivenName("Ing. Radovan Semančík, PhD.")); assertEquals("Semančík", basic.parseFamilyName("Ing. Radovan Semančík, PhD.")); assertEquals("Ing.", basic.parseHonorificPrefix("Ing. Radovan Semančík, PhD.")); assertEquals("PhD.", basic.parseHonorificSuffix("Ing. Radovan Semančík, PhD.")); } - + } diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestGroovyExpressions.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestGroovyExpressions.java index b0da6e77a9b..63a933e6d01 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestGroovyExpressions.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestGroovyExpressions.java @@ -52,8 +52,8 @@ protected File getTestDir() { @Test public void testExpressionPolyStringEquals101() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-1.xml", - "testExpressionPolyStringEquals101", + "expression-polystring-equals-1.xml", + "testExpressionPolyStringEquals101", ExpressionVariables.create( new QName(NS_X, "foo"), "FOO", new QName(NS_Y, "bar"), "BAR" @@ -64,8 +64,8 @@ public void testExpressionPolyStringEquals101() throws Exception { @Test public void testExpressionPolyStringEquals102() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-1.xml", - "testExpressionPolyStringEquals102", + "expression-polystring-equals-1.xml", + "testExpressionPolyStringEquals102", ExpressionVariables.create( new QName(NS_X, "foo"), "FOOBAR", new QName(NS_Y, "bar"), "BAR" @@ -76,8 +76,8 @@ public void testExpressionPolyStringEquals102() throws Exception { @Test public void testExpressionPolyStringEquals111() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-1.xml", - "testExpressionPolyStringEquals111", + "expression-polystring-equals-1.xml", + "testExpressionPolyStringEquals111", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyString("FOO"), new QName(NS_Y, "bar"), "BAR" @@ -88,20 +88,20 @@ public void testExpressionPolyStringEquals111() throws Exception { @Test public void testExpressionPolyStringEquals112() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-1.xml", - "testExpressionPolyStringEquals112", + "expression-polystring-equals-1.xml", + "testExpressionPolyStringEquals112", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyString("FOOBAR"), new QName(NS_Y, "bar"), "BAR" ), Boolean.FALSE); } - + @Test public void testExpressionPolyStringEquals121() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-1.xml", - "testExpressionPolyStringEquals121", + "expression-polystring-equals-1.xml", + "testExpressionPolyStringEquals121", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyStringType("FOO"), new QName(NS_Y, "bar"), "BAR" @@ -112,20 +112,20 @@ public void testExpressionPolyStringEquals121() throws Exception { @Test public void testExpressionPolyStringEquals122() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-1.xml", - "testExpressionPolyStringEquals122", + "expression-polystring-equals-1.xml", + "testExpressionPolyStringEquals122", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyStringType("FOOBAR"), new QName(NS_Y, "bar"), "BAR" ), Boolean.FALSE); } - + @Test public void testExpressionPolyStringEquals201() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-2.xml", - "testExpressionPolyStringEquals201", + "expression-polystring-equals-2.xml", + "testExpressionPolyStringEquals201", ExpressionVariables.create( new QName(NS_X, "foo"), "FOO", new QName(NS_Y, "bar"), "BAR" @@ -136,8 +136,8 @@ public void testExpressionPolyStringEquals201() throws Exception { @Test public void testExpressionPolyStringEquals202() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-2.xml", - "testExpressionPolyStringEquals202", + "expression-polystring-equals-2.xml", + "testExpressionPolyStringEquals202", ExpressionVariables.create( new QName(NS_X, "foo"), "FOOBAR", new QName(NS_Y, "bar"), "BAR" @@ -148,8 +148,8 @@ public void testExpressionPolyStringEquals202() throws Exception { @Test public void testExpressionPolyStringEquals211() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-2.xml", - "testExpressionPolyStringEquals211", + "expression-polystring-equals-2.xml", + "testExpressionPolyStringEquals211", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyString("FOO"), new QName(NS_Y, "bar"), "BAR" @@ -160,8 +160,8 @@ public void testExpressionPolyStringEquals211() throws Exception { @Test public void testExpressionPolyStringEquals212() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-2.xml", - "testExpressionPolyStringEquals212", + "expression-polystring-equals-2.xml", + "testExpressionPolyStringEquals212", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyString("FOOBAR"), new QName(NS_Y, "bar"), "BAR" @@ -172,8 +172,8 @@ public void testExpressionPolyStringEquals212() throws Exception { @Test public void testExpressionPolyStringEquals221() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-2.xml", - "testExpressionPolyStringEquals221", + "expression-polystring-equals-2.xml", + "testExpressionPolyStringEquals221", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyStringType("FOO"), new QName(NS_Y, "bar"), "BAR" @@ -184,20 +184,20 @@ public void testExpressionPolyStringEquals221() throws Exception { @Test public void testExpressionPolyStringEquals222() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-2.xml", - "testExpressionPolyStringEquals222", + "expression-polystring-equals-2.xml", + "testExpressionPolyStringEquals222", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyStringType("FOOBAR"), new QName(NS_Y, "bar"), "BAR" ), Boolean.FALSE); } - + @Test public void testExpressionPolyStringEqualsStringify101() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-1.xml", - "testExpressionPolyStringEqualsStringify101", + "expression-polystring-equals-stringify-1.xml", + "testExpressionPolyStringEqualsStringify101", ExpressionVariables.create( new QName(NS_X, "foo"), "FOO", new QName(NS_Y, "bar"), "BAR" @@ -208,8 +208,8 @@ public void testExpressionPolyStringEqualsStringify101() throws Exception { @Test public void testExpressionPolyStringEqualsStringify102() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-1.xml", - "testExpressionPolyStringEqualsStringify102", + "expression-polystring-equals-stringify-1.xml", + "testExpressionPolyStringEqualsStringify102", ExpressionVariables.create( new QName(NS_X, "foo"), "FOOBAR", new QName(NS_Y, "bar"), "BAR" @@ -220,8 +220,8 @@ public void testExpressionPolyStringEqualsStringify102() throws Exception { @Test public void testExpressionPolyStringEqualsStringify111() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-1.xml", - "testExpressionPolyStringEqualsStringify111", + "expression-polystring-equals-stringify-1.xml", + "testExpressionPolyStringEqualsStringify111", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyString("FOO"), new QName(NS_Y, "bar"), "BAR" @@ -232,8 +232,8 @@ public void testExpressionPolyStringEqualsStringify111() throws Exception { @Test public void testExpressionPolyStringEqualsStringify112() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-1.xml", - "testExpressionPolyStringEqualsStringify112", + "expression-polystring-equals-stringify-1.xml", + "testExpressionPolyStringEqualsStringify112", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyString("FOOBAR"), new QName(NS_Y, "bar"), "BAR" @@ -244,8 +244,8 @@ public void testExpressionPolyStringEqualsStringify112() throws Exception { @Test public void testExpressionPolyStringEqualsStringify121() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-1.xml", - "testExpressionPolyStringEqualsStringify121", + "expression-polystring-equals-stringify-1.xml", + "testExpressionPolyStringEqualsStringify121", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyStringType("FOO"), new QName(NS_Y, "bar"), "BAR" @@ -256,8 +256,8 @@ public void testExpressionPolyStringEqualsStringify121() throws Exception { @Test public void testExpressionPolyStringEqualsStringify122() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-1.xml", - "testExpressionPolyStringEqualsStringify122", + "expression-polystring-equals-stringify-1.xml", + "testExpressionPolyStringEqualsStringify122", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyStringType("FOOBAR"), new QName(NS_Y, "bar"), "BAR" @@ -268,8 +268,8 @@ public void testExpressionPolyStringEqualsStringify122() throws Exception { @Test public void testExpressionPolyStringEqualsStringify201() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-2.xml", - "testExpressionPolyStringEqualsStringify201", + "expression-polystring-equals-stringify-2.xml", + "testExpressionPolyStringEqualsStringify201", ExpressionVariables.create( new QName(NS_X, "foo"), "FOO", new QName(NS_Y, "bar"), "BAR" @@ -280,8 +280,8 @@ public void testExpressionPolyStringEqualsStringify201() throws Exception { @Test public void testExpressionPolyStringEqualsStringify202() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-2.xml", - "testExpressionPolyStringEqualsStringify202", + "expression-polystring-equals-stringify-2.xml", + "testExpressionPolyStringEqualsStringify202", ExpressionVariables.create( new QName(NS_X, "foo"), "FOOBAR", new QName(NS_Y, "bar"), "BAR" @@ -292,8 +292,8 @@ public void testExpressionPolyStringEqualsStringify202() throws Exception { @Test public void testExpressionPolyStringEqualsStringify211() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-2.xml", - "testExpressionPolyStringEqualsStringify211", + "expression-polystring-equals-stringify-2.xml", + "testExpressionPolyStringEqualsStringify211", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyString("FOO"), new QName(NS_Y, "bar"), "BAR" @@ -304,8 +304,8 @@ public void testExpressionPolyStringEqualsStringify211() throws Exception { @Test public void testExpressionPolyStringEqualsStringify212() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-2.xml", - "testExpressionPolyStringEqualsStringify212", + "expression-polystring-equals-stringify-2.xml", + "testExpressionPolyStringEqualsStringify212", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyString("FOOBAR"), new QName(NS_Y, "bar"), "BAR" @@ -316,8 +316,8 @@ public void testExpressionPolyStringEqualsStringify212() throws Exception { @Test public void testExpressionPolyStringEqualsStringify221() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-2.xml", - "testExpressionPolyStringEqualsStringify221", + "expression-polystring-equals-stringify-2.xml", + "testExpressionPolyStringEqualsStringify221", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyStringType("FOO"), new QName(NS_Y, "bar"), "BAR" @@ -328,8 +328,8 @@ public void testExpressionPolyStringEqualsStringify221() throws Exception { @Test public void testExpressionPolyStringEqualsStringify222() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-2.xml", - "testExpressionPolyStringEqualsStringify222", + "expression-polystring-equals-stringify-2.xml", + "testExpressionPolyStringEqualsStringify222", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyStringType("FOOBAR"), new QName(NS_Y, "bar"), "BAR" diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestScriptCaching.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestScriptCaching.java index d63ab7aeebe..de65ca9ef28 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestScriptCaching.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestScriptCaching.java @@ -59,16 +59,16 @@ * @author semancik */ public class TestScriptCaching { - + private static final File TEST_DIR = new File("src/test/resources/expression/groovy"); protected static File OBJECTS_DIR = new File("src/test/resources/objects"); - + private static final QName PROPERTY_NAME = new QName(MidPointConstants.NS_MIDPOINT_TEST_PREFIX, "whatever"); private static final String NS_WHATEVER = "http://whatever/xml/ns"; protected ScriptExpressionFactory scriptExpressionfactory; protected ScriptEvaluator evaluator; - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); @@ -90,44 +90,44 @@ public void setupFactory() { String languageUrl = evaluator.getLanguageUrl(); scriptExpressionfactory.registerEvaluator(languageUrl, evaluator); } - + @Test public void testGetExtensionPropertyValue() throws Exception { final String TEST_NAME = "testGetExtensionPropertyValue"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN InternalMonitor.reset(); - + assertScriptMonitor(0,0, "init"); - + // WHEN, THEN long etimeFirst = executeScript("expression-string-variables.xml", "FOOBAR", "first"); assertScriptMonitor(1,1, "first"); - + long etimeSecond = executeScript("expression-string-variables.xml", "FOOBAR", "second"); assertScriptMonitor(1,2, "second"); assertTrue("Einstein was wrong! "+etimeFirst+" -> "+etimeSecond, etimeSecond <= etimeFirst); - + long etimeThird = executeScript("expression-string-variables.xml", "FOOBAR", "second"); assertScriptMonitor(1,3, "third"); assertTrue("Einstein was wrong again! "+etimeFirst+" -> "+etimeThird, etimeThird <= etimeFirst); - + // Different script. Should compile. long horatio1Time = executeScript("expression-func-concatname.xml", "Horatio Torquemada Marley", "horatio"); assertScriptMonitor(2,4, "horatio"); - + // Same script. No compilation. long etimeFourth = executeScript("expression-string-variables.xml", "FOOBAR", "fourth"); assertScriptMonitor(2,5, "fourth"); assertTrue("Einstein was wrong all the time! "+etimeFirst+" -> "+etimeFourth, etimeFourth <= etimeFirst); - + // Try this again. No compile. long horatio2Time = executeScript("expression-func-concatname.xml", "Horatio Torquemada Marley", "horatio2"); assertScriptMonitor(2,6, "horatio2"); assertTrue("Even Horatio was wrong! "+horatio1Time+" -> "+horatio2Time, horatio2Time <= horatio1Time); } - + private void assertScriptMonitor(int expCompilations, int expExecutions, String desc) { assertEquals("Unexpected number of script compilations after "+desc, expCompilations, InternalMonitor.getCount(InternalCounters.SCRIPT_COMPILE_COUNT)); assertEquals("Unexpected number of script executions after "+desc, expExecutions, InternalMonitor.getCount(InternalCounters.SCRIPT_EXECUTION_COUNT)); @@ -138,14 +138,14 @@ private long executeScript(String filname, String expectedResult, String desc) t OperationResult result = new OperationResult(desc); ScriptExpressionEvaluatorType scriptType = parseScriptType(filname); ItemDefinition outputDefinition = new PrismPropertyDefinitionImpl(PROPERTY_NAME, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); - + ScriptExpression scriptExpression = scriptExpressionfactory.createScriptExpression(scriptType, outputDefinition, desc); ExpressionVariables variables = ExpressionVariables.create( new QName(NS_WHATEVER, "foo"), "FOO", new QName(NS_WHATEVER, "bar"), "BAR" ); - + // WHEN long startTime = System.currentTimeMillis(); List> scripResults = scriptExpression.evaluate(variables , null, false, desc, null, result); @@ -154,19 +154,19 @@ private long executeScript(String filname, String expectedResult, String desc) t // THEN System.out.println("Script results "+desc+", etime: "+(endTime - startTime)+" ms"); System.out.println(scripResults); - + String scriptResult = asScalarString(scripResults); assertEquals("Wrong script "+desc+" result", expectedResult, scriptResult); - + return (endTime - startTime); } - + private ScriptExpressionEvaluatorType parseScriptType(String fileName) throws SchemaException, IOException, JAXBException { ScriptExpressionEvaluatorType expressionType = PrismTestUtil.parseAtomicValue( new File(TEST_DIR, fileName), ScriptExpressionEvaluatorType.COMPLEX_TYPE); return expressionType; } - + private String asScalarString(List> expressionResultList) { if (expressionResultList.size() > 1) { AssertJUnit.fail("Expression produces a list of "+expressionResultList.size()+" while only expected a single value: "+expressionResultList); diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestVelocityExpressions.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestVelocityExpressions.java index b6dae54a7a4..1669b1f4249 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestVelocityExpressions.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/script/TestVelocityExpressions.java @@ -58,8 +58,8 @@ public void testExpressionList() throws Exception { @Test public void testExpressionPolyStringEquals101() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-1.xml", - "testExpressionPolyStringEquals101", + "expression-polystring-equals-1.xml", + "testExpressionPolyStringEquals101", ExpressionVariables.create( new QName(NS_X, "foo"), "FOO", new QName(NS_Y, "bar"), "BAR" @@ -70,8 +70,8 @@ public void testExpressionPolyStringEquals101() throws Exception { @Test public void testExpressionPolyStringEquals102() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-1.xml", - "testExpressionPolyStringEquals102", + "expression-polystring-equals-1.xml", + "testExpressionPolyStringEquals102", ExpressionVariables.create( new QName(NS_X, "foo"), "FOOBAR", new QName(NS_Y, "bar"), "BAR" @@ -82,8 +82,8 @@ public void testExpressionPolyStringEquals102() throws Exception { @Test public void testExpressionPolyStringEquals111() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-1.xml", - "testExpressionPolyStringEquals111", + "expression-polystring-equals-1.xml", + "testExpressionPolyStringEquals111", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyString("FOO"), new QName(NS_Y, "bar"), "BAR" @@ -94,20 +94,20 @@ public void testExpressionPolyStringEquals111() throws Exception { @Test public void testExpressionPolyStringEquals112() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-1.xml", - "testExpressionPolyStringEquals112", + "expression-polystring-equals-1.xml", + "testExpressionPolyStringEquals112", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyString("FOOBAR"), new QName(NS_Y, "bar"), "BAR" ), Boolean.FALSE); } - + @Test public void testExpressionPolyStringEquals121() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-1.xml", - "testExpressionPolyStringEquals121", + "expression-polystring-equals-1.xml", + "testExpressionPolyStringEquals121", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyStringType("FOO"), new QName(NS_Y, "bar"), "BAR" @@ -118,20 +118,20 @@ public void testExpressionPolyStringEquals121() throws Exception { @Test public void testExpressionPolyStringEquals122() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-1.xml", - "testExpressionPolyStringEquals122", + "expression-polystring-equals-1.xml", + "testExpressionPolyStringEquals122", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyStringType("FOOBAR"), new QName(NS_Y, "bar"), "BAR" ), Boolean.FALSE); } - + @Test public void testExpressionPolyStringEquals201() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-2.xml", - "testExpressionPolyStringEquals201", + "expression-polystring-equals-2.xml", + "testExpressionPolyStringEquals201", ExpressionVariables.create( new QName(NS_X, "foo"), "FOO", new QName(NS_Y, "bar"), "BAR" @@ -142,8 +142,8 @@ public void testExpressionPolyStringEquals201() throws Exception { @Test public void testExpressionPolyStringEquals202() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-2.xml", - "testExpressionPolyStringEquals202", + "expression-polystring-equals-2.xml", + "testExpressionPolyStringEquals202", ExpressionVariables.create( new QName(NS_X, "foo"), "FOOBAR", new QName(NS_Y, "bar"), "BAR" @@ -154,8 +154,8 @@ public void testExpressionPolyStringEquals202() throws Exception { @Test public void testExpressionPolyStringEquals211() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-2.xml", - "testExpressionPolyStringEquals211", + "expression-polystring-equals-2.xml", + "testExpressionPolyStringEquals211", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyString("FOO"), new QName(NS_Y, "bar"), "BAR" @@ -166,8 +166,8 @@ public void testExpressionPolyStringEquals211() throws Exception { @Test public void testExpressionPolyStringEquals212() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-2.xml", - "testExpressionPolyStringEquals212", + "expression-polystring-equals-2.xml", + "testExpressionPolyStringEquals212", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyString("FOOBAR"), new QName(NS_Y, "bar"), "BAR" @@ -178,8 +178,8 @@ public void testExpressionPolyStringEquals212() throws Exception { @Test public void testExpressionPolyStringEquals221() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-2.xml", - "testExpressionPolyStringEquals221", + "expression-polystring-equals-2.xml", + "testExpressionPolyStringEquals221", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyStringType("FOO"), new QName(NS_Y, "bar"), "BAR" @@ -190,20 +190,20 @@ public void testExpressionPolyStringEquals221() throws Exception { @Test public void testExpressionPolyStringEquals222() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-2.xml", - "testExpressionPolyStringEquals222", + "expression-polystring-equals-2.xml", + "testExpressionPolyStringEquals222", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyStringType("FOOBAR"), new QName(NS_Y, "bar"), "BAR" ), Boolean.FALSE); } - + @Test public void testExpressionPolyStringEqualsStringify101() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-1.xml", - "testExpressionPolyStringEqualsStringify101", + "expression-polystring-equals-stringify-1.xml", + "testExpressionPolyStringEqualsStringify101", ExpressionVariables.create( new QName(NS_X, "foo"), "FOO", new QName(NS_Y, "bar"), "BAR" @@ -214,8 +214,8 @@ public void testExpressionPolyStringEqualsStringify101() throws Exception { @Test public void testExpressionPolyStringEqualsStringify102() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-1.xml", - "testExpressionPolyStringEqualsStringify102", + "expression-polystring-equals-stringify-1.xml", + "testExpressionPolyStringEqualsStringify102", ExpressionVariables.create( new QName(NS_X, "foo"), "FOOBAR", new QName(NS_Y, "bar"), "BAR" @@ -226,8 +226,8 @@ public void testExpressionPolyStringEqualsStringify102() throws Exception { @Test public void testExpressionPolyStringEqualsStringify111() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-1.xml", - "testExpressionPolyStringEqualsStringify111", + "expression-polystring-equals-stringify-1.xml", + "testExpressionPolyStringEqualsStringify111", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyString("FOO"), new QName(NS_Y, "bar"), "BAR" @@ -238,8 +238,8 @@ public void testExpressionPolyStringEqualsStringify111() throws Exception { @Test public void testExpressionPolyStringEqualsStringify112() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-1.xml", - "testExpressionPolyStringEqualsStringify112", + "expression-polystring-equals-stringify-1.xml", + "testExpressionPolyStringEqualsStringify112", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyString("FOOBAR"), new QName(NS_Y, "bar"), "BAR" @@ -250,8 +250,8 @@ public void testExpressionPolyStringEqualsStringify112() throws Exception { @Test public void testExpressionPolyStringEqualsStringify121() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-1.xml", - "testExpressionPolyStringEqualsStringify121", + "expression-polystring-equals-stringify-1.xml", + "testExpressionPolyStringEqualsStringify121", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyStringType("FOO"), new QName(NS_Y, "bar"), "BAR" @@ -262,8 +262,8 @@ public void testExpressionPolyStringEqualsStringify121() throws Exception { @Test public void testExpressionPolyStringEqualsStringify122() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-1.xml", - "testExpressionPolyStringEqualsStringify122", + "expression-polystring-equals-stringify-1.xml", + "testExpressionPolyStringEqualsStringify122", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyStringType("FOOBAR"), new QName(NS_Y, "bar"), "BAR" @@ -274,8 +274,8 @@ public void testExpressionPolyStringEqualsStringify122() throws Exception { @Test public void testExpressionPolyStringEqualsStringify201() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-2.xml", - "testExpressionPolyStringEqualsStringify201", + "expression-polystring-equals-stringify-2.xml", + "testExpressionPolyStringEqualsStringify201", ExpressionVariables.create( new QName(NS_X, "foo"), "FOO", new QName(NS_Y, "bar"), "BAR" @@ -286,8 +286,8 @@ public void testExpressionPolyStringEqualsStringify201() throws Exception { @Test public void testExpressionPolyStringEqualsStringify202() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-2.xml", - "testExpressionPolyStringEqualsStringify202", + "expression-polystring-equals-stringify-2.xml", + "testExpressionPolyStringEqualsStringify202", ExpressionVariables.create( new QName(NS_X, "foo"), "FOOBAR", new QName(NS_Y, "bar"), "BAR" @@ -298,8 +298,8 @@ public void testExpressionPolyStringEqualsStringify202() throws Exception { @Test public void testExpressionPolyStringEqualsStringify211() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-2.xml", - "testExpressionPolyStringEqualsStringify211", + "expression-polystring-equals-stringify-2.xml", + "testExpressionPolyStringEqualsStringify211", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyString("FOO"), new QName(NS_Y, "bar"), "BAR" @@ -310,8 +310,8 @@ public void testExpressionPolyStringEqualsStringify211() throws Exception { @Test public void testExpressionPolyStringEqualsStringify212() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-2.xml", - "testExpressionPolyStringEqualsStringify212", + "expression-polystring-equals-stringify-2.xml", + "testExpressionPolyStringEqualsStringify212", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyString("FOOBAR"), new QName(NS_Y, "bar"), "BAR" @@ -322,8 +322,8 @@ public void testExpressionPolyStringEqualsStringify212() throws Exception { @Test public void testExpressionPolyStringEqualsStringify221() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-2.xml", - "testExpressionPolyStringEqualsStringify221", + "expression-polystring-equals-stringify-2.xml", + "testExpressionPolyStringEqualsStringify221", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyStringType("FOO"), new QName(NS_Y, "bar"), "BAR" @@ -334,8 +334,8 @@ public void testExpressionPolyStringEqualsStringify221() throws Exception { @Test public void testExpressionPolyStringEqualsStringify222() throws Exception { evaluateAndAssertBooleanScalarExpresssion( - "expression-polystring-equals-stringify-2.xml", - "testExpressionPolyStringEqualsStringify222", + "expression-polystring-equals-stringify-2.xml", + "testExpressionPolyStringEqualsStringify222", ExpressionVariables.create( new QName(NS_X, "foo"), PrismTestUtil.createPolyStringType("FOOBAR"), new QName(NS_Y, "bar"), "BAR" diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/MappingTestEvaluator.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/MappingTestEvaluator.java index a39e9b8164f..75c833f4c16 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/MappingTestEvaluator.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/MappingTestEvaluator.java @@ -70,22 +70,22 @@ /** * The class that takes care of all the ornaments of value construction execution. It is used to make the * tests easy to write. - * + * * @author Radovan Semancik * */ public class MappingTestEvaluator { - + public static File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "mapping"); public static final File USER_OLD_FILE = new File(TEST_DIR, "user-jack.xml"); public static final File ACCOUNT_FILE = new File(TEST_DIR, "account-jack.xml"); public static final String USER_OLD_OID = "2f9b9299-6f45-498f-bc8e-8d17c6b93b20"; private static final File PASSWORD_POLICY_FILE = new File(TEST_DIR, "password-policy.xml"); - + private PrismContext prismContext; private MappingFactory mappingFactory; ProtectorImpl protector; - + public PrismContext getPrismContext() { return prismContext; } @@ -93,21 +93,21 @@ public PrismContext getPrismContext() { public void init() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); - + prismContext = PrismTestUtil.createInitializedPrismContext(); ObjectResolver resolver = new DirectoryFileObjectResolver(MidPointTestConstants.OBJECTS_DIR); protector = ExpressionTestUtil.createInitializedProtector(prismContext); ExpressionFactory expressionFactory = ExpressionTestUtil.createInitializedExpressionFactory(resolver, protector, prismContext, null); - + mappingFactory = new MappingFactory(); mappingFactory.setExpressionFactory(expressionFactory); mappingFactory.setObjectResolver(resolver); mappingFactory.setPrismContext(prismContext); mappingFactory.setProfiling(true); - + mappingFactory.setProtector(protector); } - + public ProtectorImpl getProtector() { return protector; } @@ -115,12 +115,12 @@ public ProtectorImpl getProtector() { public Mapping, PrismPropertyDefinition> createMapping(String filename, String testName, final StringPolicyType policy, String defaultTargetPropertyName, ObjectDelta userDelta) throws SchemaException, IOException, JAXBException, EncryptionException { return this.createMappingBuilder(filename, testName, policy, toPath(defaultTargetPropertyName), userDelta).build(); } - - public Mapping, PrismPropertyDefinition> createMapping(String filename, String testName, String defaultTargetPropertyName, + + public Mapping, PrismPropertyDefinition> createMapping(String filename, String testName, String defaultTargetPropertyName, ObjectDelta userDelta) throws SchemaException, IOException, JAXBException, EncryptionException { return this.createMappingBuilder(filename, testName, null, toPath(defaultTargetPropertyName), userDelta).build(); } - + public Mapping.Builder, PrismPropertyDefinition> createMappingBuilder(String filename, String testName, String defaultTargetPropertyName, ObjectDelta userDelta) throws SchemaException, IOException, JAXBException, EncryptionException { return createMappingBuilder(filename, testName, null, toPath(defaultTargetPropertyName), userDelta); @@ -130,12 +130,12 @@ public Mapping, PrismPropertyDefinition> createMapp ObjectDelta userDelta) throws SchemaException, IOException, JAXBException, EncryptionException { return this.createMappingBuilder(filename, testName, null, toPath(defaultTargetPropertyName), userDelta).build(); } - - public Mapping, PrismPropertyDefinition> createMapping(String filename, String testName, String defaultTargetPropertyName, + + public Mapping, PrismPropertyDefinition> createMapping(String filename, String testName, String defaultTargetPropertyName, ObjectDelta userDelta, PrismObject userOld) throws SchemaException, IOException, JAXBException { return this.createMappingBuilder(filename, testName, null, toPath(defaultTargetPropertyName), userDelta, userOld).build(); } - + public Mapping.Builder, PrismPropertyDefinition> createMappingBuilder(String filename, String testName, String defaultTargetPropertyName, ObjectDelta userDelta, PrismObject userOld) throws SchemaException, IOException, JAXBException { return this.createMappingBuilder(filename, testName, null, toPath(defaultTargetPropertyName), userDelta, userOld); @@ -144,7 +144,7 @@ public Mapping.Builder, PrismPropertyDefinition> cr public Mapping, PrismPropertyDefinition> createMapping(String filename, String testName, ItemPath defaultTargetPropertyName, ObjectDelta userDelta) throws SchemaException, IOException, JAXBException, EncryptionException { return this.createMappingBuilder(filename, testName, null, defaultTargetPropertyName, userDelta).build(); } - + public Mapping.Builder, PrismPropertyDefinition> createMappingBuilder(String filename, String testName, final StringPolicyType policy, ItemPath defaultTargetPropertyPath, ObjectDelta userDelta) throws SchemaException, IOException, JAXBException, EncryptionException { @@ -154,55 +154,55 @@ public Mapping.Builder, PrismPropertyDefinition> cr } return createMappingBuilder(filename, testName, policy, defaultTargetPropertyPath, userDelta, userOld); } - + public Mapping.Builder, PrismPropertyDefinition> createMappingBuilder(String filename, String testName, final StringPolicyType policy, ItemPath defaultTargetPropertyPath, ObjectDelta userDelta, PrismObject userOld) throws SchemaException, IOException, JAXBException { - + MappingType mappingType = PrismTestUtil.parseAtomicValue( new File(TEST_DIR, filename), MappingType.COMPLEX_TYPE); Mapping.Builder,PrismPropertyDefinition> mappingBuilder = mappingFactory.createMappingBuilder(mappingType, testName); - + // Source context: user ObjectDeltaObject userOdo = new ObjectDeltaObject<>(userOld, userDelta, null); userOdo.recompute(); mappingBuilder.setSourceContext(userOdo); - + // Variable $user mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_USER, userOdo); - + // Variable $account PrismObject account = getAccount(); ObjectDeltaObject accountOdo = new ObjectDeltaObject(account , null, null); accountOdo.recompute(); mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_ACCOUNT, accountOdo); - + // Target context: user PrismObjectDefinition userDefinition = getUserDefinition(); mappingBuilder.setTargetContext(userDefinition); - - + + StringPolicyResolver stringPolicyResolver = new StringPolicyResolver() { ItemPath outputPath; ItemDefinition outputDefinition; - + @Override public void setOutputPath(ItemPath outputPath) { this.outputPath = outputPath; } - + @Override public void setOutputDefinition(ItemDefinition outputDefinition) { this.outputDefinition = outputDefinition; } - + @Override public StringPolicyType resolve() { return policy; } }; - + mappingBuilder.setStringPolicyResolver(stringPolicyResolver); // Default target if (defaultTargetPropertyPath != null) { @@ -212,18 +212,18 @@ public StringPolicyType resolve() { } mappingBuilder.setDefaultTargetDefinition(targetDefDefinition); } - + return mappingBuilder; } - + public Mapping, PrismPropertyDefinition> createInboudMapping(String filename, String testName, ItemDelta delta, UserType user, ShadowType account, ResourceType resource, final StringPolicyType policy) throws SchemaException, IOException, JAXBException{ - + MappingType mappingType = PrismTestUtil.parseAtomicValue( new File(TEST_DIR, filename), MappingType.COMPLEX_TYPE); Mapping.Builder,PrismPropertyDefinition> builder = mappingFactory.createMappingBuilder(mappingType, testName); - - + + Source,PrismPropertyDefinition> defaultSource = new Source<>(null, delta, null, ExpressionConstants.VAR_INPUT); defaultSource.recompute(); builder.setDefaultSource(defaultSource); @@ -232,51 +232,51 @@ public Mapping, PrismPropertyDefinition> createInb builder.addVariableDefinition(ExpressionConstants.VAR_FOCUS, user); builder.addVariableDefinition(ExpressionConstants.VAR_ACCOUNT, account.asPrismObject()); builder.addVariableDefinition(ExpressionConstants.VAR_SHADOW, account.asPrismObject()); - + StringPolicyResolver stringPolicyResolver = new StringPolicyResolver() { ItemPath outputPath; ItemDefinition outputDefinition; - + @Override public void setOutputPath(ItemPath outputPath) { this.outputPath = outputPath; } - + @Override public void setOutputDefinition(ItemDefinition outputDefinition) { this.outputDefinition = outputDefinition; } - + @Override public StringPolicyType resolve() { return policy; } }; - + builder.setStringPolicyResolver(stringPolicyResolver); builder.setOriginType(OriginType.INBOUND); builder.setOriginObject(resource); - + return builder.build(); } - + protected PrismObject getUserOld() throws SchemaException, EncryptionException, IOException { PrismObject user = PrismTestUtil.parseObject(USER_OLD_FILE); ProtectedStringType passwordPs = user.asObjectable().getCredentials().getPassword().getValue(); protector.encrypt(passwordPs); return user; } - + protected PrismObject getAccount() throws SchemaException, IOException { return PrismTestUtil.parseObject(ACCOUNT_FILE); } - + public PrismObjectDefinition getUserDefinition() { return prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); } - - public PrismValueDeltaSetTriple> evaluateMapping(String filename, String testName, + + public PrismValueDeltaSetTriple> evaluateMapping(String filename, String testName, ItemPath defaultTargetPropertyPath) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, EncryptionException { Mapping,PrismPropertyDefinition> mapping = createMapping(filename, testName, defaultTargetPropertyPath, null); @@ -289,8 +289,8 @@ public PrismValueDeltaSetTriple> evaluateMapping(Str } return outputTriple; } - - public PrismValueDeltaSetTriple> evaluateMapping(String filename, String testName, + + public PrismValueDeltaSetTriple> evaluateMapping(String filename, String testName, QName defaultTargetPropertyName) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, EncryptionException { Mapping,PrismPropertyDefinition> mapping = createMapping(filename, testName, defaultTargetPropertyName, null); @@ -303,8 +303,8 @@ public PrismValueDeltaSetTriple> evaluateMapping(Str } return outputTriple; } - - public PrismValueDeltaSetTriple> evaluateMapping(String filename, String testName, + + public PrismValueDeltaSetTriple> evaluateMapping(String filename, String testName, String defaultTargetPropertyName) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, EncryptionException { Mapping,PrismPropertyDefinition> mapping = createMapping(filename, testName, defaultTargetPropertyName, null); @@ -317,26 +317,26 @@ public PrismValueDeltaSetTriple> evaluateMapping(Str } return outputTriple; } - + public void assertResult(OperationResult opResult) { if (opResult.isEmpty()) { // this is OK. Nothing added to result. return; } opResult.computeStatus(); - TestUtil.assertSuccess(opResult); + TestUtil.assertSuccess(opResult); } - public PrismValueDeltaSetTriple> evaluateMappingDynamicAdd(String filename, String testName, + public PrismValueDeltaSetTriple> evaluateMappingDynamicAdd(String filename, String testName, String defaultTargetPropertyName, String changedPropertyName, I... valuesToAdd) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, EncryptionException { return evaluateMappingDynamicAdd(filename, testName, toPath(defaultTargetPropertyName), changedPropertyName, valuesToAdd); } - - public PrismValueDeltaSetTriple> evaluateMappingDynamicAdd(String filename, String testName, + + public PrismValueDeltaSetTriple> evaluateMappingDynamicAdd(String filename, String testName, ItemPath defaultTargetPropertyPath, String changedPropertyName, I... valuesToAdd) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, EncryptionException { - ObjectDelta userDelta = ObjectDelta.createModificationAddProperty(UserType.class, USER_OLD_OID, toPath(changedPropertyName), + ObjectDelta userDelta = ObjectDelta.createModificationAddProperty(UserType.class, USER_OLD_OID, toPath(changedPropertyName), prismContext, valuesToAdd); Mapping,PrismPropertyDefinition> mapping = createMapping(filename, testName, defaultTargetPropertyPath, userDelta); OperationResult opResult = new OperationResult(testName); @@ -348,11 +348,11 @@ public PrismValueDeltaSetTriple> evaluateMappingDyna } return outputTriple; } - - public PrismValueDeltaSetTriple> evaluateMappingDynamicDelete(String filename, String testName, + + public PrismValueDeltaSetTriple> evaluateMappingDynamicDelete(String filename, String testName, String defaultTargetPropertyName, String changedPropertyName, I... valuesToAdd) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, EncryptionException { - ObjectDelta userDelta = ObjectDelta.createModificationDeleteProperty(UserType.class, USER_OLD_OID, toPath(changedPropertyName), + ObjectDelta userDelta = ObjectDelta.createModificationDeleteProperty(UserType.class, USER_OLD_OID, toPath(changedPropertyName), prismContext, valuesToAdd); Mapping,PrismPropertyDefinition> mapping = createMapping(filename, testName, defaultTargetPropertyName, userDelta); OperationResult opResult = new OperationResult(testName); @@ -364,11 +364,11 @@ public PrismValueDeltaSetTriple> evaluateMappingDyna } return outputTriple; } - - public PrismValueDeltaSetTriple> evaluateMappingDynamicReplace(String filename, String testName, + + public PrismValueDeltaSetTriple> evaluateMappingDynamicReplace(String filename, String testName, String defaultTargetPropertyName, String changedPropertyName, I... valuesToReplace) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, EncryptionException { - ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_OLD_OID, toPath(changedPropertyName), + ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_OLD_OID, toPath(changedPropertyName), prismContext, valuesToReplace); Mapping,PrismPropertyDefinition> mapping = createMapping(filename, testName, defaultTargetPropertyName, userDelta); OperationResult opResult = new OperationResult(testName); @@ -380,11 +380,11 @@ public PrismValueDeltaSetTriple> evaluateMappingDyna } return outputTriple; } - - public PrismValueDeltaSetTriple> evaluateMappingDynamicReplace(String filename, String testName, + + public PrismValueDeltaSetTriple> evaluateMappingDynamicReplace(String filename, String testName, String defaultTargetPropertyName, ItemPath changedPropertyName, I... valuesToReplace) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, EncryptionException { - ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_OLD_OID, changedPropertyName, + ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_OLD_OID, changedPropertyName, prismContext, valuesToReplace); Mapping,PrismPropertyDefinition> mapping = createMapping(filename, testName, defaultTargetPropertyName, userDelta); OperationResult opResult = new OperationResult(testName); @@ -396,11 +396,11 @@ public PrismValueDeltaSetTriple> evaluateMappingDyna } return outputTriple; } - - public PrismValueDeltaSetTriple> evaluateMappingDynamicReplace(String filename, String testName, + + public PrismValueDeltaSetTriple> evaluateMappingDynamicReplace(String filename, String testName, ItemPath defaultTargetPropertyName, String changedPropertyName, I... valuesToReplace) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, EncryptionException { - ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_OLD_OID, toPath(changedPropertyName), + ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_OLD_OID, toPath(changedPropertyName), prismContext, valuesToReplace); Mapping,PrismPropertyDefinition> mapping = createMapping(filename, testName, defaultTargetPropertyName, userDelta); OperationResult opResult = new OperationResult(testName); @@ -412,11 +412,11 @@ public PrismValueDeltaSetTriple> evaluateMappingDyna } return outputTriple; } - - public PrismValueDeltaSetTriple> evaluateMappingDynamicReplace(String filename, String testName, + + public PrismValueDeltaSetTriple> evaluateMappingDynamicReplace(String filename, String testName, ItemPath defaultTargetPropertyName, ItemPath changedPropertyName, I... valuesToReplace) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException, EncryptionException { - ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_OLD_OID, changedPropertyName, + ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_OLD_OID, changedPropertyName, prismContext, valuesToReplace); Mapping,PrismPropertyDefinition> mapping = createMapping(filename, testName, defaultTargetPropertyName, userDelta); OperationResult opResult = new OperationResult(testName); @@ -428,15 +428,15 @@ public PrismValueDeltaSetTriple> evaluateMappingDyna } return outputTriple; } - + public ItemPath toPath(String propertyName) { return new ItemPath(new QName(SchemaConstants.NS_C, propertyName)); } - + public ItemPath toPath(QName propertyName) { return new ItemPath(propertyName); } - + public static T getSingleValue(String setName, Collection> set) { assertEquals("Expected single value in "+setName+" but found "+set.size()+" values: "+set, 1, set.size()); PrismPropertyValue propertyValue = set.iterator().next(); @@ -460,7 +460,7 @@ public void assertProtectedString(String desc, ProtectedStringType ps = pval.getValue(); String zeroString = protector.decryptString(ps); assertEquals("Unexpected value in "+desc+": "+set, expected, zeroString); - + } } diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingComplex.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingComplex.java index 973c9d52d59..03b31e9617e 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingComplex.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingComplex.java @@ -39,36 +39,36 @@ * @author Radovan Semancik */ public class TestMappingComplex { - + private static final String MAPPING_COMPLEX_FILENAME = "mapping-complex-captain.xml"; - + private MappingTestEvaluator evaluator; - + @BeforeClass public void setupFactory() throws SAXException, IOException, SchemaException { evaluator = new MappingTestEvaluator(); evaluator.init(); } - + @Test public void testModifyObjectSetAdditionalName() throws Exception { final String TEST_NAME = "testModifyObjectSetAdditionalName"; System.out.println("===[ "+TEST_NAME+"]==="); - + // GIVEN - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, UserType.F_ADDITIONAL_NAME, evaluator.getPrismContext(), "Jackie"); delta.addModificationReplaceProperty(UserType.F_EMPLOYEE_NUMBER, "321"); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - MAPPING_COMPLEX_FILENAME, + MAPPING_COMPLEX_FILENAME, TEST_NAME, "title", delta); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); outputTriple.checkConsistence(); @@ -76,34 +76,34 @@ public void testModifyObjectSetAdditionalName() throws Exception { PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("Pirate Jackie (#321)")); PrismAsserts.assertTripleMinus(outputTriple, PrismTestUtil.createPolyString("Pirate null (#null)")); } - + @Test public void testModifyObjectSetAdditionalNameFalse() throws Exception { final String TEST_NAME = "testModifyObjectSetAdditionalNameFalse"; System.out.println("===[ "+TEST_NAME+"]==="); - + // GIVEN - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, UserType.F_ADDITIONAL_NAME, evaluator.getPrismContext(), "Jackie"); delta.addModificationReplaceProperty(UserType.F_EMPLOYEE_NUMBER, "321"); - + PrismObject userOld = evaluator.getUserOld(); userOld.asObjectable().getEmployeeType().clear(); userOld.asObjectable().getEmployeeType().add("WHATEVER"); Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - MAPPING_COMPLEX_FILENAME, + MAPPING_COMPLEX_FILENAME, TEST_NAME, "title", delta, userOld); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); assertNull("Unexpected value in outputTriple: "+outputTriple, outputTriple); } - + /** * Change property that is not a source in this mapping */ @@ -111,20 +111,20 @@ public void testModifyObjectSetAdditionalNameFalse() throws Exception { public void testModifyObjectUnrelated() throws Exception { final String TEST_NAME = "testModifyObjectUnrelated"; System.out.println("===[ "+TEST_NAME+"]==="); - + // GIVEN - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, evaluator.toPath("costCenter"), evaluator.getPrismContext(), "X606"); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - MAPPING_COMPLEX_FILENAME, + MAPPING_COMPLEX_FILENAME, TEST_NAME, "title", delta); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); outputTriple.checkConsistence(); @@ -132,80 +132,80 @@ public void testModifyObjectUnrelated() throws Exception { PrismAsserts.assertTripleNoPlus(outputTriple); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testModifyObjectUnrelatedFalse() throws Exception { final String TEST_NAME = "testModifyObjectUnrelatedFalse"; System.out.println("===[ "+TEST_NAME+"]==="); - + // GIVEN - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, evaluator.toPath("costCenter"), evaluator.getPrismContext(), "X606"); - + PrismObject userOld = evaluator.getUserOld(); userOld.asObjectable().getEmployeeType().clear(); userOld.asObjectable().getEmployeeType().add("WHATEVER"); Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - MAPPING_COMPLEX_FILENAME, + MAPPING_COMPLEX_FILENAME, TEST_NAME, "title", delta, userOld); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); assertNull("Unexpected value in outputTriple: "+outputTriple, outputTriple); } - + @Test public void testAddObjectUnrelatedFalse() throws Exception { final String TEST_NAME = "testAddObjectUnrelatedFalse"; System.out.println("===[ "+TEST_NAME+"]==="); - + // GIVEN PrismObject user = evaluator.getUserOld(); user.asObjectable().getEmployeeType().clear(); user.asObjectable().getEmployeeType().add("WHATEVER"); ObjectDelta delta = user.createAddDelta(); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - MAPPING_COMPLEX_FILENAME, + MAPPING_COMPLEX_FILENAME, TEST_NAME, "title", delta); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); assertNull("Unexpected value in outputTriple: "+outputTriple, outputTriple); } - + @Test public void testAddObjectUnrelatedEmptyFalse() throws Exception { final String TEST_NAME = "testAddObjectUnrelatedEmptyFalse"; System.out.println("===[ "+TEST_NAME+"]==="); - + // GIVEN PrismObject user = evaluator.getUserOld(); user.asObjectable().getEmployeeType().clear(); ObjectDelta delta = user.createAddDelta(); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - MAPPING_COMPLEX_FILENAME, + MAPPING_COMPLEX_FILENAME, TEST_NAME, "title", delta); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); assertNull("Unexpected value in outputTriple: "+outputTriple, outputTriple); } - + } diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDomain.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDomain.java index 42661a2a3f3..c7e471c2c0d 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDomain.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDomain.java @@ -40,22 +40,22 @@ /** * Tests for mapping domain. Those are multival input and multival output. - * + * * MID-3692 * @author Radovan Semancik */ public class TestMappingDomain { - + private static final String MAPPING_DOMAIN_FILENAME = "mapping-domain.xml"; - + private MappingTestEvaluator evaluator; - + @BeforeClass public void setupFactory() throws SchemaException, SAXException, IOException { evaluator = new MappingTestEvaluator(); evaluator.init(); } - + /** * Control. All goes well here. All values in the domain. */ @@ -63,27 +63,27 @@ public void setupFactory() throws SchemaException, SAXException, IOException { public void testControlReplaceSingleValue() throws Exception { final String TEST_NAME = "testControlReplaceSingleValue"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN - + PrismObject userOld = evaluator.getUserOld(); List employeeTypeOld = userOld.asObjectable().getEmployeeType(); employeeTypeOld.clear(); employeeTypeOld.add("1234567890"); - - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, UserType.F_ADDITIONAL_NAME, evaluator.getPrismContext(), "Jackie"); delta.addModificationReplaceProperty(UserType.F_EMPLOYEE_TYPE, "321"); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - MAPPING_DOMAIN_FILENAME, + MAPPING_DOMAIN_FILENAME, TEST_NAME, "organization", delta, userOld); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); outputTriple.checkConsistence(); @@ -91,7 +91,7 @@ public void testControlReplaceSingleValue() throws Exception { PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("Pirate Jackie (321)")); PrismAsserts.assertTripleMinus(outputTriple, PrismTestUtil.createPolyString("Pirate null (1234567890)")); } - + /** * Control. All goes well here. All values in the domain. */ @@ -99,49 +99,49 @@ public void testControlReplaceSingleValue() throws Exception { public void testControlReplaceMultiValue() throws Exception { final String TEST_NAME = "testControlReplaceMultiValue"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN - + PrismObject userOld = evaluator.getUserOld(); List employeeTypeOld = userOld.asObjectable().getEmployeeType(); employeeTypeOld.clear(); employeeTypeOld.add("001"); employeeTypeOld.add("002"); employeeTypeOld.add("003"); - - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, UserType.F_ADDITIONAL_NAME, evaluator.getPrismContext(), "Jackie"); delta.addModificationReplaceProperty(UserType.F_EMPLOYEE_TYPE, "991", "992"); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - MAPPING_DOMAIN_FILENAME, + MAPPING_DOMAIN_FILENAME, TEST_NAME, "organization", delta, userOld); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); outputTriple.checkConsistence(); PrismAsserts.assertTripleNoZero(outputTriple); - PrismAsserts.assertTriplePlus(outputTriple, + PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("Pirate Jackie (991)"), PrismTestUtil.createPolyString("Pirate Jackie (992)")); - PrismAsserts.assertTripleMinus(outputTriple, + PrismAsserts.assertTripleMinus(outputTriple, PrismTestUtil.createPolyString("Pirate null (001)"), PrismTestUtil.createPolyString("Pirate null (002)"), PrismTestUtil.createPolyString("Pirate null (003)")); } - + @Test public void testReplaceMixedMultiValue() throws Exception { final String TEST_NAME = "testReplaceMixedMultiValue"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN - + PrismObject userOld = evaluator.getUserOld(); List employeeTypeOld = userOld.asObjectable().getEmployeeType(); employeeTypeOld.clear(); @@ -149,42 +149,42 @@ public void testReplaceMixedMultiValue() throws Exception { employeeTypeOld.add("A02"); employeeTypeOld.add("B03"); employeeTypeOld.add("004"); - - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, UserType.F_ADDITIONAL_NAME, evaluator.getPrismContext(), "Jackie"); delta.addModificationReplaceProperty(UserType.F_EMPLOYEE_TYPE, "X91", "992", "Y93", "994"); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - MAPPING_DOMAIN_FILENAME, + MAPPING_DOMAIN_FILENAME, TEST_NAME, "organization", delta, userOld); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); mapping.evaluate(null, opResult); - + // THEN TestUtil.displayThen(TEST_NAME); PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); display("Output triple", outputTriple); outputTriple.checkConsistence(); PrismAsserts.assertTripleNoZero(outputTriple); - PrismAsserts.assertTriplePlus(outputTriple, + PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("Pirate Jackie (992)"), PrismTestUtil.createPolyString("Pirate Jackie (994)")); - PrismAsserts.assertTripleMinus(outputTriple, + PrismAsserts.assertTripleMinus(outputTriple, PrismTestUtil.createPolyString("Pirate null (001)"), PrismTestUtil.createPolyString("Pirate null (004)")); } - + @Test public void testAddMixedMultiValue() throws Exception { final String TEST_NAME = "testAddMixedMultiValue"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN - + PrismObject userOld = evaluator.getUserOld(); userOld.asObjectable().setAdditionalName(PrismTestUtil.createPolyStringType("Jackie")); List employeeTypeOld = userOld.asObjectable().getEmployeeType(); @@ -193,20 +193,20 @@ public void testAddMixedMultiValue() throws Exception { employeeTypeOld.add("A02"); employeeTypeOld.add("B03"); employeeTypeOld.add("004"); - - ObjectDelta delta = ObjectDelta.createModificationAddProperty(UserType.class, evaluator.USER_OLD_OID, + + ObjectDelta delta = ObjectDelta.createModificationAddProperty(UserType.class, evaluator.USER_OLD_OID, UserType.F_EMPLOYEE_TYPE, evaluator.getPrismContext(), "X91", "992", "Y93", "994"); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - MAPPING_DOMAIN_FILENAME, + MAPPING_DOMAIN_FILENAME, TEST_NAME, "organization", delta, userOld); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); mapping.evaluate(null, opResult); - + // THEN TestUtil.displayThen(TEST_NAME); PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); @@ -215,19 +215,19 @@ public void testAddMixedMultiValue() throws Exception { PrismAsserts.assertTripleZero(outputTriple, PrismTestUtil.createPolyString("Pirate Jackie (001)"), PrismTestUtil.createPolyString("Pirate Jackie (004)")); - PrismAsserts.assertTriplePlus(outputTriple, + PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("Pirate Jackie (992)"), PrismTestUtil.createPolyString("Pirate Jackie (994)")); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testDeleteMixedMultiValue() throws Exception { final String TEST_NAME = "testDeleteMixedMultiValue"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN - + PrismObject userOld = evaluator.getUserOld(); userOld.asObjectable().setAdditionalName(PrismTestUtil.createPolyStringType("Jackie")); List employeeTypeOld = userOld.asObjectable().getEmployeeType(); @@ -239,20 +239,20 @@ public void testDeleteMixedMultiValue() throws Exception { employeeTypeOld.add("005"); employeeTypeOld.add("C06"); employeeTypeOld.add("007"); - - ObjectDelta delta = ObjectDelta.createModificationDeleteProperty(UserType.class, evaluator.USER_OLD_OID, + + ObjectDelta delta = ObjectDelta.createModificationDeleteProperty(UserType.class, evaluator.USER_OLD_OID, UserType.F_EMPLOYEE_TYPE, evaluator.getPrismContext(), "005", "C06", "007"); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - MAPPING_DOMAIN_FILENAME, + MAPPING_DOMAIN_FILENAME, TEST_NAME, "organization", delta, userOld); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); mapping.evaluate(null, opResult); - + // THEN TestUtil.displayThen(TEST_NAME); PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); @@ -262,9 +262,9 @@ public void testDeleteMixedMultiValue() throws Exception { PrismTestUtil.createPolyString("Pirate Jackie (001)"), PrismTestUtil.createPolyString("Pirate Jackie (004)")); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleMinus(outputTriple, + PrismAsserts.assertTripleMinus(outputTriple, PrismTestUtil.createPolyString("Pirate Jackie (005)"), PrismTestUtil.createPolyString("Pirate Jackie (007)")); } - + } 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 f46334f6f83..772bddd6ad9 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 @@ -74,18 +74,18 @@ * @author Radovan Semancik */ public class TestMappingDynamicSimple { - + private static final String NS_EXTENSION = "http://midpoint.evolveum.com/xml/ns/test/extension"; private static final String PATTERN_NUMERIC = "^\\d+$"; - + private MappingTestEvaluator evaluator; - + @BeforeClass public void setupFactory() throws SAXException, IOException, SchemaException { evaluator = new MappingTestEvaluator(); evaluator.init(); } - + @Test public void testValueSingleDeep() throws Exception { // WHEN @@ -95,7 +95,7 @@ public void testValueSingleDeep() throws Exception { "costCenter", // target "employeeType", // changed property "CAPTAIN"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, "foobar"); @@ -112,7 +112,7 @@ public void testValueSingleShallow() throws Exception { "costCenter", // target "employeeType", // changed property "CAPTAIN"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, "foobar"); @@ -129,12 +129,12 @@ public void testValueMultiDeep() throws Exception { "employeeType", // target "employeeType", // changed property "CAPTAIN"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, "12345", "67890"); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } @Test @@ -146,14 +146,14 @@ public void testValueMultiShallow() throws Exception { "employeeType", // target "employeeType", // changed property "CAPTAIN"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, "12345", "67890"); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testValueSingleEnum() throws Exception { // WHEN @@ -163,7 +163,7 @@ public void testValueSingleEnum() throws Exception { new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), // target "employeeType", // changed property "CAPTAIN"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, ActivationStatusType.ENABLED); @@ -180,14 +180,14 @@ public void testAsIsAdd() throws Exception { "employeeType", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, "PIRATE"); PrismAsserts.assertTriplePlus(outputTriple, "CAPTAIN", "SWASHBUCKLER"); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testAsIsDelete() throws Exception { // WHEN @@ -197,15 +197,15 @@ public void testAsIsDelete() throws Exception { "employeeType", // target "employeeType", // changed property "PIRATE"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleMinus(outputTriple, "PIRATE"); + PrismAsserts.assertTripleMinus(outputTriple, "PIRATE"); } - - + + @Test public void testAsIsStringToPolyString() throws Exception { // WHEN @@ -213,14 +213,14 @@ public void testAsIsStringToPolyString() throws Exception { "mapping-asis.xml", "testAsIsStringToPolyString", "fullName"); // target - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, PrismTestUtil.createPolyString("PIRATE")); PrismAsserts.assertTripleNoPlus(outputTriple); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testAsIsStringToProtectedString() throws Exception { // WHEN @@ -228,14 +228,14 @@ public void testAsIsStringToProtectedString() throws Exception { "mapping-asis.xml", "testAsIsStringToProtectedString", new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE)); // target - + // THEN outputTriple.checkConsistence(); - evaluator.assertProtectedString("output zero set", outputTriple.getZeroSet(), "PIRATE"); + evaluator.assertProtectedString("output zero set", outputTriple.getZeroSet(), "PIRATE"); PrismAsserts.assertTripleNoPlus(outputTriple); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testAsIsProtectedStringToProtectedString() throws Exception { // WHEN @@ -243,14 +243,14 @@ public void testAsIsProtectedStringToProtectedString() throws Exception { "mapping-asis-password.xml", "testAsIsProtectedStringToProtectedString", new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE)); // target - + // THEN outputTriple.checkConsistence(); - evaluator.assertProtectedString("output zero set", outputTriple.getZeroSet(), "d3adM3nT3llN0Tal3s"); + evaluator.assertProtectedString("output zero set", outputTriple.getZeroSet(), "d3adM3nT3llN0Tal3s"); PrismAsserts.assertTripleNoPlus(outputTriple); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testAsIsProtectedStringToString() throws Exception { // WHEN @@ -258,14 +258,14 @@ public void testAsIsProtectedStringToString() throws Exception { "mapping-asis-password.xml", "testAsIsProtectedStringToString", UserType.F_EMPLOYEE_NUMBER); // target - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, "d3adM3nT3llN0Tal3s"); PrismAsserts.assertTripleNoPlus(outputTriple); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testAsIsProtectedStringToPolyString() throws Exception { // WHEN @@ -273,7 +273,7 @@ public void testAsIsProtectedStringToPolyString() throws Exception { "mapping-asis-password.xml", "testAsIsProtectedStringToPolyString", UserType.F_FULL_NAME); // target - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, PrismTestUtil.createPolyString("d3adM3nT3llN0Tal3s")); @@ -281,7 +281,7 @@ public void testAsIsProtectedStringToPolyString() throws Exception { PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testPathVariables() throws Exception { // WHEN @@ -291,14 +291,14 @@ public void testPathVariables() throws Exception { "employeeType", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, "jack"); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testPathExtensionProperty() throws Exception { // WHEN @@ -307,12 +307,12 @@ public void testPathExtensionProperty() throws Exception { "testPathExtensionProperty", ShadowType.F_NAME // target ); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleEmpty(outputTriple); } - + @Test public void testPathVariablesNamespace() throws Exception { // WHEN @@ -322,15 +322,15 @@ public void testPathVariablesNamespace() throws Exception { "employeeType", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, "jack"); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } - - + + @Test public void testPathVariablesPolyStringShort() throws Exception { // WHEN @@ -340,14 +340,14 @@ public void testPathVariablesPolyStringShort() throws Exception { "fullName", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, PrismTestUtil.createPolyString("Jack Sparrow")); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testPathVariablesPolyStringToStringShort() throws Exception { // WHEN @@ -357,14 +357,14 @@ public void testPathVariablesPolyStringToStringShort() throws Exception { "employeeType", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, "Jack Sparrow"); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testPathVariablesExtension() throws Exception { // WHEN @@ -374,14 +374,14 @@ public void testPathVariablesExtension() throws Exception { "employeeType", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, "jack sparrow"); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testPathVariablesPolyStringToStringLong() throws Exception { // WHEN @@ -391,14 +391,14 @@ public void testPathVariablesPolyStringToStringLong() throws Exception { "employeeType", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, "jack sparrow"); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testScriptSimpleXPath() throws Exception { // WHEN @@ -408,14 +408,14 @@ public void testScriptSimpleXPath() throws Exception { "employeeType", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, "fooBAR"); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testScriptSimpleGroovy() throws Exception { // WHEN @@ -425,14 +425,14 @@ public void testScriptSimpleGroovy() throws Exception { "employeeType", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, "fooBAR"); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testScriptVariablesXPath() throws Exception { // WHEN @@ -442,14 +442,14 @@ public void testScriptVariablesXPath() throws Exception { "employeeType", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, "Captain barbossa"); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testScriptVariablesGroovy() throws Exception { // WHEN @@ -459,12 +459,12 @@ public void testScriptVariablesGroovy() throws Exception { "employeeType", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, "Captain barbossa"); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } @Test @@ -476,14 +476,14 @@ public void testScriptVariablesPolyStringXPath() throws Exception { "fullName", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, new PolyString("Captain Jack Sparrow", "captain jack sparrow")); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testScriptVariablesPolyStringGroovy() throws Exception { // WHEN @@ -493,14 +493,14 @@ public void testScriptVariablesPolyStringGroovy() throws Exception { "fullName", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, new PolyString("Captain Jack Sparrow", "captain jack sparrow")); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testScriptVariablesPolyStringGroovyOp() throws Exception { // WHEN @@ -510,14 +510,14 @@ public void testScriptVariablesPolyStringGroovyOp() throws Exception { "fullName", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, new PolyString("Captain J. Sparrow", "captain j sparrow")); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testScriptVariablesPolyStringGroovyOrig() throws Exception { // WHEN @@ -527,14 +527,14 @@ public void testScriptVariablesPolyStringGroovyOrig() throws Exception { "description", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, "Captain J"); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testScriptVariablesPolyStringGroovyNorm() throws Exception { // WHEN @@ -544,11 +544,11 @@ public void testScriptVariablesPolyStringGroovyNorm() throws Exception { "description", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values - + // THEN PrismAsserts.assertTripleZero(outputTriple, "Captain j"); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } @Test @@ -560,14 +560,14 @@ public void testScriptVariablesPolyStringGroovyNormReplace() throws Exception { "description", // target "fullName", // changed property PrismTestUtil.createPolyString("Barbossa")); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTriplePlus(outputTriple, "Captain b"); - PrismAsserts.assertTripleMinus(outputTriple, "Captain j"); + PrismAsserts.assertTripleMinus(outputTriple, "Captain j"); } - + @Test public void testScriptVariablesPolyStringGroovyNormReplaceNull() throws Exception { // WHEN @@ -577,12 +577,12 @@ public void testScriptVariablesPolyStringGroovyNormReplaceNull() throws Exceptio "description", // target "fullName" // changed property ); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleMinus(outputTriple, "Captain j"); + PrismAsserts.assertTripleMinus(outputTriple, "Captain j"); } @Test @@ -594,14 +594,14 @@ public void testAsIsVariablesPolyStringNorm() throws Exception { "description", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, "jack sparrow"); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testAsIsVariablesPolyStringOrig() throws Exception { // WHEN @@ -611,12 +611,12 @@ public void testAsIsVariablesPolyStringOrig() throws Exception { "description", // target "employeeType", // changed property "CAPTAIN", "SWASHBUCKLER"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, "Jack Sparrow"); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } @@ -625,7 +625,7 @@ public void testScriptExtraVariablesRef() throws Exception { // GIVEN Mapping.Builder,PrismPropertyDefinition> builder = evaluator.createMappingBuilder("mapping-script-extra-variables.xml", "testScriptExtraVariablesRef", "employeeType", null); - + Map vars = new HashMap(); ObjectReferenceType ref = MiscSchemaUtil.createObjectReference( "c0c010c0-d34d-b33f-f00d-111111111112", @@ -634,12 +634,12 @@ public void testScriptExtraVariablesRef() throws Exception { builder.addVariableDefinitions(vars); Mapping,PrismPropertyDefinition> mapping = builder.build(); - + OperationResult opResult = new OperationResult("testScriptExtraVariablesRef"); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); outputTriple.checkConsistence(); @@ -655,7 +655,7 @@ public void testScriptExtraVariablesJaxb() throws Exception { TestUtil.displayTestTitle(TEST_NAME); Mapping.Builder,PrismPropertyDefinition> builder = evaluator.createMappingBuilder("mapping-script-extra-variables.xml", TEST_NAME, "employeeType", null); - + Map vars = new HashMap(); UserType userType = (UserType) PrismTestUtil.parseObject( new File(MidPointTestConstants.OBJECTS_DIR, "c0c010c0-d34d-b33f-f00d-111111111112.xml")).asObjectable(); @@ -664,10 +664,10 @@ public void testScriptExtraVariablesJaxb() throws Exception { Mapping,PrismPropertyDefinition> mapping = builder.build(); OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); outputTriple.checkConsistence(); @@ -675,7 +675,7 @@ public void testScriptExtraVariablesJaxb() throws Exception { PrismAsserts.assertTripleNoPlus(outputTriple); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testScriptFullNameNoChange() throws Exception { // WHEN @@ -683,15 +683,15 @@ public void testScriptFullNameNoChange() throws Exception { "mapping-script-fullname.xml", "testScriptVariablesPolyStringGroovy", "fullName"); // target - - + + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, PrismTestUtil.createPolyString("Jack Sparrow")); PrismAsserts.assertTripleNoPlus(outputTriple); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testScriptFullNameReplaceGivenName() throws Exception { final String TEST_NAME = "testScriptFullNameReplaceGivenName"; @@ -703,34 +703,34 @@ public void testScriptFullNameReplaceGivenName() throws Exception { "fullName", // target "givenName", // changed property PrismTestUtil.createPolyString("Jackie")); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("Jackie Sparrow")); PrismAsserts.assertTripleMinus(outputTriple, PrismTestUtil.createPolyString("Jack Sparrow")); } - + @Test public void testScriptFullNameDeleteGivenName() throws Exception { final String TEST_NAME = "testScriptFullNameDeleteGivenName"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN ObjectDelta delta = ObjectDelta.createModificationDeleteProperty(UserType.class, evaluator.USER_OLD_OID, UserType.F_GIVEN_NAME, evaluator.getPrismContext(), PrismTestUtil.createPolyString("Jack")); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( "mapping-script-fullname.xml", TEST_NAME, "fullName", // target delta); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); outputTriple.checkConsistence(); @@ -738,30 +738,30 @@ public void testScriptFullNameDeleteGivenName() throws Exception { PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("Sparrow")); PrismAsserts.assertTripleMinus(outputTriple, PrismTestUtil.createPolyString("Jack Sparrow")); } - + @Test public void testScriptFullNameDeleteGivenNameFromNull() throws Exception { final String TEST_NAME = "testScriptFullNameDeleteGivenNameFromNull"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN - ObjectDelta delta = ObjectDelta.createModificationDeleteProperty(UserType.class, evaluator.USER_OLD_OID, + ObjectDelta delta = ObjectDelta.createModificationDeleteProperty(UserType.class, evaluator.USER_OLD_OID, UserType.F_GIVEN_NAME, evaluator.getPrismContext(), PrismTestUtil.createPolyString("Jack")); - + PrismObject userOld = evaluator.getUserOld(); userOld.asObjectable().setGivenName(null); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( "mapping-script-fullname.xml", TEST_NAME, "fullName", // target delta, userOld); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); outputTriple.checkConsistence(); @@ -769,28 +769,28 @@ public void testScriptFullNameDeleteGivenNameFromNull() throws Exception { PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("Sparrow")); PrismAsserts.assertTripleMinus(outputTriple, PrismTestUtil.createPolyString("Jack Sparrow")); } - + @Test public void testScriptFullNameDeleteGivenNameFamilyName() throws Exception { final String TEST_NAME = "testScriptFullNameDeleteGivenNameFamilyName"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN ObjectDelta delta = ObjectDelta.createModificationDeleteProperty(UserType.class, evaluator.USER_OLD_OID, UserType.F_GIVEN_NAME, evaluator.getPrismContext(), PrismTestUtil.createPolyString("Jack")); delta.addModificationDeleteProperty(UserType.F_FAMILY_NAME, PrismTestUtil.createPolyString("Sparrow")); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( "mapping-script-fullname.xml", TEST_NAME, "fullName", // target delta); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); outputTriple.checkConsistence(); @@ -798,7 +798,7 @@ public void testScriptFullNameDeleteGivenNameFamilyName() throws Exception { PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("John Doe")); PrismAsserts.assertTripleMinus(outputTriple, PrismTestUtil.createPolyString("Jack Sparrow")); } - + /** * Change an unrelated property. See that it does not die. */ @@ -811,14 +811,14 @@ public void testScriptFullNameReplaceEmployeeNumber() throws Exception { "fullName", // target "employeeNumber", // changed property "666"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, PrismTestUtil.createPolyString("Jack Sparrow")); PrismAsserts.assertTripleNoPlus(outputTriple); PrismAsserts.assertTripleNoMinus(outputTriple); } - + /** * Return type is a date, script returns string. */ @@ -831,7 +831,7 @@ public void testScriptDateGroovy() throws Exception { new ItemPath(UserType.F_ACTIVATION, ActivationType.F_VALID_FROM), // target "employeeNumber", // changed property "1975-05-30"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple); @@ -867,12 +867,12 @@ public void testScriptRootNodeRef() throws Exception { "c0c010c0-d34d-b33f-f00d-111111111111", UserType.COMPLEX_TYPE)) .build(); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); outputTriple.checkConsistence(); @@ -895,10 +895,10 @@ public void testScriptRootNodeJaxb() throws Exception { .build(); OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); outputTriple.checkConsistence(); @@ -916,11 +916,11 @@ public void testScriptListRelativeXPath() throws Exception { "organizationalUnit", // target "organizationalUnit", // changed property PrismTestUtil.createPolyString("Antropomorphic Personifications")); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, - PrismTestUtil.createPolyString("The Guild of Brethren of the Coast"), + PrismTestUtil.createPolyString("The Guild of Brethren of the Coast"), PrismTestUtil.createPolyString("The Guild of Davie Jones' Locker")); PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("The Guild of Antropomorphic Personifications")); PrismAsserts.assertTripleNoMinus(outputTriple); @@ -935,27 +935,27 @@ public void testScriptListRelativeGroovy() throws Exception { "organizationalUnit", // target "organizationalUnit", // changed property PrismTestUtil.createPolyString("Antropomorphic Personifications")); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, - PrismTestUtil.createPolyString("The Guild of Brethren of the Coast"), + PrismTestUtil.createPolyString("The Guild of Brethren of the Coast"), PrismTestUtil.createPolyString("The Guild of Davie Jones' Locker")); PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("The Guild of Antropomorphic Personifications")); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testScriptListAbsoluteXPath() throws Exception { testScriptListAbsolute("mapping-script-list-absolute-xpath.xml"); } - + @Test public void testScriptListAbsoluteGroovy() throws Exception { testScriptListAbsolute("mapping-script-list-absolute-groovy.xml"); } - + public void testScriptListAbsolute(String fileName) throws Exception { // WHEN @@ -965,17 +965,17 @@ public void testScriptListAbsolute(String fileName) throws Exception { "organizationalUnit", // target "organizationalUnit", // changed property PrismTestUtil.createPolyString("Antropomorphic Personifications")); // changed values - + // THEN outputTriple.checkConsistence(); - PrismAsserts.assertTripleZero(outputTriple, - PrismTestUtil.createPolyString("Brethren of the Coast"), + PrismAsserts.assertTripleZero(outputTriple, + PrismTestUtil.createPolyString("Brethren of the Coast"), PrismTestUtil.createPolyString("Davie Jones' Locker")); PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("Antropomorphic Personifications")); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testValueConditionTrue() throws Exception { // WHEN @@ -985,14 +985,14 @@ public void testValueConditionTrue() throws Exception { "employeeType", // target "employeeType", // changed property "DRUNKARD"); // changed values - + // THEN outputTriple.checkConsistence(); PrismAsserts.assertTripleZero(outputTriple, "foobar"); PrismAsserts.assertTripleNoPlus(outputTriple); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testValueConditionFalse() throws Exception { // WHEN @@ -1002,33 +1002,33 @@ public void testValueConditionFalse() throws Exception { "employeeType", // target "employeeType", // changed property "DRUNKARD"); // changed values - + // THEN assertNull("Unexpected value in outputTriple", outputTriple); } - - - + + + @Test public void testConditionNonEmptyCaptain() throws Exception { // GIVEN final String TEST_NAME = "testConditionNonEmptyCaptain"; TestUtil.displayTestTitle(TEST_NAME); - + PrismObject user = evaluator.getUserOld(); user.asObjectable().getEmployeeType().clear(); user.asObjectable().getEmployeeType().add("CAPTAIN"); ObjectDelta delta = ObjectDelta.createAddDelta(user); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - "mapping-condition-nonempty.xml", + "mapping-condition-nonempty.xml", TEST_NAME, "title", delta); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); outputTriple.checkConsistence(); @@ -1036,84 +1036,84 @@ public void testConditionNonEmptyCaptain() throws Exception { PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("The CAPTAIN")); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testConditionNonEmptyEmpty() throws Exception { // GIVEN final String TEST_NAME = "testConditionNonEmptyEmpty"; TestUtil.displayTestTitle(TEST_NAME); - + PrismObject user = evaluator.getUserOld(); user.asObjectable().getEmployeeType().clear(); user.asObjectable().getEmployeeType().add(""); ObjectDelta delta = ObjectDelta.createAddDelta(user); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - "mapping-condition-nonempty.xml", + "mapping-condition-nonempty.xml", TEST_NAME, "title", delta); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); assertNull("Unexpected value in outputTriple", outputTriple); } - + @Test public void testConditionNonEmptyNoValue() throws Exception { // GIVEN final String TEST_NAME = "testConditionNonEmptyNoValue"; TestUtil.displayTestTitle(TEST_NAME); - + PrismObject user = evaluator.getUserOld(); user.asObjectable().getEmployeeType().clear(); ObjectDelta delta = ObjectDelta.createAddDelta(user); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - "mapping-condition-nonempty.xml", + "mapping-condition-nonempty.xml", TEST_NAME, "title", delta); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); assertNull("Unexpected value in outputTriple", outputTriple); } - + @Test public void testScriptTransformMultiAddDelete() throws Exception { final String TEST_NAME = "testScriptTransformMultiAddDelete"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN ObjectDelta delta = ObjectDelta.createEmptyModifyDelta(UserType.class, evaluator.USER_OLD_OID, evaluator.getPrismContext()); PropertyDelta propDelta = delta.createPropertyModification(evaluator.toPath("employeeType")); propDelta.addValueToAdd(new PrismPropertyValue("CAPTAIN")); propDelta.addValueToDelete(new PrismPropertyValue("LANDLUBER")); delta.addModification(propDelta); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - "mapping-script-transform.xml", + "mapping-script-transform.xml", TEST_NAME, "organizationalUnit", delta); - + PrismObject user = (PrismObject) mapping.getSourceContext().getOldObject(); user.asObjectable().getEmployeeType().add("LANDLUBER"); mapping.getSourceContext().recompute(); display("user before", user); display("delta", delta); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); mapping.evaluate(null, opResult); - + // THEN TestUtil.displayThen(TEST_NAME); PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); @@ -1130,28 +1130,28 @@ public void testScriptTransformMultiAddDelete() throws Exception { public void testScriptTransformMultiReplace() throws Exception { final String TEST_NAME = "testScriptTransformMultiReplace"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN ObjectDelta delta = ObjectDelta.createEmptyModifyDelta(UserType.class, evaluator.USER_OLD_OID, evaluator.getPrismContext()); PropertyDelta propDelta = delta.createPropertyModification(evaluator.toPath("employeeType")); propDelta.addValueToReplace(new PrismPropertyValue("CAPTAIN")); delta.addModification(propDelta); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - "mapping-script-transform.xml", + "mapping-script-transform.xml", TEST_NAME, "organizationalUnit", delta); - + PrismObject user = (PrismObject) mapping.getSourceContext().getOldObject(); - + display("user before", user); display("delta", delta); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); mapping.evaluate(null, opResult); - + // THEN TestUtil.displayThen(TEST_NAME); PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); @@ -1166,37 +1166,37 @@ public void testScriptTransformMultiReplace() throws Exception { public void testInboundMapping() throws Exception{ final String TEST_NAME = "testInboundMapping"; TestUtil.displayTestTitle(TEST_NAME); - + PrismObject account = PrismTestUtil.parseObject(new File(MappingTestEvaluator.TEST_DIR + "/account-inbound-mapping.xml")); Item oldItem = account.findItem(new ItemPath(ShadowType.F_ATTRIBUTES, SchemaTestConstants.ICFS_NAME)); ItemDelta delta = PropertyDelta.createModificationAddProperty(SchemaTestConstants.ICFS_NAME_PATH, (PrismPropertyDefinition) oldItem.getDefinition(), ((PrismPropertyValue) oldItem.getValue(0)).getValue()); - + PrismObject user = evaluator.getUserDefinition().instantiate(); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createInboudMapping("mapping-inbound.xml", TEST_NAME, delta, user.asObjectable(), account.asObjectable(), null, null); - + OperationResult opResult = new OperationResult(TEST_NAME); mapping.evaluate(null, opResult); - + PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); outputTriple.checkConsistence(); assertTripleZero(outputTriple, PrismTestUtil.createPolyString("pavolr")); PrismAsserts.assertTripleNoPlus(outputTriple); assertTripleNoMinus(outputTriple); } - + @Test public void testGenerateDefault() throws Exception { final String TEST_NAME = "testGenerateDefault"; TestUtil.displayTestTitle(TEST_NAME); - + final StringPolicyType stringPolicy = evaluator.getStringPolicy(); // GIVEN - Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping("mapping-generate.xml", + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping("mapping-generate.xml", TEST_NAME, stringPolicy, "employeeNumber", null); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN (1) mapping.evaluate(null, opResult); @@ -1210,7 +1210,7 @@ public void testGenerateDefault() throws Exception { assertGeneratedValue(value1, stringPolicy, null, false, false); mapping = evaluator.createMapping("mapping-generate.xml", TEST_NAME, stringPolicy, "employeeNumber", null); - + // WHEN (2) mapping.evaluate(null, opResult); @@ -1231,13 +1231,13 @@ public void testGeneratePolicy() throws Exception { final String TEST_NAME = "testGeneratePolicy"; generatePolicy(TEST_NAME, "mapping-generate-policy.xml", "c0c010c0-d34d-b33f-f00d-999888111111.xml", null, false); } - + @Test public void testGeneratePolicyEmpty() throws Exception { final String TEST_NAME = "testGeneratePolicy"; generatePolicy(TEST_NAME, "mapping-generate-policy-empty.xml", "c0c010c0-d34d-b33f-f00d-999888111114.xml", null, true); } - + @Test public void testGeneratePolicyBad() throws Exception { final String TEST_NAME = "testGeneratePolicy"; @@ -1248,28 +1248,28 @@ public void testGeneratePolicyBad() throws Exception { // This is expected, the policy is broken } } - + @Test public void testGeneratePolicyNumericString() throws Exception { final String TEST_NAME = "testGeneratePolicyNumericString"; - generatePolicy(TEST_NAME, "mapping-generate-policy-numeric.xml", "c0c010c0-d34d-b33f-f00d-999888111112.xml", + generatePolicy(TEST_NAME, "mapping-generate-policy-numeric.xml", "c0c010c0-d34d-b33f-f00d-999888111112.xml", PATTERN_NUMERIC, false); } - + private void generatePolicy(final String TEST_NAME, String mappingFileName, String policyFileName, String pattern, boolean ignoreMax) throws Exception { TestUtil.displayTestTitle(TEST_NAME); - + // This is just for validation. The expression has to resolve reference of its own PrismObject valuePolicy = PrismTestUtil.parseObject( new File(MidPointTestConstants.OBJECTS_DIR, policyFileName)); final StringPolicyType stringPolicy = valuePolicy.asObjectable().getStringPolicy(); // GIVEN - Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping(mappingFileName, + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping(mappingFileName, TEST_NAME, stringPolicy, "employeeNumber", null); - - OperationResult opResult = new OperationResult(TEST_NAME); + OperationResult opResult = new OperationResult(TEST_NAME); + // WHEN (1) mapping.evaluate(null, opResult); @@ -1286,7 +1286,7 @@ private void generatePolicy(final String TEST_NAME, String mappingFileName, Stri // GIVEN (2) mapping = evaluator.createMapping(mappingFileName, TEST_NAME, stringPolicy, "employeeNumber", null); - + // WHEN (2) mapping.evaluate(null, opResult); @@ -1302,7 +1302,7 @@ private void generatePolicy(final String TEST_NAME, String mappingFileName, Stri assertFalse("Generated the same value", value1.equals(value2)); } - + private void assertGeneratedValue(String value, StringPolicyType stringPolicy, String pattern, boolean ignoreMin, boolean ignoreMax) { if (stringPolicy == null) { assertEquals("Unexpected generated value length", GenerateExpressionEvaluator.DEFAULT_LENGTH, value.length()); @@ -1323,28 +1323,28 @@ private void assertGeneratedValue(String value, StringPolicyType stringPolicy, S @Test public void testGeneratePolicyNumericInt() throws Exception { final String TEST_NAME = "testGeneratePolicyNumericInt"; - generatePolicyNumeric(TEST_NAME, "mapping-generate-policy-numeric.xml", + generatePolicyNumeric(TEST_NAME, "mapping-generate-policy-numeric.xml", "c0c010c0-d34d-b33f-f00d-999888111112.xml", "intType", Integer.class); } - + @Test public void testGeneratePolicyNumericInteger() throws Exception { final String TEST_NAME = "testGeneratePolicyNumericInt"; - generatePolicyNumeric(TEST_NAME, "mapping-generate-policy-numeric.xml", + generatePolicyNumeric(TEST_NAME, "mapping-generate-policy-numeric.xml", "c0c010c0-d34d-b33f-f00d-999888111112.xml", "integerType", Integer.class); } - + @Test public void testGeneratePolicyNumericLong() throws Exception { final String TEST_NAME = "testGeneratePolicyNumericInt"; - generatePolicyNumeric(TEST_NAME, "mapping-generate-policy-numeric.xml", + generatePolicyNumeric(TEST_NAME, "mapping-generate-policy-numeric.xml", "c0c010c0-d34d-b33f-f00d-999888111112.xml", "longType", Long.class); } - + private void generatePolicyNumeric(final String TEST_NAME, String mappingFileName, String policyFileName, String extensionPropName, Class clazz) throws Exception { TestUtil.displayTestTitle(TEST_NAME); - + // This is just for validation. The expression has to resolve reference of its own PrismObject valuePolicy = PrismTestUtil.parseObject( new File(MidPointTestConstants.OBJECTS_DIR, policyFileName)); @@ -1355,9 +1355,9 @@ TEST_NAME, stringPolicy, new ItemPath( UserType.F_EXTENSION, new QName(NS_EXTENSION, extensionPropName)), null) .build(); - - OperationResult opResult = new OperationResult(TEST_NAME); + OperationResult opResult = new OperationResult(TEST_NAME); + // WHEN (1) mapping.evaluate(null, opResult); @@ -1374,13 +1374,13 @@ TEST_NAME, stringPolicy, new ItemPath( assertGeneratedValue(value1.toString(), stringPolicy, PATTERN_NUMERIC, true, false); // GIVEN (2) - + mapping = evaluator.createMappingBuilder(mappingFileName, TEST_NAME, stringPolicy, new ItemPath( UserType.F_EXTENSION, new QName(NS_EXTENSION, extensionPropName)), null) .build(); - + // WHEN (2) mapping.evaluate(null, opResult); @@ -1402,10 +1402,10 @@ public void testGenerateProtectedString() throws Exception { final String TEST_NAME = "testGenerateProtectedString"; TestUtil.displayTestTitle(TEST_NAME); // GIVEN - Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping("mapping-generate.xml", + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping("mapping-generate.xml", TEST_NAME, SchemaConstants.PATH_PASSWORD_VALUE, null); OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); @@ -1415,10 +1415,10 @@ public void testGenerateProtectedString() throws Exception { ProtectedStringType value1 = MappingTestEvaluator.getSingleValue("plus set", outputTriple.getZeroSet()); PrismAsserts.assertTripleNoPlus(outputTriple); PrismAsserts.assertTripleNoMinus(outputTriple); - + System.out.println("Generated excrypted value: "+value1); assertNotNull(value1); assertNotNull(value1.getEncryptedDataType()); } - + } 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 8695931d34a..a797c2dba73 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 @@ -52,59 +52,59 @@ * @author Radovan Semancik */ public class TestMappingDynamicSysVar { - + private static final String NS_EXTENSION = "http://midpoint.evolveum.com/xml/ns/test/extension"; private static final String PATTERN_NUMERIC = "^\\d+$"; - + private MappingTestEvaluator evaluator; - + @BeforeClass public void setupFactory() throws SAXException, IOException, SchemaException { evaluator = new MappingTestEvaluator(); evaluator.init(); } - + @Test public void testScriptSystemVariablesConditionAddObjectTrueGroovy() throws Exception { testScriptSystemVariablesConditionAddObjectTrue("mapping-script-system-variables-condition-groovy.xml"); } - + @Test public void testScriptSystemVariablesConditionAddObjectTrueSourcecontextGroovy() throws Exception { testScriptSystemVariablesConditionAddObjectTrue("mapping-script-system-variables-condition-sourcecontext-groovy.xml"); } - + @Test public void testScriptSystemVariablesConditionAddObjectTrueXPath() throws Exception { testScriptSystemVariablesConditionAddObjectTrue("mapping-script-system-variables-condition-xpath.xml"); } - + public void testScriptSystemVariablesConditionAddObjectTrue(String filename) throws Exception { // GIVEN final String TEST_NAME = "testScriptSystemVariablesConditionAddObjectTrue"; System.out.println("===[ "+TEST_NAME+"]==="); - + PrismObject user = evaluator.getUserOld(); user.asObjectable().getEmployeeType().clear(); user.asObjectable().getEmployeeType().add("CAPTAIN"); ObjectDelta delta = ObjectDelta.createAddDelta(user); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - filename, + filename, TEST_NAME, "title", delta); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("Captain jack")); PrismAsserts.assertTripleNoMinus(outputTriple); } - + /** * Change property that is not a source in this mapping */ @@ -112,59 +112,59 @@ public void testScriptSystemVariablesConditionAddObjectTrue(String filename) thr public void testScriptSystemVariablesConditionModifyObjectTrueGroovyUnrelated() throws Exception { final String TEST_NAME = "testScriptSystemVariablesConditionAddObjectTrueGroovyUnrelated"; System.out.println("===[ "+TEST_NAME+"]==="); - + // GIVEN - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, evaluator.toPath("employeeNumber"), evaluator.getPrismContext(), "666"); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - "mapping-script-system-variables-condition-groovy.xml", + "mapping-script-system-variables-condition-groovy.xml", TEST_NAME, "title", delta); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); assertNull("Unexpected value in outputTriple: "+outputTriple, outputTriple); } - + @Test public void testScriptSystemVariablesConditionAddObjectFalseGroovy() throws Exception { testScriptSystemVariablesConditionAddObjectFalse("mapping-script-system-variables-condition-groovy.xml"); } - + @Test public void testScriptSystemVariablesConditionAddObjectFalseSourcecontextGroovy() throws Exception { testScriptSystemVariablesConditionAddObjectFalse("mapping-script-system-variables-condition-sourcecontext-groovy.xml"); } - + @Test public void testScriptSystemVariablesConditionAddObjectFalseXPath() throws Exception { testScriptSystemVariablesConditionAddObjectFalse("mapping-script-system-variables-condition-xpath.xml"); } - + public void testScriptSystemVariablesConditionAddObjectFalse(String filename) throws Exception { // GIVEN final String TEST_NAME = "testScriptSystemVariablesConditionAddObjectFalse"; System.out.println("===[ "+TEST_NAME+"]==="); - + PrismObject user = evaluator.getUserOld(); user.asObjectable().getEmployeeType().clear(); user.asObjectable().getEmployeeType().add("SAILOR"); ObjectDelta delta = ObjectDelta.createAddDelta(user); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - filename, + filename, TEST_NAME, "title", delta); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); assertNull("Unexpected output triple: "+outputTriple, outputTriple); @@ -174,112 +174,112 @@ public void testScriptSystemVariablesConditionAddObjectFalse(String filename) th public void testScriptSystemVariablesConditionAddObjectFalseNoValGroovy() throws Exception { testScriptSystemVariablesConditionAddObjectFalseNoVal("mapping-script-system-variables-condition-groovy.xml"); } - + @Test public void testScriptSystemVariablesConditionAddObjectFalseNoValSourcecontextGroovy() throws Exception { testScriptSystemVariablesConditionAddObjectFalseNoVal("mapping-script-system-variables-condition-sourcecontext-groovy.xml"); } - + @Test public void testScriptSystemVariablesConditionAddObjectFalseNoValXPath() throws Exception { testScriptSystemVariablesConditionAddObjectFalseNoVal("mapping-script-system-variables-condition-xpath.xml"); } - + public void testScriptSystemVariablesConditionAddObjectFalseNoVal(String filename) throws Exception { // GIVEN final String TEST_NAME = "testScriptSystemVariablesConditionAddObjectFalseNoVal"; System.out.println("===[ "+TEST_NAME+"]==="); - + PrismObject user = evaluator.getUserOld(); PrismProperty employeeTypeProperty = user.findProperty(UserType.F_EMPLOYEE_TYPE); employeeTypeProperty.clear(); ObjectDelta delta = ObjectDelta.createAddDelta(user); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - filename, + filename, TEST_NAME, "title", delta); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); assertNull("Unexpected output triple: "+outputTriple, outputTriple); } - + @Test public void testScriptSystemVariablesConditionAddObjectFalseNoPropertyGroovy() throws Exception { testScriptSystemVariablesConditionAddObjectFalseNoProperty("mapping-script-system-variables-condition-groovy.xml"); } - + @Test public void testScriptSystemVariablesConditionAddObjectFalseNoPropertySourcecontextGroovy() throws Exception { testScriptSystemVariablesConditionAddObjectFalseNoProperty("mapping-script-system-variables-condition-sourcecontext-groovy.xml"); } - + @Test public void testScriptSystemVariablesConditionAddObjectFalseNoPropertyXPath() throws Exception { testScriptSystemVariablesConditionAddObjectFalseNoProperty("mapping-script-system-variables-condition-xpath.xml"); } - + public void testScriptSystemVariablesConditionAddObjectFalseNoProperty(String filename) throws Exception { // GIVEN final String TEST_NAME = "testScriptSystemVariablesConditionAddObjectFalseNoProperty"; System.out.println("===[ "+TEST_NAME+"]==="); - - + + PrismObject user = evaluator.getUserOld(); user.removeProperty(UserType.F_EMPLOYEE_TYPE); ObjectDelta delta = ObjectDelta.createAddDelta(user); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - filename, + filename, TEST_NAME, "title", delta); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); assertNull("Unexpected output triple: "+outputTriple, outputTriple); } - + @Test public void testScriptSystemVariablesConditionTrueToTrueGroovy() throws Exception { testScriptSystemVariablesConditionTrueToTrue("mapping-script-system-variables-condition-groovy.xml"); } - + @Test public void testScriptSystemVariablesConditionTrueToTrueXPath() throws Exception { testScriptSystemVariablesConditionTrueToTrue("mapping-script-system-variables-condition-xpath.xml"); } - + public void testScriptSystemVariablesConditionTrueToTrue(String filename) throws Exception { // GIVEN final String TEST_NAME = "testScriptSystemVariablesConditionTrueToTrue"; System.out.println("===[ "+TEST_NAME+"]==="); - - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, evaluator.toPath("name"), evaluator.getPrismContext(), PrismTestUtil.createPolyString("Jack")); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - filename, + filename, TEST_NAME, "title", delta); - + PrismObject user = (PrismObject) mapping.getSourceContext().getOldObject(); user.asObjectable().getEmployeeType().add("CAPTAIN"); mapping.getSourceContext().recompute(); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); PrismAsserts.assertTripleNoZero(outputTriple); @@ -291,190 +291,190 @@ public void testScriptSystemVariablesConditionTrueToTrue(String filename) throws public void testScriptSystemVariablesConditionFalseToFalseGroovy() throws Exception { testScriptSystemVariablesConditionFalseToFalse("mapping-script-system-variables-condition-groovy.xml"); } - + @Test public void testScriptSystemVariablesConditionFalseToFalseXPath() throws Exception { testScriptSystemVariablesConditionFalseToFalse("mapping-script-system-variables-condition-xpath.xml"); } - + public void testScriptSystemVariablesConditionFalseToFalse(String filename) throws Exception { // GIVEN final String TEST_NAME = "testScriptSystemVariablesConditionFalseToFalse"; System.out.println("===[ "+TEST_NAME+"]==="); - - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, evaluator.toPath("name"), evaluator.getPrismContext(), PrismTestUtil.createPolyString("Jack")); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - filename, + filename, TEST_NAME, "title", delta); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); assertNull("Unexpected value in outputTriple: "+outputTriple, outputTriple); } - + @Test public void testScriptSystemVariablesConditionFalseToTrueGroovy() throws Exception { testScriptSystemVariablesConditionFalseToTrue("mapping-script-system-variables-condition-groovy.xml"); } - + @Test public void testScriptSystemVariablesConditionFalseToTrueXPath() throws Exception { testScriptSystemVariablesConditionFalseToTrue("mapping-script-system-variables-condition-xpath.xml"); } - + public void testScriptSystemVariablesConditionFalseToTrue(String filename) throws Exception { // GIVEN final String TEST_NAME = "testScriptSystemVariablesConditionFalseToTrue"; System.out.println("===[ "+TEST_NAME+"]==="); - - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, evaluator.toPath("name"), evaluator.getPrismContext(), PrismTestUtil.createPolyString("Jack")); delta.addModificationAddProperty(evaluator.toPath("employeeType"), "CAPTAIN"); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( filename, TEST_NAME, "title", delta); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("Captain Jack")); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testScriptSystemVariablesConditionTrueToFalseGroovy() throws Exception { testScriptSystemVariablesConditionTrueToFalse("mapping-script-system-variables-condition-groovy.xml"); } - + @Test public void testScriptSystemVariablesConditionTrueToFalseXPath() throws Exception { testScriptSystemVariablesConditionTrueToFalse("mapping-script-system-variables-condition-xpath.xml"); } - + public void testScriptSystemVariablesConditionTrueToFalse(String filename) throws Exception { // GIVEN final String TEST_NAME = "testScriptSystemVariablesConditionTrueToFalse"; System.out.println("===[ "+TEST_NAME+"]==="); - - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, evaluator.toPath("name"), evaluator.getPrismContext(), "Jack"); delta.addModificationDeleteProperty(evaluator.toPath("employeeType"), "CAPTAIN"); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( filename, TEST_NAME, "title", delta); - + PrismObject user = (PrismObject) mapping.getSourceContext().getOldObject(); user.asObjectable().getEmployeeType().add("CAPTAIN"); mapping.getSourceContext().recompute(); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTripleNoPlus(outputTriple); PrismAsserts.assertTripleMinus(outputTriple, PrismTestUtil.createPolyString("Captain jack")); } - + @Test public void testScriptSystemVariablesConditionEmptyTrue() throws Exception { final String TEST_NAME = "testScriptSystemVariablesConditionEmptyTrue"; testScriptSystemVariablesConditionEmptyTrue(TEST_NAME, "mapping-script-system-variables-condition-empty.xml"); } - + @Test public void testScriptSystemVariablesConditionEmptyTrueFunction() throws Exception { final String TEST_NAME = "testScriptSystemVariablesConditionEmptyTrueFunction"; testScriptSystemVariablesConditionEmptyTrue(TEST_NAME, "mapping-script-system-variables-condition-empty-function.xml"); } - + @Test public void testScriptSystemVariablesConditionEmptySingleTrue() throws Exception { final String TEST_NAME = "testScriptSystemVariablesConditionEmptySingleTrue"; testScriptSystemVariablesConditionEmptyTrue(TEST_NAME, "mapping-script-system-variables-condition-empty-single.xml"); } - + @Test public void testScriptSystemVariablesConditionEmptySingleTrueFunction() throws Exception { final String TEST_NAME = "testScriptSystemVariablesConditionEmptySingleTrueFunction"; testScriptSystemVariablesConditionEmptyTrue(TEST_NAME, "mapping-script-system-variables-condition-empty-single-function.xml"); } - + public void testScriptSystemVariablesConditionEmptyTrue(final String TEST_NAME, String filename) throws Exception { System.out.println("===[ "+TEST_NAME+"]==="); - + // GIVEN - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, evaluator.toPath("name"), evaluator.getPrismContext(), PrismTestUtil.createPolyString("Jack")); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - filename, + filename, TEST_NAME, "title", delta); - + PrismObject user = (PrismObject) mapping.getSourceContext().getOldObject(); user.asObjectable().getEmployeeType().clear(); user.asObjectable().setEmployeeNumber(null); mapping.getSourceContext().recompute(); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("Landlubber Jack")); PrismAsserts.assertTripleMinus(outputTriple, PrismTestUtil.createPolyString("Landlubber jack")); } - + @Test public void testScriptSystemVariablesConditionEmptySingleFalseToTrue() throws Exception { final String TEST_NAME = "testScriptSystemVariablesConditionEmptySingleFalseToTrue"; testScriptSystemVariablesConditionEmptyFalseToTrue(TEST_NAME, "mapping-script-system-variables-condition-empty-single.xml"); } - + @Test public void testScriptSystemVariablesConditionEmptySingleFalseToTrueFunction() throws Exception { final String TEST_NAME = "testScriptSystemVariablesConditionEmptySingleFalseToTrueFunction"; testScriptSystemVariablesConditionEmptyFalseToTrue(TEST_NAME, "mapping-script-system-variables-condition-empty-single-function.xml"); } - + public void testScriptSystemVariablesConditionEmptyFalseToTrue(final String TEST_NAME, String filename) throws Exception { System.out.println("===[ "+TEST_NAME+"]==="); - + // GIVEN - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, evaluator.toPath("employeeNumber"), evaluator.getPrismContext()); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - filename, + filename, TEST_NAME, "title", delta); - + PrismObject user = (PrismObject) mapping.getSourceContext().getOldObject(); user.asObjectable().setEmployeeNumber("666"); mapping.getSourceContext().recompute(); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); PrismAsserts.assertTripleNoZero(outputTriple); @@ -487,83 +487,83 @@ public void testScriptSystemVariablesConditionEmptyFalse() throws Exception { final String TEST_NAME = "testScriptSystemVariablesConditionEmptyFalse"; testScriptSystemVariablesConditionEmptyFalse(TEST_NAME, "mapping-script-system-variables-condition-empty.xml"); } - + @Test public void testScriptSystemVariablesConditionEmptyFalseFunction() throws Exception { final String TEST_NAME = "testScriptSystemVariablesConditionEmptyFalse"; testScriptSystemVariablesConditionEmptyFalse(TEST_NAME, "mapping-script-system-variables-condition-empty-function.xml"); } - + @Test public void testScriptSystemVariablesConditionEmptySingleFalse() throws Exception { final String TEST_NAME = "testScriptSystemVariablesConditionEmptySingleFalse"; testScriptSystemVariablesConditionEmptyFalse(TEST_NAME, "mapping-script-system-variables-condition-empty-single.xml"); } - + @Test public void testScriptSystemVariablesConditionEmptySingleFalseFunction() throws Exception { final String TEST_NAME = "testScriptSystemVariablesConditionEmptySingleFalseFunction"; testScriptSystemVariablesConditionEmptyFalse(TEST_NAME, "mapping-script-system-variables-condition-empty-single-function.xml"); } - + public void testScriptSystemVariablesConditionEmptyFalse(final String TEST_NAME, String filename) throws Exception { System.out.println("===[ "+TEST_NAME+"]==="); - + // GIVEN - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, evaluator.toPath("name"), evaluator.getPrismContext(), PrismTestUtil.createPolyString("Jack")); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - filename, + filename, TEST_NAME, "title", delta); - + PrismObject user = (PrismObject) mapping.getSourceContext().getOldObject(); user.asObjectable().getEmployeeType().add("SAILOR"); user.asObjectable().setEmployeeNumber("666"); mapping.getSourceContext().recompute(); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); assertNull("Unexpected value in outputTriple: "+outputTriple, outputTriple); } - + @Test public void testScriptSystemVariablesConditionEmptySingleTrueToFalse() throws Exception { final String TEST_NAME = "testScriptSystemVariablesConditionEmptySingleTrueToFalse"; testScriptSystemVariablesConditionEmptyTrueToFalse(TEST_NAME, "mapping-script-system-variables-condition-empty-single.xml"); } - + @Test public void testScriptSystemVariablesConditionEmptySingleTrueToFalseFunction() throws Exception { final String TEST_NAME = "testScriptSystemVariablesConditionEmptySingleTrueToFalseFunction"; testScriptSystemVariablesConditionEmptyTrueToFalse(TEST_NAME, "mapping-script-system-variables-condition-empty-single-function.xml"); } - + public void testScriptSystemVariablesConditionEmptyTrueToFalse(final String TEST_NAME, String filename) throws Exception { System.out.println("===[ "+TEST_NAME+"]==="); - + // GIVEN - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, evaluator.toPath("employeeNumber"), evaluator.getPrismContext(), "666"); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - filename, + filename, TEST_NAME, "title", delta); - + PrismObject user = (PrismObject) mapping.getSourceContext().getOldObject(); user.asObjectable().setEmployeeNumber(null); mapping.getSourceContext().recompute(); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); PrismAsserts.assertTripleNoZero(outputTriple); @@ -575,74 +575,74 @@ public void testScriptSystemVariablesConditionEmptyTrueToFalse(final String TEST public void testNpeFalseToTrue() throws Exception { final String TEST_NAME = "testNpeFalseToTrue"; System.out.println("===[ "+TEST_NAME+"]==="); - + // GIVEN - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, UserType.F_ADDITIONAL_NAME, evaluator.getPrismContext(), "Captain Sparrow"); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - "mapping-npe.xml", + "mapping-npe.xml", TEST_NAME, "title", delta); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("15")); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testNpeTrueToFalse() throws Exception { final String TEST_NAME = "testNpeTrueToFalse"; System.out.println("===[ "+TEST_NAME+"]==="); - + // GIVEN - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, UserType.F_ADDITIONAL_NAME, evaluator.getPrismContext()); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - "mapping-npe.xml", + "mapping-npe.xml", TEST_NAME, "title", delta); - + PrismObject user = (PrismObject) mapping.getSourceContext().getOldObject(); user.asObjectable().setAdditionalName(PrismTestUtil.createPolyStringType("Sultan of the Caribbean")); mapping.getSourceContext().recompute(); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTripleNoPlus(outputTriple); PrismAsserts.assertTripleMinus(outputTriple, PrismTestUtil.createPolyString("23")); } - + @Test public void testPathEnum() throws Exception { final String TEST_NAME = "testPathEnum"; System.out.println("===[ "+TEST_NAME+"]==="); - + // GIVEN - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, evaluator.getPrismContext(), ActivationStatusType.DISABLED); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - "mapping-path-enum.xml", + "mapping-path-enum.xml", TEST_NAME, "costCenter", delta); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); System.out.println("Output triple"); @@ -651,7 +651,7 @@ public void testPathEnum() throws Exception { PrismAsserts.assertTriplePlus(outputTriple, ActivationStatusType.DISABLED.value()); PrismAsserts.assertTripleMinus(outputTriple, ActivationStatusType.ENABLED.value()); } - + @Test public void testEmployeeNumberString() throws Exception { // WHEN @@ -661,7 +661,7 @@ public void testEmployeeNumberString() throws Exception { "employeeType", // target "employeeNumber", // changed property "666"); // changed values - + // THEN PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTriplePlus(outputTriple, "666"); @@ -679,12 +679,12 @@ public void testEmployeeNumberPolyString() throws Exception { "additionalName", // target "employeeNumber", // changed property "666"); // changed values - + // THEN PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("666")); PrismAsserts.assertTripleNoMinus(outputTriple); - + // Make sure it is recomputed PolyString plusval = outputTriple.getPlusSet().iterator().next().getValue(); System.out.println("Plus polystring\n"+ plusval.debugDump()); @@ -700,13 +700,13 @@ public void testEmployeeNumberInt() throws Exception { new ItemPath(UserType.F_EXTENSION, SchemaTestConstants.EXTENSION_INT_TYPE_ELEMENT), // target "employeeNumber", // changed property "666"); // changed values - + // THEN PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTriplePlus(outputTriple, 666); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testEmployeeNumberInteger() throws Exception { // WHEN @@ -716,13 +716,13 @@ public void testEmployeeNumberInteger() throws Exception { new ItemPath(UserType.F_EXTENSION, SchemaTestConstants.EXTENSION_INTEGER_TYPE_ELEMENT), // target "employeeNumber", // changed property "666"); // changed values - + // THEN PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTriplePlus(outputTriple, new BigInteger("666")); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testEmployeeNumberLong() throws Exception { // WHEN @@ -732,13 +732,13 @@ public void testEmployeeNumberLong() throws Exception { new ItemPath(UserType.F_EXTENSION, SchemaTestConstants.EXTENSION_LONG_TYPE_ELEMENT), // target "employeeNumber", // changed property "666"); // changed values - + // THEN PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTriplePlus(outputTriple, 666L); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testEmployeeNumberDecimal() throws Exception { // WHEN @@ -748,13 +748,13 @@ public void testEmployeeNumberDecimal() throws Exception { new ItemPath(UserType.F_EXTENSION, SchemaTestConstants.EXTENSION_DECIMAL_TYPE_ELEMENT), // target "employeeNumber", // changed property "666.33"); // changed values - + // THEN PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTriplePlus(outputTriple, new BigDecimal("666.33")); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testEmployeeNumberProtectedString() throws Exception { // WHEN @@ -764,36 +764,36 @@ public void testEmployeeNumberProtectedString() throws Exception { new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), // target "employeeNumber", // changed property "666"); // changed values - + // THEN - + evaluator.assertProtectedString("plus set", outputTriple.getPlusSet(), "666"); PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testEmployeeTypeDeltaAreplaceB() throws Exception { final String TEST_NAME = "testEmployeeTypeDeltaAreplaceB"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, UserType.F_EMPLOYEE_TYPE, evaluator.getPrismContext(), "B"); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - "mapping-script-system-variables-employee-type.xml", + "mapping-script-system-variables-employee-type.xml", TEST_NAME, "employeeType", delta); - + PrismObject user = (PrismObject) mapping.getSourceContext().getOldObject(); setEmployeeType(user.asObjectable(), "A"); mapping.getSourceContext().recompute(); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN evaluator.assertResult(opResult); PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); @@ -801,29 +801,29 @@ public void testEmployeeTypeDeltaAreplaceB() throws Exception { PrismAsserts.assertTriplePlus(outputTriple, "B"); PrismAsserts.assertTripleMinus(outputTriple, "A"); } - + @Test public void testEmployeeTypeDeltaNullreplaceB() throws Exception { final String TEST_NAME = "testEmployeeTypeDeltaNullreplaceB"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, UserType.F_EMPLOYEE_TYPE, evaluator.getPrismContext(), "B"); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - "mapping-script-system-variables-employee-type.xml", + "mapping-script-system-variables-employee-type.xml", TEST_NAME, "employeeType", delta); - + PrismObject user = (PrismObject) mapping.getSourceContext().getOldObject(); setEmployeeType(user.asObjectable()); mapping.getSourceContext().recompute(); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN evaluator.assertResult(opResult); PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); @@ -831,29 +831,29 @@ public void testEmployeeTypeDeltaNullreplaceB() throws Exception { PrismAsserts.assertTriplePlus(outputTriple, "B"); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testEmployeeTypeDeltaBreplaceB() throws Exception { final String TEST_NAME = "testEmployeeTypeDeltaBreplaceB"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, UserType.F_EMPLOYEE_TYPE, evaluator.getPrismContext(), "B"); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - "mapping-script-system-variables-employee-type.xml", + "mapping-script-system-variables-employee-type.xml", TEST_NAME, "employeeType", delta); - + PrismObject user = (PrismObject) mapping.getSourceContext().getOldObject(); setEmployeeType(user.asObjectable(), "B"); mapping.getSourceContext().recompute(); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN evaluator.assertResult(opResult); PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); @@ -861,46 +861,46 @@ public void testEmployeeTypeDeltaBreplaceB() throws Exception { PrismAsserts.assertTriplePlus(outputTriple, "B"); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testEmployeeTypeDeltaAaddB() throws Exception { final String TEST_NAME = "testEmployeeTypeDeltaAaddB"; TestUtil.displayTestTitle(TEST_NAME); - + // WHEN PrismValueDeltaSetTriple> outputTriple = employeeTypeDeltaABAdd(TEST_NAME, "B", "A"); - + // THEN PrismAsserts.assertTripleZero(outputTriple, "A"); PrismAsserts.assertTriplePlus(outputTriple, "B"); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testEmployeeTypeDeltaABaddB() throws Exception { final String TEST_NAME = "testEmployeeTypeDeltaABaddB"; TestUtil.displayTestTitle(TEST_NAME); - + // WHEN PrismValueDeltaSetTriple> outputTriple = employeeTypeDeltaABAdd(TEST_NAME, "B", "A", "B"); - + // THEN PrismAsserts.assertTripleZero(outputTriple, "A"); PrismAsserts.assertTriplePlus(outputTriple, "B"); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testEmployeeTypeDeltaBaddB() throws Exception { final String TEST_NAME = "testEmployeeTypeDeltaBaddB"; TestUtil.displayTestTitle(TEST_NAME); - + // WHEN PrismValueDeltaSetTriple> outputTriple = employeeTypeDeltaABAdd(TEST_NAME, "B", "B"); - + // THEN PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTriplePlus(outputTriple, "B"); @@ -911,11 +911,11 @@ public void testEmployeeTypeDeltaBaddB() throws Exception { public void testEmployeeTypeDeltaNulladdB() throws Exception { final String TEST_NAME = "testEmployeeTypeDeltaNulladdB"; TestUtil.displayTestTitle(TEST_NAME); - + // WHEN PrismValueDeltaSetTriple> outputTriple = employeeTypeDeltaABAdd(TEST_NAME, "B"); - + // THEN PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTriplePlus(outputTriple, "B"); @@ -925,45 +925,45 @@ public void testEmployeeTypeDeltaNulladdB() throws Exception { public PrismValueDeltaSetTriple> employeeTypeDeltaABAdd( final String TEST_NAME, String addVal, String... oldVals) throws Exception { TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN - ObjectDelta delta = ObjectDelta.createModificationAddProperty(UserType.class, evaluator.USER_OLD_OID, + ObjectDelta delta = ObjectDelta.createModificationAddProperty(UserType.class, evaluator.USER_OLD_OID, UserType.F_EMPLOYEE_TYPE, evaluator.getPrismContext(), addVal); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - "mapping-script-system-variables-employee-type.xml", + "mapping-script-system-variables-employee-type.xml", TEST_NAME, "employeeType", delta); - + PrismObject user = (PrismObject) mapping.getSourceContext().getOldObject(); setEmployeeType(user.asObjectable(), oldVals); mapping.getSourceContext().recompute(); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN evaluator.assertResult(opResult); return mapping.getOutputTriple(); } - + private void setEmployeeType(UserType userType, String... vals) { userType.getEmployeeType().clear(); for (String val: vals) { userType.getEmployeeType().add(val); } } - + @Test public void testEmployeeTypeDeltaBdeleteB() throws Exception { final String TEST_NAME = "testEmployeeTypeDeltaBdeleteB"; TestUtil.displayTestTitle(TEST_NAME); - + // WHEN - PrismValueDeltaSetTriple> outputTriple = + PrismValueDeltaSetTriple> outputTriple = employeeTypeDeltaDelete(TEST_NAME, "B", "B"); - + // THEN PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTripleNoPlus(outputTriple); @@ -974,11 +974,11 @@ public void testEmployeeTypeDeltaBdeleteB() throws Exception { public void testEmployeeTypeDeltaABdeleteB() throws Exception { final String TEST_NAME = "testEmployeeTypeDeltaABdeleteB"; TestUtil.displayTestTitle(TEST_NAME); - + // WHEN - PrismValueDeltaSetTriple> outputTriple = + PrismValueDeltaSetTriple> outputTriple = employeeTypeDeltaDelete(TEST_NAME, "B", "A", "B"); - + // THEN PrismAsserts.assertTripleZero(outputTriple, "A"); PrismAsserts.assertTripleNoPlus(outputTriple); @@ -989,11 +989,11 @@ public void testEmployeeTypeDeltaABdeleteB() throws Exception { public void testEmployeeTypeDeltaAdeleteB() throws Exception { final String TEST_NAME = "testEmployeeTypeDeltaAdeleteB"; TestUtil.displayTestTitle(TEST_NAME); - + // WHEN - PrismValueDeltaSetTriple> outputTriple = + PrismValueDeltaSetTriple> outputTriple = employeeTypeDeltaDelete(TEST_NAME, "B", "A"); - + // THEN PrismAsserts.assertTripleZero(outputTriple, "A"); PrismAsserts.assertTripleNoPlus(outputTriple); @@ -1004,11 +1004,11 @@ public void testEmployeeTypeDeltaAdeleteB() throws Exception { public void testEmployeeTypeDeltaNulldeleteB() throws Exception { final String TEST_NAME = "testEmployeeTypeDeltaNulldeleteB"; TestUtil.displayTestTitle(TEST_NAME); - + // WHEN - PrismValueDeltaSetTriple> outputTriple = + PrismValueDeltaSetTriple> outputTriple = employeeTypeDeltaDelete(TEST_NAME, "B"); - + // THEN PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTripleNoPlus(outputTriple); @@ -1017,29 +1017,29 @@ public void testEmployeeTypeDeltaNulldeleteB() throws Exception { public PrismValueDeltaSetTriple> employeeTypeDeltaDelete(final String TEST_NAME, String delVal, String... oldVals) throws Exception { TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN - ObjectDelta delta = ObjectDelta.createModificationDeleteProperty(UserType.class, evaluator.USER_OLD_OID, + ObjectDelta delta = ObjectDelta.createModificationDeleteProperty(UserType.class, evaluator.USER_OLD_OID, UserType.F_EMPLOYEE_TYPE, evaluator.getPrismContext(), delVal); - + Mapping,PrismPropertyDefinition> mapping = evaluator.createMapping( - "mapping-script-system-variables-employee-type.xml", + "mapping-script-system-variables-employee-type.xml", TEST_NAME, "employeeType", delta); - + PrismObject user = (PrismObject) mapping.getSourceContext().getOldObject(); setEmployeeType(user.asObjectable(), oldVals); mapping.getSourceContext().recompute(); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN evaluator.assertResult(opResult); return mapping.getOutputTriple(); } - + @Test public void testPasswordString() throws Exception { // WHEN @@ -1049,13 +1049,13 @@ public void testPasswordString() throws Exception { "employeeType", // target new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), // changed property evaluator.createProtectedString("weighAnch0r")); // changed values - + // THEN PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTriplePlus(outputTriple, "weighAnch0r"); PrismAsserts.assertTripleMinus(outputTriple, "d3adM3nT3llN0Tal3s"); } - + @Test public void testPasswordPolyString() throws Exception { // WHEN @@ -1065,13 +1065,13 @@ public void testPasswordPolyString() throws Exception { UserType.F_ADDITIONAL_NAME.getLocalPart(), // target new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), // changed property evaluator.createProtectedString("weighAnch0r")); // changed values - + // THEN PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("weighAnch0r")); PrismAsserts.assertTripleMinus(outputTriple, PrismTestUtil.createPolyString("d3adM3nT3llN0Tal3s")); } - + @Test public void testPasswordProtectedString() throws Exception { // WHEN @@ -1081,13 +1081,13 @@ public void testPasswordProtectedString() throws Exception { new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), // target new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), // changed property evaluator.createProtectedString("weighAnch0r")); // changed values - + // THEN PrismAsserts.assertTripleNoZero(outputTriple); evaluator.assertProtectedString("plus set", outputTriple.getPlusSet(), "weighAnch0r"); evaluator.assertProtectedString("minus set", outputTriple.getMinusSet(), "d3adM3nT3llN0Tal3s"); } - + @Test public void testPasswordDecryptString() throws Exception { // WHEN @@ -1097,7 +1097,7 @@ public void testPasswordDecryptString() throws Exception { "employeeType", // target new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), // changed property evaluator.createProtectedString("weighAnch0r")); // changed values - + // THEN PrismAsserts.assertTripleNoZero(outputTriple); PrismAsserts.assertTriplePlus(outputTriple, "weighAnch0r123"); diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingStatic.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingStatic.java index 889aa9a32a7..e9658a2a432 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingStatic.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingStatic.java @@ -32,13 +32,13 @@ public class TestMappingStatic { private MappingTestEvaluator evaluator; - + @BeforeClass public void setupFactory() throws SAXException, IOException, SchemaException { evaluator = new MappingTestEvaluator(); evaluator.init(); } - + @Test public void testValueSingleDeep() throws Exception { // WHEN @@ -46,13 +46,13 @@ public void testValueSingleDeep() throws Exception { "mapping-value-single-deep.xml", "testValue", "costCenter"); // target - + // THEN PrismAsserts.assertTripleZero(outputTriple, "foobar"); PrismAsserts.assertTripleNoPlus(outputTriple); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testValueSingleShallow() throws Exception { // WHEN @@ -60,13 +60,13 @@ public void testValueSingleShallow() throws Exception { "mapping-value-single-shallow.xml", "testValue", "costCenter"); // target - + // THEN PrismAsserts.assertTripleZero(outputTriple, "foobar"); PrismAsserts.assertTripleNoPlus(outputTriple); PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testValueMultiDeep() throws Exception { // WHEN @@ -74,11 +74,11 @@ public void testValueMultiDeep() throws Exception { "mapping-value-multi-deep.xml", "testValueMulti", "employeeType"); // target - + // THEN PrismAsserts.assertTripleZero(outputTriple, "12345", "67890"); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } @Test @@ -88,13 +88,13 @@ public void testValueMultiShallow() throws Exception { "mapping-value-multi-shallow.xml", "testValueMulti", "employeeType"); // target - + // THEN PrismAsserts.assertTripleZero(outputTriple, "12345", "67890"); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testPathNoSource() throws Exception { // WHEN @@ -102,13 +102,13 @@ public void testPathNoSource() throws Exception { "mapping-path-system-variables-nosource.xml", "testPathNoSource", "employeeType"); // target - + // THEN PrismAsserts.assertTripleZero(outputTriple, "jack"); PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); } - + @Test public void testConstFoo() throws Exception { // WHEN @@ -116,7 +116,7 @@ public void testConstFoo() throws Exception { "mapping-const-foo.xml", "testValue", "costCenter"); // target - + // THEN PrismAsserts.assertTripleZero(outputTriple, "foobar"); PrismAsserts.assertTripleNoPlus(outputTriple); 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 7f923bb3947..79ae7b9fa6b 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 @@ -48,7 +48,7 @@ * @author Radovan Semancik */ public class TestMappingTime { - + 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"; private static final XMLGregorianCalendar TIME_PAST = XmlTypeConverter.createXMLGregorianCalendar(2001, 2, 3, 4, 5, 6); @@ -57,143 +57,143 @@ public class TestMappingTime { private static final XMLGregorianCalendar TIME_MAPPING_DISABLED_PLUS_1D = XmlTypeConverter.createXMLGregorianCalendar(2013, 5, 31, 9, 30, 0); private static final XMLGregorianCalendar TIME_MAPPING_DISABLED_PLUS_10D = XmlTypeConverter.createXMLGregorianCalendar(2013, 6, 9, 9, 30, 0); private static final XMLGregorianCalendar TIME_MAPPING_DISABLED_PLUS_1M = XmlTypeConverter.createXMLGregorianCalendar(2013, 6, 30, 9, 30, 0); - + private MappingTestEvaluator evaluator; - + @BeforeClass public void setupFactory() throws SAXException, IOException, SchemaException { evaluator = new MappingTestEvaluator(); evaluator.init(); } - + @Test public void testBeforeTimeFrom() throws Exception { final String TEST_NAME = "testBeforeTimeFrom"; System.out.println("===[ "+TEST_NAME+"]==="); - + // GIVEN - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, UserType.F_EMPLOYEE_TYPE, evaluator.getPrismContext(), "CAPTAIN"); - + Mapping.Builder,PrismPropertyDefinition> builder = evaluator.createMappingBuilder( - MAPPING_TIME_FROM_TO_FILENAME, + MAPPING_TIME_FROM_TO_FILENAME, TEST_NAME, "title", delta); builder.setNow(TIME_PAST); Mapping,PrismPropertyDefinition> mapping = builder.build(); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); assertNullTriple(outputTriple); assertNextRecompute(mapping, TIME_MAPPING_DISABLED_PLUS_1D); } - + @Test public void testBetweenTimes() throws Exception { final String TEST_NAME = "testBetweenTimes"; System.out.println("===[ "+TEST_NAME+"]==="); - + // GIVEN - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, UserType.F_EMPLOYEE_TYPE, evaluator.getPrismContext(), "CAPTAIN"); - + Mapping.Builder,PrismPropertyDefinition> builder = evaluator.createMappingBuilder( - MAPPING_TIME_FROM_TO_FILENAME, + MAPPING_TIME_FROM_TO_FILENAME, TEST_NAME, "title", delta); builder.setNow(TIME_BETWEEN); Mapping,PrismPropertyDefinition> mapping = builder.build(); OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); PrismAsserts.assertTripleNoZero(outputTriple); 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 = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, UserType.F_EMPLOYEE_TYPE, evaluator.getPrismContext(), "CAPTAIN"); - + Mapping.Builder,PrismPropertyDefinition> builder = evaluator.createMappingBuilder( - MAPPING_TIME_FROM_TO_FILENAME, + MAPPING_TIME_FROM_TO_FILENAME, TEST_NAME, "title", delta); builder.setNow(TIME_FUTURE); Mapping,PrismPropertyDefinition> mapping = builder.build(); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); assertNullTriple(outputTriple); - + assertNextRecompute(mapping, null); } - + @Test public void testExistenceBefore() throws Exception { final String TEST_NAME = "testExistenceBefore"; System.out.println("===[ "+TEST_NAME+"]==="); - + // GIVEN Mapping.Builder,PrismPropertyDefinition> builder = evaluator.createMappingBuilder( - MAPPING_TIME_ACTIVATION, + MAPPING_TIME_ACTIVATION, TEST_NAME, "title", null); - + builder.setNow(TIME_PAST); - + PrismPropertyDefinition existenceDef = new PrismPropertyDefinitionImpl<>( ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_BOOLEAN, evaluator.getPrismContext()); builder.setDefaultTargetDefinition(existenceDef); Mapping,PrismPropertyDefinition> mapping = builder.build(); - + OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); assertNullTriple(outputTriple); - + assertNextRecompute(mapping, TIME_MAPPING_DISABLED_PLUS_1M); } - + @Test public void testExistenceAfter() throws Exception { final String TEST_NAME = "testExistenceAfter"; System.out.println("===[ "+TEST_NAME+"]==="); - + // GIVEN Mapping.Builder,PrismPropertyDefinition> builder = evaluator.createMappingBuilder( - MAPPING_TIME_ACTIVATION, + MAPPING_TIME_ACTIVATION, TEST_NAME, "title", null); builder.setNow(TIME_FUTURE); - + PrismPropertyDefinition existenceDef = new PrismPropertyDefinitionImpl<>( ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_BOOLEAN, evaluator.getPrismContext()); @@ -202,35 +202,35 @@ public void testExistenceAfter() throws Exception { Mapping,PrismPropertyDefinition> mapping = builder.build(); OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); PrismAsserts.assertTripleZero(outputTriple, false); 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); - + Mapping.Builder,PrismPropertyDefinition> builder = evaluator.createMappingBuilder( - MAPPING_TIME_ACTIVATION, + MAPPING_TIME_ACTIVATION, TEST_NAME, "title", null, userOld); - + builder.setNow(TIME_PAST); - + PrismPropertyDefinition existenceDef = new PrismPropertyDefinitionImpl<>( ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_BOOLEAN, evaluator.getPrismContext()); @@ -239,38 +239,38 @@ public void testNoReferenceTime() throws Exception { Mapping,PrismPropertyDefinition> mapping = builder.build(); OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); assertNullTriple(outputTriple); - + assertNextRecompute(mapping, null); } - + @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 = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, new ItemPath(UserType.F_ACTIVATION, ActivationType.F_DISABLE_TIMESTAMP), evaluator.getPrismContext(), disableTimestamp); - + Mapping.Builder,PrismPropertyDefinition> builder = evaluator.createMappingBuilder( - MAPPING_TIME_ACTIVATION, + MAPPING_TIME_ACTIVATION, TEST_NAME, "title", delta, userOld); - + builder.setNow(TIME_PAST); - + PrismPropertyDefinition existenceDef = new PrismPropertyDefinitionImpl<>( ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_BOOLEAN, evaluator.getPrismContext()); @@ -279,37 +279,37 @@ public void testSetReferenceTimeBefore() throws Exception { Mapping,PrismPropertyDefinition> mapping = builder.build(); OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); assertNullTriple(outputTriple); - + assertNextRecompute(mapping, TIME_MAPPING_DISABLED_PLUS_1M); } - + @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(); userOld.asObjectable().getActivation().setDisableTimestamp(null); - - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, new ItemPath(UserType.F_ACTIVATION, ActivationType.F_DISABLE_TIMESTAMP), evaluator.getPrismContext(), disableTimestamp); - + Mapping.Builder,PrismPropertyDefinition> builder = evaluator.createMappingBuilder( - MAPPING_TIME_ACTIVATION, + MAPPING_TIME_ACTIVATION, TEST_NAME, "title", delta, userOld); - + builder.setNow(TIME_FUTURE); - + PrismPropertyDefinition existenceDef = new PrismPropertyDefinitionImpl<>( ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_BOOLEAN, evaluator.getPrismContext()); @@ -318,16 +318,16 @@ public void testSetReferenceTimeAfter() throws Exception { Mapping,PrismPropertyDefinition> mapping = builder.build(); OperationResult opResult = new OperationResult(TEST_NAME); - + // WHEN mapping.evaluate(null, opResult); - + // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); PrismAsserts.assertTripleZero(outputTriple, false); PrismAsserts.assertTripleNoPlus(outputTriple); PrismAsserts.assertTripleNoMinus(outputTriple); - + assertNextRecompute(mapping, null); } @@ -339,5 +339,5 @@ private void assertNextRecompute(Mapping mapping, XMLGregorianCalendar expe XMLGregorianCalendar nextRecomputeTime = mapping.getNextRecomputeTime(); assertEquals("Wrong nextRecomputeTime in mapping "+mapping, expected, nextRecomputeTime); } - + } diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestValueConstructionAbsolute.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestValueConstructionAbsolute.java index 960d76f77a0..8013e7b66b2 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestValueConstructionAbsolute.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestValueConstructionAbsolute.java @@ -27,7 +27,7 @@ public class TestValueConstructionAbsolute { private MappingTestEvaluator evaluator; - + @BeforeClass public void setupFactory() throws SAXException, IOException, SchemaException { evaluator = new MappingTestEvaluator(); @@ -38,14 +38,14 @@ public void setupFactory() throws SAXException, IOException, SchemaException { // @Test // public void testConstructionExpressionInputMulti() throws JAXBException, ExpressionEvaluationException, ObjectNotFoundException, SchemaException, FileNotFoundException { // // WHEN -// PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd(String.class, +// PrismValueDeltaSetTriple> outputTriple = evaluator.evaluateMappingDynamicAdd(String.class, // "absolute/construction-expression-input-multi.xml", "employeeType", "rock", null, "testConstructionExpressionSimple", // "apple", "orange"); -// +// // // THEN // PrismAsserts.assertTripleZero(outputTriple, "apple", "orange", "rock" ); // PrismAsserts.assertTripleNoPlus(outputTriple); // PrismAsserts.assertTripleNoMinus(outputTriple); // } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelConstants.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelConstants.java index 04622a965b7..4cb73446db6 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelConstants.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelConstants.java @@ -25,9 +25,9 @@ * */ public class ModelConstants { - + public static final String NS_MODEL_TRIGGER_PREFIX = SchemaConstants.NS_MODEL +"/trigger"; - + public static final String NS_SYNCHRONIZATION_TASK_PREFIX = ModelPublicConstants.NS_SYNCHRONIZATION_TASK_PREFIX; public static final String NS_IMPORT_OBJECTS_PREFIX = SchemaConstants.NS_MODEL +"/import-objects"; diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelCrudService.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelCrudService.java index 0277062f415..469a8aa793a 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelCrudService.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelCrudService.java @@ -76,37 +76,37 @@ /** * Simple version of model service exposing CRUD-like operations. This is common facade for webservice and REST services. * It takes care of all the "details" of externalized obejcts such as applying correct definitions and so on. - * + * * @author Radovan Semancik * */ @Component public class ModelCrudService { - + String CLASS_NAME_WITH_DOT = ModelCrudService.class.getName() + "."; String ADD_OBJECT = CLASS_NAME_WITH_DOT + "addObject"; String MODIFY_OBJECT = CLASS_NAME_WITH_DOT + "modifyObject"; String DELETE_OBJECT = CLASS_NAME_WITH_DOT + "deleteObject"; - + private static final Trace LOGGER = TraceManager.getTrace(ModelCrudService.class); - + @Autowired(required = true) ModelService modelService; @Autowired TaskService taskService; - + @Autowired(required = true) PrismContext prismContext; - + @Autowired(required = true) @Qualifier("cacheRepositoryService") RepositoryService repository; - + @Autowired(required = true) private Protector protector; - + @Autowired(required = true) private ChangeNotificationDispatcher dispatcher; @@ -114,7 +114,7 @@ public PrismObject getObject(Class clazz, String oi Collection> options, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { return modelService.getObject(clazz, oid, options, task, parentResult); - } + } public List> searchObjects(Class type, ObjectQuery query, Collection> options, Task task, OperationResult parentResult) @@ -122,12 +122,12 @@ public List> searchObjects(Class type, SecurityViolationException, ExpressionEvaluationException { return modelService.searchObjects(type, query, options, task, parentResult); } - + public void notifyChange(ResourceObjectShadowChangeDescriptionType changeDescription, OperationResult parentResult, Task task) throws SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ObjectNotFoundException, GenericConnectorException, ObjectAlreadyExistsException, ExpressionEvaluationException{ - + String oldShadowOid = changeDescription.getOldShadowOid(); ResourceEventDescription eventDescription = new ResourceEventDescription(); - + PrismObject oldShadow = null; LOGGER.trace("resolving old object"); if (!StringUtils.isEmpty(oldShadowOid)){ @@ -137,7 +137,7 @@ public void notifyChange(ResourceObjectShadowChangeDescriptionType changeDescrip } else{ LOGGER.trace("Old shadow null"); } - + PrismObject currentShadow = null; ShadowType currentShadowType = changeDescription.getCurrentShadow(); LOGGER.trace("resolving current shadow"); @@ -146,17 +146,17 @@ public void notifyChange(ResourceObjectShadowChangeDescriptionType changeDescrip currentShadow = currentShadowType.asPrismObject(); LOGGER.trace("current shadow resolved to {}", currentShadow.debugDump()); } - + eventDescription.setCurrentShadow(currentShadow); - + ObjectDeltaType deltaType = changeDescription.getObjectDelta(); ObjectDelta delta = null; - + PrismObject shadowToAdd = null; if (deltaType != null){ - + delta = ObjectDelta.createEmptyDelta(ShadowType.class, deltaType.getOid(), prismContext, ChangeType.toChangeType(deltaType.getChangeType())); - + if (delta.getChangeType() == ChangeType.ADD) { // LOGGER.trace("determined ADD change "); if (deltaType.getObjectToAdd() == null){ @@ -171,27 +171,27 @@ public void notifyChange(ResourceObjectShadowChangeDescriptionType changeDescrip // return handleTaskResult(task); } prismContext.adopt((ShadowType)objToAdd); - + shadowToAdd = ((ShadowType) objToAdd).asPrismObject(); LOGGER.trace("object to add: {}", shadowToAdd.debugDump()); delta.setObjectToAdd(shadowToAdd); } else { Collection modifications = DeltaConvertor.toModifications(deltaType.getItemDelta(), prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(ShadowType.class)); delta.getModifications().addAll(modifications); - } + } } Collection> deltas = new ArrayList>(); deltas.add(delta); Utils.encrypt(deltas, protector, null, parentResult); eventDescription.setDelta(delta); - + eventDescription.setSourceChannel(changeDescription.getChannel()); - + dispatcher.notifyEvent(eventDescription, task, parentResult); parentResult.computeStatus(); task.setResult(parentResult); } - + /** *

    @@ -220,7 +220,7 @@ public void notifyChange(ResourceObjectShadowChangeDescriptionType changeDescrip * the underlying schema of the storage system or the schema enforced by the * implementation. *

    - * + * * @param object * object to create * @param parentResult @@ -234,10 +234,10 @@ public void notifyChange(ResourceObjectShadowChangeDescriptionType changeDescrip * @throws SchemaException * error dealing with resource schema, e.g. created object does * not conform to schema - * @throws ExpressionEvaluationException + * @throws ExpressionEvaluationException * evaluation of expression associated with the object has failed - * @throws CommunicationException - * @throws ConfigurationException + * @throws CommunicationException + * @throws ConfigurationException * @throws PolicyViolationException * Policy violation was detected during processing of the object * @throws IllegalArgumentException @@ -246,7 +246,7 @@ public void notifyChange(ResourceObjectShadowChangeDescriptionType changeDescrip * unknown error from underlying layers or other unexpected * state */ - public String addObject(PrismObject object, ModelExecuteOptions options, Task task, + public String addObject(PrismObject object, ModelExecuteOptions options, Task task, OperationResult parentResult) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { @@ -254,7 +254,7 @@ public String addObject(PrismObject object, ModelExecu Validate.notNull(parentResult, "Result type must not be null."); object.checkConsistence(); - + T objectType = object.asObjectable(); prismContext.adopt(objectType); @@ -271,17 +271,17 @@ public String addObject(PrismObject object, ModelExecu LOGGER.trace("Entering addObject with {}", object); LOGGER.trace(object.debugDump()); } - + if (options == null) { if (StringUtils.isNotEmpty(objectType.getVersion())) { options = ModelExecuteOptions.createOverwrite(); } } - + ObjectDelta objectDelta = ObjectDelta.createAddDelta(object); Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); modelService.executeChanges(deltas, options, task, result); - + oid = objectDelta.getOid(); result.computeStatus(); @@ -296,7 +296,7 @@ public String addObject(PrismObject object, ModelExecu return oid; } - + /** *

    * Deletes object with specified OID. @@ -304,7 +304,7 @@ public String addObject(PrismObject object, ModelExecu *

    * Must fail if object with specified OID does not exists. Should be atomic. *

    - * + * * @param oid * OID of object to delete * @param parentResult @@ -313,9 +313,9 @@ public String addObject(PrismObject object, ModelExecu * specified object does not exist * @throws IllegalArgumentException * wrong OID format, described change is not applicable - * @throws CommunicationException - * @throws ConfigurationException - * @throws PolicyViolationException + * @throws CommunicationException + * @throws ConfigurationException + * @throws PolicyViolationException * Policy violation was detected during processing of the object * @throws SystemException * unknown error from underlying layers or other unexpected @@ -339,7 +339,7 @@ public void deleteObject(Class clazz, String oid, Mode objectDelta.setOid(oid); LOGGER.trace("Deleting object with oid {}.", new Object[] { oid }); - + Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); modelService.executeChanges(deltas, options, task, result); @@ -367,7 +367,7 @@ public void deleteObject(Class clazz, String oid, Mode RepositoryCache.exit(); } } - + /** *

    * Modifies object using relative change description. @@ -387,7 +387,7 @@ public void deleteObject(Class clazz, String oid, Mode * underlying schema of the storage system or the schema enforced by the * implementation. *

    - * + * * @param parentResult * parent OperationResult (in/out) * @throws ObjectNotFoundException @@ -396,10 +396,10 @@ public void deleteObject(Class clazz, String oid, Mode * resulting object would violate the schema * @throws ExpressionEvaluationException * evaluation of expression associated with the object has failed - * @throws CommunicationException + * @throws CommunicationException * @throws ObjectAlreadyExistsException * If the account or another "secondary" object already exists and cannot be created - * @throws PolicyViolationException + * @throws PolicyViolationException * Policy violation was detected during processing of the object * @throws IllegalArgumentException * wrong OID format, described change is not applicable @@ -442,7 +442,7 @@ public void modifyObject(Class type, String oid, modelService.executeChanges(deltas, options, task, result); result.computeStatus(); - + } catch (ExpressionEvaluationException ex) { LOGGER.error("model.modifyObject failed: {}", ex.getMessage(), ex); result.recordFatalError(ex); @@ -487,8 +487,8 @@ public void importFromResource(String resourceOid, QName objectClass, Task task, public OperationResult testResource(String resourceOid, Task task) throws ObjectNotFoundException { return modelService.testResource(resourceOid, task); } - - + + //TASK AREA public boolean suspendTasks(Collection taskOids, long waitForStop, OperationResult parentResult) throws SecurityViolationException, ObjectNotFoundException, SchemaException { return taskService.suspendTasks(taskOids, waitForStop, parentResult); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelObjectResolver.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelObjectResolver.java index 859538bd3da..1095ec70f0f 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelObjectResolver.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelObjectResolver.java @@ -64,11 +64,11 @@ public class ModelObjectResolver implements ObjectResolver { @Autowired(required = true) private transient ProvisioningService provisioning; - + @Autowired(required = true) @Qualifier("cacheRepositoryService") private transient RepositoryService cacheRepositoryService; - + @Autowired(required = true) private transient PrismContext prismContext; @@ -80,9 +80,9 @@ public class ModelObjectResolver implements ObjectResolver { @Autowired(required = false) private transient HookRegistry hookRegistry; - + private static final Trace LOGGER = TraceManager.getTrace(ModelObjectResolver.class); - + @Override public O resolve(ObjectReferenceType ref, Class expectedType, Collection> options, String contextDescription, Object task, OperationResult result) throws ObjectNotFoundException, SchemaException { @@ -109,7 +109,7 @@ public O resolve(ObjectReferenceType ref, Class expect throw new SystemException("Error resolving object with oid '" + oid + "': "+ex.getMessage(), ex); } } - + public PrismObject resolve(PrismReferenceValue refVal, String string, Task task, OperationResult result) throws ObjectNotFoundException { return resolve(refVal, string, null, task, result); } @@ -128,8 +128,8 @@ public PrismObject resolve(PrismReferenceValue refVal, } return (PrismObject) (getObjectSimple((Class)typeClass, oid, options, task, result)).asPrismObject(); } - - public T getObjectSimple(Class clazz, String oid, GetOperationOptions options, Task task, + + public T getObjectSimple(Class clazz, String oid, GetOperationOptions options, Task task, OperationResult result) throws ObjectNotFoundException { try { return getObject(clazz, oid, SelectorOptions.createCollection(options), task, result); @@ -145,7 +145,7 @@ public T getObjectSimple(Class clazz, String oid, GetO throw new SystemException("Error resolving object with oid '" + oid + "': "+ex.getMessage(), ex); } } - + public T getObject(Class clazz, String oid, Collection> options, Task task, OperationResult result) throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { T objectType = null; @@ -203,7 +203,7 @@ public T getObject(Class clazz, String oid, Collection return objectType; } - + @Override public void searchIterative(Class type, ObjectQuery query, Collection> options, ResultHandler handler, Object task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { @@ -213,7 +213,7 @@ public void searchIterative(Class type, ObjectQuery qu cacheRepositoryService.searchObjectsIterative(type, query, handler, options, false, parentResult); // TODO pull up into resolver interface } } - + public Integer countObjects(Class type, ObjectQuery query, Collection> options, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { if (ObjectTypes.isClassManagedByProvisioning(type)) { return provisioning.countObjects(type, query, options, task, parentResult); @@ -221,7 +221,7 @@ public Integer countObjects(Class type, ObjectQuery qu return cacheRepositoryService.countObjects(type, query, parentResult); } } - + public PrismObject getSystemConfiguration(OperationResult result) throws ObjectNotFoundException, SchemaException { PrismObject config = cacheRepositoryService.getObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, result); @@ -235,7 +235,7 @@ public PrismObject getSystemConfiguration(OperationResu } return config; } - + public PrismObject searchOrgTreeWidthFirstReference(PrismObject object, Function, ObjectReferenceType> function, String shortDesc, Task task, OperationResult result) throws SchemaException { if (object == null) { @@ -267,7 +267,7 @@ public PrismObject searchOrgTree // and that may mean the misconfiguration could not be easily fixed. LOGGER.warn("Cannot find object {} referenced in {} while resolving {}", orgRefValue.getOid(), object, shortDesc); continue; - } + } if (resolvedObject != null) { if (resultObject == null) { resultObject = resolvedObject; @@ -277,7 +277,7 @@ public PrismObject searchOrgTree } } } - + } catch (ObjectNotFoundException ex) { // Just log the error, but do not fail on that. Failing would prohibit login // and that may mean the misconfiguration could not be easily fixed. @@ -286,11 +286,11 @@ public PrismObject searchOrgTree } } } - + if (resultObject != null) { return resultObject; } - + // go deeper for (PrismObject org : orgs) { PrismObject val = searchOrgTreeWidthFirstReference((PrismObject) org, function, shortDesc, task, result); @@ -298,10 +298,10 @@ public PrismObject searchOrgTree return val; } } - + return null; } - + public R searchOrgTreeWidthFirst(PrismObject object, Function, R> function, Task task, OperationResult result) { PrismReference orgRef = object.findReference(ObjectType.F_PARENT_ORG_REF); @@ -329,7 +329,7 @@ public R searchOrgTreeWidthFirst(PrismObject object, } } } - + // go deeper for (PrismObject orgType : orgs) { R val = searchOrgTreeWidthFirst((PrismObject) orgType, function, task, result); @@ -337,7 +337,7 @@ public R searchOrgTreeWidthFirst(PrismObject object, return val; } } - + return null; } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelRestService.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelRestService.java index 6194c3b23f1..3709757743d 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelRestService.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelRestService.java @@ -103,10 +103,10 @@ public class ModelRestService { public static final String OPERATION_GET_LOG_FILE_SIZE = CLASS_DOT + "getLogFileSize"; public static final String OPERATION_VALIDATE_VALUE = CLASS_DOT + "validateValue"; public static final String OPERATION_GENERATE_VALUE = CLASS_DOT + "generateValue"; - + private static final String CURRENT = "current"; private static final String VALIDATE = "validate"; - + @Autowired private ModelCrudService model; @Autowired private ScriptingService scriptingService; @Autowired private ModelService modelService; @@ -126,7 +126,7 @@ public class ModelRestService { public ModelRestService() { // nothing to do } - + @POST @Path("/{type}/{oid}/generate") @Consumes({"application/xml", "application/json", "application/yaml"}) @@ -153,10 +153,10 @@ public Response generateValue(@PathParam("type") String t } else { response = RestServiceUtil.createResponse(Response.Status.BAD_REQUEST, parentResult, parentResult); } - + // ResponseBuilder responseBuilder = Response.ok(policyItemsDefinition); // response = responseBuilder.build(); - + } catch (Exception ex) { parentResult.computeStatus(); response = RestServiceUtil.handleException(parentResult, ex); @@ -177,7 +177,7 @@ private Response createNoPolicyItemsDefinitionsResponse(OperationResult parentRe @Consumes({"application/xml", "application/json", "application/yaml"}) @Produces({"application/xml", "application/json", "application/yaml"}) public Response validateValue(@PathParam("type") String type, @PathParam("oid") String oid, PolicyItemsDefinitionType policyItemsDefinition, @Context MessageContext mc) { - + Task task = RestServiceUtil.initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_VALIDATE_VALUE); @@ -198,7 +198,7 @@ public Response validateValue(@PathParam("type") String t responseBuilder = Response.status(Status.CONFLICT).entity(parentResult); response = responseBuilder.build(); } - + } catch (Exception ex) { parentResult.computeStatus(); response = RestServiceUtil.handleException(parentResult, ex); @@ -219,7 +219,7 @@ public Response getValuePolicyForUser(@PathParam("id") String oid, @Context Mess Response response; try { - + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createRaw()); PrismObject user = model.getObject(UserType.class, oid, options, task, parentResult); @@ -318,7 +318,7 @@ public Response getSelf(@Context MessageContext mc){ finishRequest(task); return response; } - + @POST @Path("/{type}") @@ -372,7 +372,7 @@ public Response addObject(@PathParam("type") String type, finishRequest(task); return response; } - + @GET @Path("/{type}") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, "application/yaml"}) @@ -384,7 +384,7 @@ public Response searchObjectsByType(@PathParam("type") St Class clazz = ObjectTypes.getClassFromRestType(type); Response response; try { - + Collection> searchOptions = GetOperationOptions.fromRestOptions(options, null, null); List> objects = model.searchObjects(clazz, null, searchOptions, task, parentResult); @@ -393,7 +393,7 @@ public Response searchObjectsByType(@PathParam("type") St List list = objects.stream().map(o -> convert(clazz, o, parentResult.createOperationResultType())).collect(Collectors.toList()); listType.getObject().addAll(list); } - + response = RestServiceUtil.createResponse(Response.Status.OK, listType, parentResult, true); // response = Response.ok().entity(listType).build(); } catch (Exception ex) { @@ -404,7 +404,7 @@ public Response searchObjectsByType(@PathParam("type") St finishRequest(task); return response; } - + private ObjectType convert(Class clazz, PrismObject o, OperationResultType result) { ObjectType objType = null; try { @@ -416,8 +416,8 @@ private ObjectType convert(Class clazz, PrismObject o, Ope // TODO Auto-generated catch block return objType; } - - + + } // currently unused; but potentially useful in future @@ -945,7 +945,7 @@ public Response getLog(@QueryParam("fromPosition") Long fromPosition, @QueryPara builder.header("CurrentLogFileSize", content.getLogFileSize()); response = builder.build(); - + } catch (Exception ex) { LoggingUtils.logUnexpectedException(LOGGER, "Cannot get log file content: fromPosition={}, maxSize={}", ex, fromPosition, maxSize); response = RestServiceUtil.handleException(result, ex); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelWebService.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelWebService.java index 16959ab126e..6dd4e911286 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelWebService.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelWebService.java @@ -63,18 +63,18 @@ import java.util.List; /** - * + * * @author lazyman - * + * */ @Service public class ModelWebService extends AbstractModelWebService implements ModelPortType, ModelPort { private static final Trace LOGGER = TraceManager.getTrace(ModelWebService.class); - + @Autowired(required = true) private ModelCrudService model; - + @Autowired private ScriptingService scriptingService; @@ -252,7 +252,7 @@ private ExecuteScriptsResponseType doExecuteScripts(List> scripts try { for (JAXBElement script : scriptsToExecute) { - + Object scriptValue = script.getValue(); if (!(scriptValue instanceof ScriptingExpressionType)) { throw new SchemaException("Expected that scripts will be of type ScriptingExpressionType, but it was "+scriptValue.getClass().getName()); @@ -321,7 +321,7 @@ private OperationResultType handleOperationResult(OperationResult result) { result.recordSuccess(); return result.createOperationResultType(); } - + private void notNullResultHolder(Holder holder) throws FaultMessage { notNullArgument(holder, "Holder must not be null."); notNullArgument(holder.value, "Result type must not be null."); @@ -412,17 +412,17 @@ public TaskType importFromResource(String resourceOid, QName objectClass) return null; } } - + @Override public TaskType notifyChange(ResourceObjectShadowChangeDescriptionType changeDescription) throws FaultMessage { // TODO Auto-generated method stub notNullArgument(changeDescription, "Change description must not be null"); LOGGER.trace("notify change started"); - + Task task = createTaskInstance(NOTIFY_CHANGE); OperationResult parentResult = task.getResult(); - + try { model.notifyChange(changeDescription, parentResult, task); } catch (ObjectNotFoundException | SchemaException | CommunicationException | ConfigurationException | SecurityViolationException | ObjectAlreadyExistsException | ExpressionEvaluationException | RuntimeException | Error ex) { @@ -430,21 +430,21 @@ public TaskType notifyChange(ResourceObjectShadowChangeDescriptionType changeDes auditLogout(task); throwFault(ex, parentResult); } - - + + LOGGER.info("notify change ended."); LOGGER.info("result of notify change: {}", parentResult.debugDump()); return handleTaskResult(task); } - + /** * return appropriate form of taskType (and result) to * return back to a web service caller. - * + * * @param task */ private TaskType handleTaskResult(Task task) { return task.getTaskPrismObject().asObjectable(); } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelWebServiceRaw.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelWebServiceRaw.java index 6daca2981b2..392dfcd50de 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelWebServiceRaw.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelWebServiceRaw.java @@ -68,9 +68,9 @@ import java.io.StringWriter; /** - * + * * @author mederly - * + * */ @Service public class ModelWebServiceRaw implements Provider { @@ -89,10 +89,10 @@ public class ModelWebServiceRaw implements Provider { @Autowired private ModelWebService ws; - + @Autowired private PrismContext prismContext; - + @Override public DOMSource invoke(DOMSource request) { try { @@ -208,7 +208,7 @@ public DOMSource invokeAllowingFaults(DOMSource request) throws FaultMessage { return new DOMSource(response); } - + private void serializeFaultMessage(Detail detail, FaultMessage faultMessage) { MiscSchemaUtil.serializeFaultMessage(detail, faultMessage, prismContext, LOGGER); } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/PolicyDecision.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/PolicyDecision.java index f49bf71c1c4..23bae46a185 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/PolicyDecision.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/PolicyDecision.java @@ -17,12 +17,12 @@ /** * Describes what the policy "decides" about a specific account. - * + * * @author Radovan Semancik * */ public enum PolicyDecision { - + ADD, DELETE, KEEP, diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/UserComputer.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/UserComputer.java index 0696ab36d2c..f2ce804e065 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/UserComputer.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/UserComputer.java @@ -29,7 +29,7 @@ */ @Component public class UserComputer { - + @Autowired(required = true) private ActivationComputer activationComputer; @@ -40,5 +40,5 @@ public void recompute(PrismObject user) { activationComputer.computeEffective(userType.getLifecycleState(), activationType); } } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/cleanup/ShadowRefreshTaskHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/cleanup/ShadowRefreshTaskHandler.java index 2bb136d1d7f..83a470e916c 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/cleanup/ShadowRefreshTaskHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/cleanup/ShadowRefreshTaskHandler.java @@ -40,7 +40,7 @@ /** * Scanner that looks for pending operations in the shadows and updates the status. - * + * * @author Radovan Semancik */ @Component @@ -50,14 +50,14 @@ public class ShadowRefreshTaskHandler extends AbstractScannerTaskHandler getType(Task task) { return ShadowType.class; } - + @Override protected boolean useRepositoryDirectly(AbstractScannerResultHandler resultHandler, TaskRunResult runResult, Task coordinatorTask, OperationResult opResult) { return true; @@ -84,7 +84,7 @@ protected ObjectQuery createQuery(AbstractScannerResultHandler handl ObjectFilter filter = QueryBuilder.queryFor(ShadowType.class, prismContext) .exists(ShadowType.F_PENDING_OPERATION) .buildFilter(); - + query.setFilter(filter); return query; } @@ -98,7 +98,7 @@ protected void finish(AbstractScannerResultHandler handler, TaskRunR @Override protected AbstractScannerResultHandler createHandler(TaskRunResult runResult, final Task coordinatorTask, OperationResult opResult) { - + AbstractScannerResultHandler handler = new AbstractScannerResultHandler( coordinatorTask, ShadowRefreshTaskHandler.class.getName(), "shadowRefresh", "shadow refresh task", taskManager) { @Override @@ -106,7 +106,7 @@ protected boolean handleObject(PrismObject object, Task workerTask, LOGGER.trace("Refreshing {}", object); provisioningService.refreshShadow(object, null, workerTask, result); - + LOGGER.trace("Refreshed {}", object); return true; } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/AuditController.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/AuditController.java index 2fbcee14162..684b5173626 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/AuditController.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/AuditController.java @@ -56,15 +56,15 @@ */ @Component public class AuditController implements ModelAuditService { - + private static final Trace LOGGER = TraceManager.getTrace(AuditController.class); - + @Autowired(required=true) private AuditService auditService; - + @Autowired(required=true) private ModelObjectResolver objectResolver; - + @Autowired(required = true) private SecurityEnforcer securityEnforcer; @@ -97,7 +97,7 @@ public void cleanupAudit(CleanupPolicyType policy, OperationResult parentResult) authorize(ModelAuthorizationAction.AUDIT_MANAGE, parentResult); auditService.cleanupAudit(policy, parentResult); } - + /* (non-Javadoc) * @see com.evolveum.midpoint.audit.api.AuditService#supportsRetrieval() */ @@ -108,24 +108,24 @@ public boolean supportsRetrieval() { @Override public PrismObject reconstructObject(Class type, String oid, String eventIdentifier, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException { - + // TODO: authorizations - + O currentObjectType = objectResolver.getObjectSimple(type, oid, null, task, result); PrismObject currentObject = (PrismObject) currentObjectType.asPrismObject(); - + List changeTrail = getChangeTrail(oid, eventIdentifier); LOGGER.trace("Found change trail for {} containing {} events", oid, changeTrail.size()); - + LOGGER.info("TRAIL:\n{}", DebugUtil.debugDump(changeTrail, 1)); - + PrismObject objectFromLastEvent = getObjectFromLastEvent(currentObject, changeTrail, eventIdentifier); if (objectFromLastEvent != null) { return objectFromLastEvent; } - + PrismObject reconstructedObject = rollBackTime(currentObject.clone(), changeTrail); - + return reconstructedObject; } @@ -138,7 +138,7 @@ private List getChangeTrail(String targetOid, String finalEven LOGGER.trace("Final event:\n{}", finalEvent.debugDump(1)); } List changeTrail = getChangeTrail(targetOid, XmlTypeConverter.createXMLGregorianCalendar(finalEvent.getTimestamp())); - + // The search may have returned more events that we want to, e.g. if two // events happened in the same millisecond. Iterator iterator = changeTrail.iterator(); @@ -151,7 +151,7 @@ private List getChangeTrail(String targetOid, String finalEven foundFinalEvent = true; } } - + return changeTrail; } @@ -161,10 +161,10 @@ private List getChangeTrail(String targetOid, XMLGregorianCale params.put("targetOid", targetOid); params.put("stage", AuditEventStage.EXECUTION); return auditService.listRecords( - "from RAuditEventRecord as aer where (aer.timestamp >= :from) and (aer.targetOid = :targetOid) and (aer.eventStage = :stage) order by aer.timestamp desc", + "from RAuditEventRecord as aer where (aer.timestamp >= :from) and (aer.targetOid = :targetOid) and (aer.eventStage = :stage) order by aer.timestamp desc", params); } - + private AuditEventRecord findEvent(String eventIdentifier) { Map params = new HashMap<>(); params.put("eventIdentifier", eventIdentifier); @@ -177,8 +177,8 @@ private AuditEventRecord findEvent(String eventIdentifier) { } return listRecords.get(0); } - - + + private PrismObject getObjectFromLastEvent(PrismObject object, List changeTrail, String eventIdentifier) { if (changeTrail.isEmpty()) { return object; @@ -205,8 +205,8 @@ private PrismObject getObjectFromLastEvent(PrismObject } return null; } - - private PrismObject rollBackTime(PrismObject object, List changeTrail) throws SchemaException { + + private PrismObject rollBackTime(PrismObject object, List changeTrail) throws SchemaException { for (AuditEventRecord event: changeTrail) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Applying event {} ({})", event.getEventIdentifier(), XmlTypeConverter.createXMLGregorianCalendar(event.getTimestamp())); @@ -232,7 +232,7 @@ private PrismObject rollBackTime(PrismObject object } } if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Object after application of event {} ({}):\n{}", event.getEventIdentifier(), + LOGGER.trace("Object after application of event {} ({}):\n{}", event.getEventIdentifier(), XmlTypeConverter.createXMLGregorianCalendar(event.getTimestamp()), object.debugDump(1)); } } @@ -244,13 +244,13 @@ private boolean isApplicable(ObjectDeltaOperation objectDelta = (ObjectDelta) lastEventDeltasOperation.getObjectDelta(); if (executionResult.getStatus() == OperationResultStatus.FATAL_ERROR) { - LOGGER.trace("Skipping delta {} in event {} because it is {}", objectDelta, lastEvent.getEventIdentifier(), + LOGGER.trace("Skipping delta {} in event {} because it is {}", objectDelta, lastEvent.getEventIdentifier(), executionResult.getStatus()); return false; } if (!object.getOid().equals(objectDelta.getOid())) { if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Skipping delta {} in event {} because OID does not match ({} vs {})", objectDelta, lastEvent.getEventIdentifier(), + LOGGER.trace("Skipping delta {} in event {} because OID does not match ({} vs {})", objectDelta, lastEvent.getEventIdentifier(), object.getOid(), objectDelta.getOid()); } return false; @@ -262,5 +262,5 @@ private void authorize(ModelAuthorizationAction action, OperationResult result) securityEnforcer.authorize(action.getUrl(), AuthorizationPhaseType.REQUEST, null, null, null, null, result); securityEnforcer.authorize(action.getUrl(), AuthorizationPhaseType.EXECUTION, null, null, null, null, result); } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/ModelController.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/ModelController.java index 2a0be97b67c..2db901f7b77 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/ModelController.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/ModelController.java @@ -100,7 +100,7 @@ * that are implemented here. *

    * Great deal of code is copied from the old ModelControllerImpl. - * + * * @author lazyman * @author Radovan Semancik * @@ -189,10 +189,10 @@ public class ModelController implements ModelService, TaskService, WorkflowServi @Autowired(required = true) private SchemaTransformer schemaTransformer; - + @Autowired(required = true) private ObjectMerger objectMerger; - + @Autowired(required = true) private SystemObjectCache systemObjectCache; @@ -245,7 +245,7 @@ public PrismObject getObject(Class clazz, String oi // Special-purpose code to hunt down read-write resource fetch from GUI. // Normally the code is not active. It is too brutal. Just for MID-3424. // if (ResourceType.class == clazz && !GetOperationOptions.isRaw(rootOptions) && !GetOperationOptions.isReadOnly(rootOptions)) { -// LOGGER.info("READWRITE resource get: {} {}:\n{}", oid, options, +// LOGGER.info("READWRITE resource get: {} {}:\n{}", oid, options, // LoggingUtils.dumpStackTrace()); // } @@ -414,11 +414,11 @@ public Collection> executeChanges(fin } }); } - + RepositoryCache.enter(); try { - + if (ModelExecuteOptions.isRaw(options)) { // Go directly to repository AuditEventRecord auditRecord = new AuditEventRecord(AuditEventType.EXECUTE_CHANGES_RAW, AuditEventStage.REQUEST); @@ -577,10 +577,10 @@ public Collection> executeChanges(fin for (LensProjectionContext projectionContext : context.getProjectionContexts()) { executedDeltas.addAll(projectionContext.getExecutedDeltas()); } - + if (context.hasExplosiveProjection()) { PrismObject focus = context.getFocusContext().getObjectAny(); - + LOGGER.debug("Recomputing {} because there was explosive projection", focus); LensContext recomputeContext = contextFactory.createRecomputeContext(focus, options, task, result); @@ -601,7 +601,7 @@ public Collection> executeChanges(fin task.markObjectActionExecutedBoundary(); } } - + invalidateCaches(executedDeltas); } catch (RuntimeException e) { // just for sure (TODO split this method into two: raw and non-raw case) @@ -610,7 +610,7 @@ public Collection> executeChanges(fin } finally { RepositoryCache.exit(); } - + return executedDeltas; } @@ -676,35 +676,35 @@ public void recompute(Class type, String oid, Task tas ModelExecuteOptions options = ModelExecuteOptions.createReconcile(); recompute(type, oid, options, task, parentResult); } - + @Override public void recompute(Class type, String oid, ModelExecuteOptions options, Task task, OperationResult parentResult) throws SchemaException, PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException, ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException { - + OperationResult result = parentResult.createMinorSubresult(RECOMPUTE); result.addParam(OperationResult.PARAM_OID, oid); result.addParam(OperationResult.PARAM_TYPE, type); - + RepositoryCache.enter(); - + try { Utils.clearRequestee(task); PrismObject focus = objectResolver.getObject(type, oid, null, task, result).asPrismContainer(); - + LOGGER.debug("Recomputing {}", focus); - LensContext lensContext = contextFactory.createRecomputeContext(focus, options, task, result); + LensContext lensContext = contextFactory.createRecomputeContext(focus, options, task, result); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Recomputing {}, context:\n{}", focus, lensContext.debugDump()); } clockwork.run(lensContext, task, result); - + result.computeStatus(); - + LOGGER.trace("Recomputing of {}: {}", focus, result.getStatus()); - + result.cleanupResult(); - + } catch (ExpressionEvaluationException e) { ModelUtils.recordFatalError(result, e); throw e; @@ -1089,7 +1089,7 @@ public SearchResultMetadata searchObjectsIterative(Class< final OperationResult result = parentResult.createSubresult(SEARCH_OBJECTS); result.addParam(OperationResult.PARAM_QUERY, query); result.addArbitraryObjectAsParam("searchProvider", searchProvider); - + query = preProcessQuerySecurity(type, query); if (isFilterNone(query, result)) { return null; @@ -1116,7 +1116,7 @@ public SearchResultMetadata searchObjectsIterative(Class< return handler.handle(object, parentResult1); }; - + SearchResultMetadata metadata; try { RepositoryCache.enter(); @@ -1142,7 +1142,7 @@ public SearchResultMetadata searchObjectsIterative(Class< } finally { RepositoryCache.exit(); } - + return metadata; } @@ -1168,7 +1168,7 @@ public Integer countObjects(Class type, ObjectQuery qu OperationResult result = parentResult.createMinorSubresult(COUNT_OBJECTS); result.addParam(OperationResult.PARAM_QUERY, query); - + query = preProcessQuerySecurity(type, query); if (isFilterNone(query, result)) { return 0; @@ -1197,13 +1197,13 @@ public Integer countObjects(Class type, ObjectQuery qu } finally { RepositoryCache.exit(); } - + result.computeStatus(); result.cleanupResult(); return count; - + } - + @Override @Deprecated public PrismObject findShadowOwner(String accountOid, Task task, OperationResult parentResult) @@ -1214,14 +1214,14 @@ public PrismObject findShadowOwner(String accountOid, Task task, Opera RepositoryCache.enter(); PrismObject user; - + LOGGER.trace("Listing account shadow owner for account with oid {}.", new Object[]{accountOid}); OperationResult result = parentResult.createSubresult(LIST_ACCOUNT_SHADOW_OWNER); result.addParam("accountOid", accountOid); try { - + user = cacheRepositoryService.listAccountShadowOwner(accountOid, result); result.recordSuccess(); } catch (ObjectNotFoundException ex) { @@ -1255,10 +1255,10 @@ public PrismObject findShadowOwner(String accountOid, Task task, Opera throw ex; } } - + return user; } - + @Override public PrismObject searchShadowOwner(String shadowOid, Collection> rawOptions, Task task, OperationResult parentResult) throws ObjectNotFoundException, SecurityViolationException, SchemaException, ConfigurationException { @@ -1305,7 +1305,7 @@ public PrismObject searchShadowOwner(String shadowOid, Coll throw ex; } } - + return focus; } @@ -1430,7 +1430,7 @@ public void importFromResource(String resourceOid, QName objectClass, Task task, LOGGER.warn("Synchronization is disabled for "+resource+", import will probably do nothing"); } } - + result.recordStatus(OperationResultStatus.IN_PROGRESS, "Task running in background"); importAccountsFromResourceTaskHandler.launch(resource, objectClass, task, result); @@ -1441,18 +1441,18 @@ public void importFromResource(String resourceOid, QName objectClass, Task task, if (!task.isAsynchronous()) { result.recordSuccess(); } - + result.cleanupResult(); - + } catch (ObjectNotFoundException | CommunicationException | ConfigurationException | SecurityViolationException | ExpressionEvaluationException | RuntimeException | Error ex) { ModelUtils.recordFatalError(result, ex); throw ex; } finally { RepositoryCache.exit(); } - + } - + @Override public void importFromResource(String shadowOid, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, CommunicationException, @@ -1469,24 +1469,24 @@ public void importFromResource(String shadowOid, Task task, OperationResult pare try { boolean wasOk = importAccountsFromResourceTaskHandler.importSingleShadow(shadowOid, task, result); - + if (wasOk) { result.recordSuccess(); } else { // the error should be in the result already, compute should reveal that to the top-level result.computeStatus(); } - - + + result.cleanupResult(); - + } catch (ObjectNotFoundException | CommunicationException | ConfigurationException | SecurityViolationException | ExpressionEvaluationException| RuntimeException | Error ex) { ModelUtils.recordFatalError(result, ex); throw ex; } finally { RepositoryCache.exit(); } - + } @Override @@ -1545,7 +1545,7 @@ public void importObjectsFromStream(InputStream input, String language, ImportOp /* * (non-Javadoc) - * + * * @see * com.evolveum.midpoint.model.api.ModelService#discoverConnectors(com.evolveum * .midpoint.xml.ns._public.common.common_1.ConnectorHostType, @@ -1571,18 +1571,18 @@ public Set discoverConnectors(ConnectorHostType hostType, Task ta result.cleanupResult(); return new HashSet<>(connectorList); } - + /* * (non-Javadoc) - * + * * @see * com.evolveum.midpoint.model.api.ModelService#initialize(com.evolveum. * midpoint.common.result.OperationResult) */ @Override public void postInit(OperationResult parentResult) { - systemObjectCache.invalidateCaches(); // necessary for testing situations where we re-import different system configurations with the same version (on system init) + systemObjectCache.invalidateCaches(); // necessary for testing situations where we re-import different system configurations with the same version (on system init) RepositoryCache.enter(); OperationResult result = parentResult.createSubresult(POST_INIT); @@ -1801,7 +1801,7 @@ private ObjectQuery updateObjectQuery(ObjectQuery origQuery, ObjectFilter update return objectQuery; } } - + //region Task-related operations @Override @@ -2068,25 +2068,25 @@ public AccessCertificationCampaignType createCampaign(String definitionOid, Task //endregion @Override - public Collection> mergeObjects(Class type, - String leftOid, String rightOid, String mergeConfigurationName, Task task, OperationResult parentResult) + public Collection> mergeObjects(Class type, + String leftOid, String rightOid, String mergeConfigurationName, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ConfigurationException, ObjectAlreadyExistsException, ExpressionEvaluationException, CommunicationException, PolicyViolationException, SecurityViolationException { - + OperationResult result = parentResult.createSubresult(MERGE_OBJECTS); result.addParam("leftOid", leftOid); result.addParam("rightOid", rightOid); result.addParam("class", type); - + RepositoryCache.enter(); - + try { - - Collection> deltas = + + Collection> deltas = objectMerger.mergeObjects(type, leftOid, rightOid, mergeConfigurationName, task, result); - + result.computeStatus(); return deltas; - + } catch (ObjectNotFoundException | SchemaException | ConfigurationException | ObjectAlreadyExistsException | ExpressionEvaluationException | CommunicationException | PolicyViolationException | SecurityViolationException | RuntimeException | Error e) { ModelUtils.recordFatalError(result, e); throw e; @@ -2094,6 +2094,6 @@ public Collection user; try { user = getObjectDefinition(UserType.class).instantiate(); } catch (SchemaException e) { result.recordFatalError(e); return; - } + } UserType userType = user.asObjectable(); - + String name = generateRandomName(); PolyStringType namePolyStringType = toPolyStringType(name); userType.setName(namePolyStringType); @@ -231,7 +231,7 @@ private void repositorySelfTestUser(Task task, OperationResult testResult) { userType.getEmployeeType().add(USER_EMPLOYEE_TYPE[1]); userType.getOrganization().add(toPolyStringType(USER_ORGANIZATION[0])); userType.getOrganization().add(toPolyStringType(USER_ORGANIZATION[1])); - + String oid; try { oid = repositoryService.addObject(user, null, result); @@ -239,12 +239,12 @@ private void repositorySelfTestUser(Task task, OperationResult testResult) { result.recordFatalError(e); return; } - + try { { OperationResult subresult = result.createSubresult(result.getOperation()+".getObject"); - + PrismObject userRetrieved; try { userRetrieved = repositoryService.getObject(UserType.class, oid, null, subresult); @@ -252,20 +252,20 @@ private void repositorySelfTestUser(Task task, OperationResult testResult) { result.recordFatalError(e); return; } - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Self-test:user getObject:\n{}", userRetrieved.debugDump()); } - + checkUser(userRetrieved, name, subresult); - + subresult.recordSuccessIfUnknown(); } - + { OperationResult subresult = result.createSubresult(result.getOperation()+".searchObjects.fullName"); try { - + ObjectQuery query = QueryBuilder.queryFor(UserType.class, prismContext) .item(UserType.F_FULL_NAME).eq(toPolyString(USER_FULL_NAME)) .build(); @@ -275,10 +275,10 @@ private void repositorySelfTestUser(Task task, OperationResult testResult) { LOGGER.trace("Self-test:user searchObjects:\n{}", DebugUtil.debugDump(foundObjects)); } assertSingleSearchResult("user", foundObjects, subresult); - + PrismObject userRetrieved = foundObjects.iterator().next(); checkUser(userRetrieved, name, subresult); - + subresult.recordSuccessIfUnknown(); } catch (SchemaException | RuntimeException e) { subresult.recordFatalError(e); @@ -299,17 +299,17 @@ private void repositorySelfTestUser(Task task, OperationResult testResult) { LOGGER.trace("Self-test:user searchObjects:\n{}", DebugUtil.debugDump(foundObjects)); } assertSingleSearchResult("user", foundObjects, subresult); - + PrismObject userRetrieved = foundObjects.iterator().next(); checkUser(userRetrieved, name, subresult); - + subresult.recordSuccessIfUnknown(); } catch (SchemaException | RuntimeException e) { subresult.recordFatalError(e); return; } } - + // MID-1116 { OperationResult subresult = result.createSubresult(result.getOperation()+".searchObjects.organization"); @@ -323,20 +323,20 @@ private void repositorySelfTestUser(Task task, OperationResult testResult) { LOGGER.trace("Self-test:user searchObjects:\n{}", DebugUtil.debugDump(foundObjects)); } assertSingleSearchResult("user", foundObjects, subresult); - + PrismObject userRetrieved = foundObjects.iterator().next(); checkUser(userRetrieved, name, subresult); - + subresult.recordSuccessIfUnknown(); } catch (SchemaException | RuntimeException e) { subresult.recordFatalError(e); return; } } - + } finally { - + try { repositoryService.deleteObject(UserType.class, oid, testResult); } catch (ObjectNotFoundException | RuntimeException e) { @@ -346,7 +346,7 @@ private void repositorySelfTestUser(Task task, OperationResult testResult) { result.computeStatus(); } - + } private void checkUser(PrismObject userRetrieved, String name, OperationResult subresult) { @@ -461,7 +461,7 @@ private void assertSingleSearchResult(String objectTypeMessage, List void checkObjectProperty(PrismObject object, QName propQName, OperationResult parentResult, T... expectedValues) { String propName = propQName.getLocalPart(); OperationResult result = parentResult.createSubresult(parentResult.getOperation() + ".checkObjectProperty." + propName); @@ -471,7 +471,7 @@ private void checkObjectProperty(PrismObject object, assertMultivalue("User, property '"+propName+"'", expectedValues, actualValues, result); result.recordSuccessIfUnknown(); } - + private void assertMultivalue(String message, T expectedVals[], Collection actualVals, OperationResult result) { if (expectedVals.length != actualVals.size()) { fail(message+": expected "+expectedVals.length+" values but has "+actualVals.size()+" values: "+actualVals, result); @@ -501,7 +501,7 @@ private void checkObjectPropertyPolyString(PrismObject assertMultivaluePolyString("User, property '"+propName+"'", expectedValues, actualValues, result); result.recordSuccessIfUnknown(); } - + private void assertMultivaluePolyString(String message, String expectedOrigs[], Collection actualPolyStrings, OperationResult result) { if (expectedOrigs.length != actualPolyStrings.size()) { fail(message+": expected "+expectedOrigs.length+" values but has "+actualPolyStrings.size()+" values: "+actualPolyStrings, result); @@ -522,7 +522,7 @@ private void assertMultivaluePolyString(String message, String expectedOrigs[], } } } - + private void assertPolyString(String message, String expectedOrig, PolyString actualPolyString, OperationResult result) { assertEquals(message+ ", orig", expectedOrig, actualPolyString.getOrig(), result); assertEquals(message+ ", norm", polyStringNorm(expectedOrig), actualPolyString.getNorm(), result); @@ -536,7 +536,7 @@ private void assertPolyStringType(String message, String expectedName, PolyStrin private String polyStringNorm(String orig) { return prismContext.getDefaultPolyStringNormalizer().normalize(orig); } - + private void assertTrue(String message, boolean condition, OperationResult result) { if (!condition) { fail(message, result); @@ -548,7 +548,7 @@ private void assertEquals(String message, Object expected, Object actual, Operat fail(message + "; expected "+expected+", actual "+actual, result); } } - + private void fail(String message, OperationResult result) { result.recordFatalError(message); LOGGER.error("Repository self-test assertion failed: {}", message); @@ -563,7 +563,7 @@ private PolyStringType toPolyStringType(String orig) { polyStringType.setOrig(orig); return polyStringType; } - + private PolyString toPolyString(String orig) { PolyString polyString = new PolyString(orig); polyString.recompute(prismContext.getDefaultPolyStringNormalizer()); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/ModelInteractionServiceImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/ModelInteractionServiceImpl.java index e2a477e26c0..8f90e6d3580 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/ModelInteractionServiceImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/ModelInteractionServiceImpl.java @@ -108,9 +108,9 @@ */ @Component("modelInteractionService") public class ModelInteractionServiceImpl implements ModelInteractionService { - + private static final Trace LOGGER = TraceManager.getTrace(ModelInteractionServiceImpl.class); - + @Autowired private ContextFactory contextFactory; @Autowired private Projector projector; @Autowired private SecurityEnforcer securityEnforcer; @@ -167,10 +167,10 @@ public ModelContext previewChanges( clonedDeltas.add(delta.clone()); } } - + OperationResult result = parentResult.createSubresult(PREVIEW_CHANGES); LensContext context; - + try { RepositoryCache.enter(); //used cloned deltas instead of origin deltas, because some of the values should be lost later.. @@ -180,7 +180,7 @@ public ModelContext previewChanges( LOGGER.trace("Preview changes context:\n{}", context.debugDump()); } context.setProgressListeners(listeners); - + projector.projectAllWaves(context, "preview", task, result); context.distributeResource(); @@ -189,7 +189,7 @@ public ModelContext previewChanges( hook.invokePreview(context, task, result); } } - + } catch (ConfigurationException | SecurityViolationException | ObjectNotFoundException | SchemaException | CommunicationException | PolicyViolationException | RuntimeException | ObjectAlreadyExistsException | ExpressionEvaluationException e) { @@ -202,7 +202,7 @@ public ModelContext previewChanges( if (LOGGER.isDebugEnabled()) { LOGGER.debug("Preview changes output:\n{}", context.debugDump()); } - + result.computeStatus(); result.cleanupResult(); @@ -213,12 +213,12 @@ public ModelContext previewChanges( public ModelContext unwrapModelContext(LensContextType wrappedContext, Task task, OperationResult result) throws SchemaException, ConfigurationException, ObjectNotFoundException, CommunicationException, ExpressionEvaluationException { return LensContext.fromLensContextType(wrappedContext, prismContext, provisioning, task, result); } - + @Override public PrismObjectDefinition getEditObjectDefinition(PrismObject object, AuthorizationPhaseType phase, Task task, OperationResult parentResult) throws SchemaException, ConfigurationException, ObjectNotFoundException { OperationResult result = parentResult.createMinorSubresult(GET_EDIT_OBJECT_DEFINITION); PrismObjectDefinition objectDefinition = object.getDefinition().deepClone(true); - + PrismObject baseObject = object; if (object.getOid() != null) { // Re-read the object from the repository to make sure we have all the properties. @@ -227,7 +227,7 @@ public PrismObjectDefinition getEditObjectDefinition(P // MID-3126, see also MID-3435 baseObject = cacheRepositoryService.getObject(object.getCompileTimeClass(), object.getOid(), null, result); } - + // TODO: maybe we need to expose owner resolver in the interface? ObjectSecurityConstraints securityConstraints = securityEnforcer.compileSecurityConstraints(baseObject, null); if (LOGGER.isTraceEnabled()) { @@ -238,7 +238,7 @@ public PrismObjectDefinition getEditObjectDefinition(P result.setStatus(OperationResultStatus.NOT_APPLICABLE); return null; } - + ObjectTemplateType objectTemplateType = null; try { objectTemplateType = schemaTransformer.determineObjectTemplate(object, phase, result); @@ -246,9 +246,9 @@ public PrismObjectDefinition getEditObjectDefinition(P result.recordFatalError(e); } schemaTransformer.applyObjectTemplateToDefinition(objectDefinition, objectTemplateType, result); - + schemaTransformer.applySecurityConstraints(objectDefinition, securityConstraints, phase); - + if (object.canRepresent(ShadowType.class)) { PrismObject shadow = (PrismObject)object; String resourceOid = ShadowUtil.getResourceOid(shadow); @@ -267,17 +267,17 @@ public PrismObjectDefinition getEditObjectDefinition(P } } } - + result.computeStatus(); return objectDefinition; } - + @Override public PrismObjectDefinition getEditShadowDefinition(ResourceShadowDiscriminator discr, AuthorizationPhaseType phase, Task task, OperationResult parentResult) throws SchemaException, ConfigurationException, ObjectNotFoundException { // HACK hack hack // Make a dummy shadow instance here and evaluate the schema for that. It is not 100% correct. But good enough for now. // TODO: refactor when we add better support for multi-tenancy - + PrismObject shadow = prismContext.createObject(ShadowType.class); ShadowType shadowType = shadow.asObjectable(); ObjectReferenceType resourceRef = new ObjectReferenceType(); @@ -288,15 +288,15 @@ public PrismObjectDefinition getEditShadowDefinition(ResourceShadowD shadowType.setIntent(discr.getIntent()); shadowType.setObjectClass(discr.getObjectClass()); } - - return getEditObjectDefinition(shadow, phase, task, parentResult); + + return getEditObjectDefinition(shadow, phase, task, parentResult); } @Override public RefinedObjectClassDefinition getEditObjectClassDefinition(PrismObject shadow, PrismObject resource, AuthorizationPhaseType phase) throws SchemaException { Validate.notNull(resource, "Resource must not be null"); - + RefinedResourceSchema refinedSchema = RefinedResourceSchemaImpl.getRefinedSchema(resource); CompositeRefinedObjectClassDefinition rocd = refinedSchema.determineCompositeObjectClassDefinition(shadow); if (rocd == null) { @@ -304,7 +304,7 @@ public RefinedObjectClassDefinition getEditObjectClassDefinition(PrismObject> getActionUrls() { } @Override - public RoleSelectionSpecification getAssignableRoleSpecification(PrismObject focus, OperationResult parentResult) + public RoleSelectionSpecification getAssignableRoleSpecification(PrismObject focus, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ConfigurationException { OperationResult result = parentResult.createMinorSubresult(GET_ASSIGNABLE_ROLE_SPECIFICATION); - + RoleSelectionSpecification spec = new RoleSelectionSpecification(); - + ObjectSecurityConstraints securityConstraints = securityEnforcer.compileSecurityConstraints(focus, null); if (securityConstraints == null) { return null; } - AuthorizationDecisionType decision = securityConstraints.findItemDecision(new ItemPath(FocusType.F_ASSIGNMENT), + AuthorizationDecisionType decision = securityConstraints.findItemDecision(new ItemPath(FocusType.F_ASSIGNMENT), ModelAuthorizationAction.MODIFY.getUrl(), AuthorizationPhaseType.REQUEST); if (decision == AuthorizationDecisionType.ALLOW) { getAllRoleTypesSpec(spec, result); @@ -397,9 +397,9 @@ public RoleSelectionSpecification getAssignableRoleSpecifi spec.setFilter(NoneFilter.createNone()); return spec; } - + try { - ObjectFilter filter = securityEnforcer.preProcessObjectFilter(ModelAuthorizationAction.ASSIGN.getUrl(), + ObjectFilter filter = securityEnforcer.preProcessObjectFilter(ModelAuthorizationAction.ASSIGN.getUrl(), AuthorizationPhaseType.REQUEST, AbstractRoleType.class, focus, AllFilter.createAll()); LOGGER.trace("assignableRoleSpec filter: {}", filter); spec.setFilter(filter); @@ -433,7 +433,7 @@ public RoleSelectionSpecification getAssignableRoleSpecifi if (roleTypeDvals == null || roleTypeDvals.isEmpty()) { getAllRoleTypesSpec(spec, result); result.recordSuccess(); - return spec; + return spec; } else { addRoleTypeSpecEntries(spec, roleTypeDvals, result); } @@ -445,8 +445,8 @@ public RoleSelectionSpecification getAssignableRoleSpecifi throw e; } } - - private void addRoleTypeSpecEntries(RoleSelectionSpecification spec, + + private void addRoleTypeSpecEntries(RoleSelectionSpecification spec, Collection roleTypeDvals, OperationResult result) throws ObjectNotFoundException, SchemaException, ConfigurationException { if (roleTypeDvals == null || roleTypeDvals.isEmpty()) { getAllRoleTypesSpec(spec, result); @@ -464,14 +464,14 @@ private void addRoleTypeSpecEntries(RoleSelectionSpecification spec, spec.addRoleType(positiveEntry); } } - + } else { spec.addRoleTypes(roleTypeDvals); } } } - private RoleSelectionSpecification getAllRoleTypesSpec(RoleSelectionSpecification spec, OperationResult result) + private RoleSelectionSpecification getAllRoleTypesSpec(RoleSelectionSpecification spec, OperationResult result) throws ObjectNotFoundException, SchemaException, ConfigurationException { Collection allEntries = getRoleSpecEntriesForAllRoles(result); if (allEntries == null || allEntries.isEmpty()) { @@ -480,8 +480,8 @@ private RoleSelectionSpecification getAllRoleTypesSpec(RoleSelectionSpecificatio spec.addRoleTypes(allEntries); return spec; } - - private Collection getRoleSpecEntriesForAllRoles(OperationResult result) + + private Collection getRoleSpecEntriesForAllRoles(OperationResult result) throws ObjectNotFoundException, SchemaException, ConfigurationException { ObjectTemplateType objectTemplateType = schemaTransformer.determineObjectTemplate(RoleType.class, AuthorizationPhaseType.REQUEST, result); if (objectTemplateType == null) { @@ -505,7 +505,7 @@ private Collection getRoleSpecEntriesForAllRoles(Operati } Collection> options = SelectorOptions.createCollection(LookupTableType.F_ROW, GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE)); - PrismObject lookup = cacheRepositoryService.getObject(LookupTableType.class, valueEnumerationRef.getOid(), + PrismObject lookup = cacheRepositoryService.getObject(LookupTableType.class, valueEnumerationRef.getOid(), options, result); for (LookupTableRowType row: lookup.asObjectable().getRow()) { PolyStringType polyLabel = row.getLabel(); @@ -562,7 +562,7 @@ private Collection getRoleSelectionSpecEntries(ObjectFil throw new UnsupportedOperationException("Unexpected filter "+filter); } } - + private Collection createSingleDisplayableValueCollection( RoleSelectionSpecEntry dval) { if (dval == null) { @@ -586,8 +586,8 @@ private RoleSelectionSpecEntry getRoleSelectionSpecEq(EqualFilter eqFilt return null; } - - + + @Override public boolean canSearch(Class resultType, Class objectType, String objectOid, boolean includeSpecial, ObjectQuery query, Task task, OperationResult result) throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { @@ -620,7 +620,7 @@ public RegistrationsPolicyType getRegistrationPolicy(PrismObject user, @Override public CredentialsPolicyType getCredentialsPolicy(PrismObject user, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { // TODO: check for user membership in an organization (later versions) - + OperationResult result = parentResult.createMinorSubresult(GET_CREDENTIALS_POLICY); return resolvePolicyTypeFromSecurityPolicy(CredentialsPolicyType.class, SecurityPolicyType.F_CREDENTIALS, user, task, result); @@ -651,13 +651,13 @@ public SecurityPolicyType getSecurityPolicy(PrismObject user, Task tas result.recordNotApplicableIfUnknown(); return null; } - + SecurityPolicyType securityPolicyType = securityHelper.locateSecurityPolicy(user, systemConfiguration, task, result); if (securityPolicyType == null) { result.recordNotApplicableIfUnknown(); return null; } - + return securityPolicyType; }catch (SchemaException e) { result.recordFatalError(e); @@ -673,7 +673,7 @@ public AdminGuiConfigurationType getAdminGuiConfiguration(Task task, OperationRe } catch (SecurityViolationException e) { LOGGER.warn("Security violation while getting principlal to get GUI config: {}", e.getMessage(), e); } - + if (principal == null) { PrismObject systemConfiguration = systemObjectCache.getSystemConfiguration(parentResult); if (systemConfiguration == null) { @@ -684,7 +684,7 @@ public AdminGuiConfigurationType getAdminGuiConfiguration(Task task, OperationRe return principal.getAdminGuiConfiguration(); } } - + @Override public SystemConfigurationType getSystemConfiguration(OperationResult parentResult) throws ObjectNotFoundException, SchemaException { PrismObject systemConfiguration = systemObjectCache.getSystemConfiguration(parentResult); @@ -723,7 +723,7 @@ public boolean checkPassword(String userOid, ProtectedStringType password, Task result.recordFatalError(e); throw e; } - if (userType.getCredentials() == null || userType.getCredentials().getPassword() == null + if (userType.getCredentials() == null || userType.getCredentials().getPassword() == null || userType.getCredentials().getPassword().getValue() == null) { return password == null; } @@ -770,14 +770,14 @@ public MergeDeltas mergeObjectsPreviewDeltas(Class String rightOid, String mergeConfigurationName, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ConfigurationException, ExpressionEvaluationException, CommunicationException, SecurityViolationException { OperationResult result = parentResult.createMinorSubresult(MERGE_OBJECTS_PREVIEW_DELTA); - + try { - + MergeDeltas mergeDeltas = objectMerger.computeMergeDeltas(type, leftOid, rightOid, mergeConfigurationName, task, result); - + result.computeStatus(); return mergeDeltas; - + } catch (ObjectNotFoundException | SchemaException | ConfigurationException | ExpressionEvaluationException | CommunicationException | SecurityViolationException | RuntimeException | Error e) { result.recordFatalError(e); @@ -787,31 +787,31 @@ public MergeDeltas mergeObjectsPreviewDeltas(Class @Override public PrismObject mergeObjectsPreviewObject(Class type, String leftOid, - String rightOid, String mergeConfigurationName, Task task, OperationResult parentResult) + String rightOid, String mergeConfigurationName, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ConfigurationException, ExpressionEvaluationException, CommunicationException, SecurityViolationException { OperationResult result = parentResult.createMinorSubresult(MERGE_OBJECTS_PREVIEW_OBJECT); - + try { - + MergeDeltas mergeDeltas = objectMerger.computeMergeDeltas(type, leftOid, rightOid, mergeConfigurationName, task, result); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Merge preview {} + {} deltas:\n{}", leftOid, rightOid, mergeDeltas.debugDump(1)); } - + final PrismObject objectLeft = (PrismObject) objectResolver.getObjectSimple(type, leftOid, null, task, result).asPrismObject(); - + if (mergeDeltas == null) { result.computeStatus(); return objectLeft; } - + mergeDeltas.getLeftObjectDelta().applyTo(objectLeft); mergeDeltas.getLeftLinkDelta().applyTo(objectLeft); - + result.computeStatus(); return objectLeft; - + } catch (ObjectNotFoundException | SchemaException | ConfigurationException | ExpressionEvaluationException | CommunicationException | SecurityViolationException | RuntimeException | Error e) { result.recordFatalError(e); @@ -831,7 +831,7 @@ public void generateValue(PrismObject object, PolicyIt CommunicationException, ConfigurationException, SecurityViolationException, PolicyViolationException { String oid = object.getOid(); OperationResult result = parentResult.createSubresult(OPERATION_GENERATE_VALUE); - + Class clazz = (Class) object.asObjectable().getClass(); ValuePolicyType valuePolicy = null; try { @@ -847,23 +847,23 @@ public void generateValue(PrismObject object, PolicyIt Collection> deltasToExecute = new ArrayList<>(); for (PolicyItemDefinitionType policyItemDefinition : policyItemsDefinition.getPolicyItemDefinition()) { OperationResult generateValueResult = parentResult.createSubresult(OPERATION_GENERATE_VALUE); - + ItemPath path = getPath(policyItemDefinition); if (path == null) { LOGGER.error("No item path defined in the target for policy item definition. Cannot generate value"); generateValueResult.recordFatalError("No item path defined in the target for policy item definition. Cannot generate value"); continue; } - + result.addArbitraryObjectAsParam("policyItemPath", path); - + PrismPropertyDefinition propertyDef = getItemDefinition(object, path); if (propertyDef == null) { LOGGER.error("No definition for property {} in object. Is the path referencing prism property?" + path, object); generateValueResult.recordFatalError("No definition for property " + path + " in object " + object + ". Is the path referencing prism property?"); continue; } - + LOGGER.trace("Default value policy: {}" , valuePolicy); try { generateValue(object, valuePolicy, policyItemDefinition, task, generateValueResult); @@ -893,25 +893,25 @@ public void generateValue(PrismObject object, PolicyIt result.recordFatalError("Could not execute deltas for gegenerated values. Reason: "+ e.getMessage(), e); throw e; } - - + + } - + private ItemPath getPath(PolicyItemDefinitionType policyItemDefinition){ PolicyItemTargetType target = policyItemDefinition.getTarget(); - + if (target == null ) { return null; } - + ItemPathType itemPathType = target.getPath(); if (itemPathType == null) { - + return null; } return itemPathType.getItemPath(); } - + private PrismPropertyDefinition getItemDefinition(PrismObject object, ItemPath path){ ItemDefinition itemDef = object.getDefinition().findItemDefinition(path); if (itemDef == null) { @@ -919,10 +919,10 @@ private PrismPropertyDefinition getItemDefinition(Pris } else if (!(itemDef instanceof PrismPropertyDefinition)) { return null; } - + return (PrismPropertyDefinition) itemDef; } - + private void collectDeltasForGeneratedValuesIfNeeded(PrismObject object, PolicyItemDefinitionType policyItemDefinition, Collection> deltasToExecute, ItemPath path, PrismPropertyDefinition itemDef) throws SchemaException { @@ -969,7 +969,7 @@ private void generateValue(PrismObject object, ValuePo "generating value for" + targetPath, task, result); policyItemDefinition.setValue(newValue); } - + private ValuePolicyType resolveValuePolicy(PolicyItemDefinitionType policyItemDefinition, ValuePolicyType defaultPolicy, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException { if (policyItemDefinition.getValuePolicyRef() != null) { @@ -998,7 +998,7 @@ private ValuePolicyType getValuePolicy(PrismObject obj if (object.getCompileTimeClass().isAssignableFrom(UserType.class)) { policy = getCredentialsPolicy((PrismObject) object, task, parentResult); } - + SystemConfigurationType systemConfigurationType = getSystemConfiguration(parentResult); if (!containsValuePolicyDefinition(policy)) { SecurityPolicyType securityPolicy = securityHelper.locateGlobalSecurityPolicy(systemConfigurationType, task, parentResult); @@ -1006,24 +1006,24 @@ private ValuePolicyType getValuePolicy(PrismObject obj policy = securityPolicy.getCredentials(); } } - + if (!containsValuePolicyDefinition(policy)) { SecurityPolicyType securityPolicy = securityHelper.locateGlobalPasswordPolicy(systemConfigurationType, task, parentResult); if (securityPolicy != null) { policy = securityPolicy.getCredentials(); } } - + if (containsValuePolicyDefinition(policy)){ - + if (policy.getPassword().getValuePolicyRef() != null) { return objectResolver.resolve(policy.getPassword().getValuePolicyRef(), ValuePolicyType.class, null, "valuePolicyRef in password credential policy", task, parentResult); } else if (policy.getPassword().getPasswordPolicyRef() != null) { // DEPRECATED return objectResolver.resolve(policy.getPassword().getPasswordPolicyRef(), ValuePolicyType.class, null, "valuePolicyRef in password credential policy", task, parentResult); } - } - + } + return null; } @@ -1031,26 +1031,26 @@ private boolean containsValuePolicyDefinition(CredentialsPolicyType policy) { if (policy == null) { return false; } - + if (policy.getPassword() == null) { return false; } - + if (policy.getPassword().getValuePolicyRef() != null) { return true; } - + if (policy.getPassword().getPasswordPolicyRef() != null) { return true; } - - return false; + + return false; } - + private boolean validateValue(PrismObject object, ValuePolicyType policy, PolicyItemDefinitionType policyItemDefinition, Task task, OperationResult parentResult) throws ExpressionEvaluationException, SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, PolicyViolationException { ValuePolicyType stringPolicy = resolveValuePolicy(policyItemDefinition, policy, task, parentResult); - + RawType rawValue = (RawType) policyItemDefinition.getValue(); String valueToValidate = null; @@ -1078,7 +1078,7 @@ private boolean validateValue(PrismObject object, V throw new SchemaException("Attribute " + property + " has no value. Nothing to validate"); } - + PrismPropertyDefinition itemToValidateDefinition = property.getDefinition(); QName definitionName = itemToValidateDefinition.getTypeName(); if (!isSupportedType(definitionName)) { @@ -1089,7 +1089,7 @@ private boolean validateValue(PrismObject object, V throw new SchemaException("Trying to validate string policy on the property of type " + itemToValidateDefinition + " failed. Unsupported type."); } - + if (itemToValidateDefinition.isSingleValue()) { if (definitionName.equals(PolyStringType.COMPLEX_TYPE)) { valueToValidate = ((PolyString) property.getRealValue()).getOrig(); @@ -1129,28 +1129,28 @@ private boolean validateValue(PrismObject object, V } result.computeStatusIfUnknown(); } - + parentResult.computeStatus(); policyItemDefinition.setResult(parentResult.createOperationResultType()); - + return parentResult.isAcceptable(); } - + private boolean isSupportedType(QName type) { - + if (QNameUtil.qNameToUri(type).equals(QNameUtil.qNameToUri(DOMUtil.XSD_STRING))){ return true; } - + if (QNameUtil.qNameToUri(type).equals(QNameUtil.qNameToUri(PolyStringType.COMPLEX_TYPE))) { return true; } - + if (QNameUtil.qNameToUri(type).equals(QNameUtil.qNameToUri(ProtectedStringType.COMPLEX_TYPE))) { return true; } - + return false; } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/ModelUtils.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/ModelUtils.java index 29ce88e2587..1293aa5e716 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/ModelUtils.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/ModelUtils.java @@ -37,9 +37,9 @@ import java.util.List; /** - * + * * @author lazyman - * + * */ public class ModelUtils { @@ -57,7 +57,7 @@ public static void validatePaging(ObjectPaging paging) { throw new IllegalArgumentException("Paging offset index must be more than 0."); } } - + public static void recordFatalError(OperationResult result, Throwable e) { recordFatalError(result, e.getMessage(), e); } @@ -70,7 +70,7 @@ public static void recordFatalError(OperationResult result, String message, Thro result.recordFatalError(message, e); result.cleanupResult(e); } - + public static void recordPartialError(OperationResult result, Throwable e) { recordPartialError(result, e.getMessage(), e); } @@ -83,7 +83,7 @@ public static void recordPartialError(OperationResult result, String message, Th result.recordPartialError(message, e); result.cleanupResult(e); } - + public static String getOperationUrlFromDelta(ObjectDelta delta) { if (delta == null) { return null; @@ -109,7 +109,7 @@ public static ObjectPolicyConfigurationType determineObje } return determineObjectPolicyConfiguration(object.getCompileTimeClass(), subTypes, systemConfigurationType); } - + public static ObjectPolicyConfigurationType determineObjectPolicyConfiguration(Class objectClass, List objectSubtypes, SystemConfigurationType systemConfigurationType) throws ConfigurationException { ObjectPolicyConfigurationType applicablePolicyConfigurationType = null; for (ObjectPolicyConfigurationType aPolicyConfigurationType: systemConfigurationType.getDefaultObjectPolicyConfiguration()) { @@ -150,7 +150,7 @@ public static ObjectPolicyConfigurationType determineObje return aPolicyConfigurationType; } } - + // Deprecated method to specify user template. For compatibility only if (objectClass == UserType.class) { ObjectReferenceType templateRef = systemConfigurationType.getDefaultUserTemplateRef(); @@ -161,7 +161,7 @@ public static ObjectPolicyConfigurationType determineObje policy.setObjectTemplateRef(templateRef.clone()); return policy; } - + return null; } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/ObjectMerger.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/ObjectMerger.java index b6a568b6512..e54dcec3349 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/ObjectMerger.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/ObjectMerger.java @@ -87,61 +87,61 @@ /** * Class responsible for object merging. This acts as a controller * for the merge operation and merge preview. - * + * * @author semancik */ @Component public class ObjectMerger { - + private static final Trace LOGGER = TraceManager.getTrace(ObjectMerger.class); - + public static final String SIDE_LEFT = "left"; public static final String SIDE_RIGHT = "right"; - + @Autowired(required = true) private ModelObjectResolver objectResolver; - + @Autowired(required = true) private SystemObjectCache systemObjectCache; - + @Autowired(required = true) private ExpressionFactory expressionFactory; - + @Autowired(required = true) PrismContext prismContext; - + // TODO: circular dependency to model controller. Not good. // But cannot fix it right now. TODO: later refactor. // MID-3459 @Autowired(required = true) private ModelService modelController; - - public Collection> mergeObjects(Class type, - String leftOid, String rightOid, String mergeConfigurationName, Task task, OperationResult result) - throws ObjectNotFoundException, SchemaException, ConfigurationException, - ObjectAlreadyExistsException, ExpressionEvaluationException, CommunicationException, + + public Collection> mergeObjects(Class type, + String leftOid, String rightOid, String mergeConfigurationName, Task task, OperationResult result) + throws ObjectNotFoundException, SchemaException, ConfigurationException, + ObjectAlreadyExistsException, ExpressionEvaluationException, CommunicationException, PolicyViolationException, SecurityViolationException { MergeDeltas deltas = computeMergeDeltas(type, leftOid, rightOid, mergeConfigurationName, task, result); - + if (LOGGER.isDebugEnabled()) { LOGGER.debug("Merge {} + {} = (computed deltas)\n{}", leftOid, rightOid, deltas.debugDump(1)); } - + Collection> executedDeltas = new ArrayList<>(); - + LOGGER.trace("Executing right link delta (raw): {}", deltas.getRightLinkDelta()); executeDelta(deltas.getRightLinkDelta(), ModelExecuteOptions.createRaw(), executedDeltas, task, result); - + LOGGER.trace("Executing left link delta (raw): {}", deltas.getLeftLinkDelta()); executeDelta(deltas.getLeftLinkDelta(), ModelExecuteOptions.createRaw(), executedDeltas, task, result); - + LOGGER.trace("Executing left object delta: {}", deltas.getLeftObjectDelta()); executeDelta(deltas.getLeftObjectDelta(), null, executedDeltas, task, result); result.computeStatus(); if (result.isSuccess()) { - // Do not delete the other object if the execution was not success. - // We might need to re-try the merge if it has failed and for that we need the right object. + // Do not delete the other object if the execution was not success. + // We might need to re-try the merge if it has failed and for that we need the right object. ObjectDelta deleteDelta = ObjectDelta.createDeleteDelta(type, rightOid, prismContext); Collection> executedDeleteDeltas = modelController.executeChanges(MiscSchemaUtil.createCollection(deleteDelta), null, task, result); executedDeltas.addAll(executedDeleteDeltas); @@ -149,55 +149,55 @@ public Collection void executeDelta(ObjectDelta objectDelta, ModelExecuteOptions options, - Collection> executedDeltas, + Collection> executedDeltas, Task task, OperationResult result) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { - + result.computeStatus(); if (!result.isSuccess()) { return; } - + if (objectDelta != null && !objectDelta.isEmpty()) { - Collection> deltaExecutedDeltas = + Collection> deltaExecutedDeltas = modelController.executeChanges(MiscSchemaUtil.createCollection(objectDelta), options, task, result); - - executedDeltas.addAll(deltaExecutedDeltas); + + executedDeltas.addAll(deltaExecutedDeltas); } } - public MergeDeltas computeMergeDeltas(Class type, String leftOid, String rightOid, - final String mergeConfigurationName, final Task task, final OperationResult result) + public MergeDeltas computeMergeDeltas(Class type, String leftOid, String rightOid, + final String mergeConfigurationName, final Task task, final OperationResult result) throws ObjectNotFoundException, SchemaException, ConfigurationException, ExpressionEvaluationException, CommunicationException, SecurityViolationException { - + final PrismObject objectLeft = (PrismObject) objectResolver.getObjectSimple(type, leftOid, null, task, result).asPrismObject(); final PrismObject objectRight = (PrismObject) objectResolver.getObjectSimple(type, rightOid, null, task, result).asPrismObject(); - + PrismObject systemConfiguration = systemObjectCache.getSystemConfiguration(result); MergeConfigurationType mergeConfiguration = selectConfiguration(systemConfiguration, mergeConfigurationName); if (mergeConfiguration == null) { throw new ConfigurationException("No merge configuration defined"); } - + // The "left" object is always the one that will be the result. We will use its OID. final ObjectDelta leftObjectDelta = objectLeft.createModifyDelta(); final ObjectDelta leftLinkDelta = objectLeft.createModifyDelta(); final ObjectDelta rightLinkDelta = objectRight.createModifyDelta(); final List processedPaths = new ArrayList<>(); - + computeItemDeltas(leftObjectDelta, objectLeft, objectRight, processedPaths, mergeConfiguration, mergeConfigurationName, task, result); computeDefaultDeltas(leftObjectDelta, objectLeft, objectRight, processedPaths, mergeConfiguration, mergeConfigurationName, task, result); - + computeProjectionDeltas(leftLinkDelta, rightLinkDelta, objectLeft, objectRight, mergeConfiguration, mergeConfigurationName, task, result); - + return new MergeDeltas<>(leftObjectDelta, leftLinkDelta, rightLinkDelta); } - - private void computeItemDeltas(final ObjectDelta leftObjectDelta, + + private void computeItemDeltas(final ObjectDelta leftObjectDelta, final PrismObject objectLeft, final PrismObject objectRight, final List processedPaths, MergeConfigurationType mergeConfiguration, final String mergeConfigurationName, final Task task, final OperationResult result) throws SchemaException, ConfigurationException, ExpressionEvaluationException, ObjectNotFoundException { - + for (ItemRefMergeConfigurationType itemMergeConfig: mergeConfiguration.getItem()) { ItemPath itemPath = itemMergeConfig.getRef().getItemPath(); processedPaths.add(itemPath); @@ -207,35 +207,35 @@ private void computeItemDeltas(final ObjectDelta leftO leftObjectDelta.addModification(itemDelta); } } - + } - - private void computeDefaultDeltas(final ObjectDelta leftObjectDelta, + + private void computeDefaultDeltas(final ObjectDelta leftObjectDelta, final PrismObject objectLeft, final PrismObject objectRight, final List processedPaths, MergeConfigurationType mergeConfiguration, final String mergeConfigurationName, final Task task, final OperationResult result) throws SchemaException, ConfigurationException, ExpressionEvaluationException, ObjectNotFoundException { - + final ItemMergeConfigurationType defaultItemMergeConfig = mergeConfiguration.getDefault(); if (defaultItemMergeConfig != null) { try { - - Visitor visitor = new Visitor() { + + Visitor visitor = new Visitor() { @Override public void visit(Visitable visitable) { if (!(visitable instanceof Item)) { return; } Item item = (Item)visitable; - + ItemPath itemPath = item.getPath(); if (itemPath == null || itemPath.isEmpty()) { return; } - + if (SchemaConstants.PATH_LINK_REF.equivalent(itemPath)) { // Skip. There is a special processing for this. return; } - + boolean found = false; for (ItemPath processedPath: processedPaths) { // Need to check for super-paths here. @@ -251,7 +251,7 @@ public void visit(Visitable visitable) { return; } processedPaths.add(itemPath); - + if (item instanceof PrismContainer) { if (item.getDefinition().isSingleValue()) { // Ignore single-valued containers such as extension or activation @@ -263,7 +263,7 @@ public void visit(Visitable visitable) { } } - + ItemDelta itemDelta; try { itemDelta = mergeItem(objectLeft, objectRight, mergeConfigurationName, defaultItemMergeConfig, itemPath, @@ -274,14 +274,14 @@ public void visit(Visitable visitable) { LOGGER.trace("Item {} delta (default): {}", itemPath, itemDelta); if (itemDelta != null && !itemDelta.isEmpty()) { leftObjectDelta.addModification(itemDelta); - } + } } }; - + objectLeft.accept(visitor); objectRight.accept(visitor); - + } catch (TunnelException te) { if (te.getCause() instanceof SchemaException) { throw (SchemaException)te.getCause(); @@ -296,42 +296,42 @@ public void visit(Visitable visitable) { } } } - + } - + private void computeProjectionDeltas(final ObjectDelta leftLinkDelta, ObjectDelta rightLinkDelta, final PrismObject objectLeft, final PrismObject objectRight, MergeConfigurationType mergeConfiguration, final String mergeConfigurationName, final Task task, final OperationResult result) throws SchemaException, ConfigurationException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, SecurityViolationException { - + List projectionsLeft = getProjections(objectLeft, task, result); List projectionsRight = getProjections(objectRight, task, result); List mergedProjections = new ArrayList<>(); List matchedProjections = new ArrayList<>(); - + ProjectionMergeConfigurationType defaultProjectionMergeConfig = null; for (ProjectionMergeConfigurationType projectionMergeConfig: mergeConfiguration.getProjection()) { if (projectionMergeConfig.getProjectionDiscriminator() == null && projectionMergeConfig.getSituation() == null) { defaultProjectionMergeConfig = projectionMergeConfig; } else { - takeProjections(projectionMergeConfig.getLeft(), mergedProjections, matchedProjections, + takeProjections(projectionMergeConfig.getLeft(), mergedProjections, matchedProjections, projectionsLeft, projectionsLeft, projectionsRight, projectionMergeConfig); - takeProjections(projectionMergeConfig.getRight(), mergedProjections, matchedProjections, + takeProjections(projectionMergeConfig.getRight(), mergedProjections, matchedProjections, projectionsRight, projectionsLeft, projectionsRight, projectionMergeConfig); } } - + LOGGER.trace("Merged projections (before default): {}", mergedProjections); LOGGER.trace("Matched projections (before default): {}", matchedProjections); - + if (defaultProjectionMergeConfig != null) { takeUnmatchedProjections(defaultProjectionMergeConfig.getLeft(), mergedProjections, matchedProjections, projectionsLeft); takeUnmatchedProjections(defaultProjectionMergeConfig.getRight(), mergedProjections, matchedProjections, projectionsRight); } - + LOGGER.trace("Merged projections: {}", mergedProjections); - + checkConflict(mergedProjections); - + for (ShadowType mergedProjection: mergedProjections) { PrismReferenceValue leftLinkRef = findLinkRef(objectLeft, mergedProjection); if (leftLinkRef == null) { @@ -343,7 +343,7 @@ private void computeProjectionDeltas(final ObjectDelta LOGGER.trace("Projection already at the left: {}", mergedProjection); } } - + for (PrismReferenceValue leftLinkRef: getLinkRefs(objectLeft)) { if (!hasProjection(mergedProjections, leftLinkRef)) { LOGGER.trace("Removing left projection: {}", leftLinkRef); @@ -352,13 +352,13 @@ private void computeProjectionDeltas(final ObjectDelta LOGGER.trace("Left projection stays: {}", leftLinkRef); } } - + } private void addLinkDelta(ObjectDelta objectDelta, PrismReferenceValue linkRef) { objectDelta.addModificationAddReference(FocusType.F_LINK_REF, linkRef.clone()); } - + private void addUnlinkDelta(ObjectDelta objectDelta, PrismReferenceValue linkRef) { objectDelta.addModificationDeleteReference(FocusType.F_LINK_REF, linkRef.clone()); } @@ -371,7 +371,7 @@ private PrismReferenceValue findLinkRef(PrismObject ob } return null; } - + private List getLinkRefs(PrismObject object) { PrismReference ref = object.findReference(FocusType.F_LINK_REF); if (ref == null) { @@ -380,7 +380,7 @@ private List getLinkRefs(PrismObject return ref.getValues(); } } - + private boolean hasProjection(List mergedProjections, PrismReferenceValue leftLinkRef) { for (ShadowType projection: mergedProjections) { if (projection.getOid().equals(leftLinkRef.getOid())) { @@ -389,7 +389,7 @@ private boolean hasProjection(List mergedProjections, PrismReference } return false; } - + private boolean hasProjection(List mergedProjections, ShadowType candidateProjection) { for (ShadowType projection: mergedProjections) { if (projection.getOid().equals(candidateProjection.getOid())) { @@ -411,41 +411,41 @@ private List getProjections(PrismObject ob return projections; } - private void takeProjections(MergeStategyType strategy, List mergedProjections, + private void takeProjections(MergeStategyType strategy, List mergedProjections, List matchedProjections, List candidateProjections, - List projectionsLeft, List projectionsRight, + List projectionsLeft, List projectionsRight, ProjectionMergeConfigurationType projectionMergeConfig) { - + if (LOGGER.isTraceEnabled()) { - - LOGGER.trace("TAKE: Evaluating situation {}, discriminator: {}", + + LOGGER.trace("TAKE: Evaluating situation {}, discriminator: {}", projectionMergeConfig.getSituation(), projectionMergeConfig.getProjectionDiscriminator()); } for (ShadowType candidateProjection: candidateProjections) { - - if (projectionMatches(candidateProjection, projectionsLeft, projectionsRight, projectionMergeConfig)) { + + if (projectionMatches(candidateProjection, projectionsLeft, projectionsRight, projectionMergeConfig)) { LOGGER.trace("Projection matches {}", candidateProjection); matchedProjections.add(candidateProjection); - + if (strategy == MergeStategyType.TAKE) { mergedProjections.add(candidateProjection); - + } else if (strategy == null || strategy == MergeStategyType.IGNORE) { // Nothing to do here - + } else { throw new UnsupportedOperationException("Merge strategy "+strategy+" is not supported"); } - + } else { LOGGER.trace("Discriminator does NOT match {}", candidateProjection); } } - - + + } - + private boolean projectionMatches(ShadowType candidateProjection, List projectionsLeft, List projectionsRight, ProjectionMergeConfigurationType projectionMergeConfig) { @@ -463,23 +463,23 @@ private boolean projectionMatches(ShadowType candidateProjection, return true; } - private void takeUnmatchedProjections(MergeStategyType strategy, List mergedProjections, + private void takeUnmatchedProjections(MergeStategyType strategy, List mergedProjections, List matchedProjections, List candidateProjections) { if (strategy == MergeStategyType.TAKE) { - + for (ShadowType candidateProjection: candidateProjections) { if (!hasProjection(matchedProjections, candidateProjection)) { mergedProjections.add(candidateProjection); } } - + } else if (strategy == null || strategy == MergeStategyType.IGNORE) { return; } else { throw new UnsupportedOperationException("Merge strategy "+strategy+" is not supported"); } } - + private ProjectionMergeSituationType determineSituation(ShadowType candidateProjection, List projectionsLeft, List projectionsRight) { boolean matchLeft = hasMatchingProjection(candidateProjection, projectionsLeft); @@ -494,7 +494,7 @@ private ProjectionMergeSituationType determineSituation(ShadowType candidateProj throw new IllegalStateException("Booom! The universe has imploded."); } } - + private boolean hasMatchingProjection(ShadowType cprojection, List projections) { for (ShadowType projection: projections) { if (ShadowUtil.isConflicting(projection, cprojection)) { @@ -517,14 +517,14 @@ private void checkConflict(List projections) throws SchemaException } } } - + private ShadowType getProjection(ObjectReferenceType linkRef, Task task, OperationResult result) throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { Collection> options = SelectorOptions.createCollection(GetOperationOptions.createNoFetch()); return objectResolver.getObject(ShadowType.class, linkRef.getOid(), options, task, result); } private ItemDelta mergeItem(PrismObject objectLeft, PrismObject objectRight, - String mergeConfigurationName, ItemMergeConfigurationType itemMergeConfig, ItemPath itemPath, + String mergeConfigurationName, ItemMergeConfigurationType itemMergeConfig, ItemPath itemPath, Task task, OperationResult result) throws SchemaException, ConfigurationException, ExpressionEvaluationException, ObjectNotFoundException { I itemLeft = (I) objectLeft.findItem(itemPath); I itemRight = (I) objectRight.findItem(itemPath); @@ -538,19 +538,19 @@ private ItemDelta mergeItem(PrismObject valueExpression = null; if (itemMergeConfig.getValueExpression() != null) { ExpressionType expressionType = itemMergeConfig.getValueExpression(); - valueExpression = expressionFactory.makeExpression(expressionType, itemDefinition, + valueExpression = expressionFactory.makeExpression(expressionType, itemDefinition, "value expression for item " + itemPath + " in merge configuration " + mergeConfigurationName, task, result); } - + ItemDelta itemDelta = itemDefinition.createEmptyDelta(itemPath); MergeStategyType leftStrategy = itemMergeConfig.getLeft(); MergeStategyType rightStrategy = itemMergeConfig.getRight(); @@ -568,7 +568,7 @@ private ItemDelta mergeItem(PrismObject valuesToTake = getValuesToTake(objectLeft, objectRight, + Collection valuesToTake = getValuesToTake(objectLeft, objectRight, SIDE_RIGHT, itemRight, rightStrategy, valueExpression, task, result); itemDelta.setValuesToReplace(valuesToTake); } @@ -581,7 +581,7 @@ private ItemDelta mergeItem(PrismObject valuesToLeave = getValuesToTake(objectLeft, objectRight, + Collection valuesToLeave = getValuesToTake(objectLeft, objectRight, SIDE_LEFT, itemLeft, leftStrategy, valueExpression, task, result); List currentLeftValues = itemLeft.getValues(); Collection leftValuesToRemove = diffValues(currentLeftValues, valuesToLeave); @@ -595,7 +595,7 @@ private ItemDelta mergeItem(PrismObject valuesToTake = getValuesToTake(objectLeft, objectRight, + Collection valuesToTake = getValuesToTake(objectLeft, objectRight, SIDE_RIGHT, itemRight, rightStrategy, valueExpression, task, result); itemDelta.addValuesToAdd(valuesToTake); return itemDelta; @@ -603,36 +603,36 @@ private ItemDelta mergeItem(PrismObject leftValuesToLeave = getValuesToTake(objectLeft, objectRight, + Collection leftValuesToLeave = getValuesToTake(objectLeft, objectRight, SIDE_LEFT, itemLeft, leftStrategy, valueExpression, task, result); - Collection rightValuesToTake = getValuesToTake(objectLeft, objectRight, + Collection rightValuesToTake = getValuesToTake(objectLeft, objectRight, SIDE_RIGHT, itemRight, rightStrategy, valueExpression, task, result); - + for (PrismValue rightValueToTake: rightValuesToTake) { if (!PrismValue.collectionContainsEquivalentValue(leftValuesToLeave, rightValueToTake)) { itemDelta.addValueToAdd(rightValueToTake); } } - + List currentLeftValues = itemLeft.getValues(); Collection leftValuesToRemove = diffValues(currentLeftValues, leftValuesToLeave); - + if (leftValuesToRemove != null && !leftValuesToRemove.isEmpty()) { itemDelta.addValuesToDelete(leftValuesToRemove); } - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Merging item {} T/T case:\n leftValuesToLeave: {}\n rightValuesToTake: {}\n leftValuesToRemove: {}\n itemDelta:\n{}", new Object[]{itemPath, leftValuesToLeave, rightValuesToTake, leftValuesToRemove, itemDelta.debugDump(2)}); } - + return itemDelta; } } } } - + private Collection diffValues(List currentValues, Collection valuesToLeave) { if (valuesToLeave == null || valuesToLeave.isEmpty()) { return PrismValue.cloneCollection(currentValues); @@ -646,8 +646,8 @@ private Collection diffValues(List currentValues, Collec return diff; } - private Collection getValuesToTake(PrismObject objectLeft, PrismObject objectRight, - String side, I origItem, MergeStategyType strategy, Expression valueExpression, Task task, OperationResult result) + private Collection getValuesToTake(PrismObject objectLeft, PrismObject objectRight, + String side, I origItem, MergeStategyType strategy, Expression valueExpression, Task task, OperationResult result) throws ConfigurationException, SchemaException, ExpressionEvaluationException, ObjectNotFoundException { if (origItem == null) { return new ArrayList<>(0); @@ -671,8 +671,8 @@ private Collection getValuesT throw new ConfigurationException("Unknown strategy "+strategy); } } - - + + private Collection cleanContainerIds(Collection pvals) { if (pvals == null) { return null; @@ -680,13 +680,13 @@ private Collection cleanContainerIds(Collection pvals) { for (PrismValue pval: pvals) { if (pval instanceof PrismContainerValue) { ((PrismContainerValue)pval).setId(null); - } + } } return pvals; - } - + } + - private Collection evaluateValueExpression(PrismObject objectLeft, PrismObject objectRight, String side, PrismValue origValue, Expression valueExpression, + private Collection evaluateValueExpression(PrismObject objectLeft, PrismObject objectRight, String side, PrismValue origValue, Expression valueExpression, Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException { ExpressionVariables variables = new ExpressionVariables(); variables.addVariableDefinition(ExpressionConstants.VAR_SIDE, side); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/RoleSelectionSpecEntry.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/RoleSelectionSpecEntry.java index 185d9a334d3..528ee84f287 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/RoleSelectionSpecEntry.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/RoleSelectionSpecEntry.java @@ -25,7 +25,7 @@ * */ public class RoleSelectionSpecEntry extends DisplayableValueImpl { - + boolean negative = false; public RoleSelectionSpecEntry(String value, String label, String description) { @@ -39,7 +39,7 @@ public boolean isNegative() { public void setNegative(boolean negative) { this.negative = negative; } - + public void negate() { this.negative = !this.negative; } @@ -52,7 +52,7 @@ public static void negate(Collection col) { entry.negate(); } } - + public static boolean hasNegative(Collection col) { if (col == null) { return false; @@ -64,7 +64,7 @@ public static boolean hasNegative(Collection col) { } return false; } - + public static boolean hasNegativeValue(Collection col, String value) { if (col == null) { return false; @@ -76,7 +76,7 @@ public static boolean hasNegativeValue(Collection col, S } return false; } - + public static Collection getPositive(Collection col) { if (col == null) { return null; diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/SchemaTransformer.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/SchemaTransformer.java index b22a3d5ca15..b2e9b9c4001 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/SchemaTransformer.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/SchemaTransformer.java @@ -51,21 +51,21 @@ /** * Transforms the schema and objects by applying security constraints, * object template schema refinements, etc. - * + * * @author semancik */ @Component public class SchemaTransformer { - + private static final Trace LOGGER = TraceManager.getTrace(SchemaTransformer.class); - + @Autowired(required = true) @Qualifier("cacheRepositoryService") private transient RepositoryService cacheRepositoryService; - + @Autowired(required = true) private SecurityEnforcer securityEnforcer; - + @Autowired(required = true) private SystemObjectCache systemObjectCache; @@ -84,7 +84,7 @@ public void applySchemasAndSecurityToObjectTypes(List applySchemasAndSecurity(object, rootOptions, options, phase, task, result); } } - + public void applySchemasAndSecurityToObjects(List> objects, GetOperationOptions rootOptions, Collection> options, AuthorizationPhaseType phase, Task task, OperationResult result) @@ -161,18 +161,18 @@ protected void applySchemaAndSecurityToObject(PrismObject /** * Validate the objects, apply security to the object definition, remove any non-visible properties (security), * apply object template definitions and so on. This method is called for - * any object that is returned from the Model Service. + * any object that is returned from the Model Service. */ public void applySchemasAndSecurity(PrismObject object, GetOperationOptions rootOptions, Collection> options, - AuthorizationPhaseType phase, Task task, OperationResult parentResult) + AuthorizationPhaseType phase, Task task, OperationResult parentResult) throws SchemaException, SecurityViolationException, ConfigurationException, ObjectNotFoundException { LOGGER.trace("applySchemasAndSecurity starting"); OperationResult result = parentResult.createMinorSubresult(SchemaTransformer.class.getName()+".applySchemasAndSecurity"); validateObject(object, rootOptions, result); - + PrismObjectDefinition objectDefinition = object.deepCloneDefinition(true); - + ObjectSecurityConstraints securityConstraints; try { securityConstraints = securityEnforcer.compileSecurityConstraints(object, null); @@ -194,7 +194,7 @@ public void applySchemasAndSecurity(PrismObject object } else { applySchemasAndSecurityPhase(object, securityConstraints, objectDefinition, rootOptions, phase, task, result); } - + ObjectTemplateType objectTemplateType; try { objectTemplateType = determineObjectTemplate(object, AuthorizationPhaseType.REQUEST, result); @@ -218,14 +218,14 @@ public void applySchemasAndSecurity(PrismObject object object.trimDefinitionTree(full); } } - + result.computeStatus(); result.recordSuccessIfUnknown(); LOGGER.trace("applySchemasAndSecurity finishing"); // to allow folding in log viewer } - - private void applySchemasAndSecurityPhase(PrismObject object, ObjectSecurityConstraints securityConstraints, PrismObjectDefinition objectDefinition, - GetOperationOptions rootOptions, AuthorizationPhaseType phase, Task task, OperationResult result) + + private void applySchemasAndSecurityPhase(PrismObject object, ObjectSecurityConstraints securityConstraints, PrismObjectDefinition objectDefinition, + GetOperationOptions rootOptions, AuthorizationPhaseType phase, Task task, OperationResult result) throws SchemaException, SecurityViolationException, ConfigurationException, ObjectNotFoundException { Validate.notNull(phase); try { @@ -235,7 +235,7 @@ private void applySchemasAndSecurityPhase(PrismObject SecurityUtil.logSecurityDeny(object, "because the authorization denies access"); throw new AuthorizationException("Access denied"); } - + AuthorizationDecisionType globalAddDecision = securityConstraints.getActionDecision(ModelAuthorizationAction.ADD.getUrl(), phase); AuthorizationDecisionType globalModifyDecision = securityConstraints.getActionDecision(ModelAuthorizationAction.MODIFY.getUrl(), phase); applySecurityConstraints(object.getValue().getItems(), securityConstraints, globalReadDecision, @@ -245,17 +245,17 @@ private void applySchemasAndSecurityPhase(PrismObject SecurityUtil.logSecurityDeny(object, "because the subject has not access to any item"); throw new AuthorizationException("Access denied"); } - + applySecurityConstraintsItemDef(objectDefinition, ItemPath.EMPTY_PATH, securityConstraints, globalReadDecision, globalAddDecision, globalModifyDecision, phase); - + } catch (SecurityViolationException | RuntimeException e) { result.recordFatalError(e); throw e; } } - - public void applySecurityConstraints(List> items, ObjectSecurityConstraints securityConstraints, - AuthorizationDecisionType defaultReadDecision, AuthorizationDecisionType defaultAddDecision, AuthorizationDecisionType defaultModifyDecision, + + public void applySecurityConstraints(List> items, ObjectSecurityConstraints securityConstraints, + AuthorizationDecisionType defaultReadDecision, AuthorizationDecisionType defaultAddDecision, AuthorizationDecisionType defaultModifyDecision, AuthorizationPhaseType phase) { LOGGER.trace("applySecurityConstraints(items): items={}, phase={}, defaults R={}, A={}, M={}", items, phase, defaultReadDecision, defaultAddDecision, defaultModifyDecision); @@ -318,7 +318,7 @@ public void applySecurityConstraints(List> items, ObjectSecurityConstr } } } - + public void applySecurityConstraints(D itemDefinition, ObjectSecurityConstraints securityConstraints, AuthorizationPhaseType phase) { if (phase == null) { @@ -328,7 +328,7 @@ public void applySecurityConstraints(D itemDefinition applySecurityConstraintsPhase(itemDefinition, securityConstraints, phase); } } - + private void applySecurityConstraintsPhase(D itemDefinition, ObjectSecurityConstraints securityConstraints, AuthorizationPhaseType phase) { Validate.notNull(phase); @@ -339,16 +339,16 @@ private void applySecurityConstraintsPhase(D itemDefi itemDefinition, phase, defaultReadDecision, defaultAddDecision, defaultModifyDecision); applySecurityConstraintsItemDef(itemDefinition, ItemPath.EMPTY_PATH, securityConstraints, defaultReadDecision, defaultAddDecision, defaultModifyDecision, phase); - + } - + private void applySecurityConstraintsItemDef(D itemDefinition, ItemPath itemPath, ObjectSecurityConstraints securityConstraints, AuthorizationDecisionType defaultReadDecision, AuthorizationDecisionType defaultAddDecision, AuthorizationDecisionType defaultModifyDecision, AuthorizationPhaseType phase) { AuthorizationDecisionType readDecision = computeItemDecision(securityConstraints, itemPath, ModelAuthorizationAction.READ.getUrl(), defaultReadDecision, phase); AuthorizationDecisionType addDecision = computeItemDecision(securityConstraints, itemPath, ModelAuthorizationAction.ADD.getUrl(), defaultAddDecision, phase); AuthorizationDecisionType modifyDecision = computeItemDecision(securityConstraints, itemPath, ModelAuthorizationAction.MODIFY.getUrl(), defaultModifyDecision, phase); - + boolean anySubElementRead = false; boolean anySubElementAdd = false; boolean anySubElementModify = false; @@ -371,10 +371,10 @@ private void applySecurityConstraintsItemDef(D itemDe } } } - + LOGGER.trace("applySecurityConstraints(itemDef): {}: decisions R={}, A={}, M={}; subelements R={}, A={}, M={}", itemPath, readDecision, addDecision, modifyDecision, anySubElementRead, anySubElementAdd, anySubElementModify); - + if (readDecision != AuthorizationDecisionType.ALLOW) { ((ItemDefinitionImpl) itemDefinition).setCanRead(false); } @@ -384,7 +384,7 @@ private void applySecurityConstraintsItemDef(D itemDe if (modifyDecision != AuthorizationDecisionType.ALLOW) { ((ItemDefinitionImpl) itemDefinition).setCanModify(false); } - + if (anySubElementRead) { ((ItemDefinitionImpl) itemDefinition).setCanRead(true); } @@ -395,7 +395,7 @@ private void applySecurityConstraintsItemDef(D itemDe ((ItemDefinitionImpl) itemDefinition).setCanModify(true); } } - + public AuthorizationDecisionType computeItemDecision(ObjectSecurityConstraints securityConstraints, ItemPath itemPath, String actionUrl, AuthorizationDecisionType defaultDecision, AuthorizationPhaseType phase) { AuthorizationDecisionType explicitDecision = securityConstraints.findItemDecision(itemPath, actionUrl, phase); @@ -406,7 +406,7 @@ public AuthorizationDecisionType computeItemDecision(ObjectSecurityConstraints s return defaultDecision; } } - + public ObjectTemplateType determineObjectTemplate(PrismObject object, AuthorizationPhaseType phase, OperationResult result) throws SchemaException, ConfigurationException, ObjectNotFoundException { PrismObject systemConfiguration = systemObjectCache.getSystemConfiguration(result); if (systemConfiguration == null) { @@ -423,7 +423,7 @@ public ObjectTemplateType determineObjectTemplate(PrismOb PrismObject template = cacheRepositoryService.getObject(ObjectTemplateType.class, objectTemplateRef.getOid(), null, result); return template.asObjectable(); } - + public ObjectTemplateType determineObjectTemplate(Class objectClass, AuthorizationPhaseType phase, OperationResult result) throws SchemaException, ConfigurationException, ObjectNotFoundException { PrismObject systemConfiguration = systemObjectCache.getSystemConfiguration(result); if (systemConfiguration == null) { @@ -440,7 +440,7 @@ public ObjectTemplateType determineObjectTemplate(Class template = cacheRepositoryService.getObject(ObjectTemplateType.class, objectTemplateRef.getOid(), null, result); return template.asObjectable(); } - + public void applyObjectTemplateToDefinition(PrismObjectDefinition objectDefinition, ObjectTemplateType objectTemplateType, OperationResult result) throws ObjectNotFoundException, SchemaException { if (objectTemplateType == null) { return; @@ -465,7 +465,7 @@ public void applyObjectTemplateToDefinition(PrismObjectDe } } } - + private void applyObjectTemplateToObject(PrismObject object, ObjectTemplateType objectTemplateType, OperationResult result) throws ObjectNotFoundException, SchemaException { if (objectTemplateType == null) { return; @@ -498,31 +498,31 @@ private void applyObjectTemplateToObject(PrismObject o + " as specified in item definition in "+objectTemplateType); } } - + } } - + private void applyObjectTemplateItem(ID itemDef, ObjectTemplateItemDefinitionType templateItemDefType, String desc) throws SchemaException { if (itemDef == null) { throw new SchemaException("No definition for "+desc); } - + String displayName = templateItemDefType.getDisplayName(); if (displayName != null) { ((ItemDefinitionImpl) itemDef).setDisplayName(displayName); } - + Integer displayOrder = templateItemDefType.getDisplayOrder(); if (displayOrder != null) { ((ItemDefinitionImpl) itemDef).setDisplayOrder(displayOrder); } - + Boolean emphasized = templateItemDefType.isEmphasized(); if (emphasized != null) { ((ItemDefinitionImpl) itemDef).setEmphasized(emphasized); } - + List limitations = templateItemDefType.getLimitations(); if (limitations != null) { PropertyLimitationsType limitationsType = MiscSchemaUtil.getLimitationsType(limitations, LayerType.PRESENTATION); @@ -550,15 +550,15 @@ private void applyObjectTempla } } } - + ObjectReferenceType valueEnumerationRef = templateItemDefType.getValueEnumerationRef(); if (valueEnumerationRef != null) { PrismReferenceValue valueEnumerationRVal = MiscSchemaUtil.objectReferenceTypeToReferenceValue(valueEnumerationRef); ((ItemDefinitionImpl) itemDef).setValueEnumerationRef(valueEnumerationRVal); - } + } } - - + + private void validateObject(PrismObject object, GetOperationOptions options, OperationResult result) { try { if (InternalsConfig.readEncryptionChecks) { @@ -587,13 +587,13 @@ private void validateObject(PrismObject object, GetOpe throw e; } } - + private boolean hasError(PrismObject object, OperationResult result) { if (result != null && result.isError()) { // actually, result is pretty tiny here - does not include object fetch/get operation return true; } OperationResultType fetchResult = object.asObjectable().getFetchResult(); - if (fetchResult != null && + if (fetchResult != null && (fetchResult.getStatus() == OperationResultStatusType.FATAL_ERROR || fetchResult.getStatus() == OperationResultStatusType.PARTIAL_ERROR)) { return true; diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/SelfTestData.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/SelfTestData.java index 45946ab5d74..964c076db1d 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/SelfTestData.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/SelfTestData.java @@ -17,7 +17,7 @@ /** * There are som ugly data and long strings. So let's keep this separate to keep the main code readable. - * + * * @author Radovan Semancik * */ @@ -27,7 +27,7 @@ public class SelfTestData { * Long text with national characters. This is used to test whether the database can store a long text * and that it maintains national characters. */ - public static String POLICIJA = + public static String POLICIJA = "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + @@ -35,7 +35,7 @@ public class SelfTestData { "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + - "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + + "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + @@ -63,7 +63,7 @@ public class SelfTestData { "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + - "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + + "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + @@ -91,7 +91,7 @@ public class SelfTestData { "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + - "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + + "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + @@ -119,7 +119,7 @@ public class SelfTestData { "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + - "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + + "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + @@ -147,7 +147,7 @@ public class SelfTestData { "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + - "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + + "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + @@ -175,7 +175,7 @@ public class SelfTestData { "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + - "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + + "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + @@ -203,7 +203,7 @@ public class SelfTestData { "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + - "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + + "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + @@ -231,7 +231,7 @@ public class SelfTestData { "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + - "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + + "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + @@ -259,7 +259,7 @@ public class SelfTestData { "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + - "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + + "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + @@ -287,7 +287,7 @@ public class SelfTestData { "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + - "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + + "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + @@ -315,7 +315,7 @@ public class SelfTestData { "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + - "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + + "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + @@ -343,7 +343,7 @@ public class SelfTestData { "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + - "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + + "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + @@ -371,7 +371,7 @@ public class SelfTestData { "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + - "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + + "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + @@ -399,7 +399,7 @@ public class SelfTestData { "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + - "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + + "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + @@ -427,7 +427,7 @@ public class SelfTestData { "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + - "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + + "Populáry, Karpatula. Ðuvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pólicíja, pólicíja, Sálašáry, práva Jova. Z césty príva, z césty práva, sýmpatika, korpora. " + "Populáry, Karpatula. Juvá svorno policána. Kerléš na strach, policíja. Bumtarára, bumtarára, bum. " + "Pōlicĭja, pōlicĭja, Sãlaŝåry, pràva Jova. Z céßty prïva, z cèßty pråva, sŷmpatika, korpora. " + diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/SystemConfigurationHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/SystemConfigurationHandler.java index 05cfab0baca..56af667b23e 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/SystemConfigurationHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/SystemConfigurationHandler.java @@ -52,7 +52,7 @@ */ @Component public class SystemConfigurationHandler implements ChangeHook { - + private static final Trace LOGGER = TraceManager.getTrace(SystemConfigurationHandler.class); private static final String DOT_CLASS = SystemConfigurationHandler.class + "."; @@ -65,7 +65,7 @@ public class SystemConfigurationHandler implements ChangeHook { @Autowired @Qualifier("cacheRepositoryService") private transient RepositoryService cacheRepositoryService; - + @PostConstruct public void init() { hookRegistry.registerChangeHook(HOOK_URI, this); @@ -98,7 +98,7 @@ public HookOperationMode invoke(@NotNull ModelContext } ModelContext confContext = (ModelContext)context; ModelElementContext focusContext = confContext.getFocusContext(); - + boolean isDeletion = false; // is this config-related change a deletion? PrismObject object = focusContext.getObjectNew(); if (object == null) { diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/ExpressionEnvironment.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/ExpressionEnvironment.java index c53202fb644..03981b62a79 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/ExpressionEnvironment.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/ExpressionEnvironment.java @@ -86,5 +86,5 @@ public String toString() { + projectionContext + ", currentResult=" + currentResult + ", currentTask=" + currentTask + ")"; } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/ExpressionHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/ExpressionHandler.java index ec29567d829..54ef6091840 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/ExpressionHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/ExpressionHandler.java @@ -44,9 +44,9 @@ import java.util.Collection; /** - * + * * @author lazyman - * + * */ @Component public class ExpressionHandler { @@ -54,18 +54,18 @@ public class ExpressionHandler { @Autowired(required = true) @Qualifier("cacheRepositoryService") private RepositoryService repositoryService; - + @Autowired(required = true) private ExpressionFactory expressionFactory; - + @Autowired(required = true) private ModelObjectResolver modelObjectResolver; @Autowired(required = true) private PrismContext prismContext; - + private XPathScriptEvaluator xpathEvaluator = null; - + public String evaluateExpression(ShadowType shadow, ExpressionType expressionType, String shortDesc, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException { Validate.notNull(shadow, "Resource object shadow must not be null."); @@ -73,9 +73,9 @@ public String evaluateExpression(ShadowType shadow, ExpressionType expressionTyp Validate.notNull(result, "Operation result must not be null."); ResourceType resource = resolveResource(shadow, result); - + ExpressionVariables variables = getDefaultXPathVariables(null, shadow, resource); - + PrismPropertyDefinition outputDefinition = new PrismPropertyDefinitionImpl<>(ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_STRING, prismContext); Expression,PrismPropertyDefinition> expression = expressionFactory.makeExpression(expressionType, @@ -97,7 +97,7 @@ public String evaluateExpression(ShadowType shadow, ExpressionType expressionTyp } public boolean evaluateConfirmationExpression(UserType user, ShadowType shadow, - ExpressionType expressionType, Task task, OperationResult result) + ExpressionType expressionType, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException { Validate.notNull(user, "User must not be null."); Validate.notNull(shadow, "Resource object shadow must not be null."); @@ -107,10 +107,10 @@ public boolean evaluateConfirmationExpression(UserType user, ShadowType shadow, ResourceType resource = resolveResource(shadow, result); ExpressionVariables variables = getDefaultXPathVariables(user, shadow, resource); String shortDesc = "confirmation expression for "+resource.asPrismObject(); - + PrismPropertyDefinition outputDefinition = new PrismPropertyDefinitionImpl<>(ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_BOOLEAN, prismContext); - Expression,PrismPropertyDefinition> expression = expressionFactory.makeExpression(expressionType, + Expression,PrismPropertyDefinition> expression = expressionFactory.makeExpression(expressionType, outputDefinition, shortDesc, task, result); ExpressionEvaluationContext params = new ExpressionEvaluationContext(null, variables, shortDesc, task, result); @@ -153,7 +153,7 @@ private ResourceType resolveResource(ShadowType shadow, OperationResult result) public static ExpressionVariables getDefaultXPathVariables(UserType user, ShadowType shadow, ResourceType resource) { - + ExpressionVariables variables = new ExpressionVariables(); if (user != null) { variables.addVariableDefinition(ExpressionConstants.VAR_USER, user.asPrismObject()); @@ -173,15 +173,15 @@ public static ExpressionVariables getDefaultXPathVariables(UserType user, // Called from the ObjectResolver.resolve public ObjectType resolveRef(ObjectReferenceType ref, String contextDescription, OperationResult result) throws ObjectNotFoundException, SchemaException { - + Class type = ObjectType.class; if (ref.getType() != null) { ObjectTypes objectTypeType = ObjectTypes.getObjectTypeFromTypeQName(ref.getType()); type = objectTypeType.getClassDefinition(); } - + return repositoryService.getObject(type, ref.getOid(), null, result).asObjectable(); } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/MidpointFunctionsImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/MidpointFunctionsImpl.java index 0b33f30bae2..2d6d5a40d85 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/MidpointFunctionsImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/MidpointFunctionsImpl.java @@ -104,9 +104,9 @@ public class MidpointFunctionsImpl implements MidpointFunctions { @Autowired private ModelService modelService; - + @Autowired ModelInteractionService modelInteractionService; - + @Autowired private ModelObjectResolver modelObjectResolver; @@ -116,7 +116,7 @@ public class MidpointFunctionsImpl implements MidpointFunctions { @Autowired private ProvisioningService provisioningService; - + @Autowired private SecurityEnforcer securityEnforcer; @@ -128,14 +128,14 @@ public class MidpointFunctionsImpl implements MidpointFunctions { @Autowired private WorkflowService workflowService; - + @Autowired private ConstantsManager constantsManager; public String hello(String name) { return "Hello "+name; } - + public PrismContext getPrismContext() { return prismContext; } @@ -266,7 +266,7 @@ public String getPlaintextUserPasswordFromDeltas(List> obj return null; } } - + public boolean hasLinkedAccount(String resourceOid) { LensContext ctx = ModelExpressionThreadLocalHolder.getLensContext(); if (ctx == null) { @@ -300,7 +300,7 @@ public boolean hasLinkedAccount(String resourceOid) { if (projectionContext.isThombstone()) { return false; } - + SynchronizationPolicyDecision synchronizationPolicyDecision = projectionContext.getSynchronizationPolicyDecision(); SynchronizationIntent synchronizationIntent = projectionContext.getSynchronizationIntent(); if (scriptContext == null) { @@ -355,7 +355,7 @@ public boolean hasLinkedAccount(String resourceOid) { } } } - + @Override public boolean isDirectlyAssigned(F focusType, String targetOid) { for (AssignmentType assignment: focusType.getAssignment()) { @@ -366,12 +366,12 @@ public boolean isDirectlyAssigned(F focusType, String targ } return false; } - + @Override public boolean isDirectlyAssigned(F focusType, ObjectType target) { return isDirectlyAssigned(focusType, target.getOid()); } - + @Override public boolean isDirectlyAssigned(String targetOid) { LensContext ctx = ModelExpressionThreadLocalHolder.getLensContext(); @@ -382,7 +382,7 @@ public boolean isDirectlyAssigned(String targetOid) { if (focusContext == null) { throw new IllegalStateException("No focus in lens context"); } - + PrismObject focus; ScriptExpressionEvaluationContext scriptContext = ScriptExpressionEvaluationContext.getThreadLocal(); if (scriptContext == null) { @@ -405,13 +405,13 @@ public boolean isDirectlyAssigned(String targetOid) { } return isDirectlyAssigned(focus.asObjectable(), targetOid); } - + @Override public boolean isDirectlyAssigned(ObjectType target) { return isDirectlyAssigned(target.getOid()); } - + @Override public ShadowType getLinkedShadow(FocusType focus, ResourceType resource) throws SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { @@ -424,12 +424,12 @@ public ShadowType getLinkedShadow(FocusType focus, ResourceType resource, boolea return getLinkedShadow(focus, resource.getOid(), repositoryObjectOnly); } - + @Override public ShadowType getLinkedShadow(FocusType focus, String resourceOid) throws SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { return getLinkedShadow(focus, resourceOid, false); } - + @Override public ShadowType getLinkedShadow(FocusType focus, String resourceOid, boolean repositoryObjectOnly) throws SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { if (focus == null) { @@ -456,19 +456,19 @@ public ShadowType getLinkedShadow(FocusType focus, String resourceOid, boolean r // It is safe to ignore this error in this method. LOGGER.trace("Ignoring shadow "+linkRef.getOid()+" linked in "+focus+" because it no longer exists on resource"); continue; - } + } } return shadowType; } } return null; } - + @Override public ShadowType getLinkedShadow(FocusType focus, String resourceOid, ShadowKindType kind, String intent) throws SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { return getLinkedShadow(focus, resourceOid, kind, intent, false); } - + @Override public ShadowType getLinkedShadow(FocusType focus, String resourceOid, ShadowKindType kind, String intent, boolean repositoryObjectOnly) throws SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { List linkRefs = focus.getLinkRef(); @@ -492,14 +492,14 @@ public ShadowType getLinkedShadow(FocusType focus, String resourceOid, ShadowKin // It is safe to ignore this error in this method. LOGGER.trace("Ignoring shadow "+linkRef.getOid()+" linked in "+focus+" because it no longer exists on resource"); continue; - } + } } return shadowType; } } return null; } - + @Override public boolean isFullShadow() { LensProjectionContext projectionContext = getProjectionContext(); @@ -515,20 +515,20 @@ public Integer countAccounts(String resourceOid, QName attributeName, T attr ResourceType resourceType = modelObjectResolver.getObjectSimple(ResourceType.class, resourceOid, null, null, result); return countAccounts(resourceType, attributeName, attributeValue, getCurrentTask(), result); } - + public Integer countAccounts(ResourceType resourceType, QName attributeName, T attributeValue) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { OperationResult result = getCurrentResult(MidpointFunctions.class.getName()+".countAccounts"); return countAccounts(resourceType, attributeName, attributeValue, getCurrentTask(), result); } - + public Integer countAccounts(ResourceType resourceType, String attributeName, T attributeValue) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { OperationResult result = getCurrentResult(MidpointFunctions.class.getName()+".countAccounts"); QName attributeQName = new QName(ResourceTypeUtil.getResourceNamespace(resourceType), attributeName); return countAccounts(resourceType, attributeQName, attributeValue, getCurrentTask(), result); } - + private Integer countAccounts(ResourceType resourceType, QName attributeName, T attributeValue, Task task, OperationResult result) - throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, + throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { RefinedResourceSchema rSchema = RefinedResourceSchemaImpl.getRefinedSchema(resourceType); RefinedObjectClassDefinition rAccountDef = rSchema.getDefaultRefinedDefinition(ShadowKindType.ACCOUNT); @@ -623,7 +623,7 @@ public boolean isUniqueAccountValue(ResourceType resourceType, ShadowType sh private boolean isUniqueAccountValue(ResourceType resourceType, final ShadowType shadowType, QName attributeName, T attributeValue, Task task, OperationResult result) - throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, + throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { Validate.notNull(resourceType, "Null resource"); Validate.notNull(shadowType, "Null shadow"); @@ -640,7 +640,7 @@ private boolean isUniqueAccountValue(ResourceType resourceType, final Shadow if (LOGGER.isTraceEnabled()) { LOGGER.trace("Determining uniqueness of attribute {} using query:\n{}", attributeName, query.debugDump()); } - + final Holder isUniqueHolder = new Holder(true); ResultHandler handler = new ResultHandler() { @Override @@ -661,12 +661,12 @@ public boolean handle(PrismObject object, OperationResult parentResu } } }; - + modelObjectResolver.searchIterative(ShadowType.class, query, null, handler, task, result); - + return isUniqueHolder.getValue(); } - + private LensProjectionContext getProjectionContext() { return ModelExpressionThreadLocalHolder.getProjectionContext(); } @@ -683,7 +683,7 @@ public Task getCurrentTask() { } return rv; } - + private OperationResult getCurrentResult() { OperationResult rv = ModelExpressionThreadLocalHolder.getCurrentResult(); if (rv == null) { @@ -695,7 +695,7 @@ private OperationResult getCurrentResult() { } return rv; } - + private OperationResult getCurrentResult(String operationName) { OperationResult currentResult = ModelExpressionThreadLocalHolder.getCurrentResult(); if (currentResult == null) { @@ -704,7 +704,7 @@ private OperationResult getCurrentResult(String operationName) { return currentResult; } } - + private OperationResult createSubresult(String operationName) { OperationResult currentResult = ModelExpressionThreadLocalHolder.getCurrentResult(); if (currentResult == null) { @@ -733,9 +733,9 @@ public ModelContext unwrapModelContext(LensContextType lensContextType) throws S public LensContextType wrapModelContext(LensContext lensContext) throws SchemaException { return lensContext.toLensContextType(); } - + // Convenience functions - + @Override public T createEmptyObject(Class type) throws SchemaException { PrismObjectDefinition objectDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(type); @@ -763,7 +763,7 @@ public T createEmptyObjectWithName(Class type, PolyStr objectType.setName(name); return objectType; } - + // Functions accessing modelService @Override @@ -796,7 +796,7 @@ public T resolveReferenceIfExists(ObjectReferenceType ref } @Override - public T getObject(Class type, String oid, + public T getObject(Class type, String oid, Collection> options) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, @@ -978,9 +978,9 @@ public void searchObjectsIterative(Class type, SecurityViolationException, ExpressionEvaluationException { modelService.searchObjectsIterative(type, query, handler, null, getCurrentTask(), getCurrentResult()); } - + @Override - public T searchObjectByName(Class type, String name) + public T searchObjectByName(Class type, String name) throws SecurityViolationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SchemaException, ExpressionEvaluationException { ObjectQuery nameQuery = ObjectQueryUtil.createNameQuery(name, prismContext); List> foundObjects = modelService.searchObjects(type, nameQuery, null, getCurrentTask(), getCurrentResult()); @@ -992,9 +992,9 @@ public T searchObjectByName(Class type, String name) } return foundObjects.iterator().next().asObjectable(); } - + @Override - public T searchObjectByName(Class type, PolyString name) + public T searchObjectByName(Class type, PolyString name) throws SecurityViolationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SchemaException, ExpressionEvaluationException { ObjectQuery nameQuery = ObjectQueryUtil.createNameQuery(name, prismContext); List> foundObjects = modelService.searchObjects(type, nameQuery, null, getCurrentTask(), getCurrentResult()); @@ -1006,9 +1006,9 @@ public T searchObjectByName(Class type, PolyString nam } return foundObjects.iterator().next().asObjectable(); } - + @Override - public T searchObjectByName(Class type, PolyStringType name) + public T searchObjectByName(Class type, PolyStringType name) throws SecurityViolationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SchemaException, ExpressionEvaluationException { ObjectQuery nameQuery = ObjectQueryUtil.createNameQuery(name, prismContext); List> foundObjects = modelService.searchObjects(type, nameQuery, null, getCurrentTask(), getCurrentResult()); @@ -1058,11 +1058,11 @@ public ObjectDeltaType getResourceDelta(ModelContext context, String resourceOid ObjectDelta sum = ObjectDelta.summarize(deltas); return DeltaConvertor.toObjectDeltaType(sum); } - + public long getSequenceCounter(String sequenceOid) throws ObjectNotFoundException, SchemaException { return SequentialValueExpressionEvaluator.getSequenceCounter(sequenceOid, repositoryService, getCurrentResult()); } - + // orgstruct related methods @Override @@ -1263,7 +1263,7 @@ public List getMembers(String orgOid) throws SchemaException, ObjectNo .build(); return searchObjects(UserType.class, query, null); } - + @Override public String computeProjectionLifecycle(F focus, ShadowType shadow, ResourceType resource) { if (focus == null || shadow == null) { @@ -1292,7 +1292,7 @@ public String computeProjectionLifecycle(F focus, ShadowTy } return SchemaConstants.LIFECYCLE_PROPOSED; } - + public MidPointPrincipal getPrincipal() throws SecurityViolationException { return securityEnforcer.getPrincipal(); } @@ -1307,13 +1307,13 @@ public String getChannel() { public WorkflowService getWorkflowService() { return workflowService; } - + @Override public List getShadowsToActivate(Collection projectionContexts) { List shadows = new ArrayList<>(); - + for (ModelElementContext projectionCtx : projectionContexts) { - + List executedShadowDelas = projectionCtx.getExecutedDeltas(); for (ObjectDeltaOperation shadowDelta : executedShadowDelas) { if (shadowDelta.getExecutionResult().getStatus() == OperationResultStatus.SUCCESS && shadowDelta.getObjectDelta().getChangeType() == ChangeType.ADD) { @@ -1322,7 +1322,7 @@ public List getShadowsToActivate(Collection pro if (pLifecycleState != null && !pLifecycleState.isEmpty() && SchemaConstants.LIFECYCLE_PROPOSED.equals(pLifecycleState.getRealValue())) { shadows.add(shadow.asObjectable()); } - + } } } @@ -1343,19 +1343,19 @@ public String createPasswordResetLink(UserType userType) { public String createAccountActivationLink(UserType userType) { return createBaseConfirmationLink(SchemaConstants.ACCOUNT_ACTIVATION_PREFIX, userType.getOid()); } - + private String createBaseConfirmationLink(String prefix, UserType userType) { - return getDefaultHostname() + prefix + "?" + SchemaConstants.USER_ID + "=" + userType.getName().getOrig(); + return getDefaultHostname() + prefix + "?" + SchemaConstants.USER_ID + "=" + userType.getName().getOrig(); } - + private String createBaseConfirmationLink(String prefix, String oid) { - return getDefaultHostname() + prefix + "?" + SchemaConstants.USER_ID + "=" + oid; + return getDefaultHostname() + prefix + "?" + SchemaConstants.USER_ID + "=" + oid; } - + private String createTokenConfirmationLink(String prefix, UserType userType) { - return createBaseConfirmationLink(prefix, userType) + "&" + SchemaConstants.TOKEN + "=" + getNonce(userType); + return createBaseConfirmationLink(prefix, userType) + "&" + SchemaConstants.TOKEN + "=" + getNonce(userType); } - + private String getDefaultHostname(){ SystemConfigurationType systemConfiguration; try { @@ -1372,25 +1372,25 @@ private String getDefaultHostname(){ if (StringUtils.isBlank(defautlHostname)) { LOGGER.error("No hostname defined. It can break link generation."); } - + return defautlHostname; - - + + } - + private String getNonce(UserType user) { if (user.getCredentials() == null) { return null; } - + if (user.getCredentials().getNonce() == null) { return null; } - + if (user.getCredentials().getNonce().getValue() == null) { return null; } - + try { return getPlaintext(user.getCredentials().getNonce().getValue()); } catch (EncryptionException e) { diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/ModelExpressionThreadLocalHolder.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/ModelExpressionThreadLocalHolder.java index f5eb367fe7f..eca63a6463f 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/ModelExpressionThreadLocalHolder.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/ModelExpressionThreadLocalHolder.java @@ -42,7 +42,7 @@ public class ModelExpressionThreadLocalHolder { private static ThreadLocal>> expressionEnvironmentStackTl = new ThreadLocal<>(); - + public static void pushExpressionEnvironment(ExpressionEnvironment env) { Deque> stack = expressionEnvironmentStackTl.get(); if (stack == null) { @@ -51,7 +51,7 @@ public static void pushExpressionEnvironment(ExpressionEn } stack.push((ExpressionEnvironment)env); } - + public static void popExpressionEnvironment() { Deque> stack = expressionEnvironmentStackTl.get(); stack.pop(); @@ -64,7 +64,7 @@ public static ExpressionEnvironment getExpressionEnvir } return (ExpressionEnvironment) stack.peek(); } - + public static LensContext getLensContext() { ExpressionEnvironment env = getExpressionEnvironment(); if (env == null) { @@ -72,7 +72,7 @@ public static LensContext getLensContext() { } return (LensContext) env.getLensContext(); } - + public static LensProjectionContext getProjectionContext() { ExpressionEnvironment env = getExpressionEnvironment(); if (env == null) { @@ -80,7 +80,7 @@ public static LensProjectionContext getProjectionContext( } return env.getProjectionContext(); } - + public static Task getCurrentTask() { ExpressionEnvironment env = getExpressionEnvironment(); if (env == null) { @@ -88,7 +88,7 @@ public static Task getCurrentTask() { } return env.getCurrentTask(); } - + public static OperationResult getCurrentResult() { ExpressionEnvironment env = getExpressionEnvironment(); if (env == null) { @@ -96,7 +96,7 @@ public static OperationResult getCurrentResult() { } return env.getCurrentResult(); } - + // TODO move to better place public static PrismValueDeltaSetTriple> evaluateExpressionInContext(Expression, PrismPropertyDefinition> expression, ExpressionEvaluationContext context, Task task, OperationResult result) diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/SequentialValueExpressionEvaluator.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/SequentialValueExpressionEvaluator.java index 9c1791d2276..d83beb03260 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/SequentialValueExpressionEvaluator.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/SequentialValueExpressionEvaluator.java @@ -48,7 +48,7 @@ public class SequentialValueExpressionEvaluator evaluate(ExpressionEvaluationContext context) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException { long counter = getSequenceCounter(sequentialValueEvaluatorType.getSequenceRef().getOid(), repositoryService, context.getResult()); - + Object value = ExpressionUtil.convertToOutputValue(counter, outputDefinition, protector); - + Item output = outputDefinition.instantiate(); if (output instanceof PrismProperty) { PrismPropertyValue pValue = new PrismPropertyValue(value); @@ -71,22 +71,22 @@ public PrismValueDeltaSetTriple evaluate(ExpressionEvaluationContext context) } else { throw new UnsupportedOperationException("Can only generate values of property, not "+output.getClass()); } - + return ItemDelta.toDeltaSetTriple(output, null); } - + public static long getSequenceCounter(String sequenceOid, RepositoryService repositoryService, OperationResult result) throws ObjectNotFoundException, SchemaException { LensContext ctx = ModelExpressionThreadLocalHolder.getLensContext(); if (ctx == null) { throw new IllegalStateException("No lens context"); } - + Long counter = ctx.getSequenceCounter(sequenceOid); if (counter == null) { counter = repositoryService.advanceSequence(sequenceOid, result); ctx.setSequenceCounter(sequenceOid, counter); } - + return counter; } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/SequentialValueExpressionEvaluatorFactory.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/SequentialValueExpressionEvaluatorFactory.java index ae4f7298f1c..687bb95f36e 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/SequentialValueExpressionEvaluatorFactory.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/expr/SequentialValueExpressionEvaluatorFactory.java @@ -39,7 +39,7 @@ * */ public class SequentialValueExpressionEvaluatorFactory implements ExpressionEvaluatorFactory { - + private Protector protector; private PrismContext prismContext; private RepositoryService repositoryService; @@ -68,7 +68,7 @@ public ExpressionEvaluator throw new SchemaException("More than one evaluator specified in "+contextDescription); } JAXBElement evaluatorElement = evaluatorElements.iterator().next(); - + Object evaluatorTypeObject = null; if (evaluatorElement != null) { evaluatorTypeObject = evaluatorElement.getValue(); @@ -76,13 +76,13 @@ public ExpressionEvaluator if (evaluatorTypeObject != null && !(evaluatorTypeObject instanceof SequentialValueExpressionEvaluatorType)) { throw new SchemaException("SequentialValue expression evaluator cannot handle elements of type " + evaluatorTypeObject.getClass().getName()+" in "+contextDescription); } - + SequentialValueExpressionEvaluatorType seqEvaluatorType = (SequentialValueExpressionEvaluatorType)evaluatorTypeObject; - + if (seqEvaluatorType.getSequenceRef() == null || seqEvaluatorType.getSequenceRef().getOid() == null) { throw new SchemaException("Missing sequence reference in sequentialValue expression evaluator in "+contextDescription); } - + return new SequentialValueExpressionEvaluator(seqEvaluatorType, outputDefinition, protector, repositoryService, prismContext); } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/hooks/PolicyRuleEnforcerHook.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/hooks/PolicyRuleEnforcerHook.java index 541337dc747..a3eda4eda61 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/hooks/PolicyRuleEnforcerHook.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/hooks/PolicyRuleEnforcerHook.java @@ -49,20 +49,20 @@ /** * Hook used to enforce the policy rules that have the enforce action. - * + * * @author semancik * */ @Component public class PolicyRuleEnforcerHook implements ChangeHook { - + private static final Trace LOGGER = TraceManager.getTrace(PolicyRuleEnforcerHook.class); - + public static final String HOOK_URI = SchemaConstants.NS_MODEL + "/policy-rule-enforcer-hook-3"; - + @Autowired private HookRegistry hookRegistry; @Autowired private PrismContext prismContext; - + @PostConstruct public void init() { hookRegistry.registerChangeHook(HOOK_URI, this); @@ -79,7 +79,7 @@ private class EvaluationContext { @Override public HookOperationMode invoke(@NotNull ModelContext context, @NotNull Task task, @NotNull OperationResult result) throws PolicyViolationException { - + if (context.getState() == ModelState.PRIMARY) { EvaluationContext evalCtx = invokeInternal(context, task, result); if (!evalCtx.messages.isEmpty()) { @@ -119,7 +119,7 @@ private void evaluateFocusRules(EvaluationContext evalCtx, OperationResult result) { enforceTriggeredRules(evalCtx, context.getFocusContext().getPolicyRules()); } - + private void evaluateAssignmentRules(EvaluationContext evalCtx, ModelContext context, Task task, OperationResult result) { DeltaSetTriple evaluatedAssignmentTriple = context.getEvaluatedAssignmentTriple(); @@ -139,11 +139,11 @@ private void enforceTriggeredRules(EvaluationContext evalC if (triggers.isEmpty()) { continue; } - + if (!isEnforce(policyRule)) { continue; } - + for (EvaluatedPolicyRuleTrigger trigger: triggers) { if (trigger.getMessage() != null) { evalCtx.messages.add(trigger.getMessage()); @@ -154,12 +154,12 @@ private void enforceTriggeredRules(EvaluationContext evalC private boolean isEnforce(EvaluatedPolicyRule policyRule) { PolicyActionsType actions = policyRule.getActions(); - + if (actions == null) { // enforce is NO LONGER the default return false; } - + EnforcementPolicyActionType enforcement = actions.getEnforcement(); if (enforcement == null) { return false; diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/importer/ImportAccountsFromResourceTaskHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/importer/ImportAccountsFromResourceTaskHandler.java index 1948900c076..f4e151f8b1a 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/importer/ImportAccountsFromResourceTaskHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/importer/ImportAccountsFromResourceTaskHandler.java @@ -94,16 +94,16 @@ public class ImportAccountsFromResourceTaskHandler extends AbstractSearchIterati // It is a spring bean and it is supposed to handle all search task instances // Therefore it must not have task-specific fields. It can only contain fields specific to // all tasks of a specified type - + @Autowired(required = true) private TaskManager taskManager; - + @Autowired(required = true) private ProvisioningService provisioningService; @Autowired(required = true) private ChangeNotificationDispatcher changeNotificationDispatcher; - + private PrismPropertyDefinition objectclassPropertyDefinition; private static final Trace LOGGER = TraceManager.getTrace(ImportAccountsFromResourceTaskHandler.class); @@ -143,7 +143,7 @@ public void launch(ResourceType resource, QName objectclass, Task task, Operatio // Readable task name PolyStringType polyString = new PolyStringType("Import from resource " + resource.getName()); task.setName(polyString); - + // Set reference to the resource task.setObjectRef(ObjectTypeUtil.createObjectRef(resource)); @@ -181,28 +181,28 @@ public void launch(ResourceType resource, QName objectclass, Task task, Operatio @Override protected SynchronizeAccountResultHandler createHandler(TaskRunResult runResult, Task coordinatorTask, OperationResult opResult) { - + ResourceType resource = resolveObjectRef(ResourceType.class, runResult, coordinatorTask, opResult); if (resource == null) { return null; } - + return createHandler(resource, null, runResult, coordinatorTask, opResult); } // shadowToImport - it is used to derive objectClass/intent/kind when importing a single shadow private SynchronizeAccountResultHandler createHandler(ResourceType resource, PrismObject shadowToImport, TaskRunResult runResult, Task coordinatorTask, OperationResult opResult) { - + RefinedResourceSchema refinedSchema; ObjectClassComplexTypeDefinition objectClass; try { refinedSchema = RefinedResourceSchemaImpl.getRefinedSchema(resource, LayerType.MODEL, prismContext); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Refined schema:\n{}", refinedSchema.debugDump()); } - + if (shadowToImport != null) { objectClass = Utils.determineObjectClass(refinedSchema, shadowToImport); } else { @@ -220,9 +220,9 @@ private SynchronizeAccountResultHandler createHandler(ResourceType resource, Pri runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR); return null; } - + LOGGER.info("Start executing import from resource {}, importing object class {}", resource, objectClass.getTypeName()); - + SynchronizeAccountResultHandler handler = new SynchronizeAccountResultHandler(resource, objectClass, "import", coordinatorTask, changeNotificationDispatcher, taskManager); handler.setSourceChannel(SchemaConstants.CHANGE_CHANNEL_IMPORT); @@ -230,10 +230,10 @@ private SynchronizeAccountResultHandler createHandler(ResourceType resource, Pri handler.setStopOnError(false); handler.setContextDesc("from "+resource); handler.setLogObjectProgress(true); - + return handler; } - + @Override protected boolean initializeRun(SynchronizeAccountResultHandler handler, TaskRunResult runResult, Task task, OperationResult opResult) { @@ -267,15 +267,15 @@ public String getCategoryName(Task task) { public List getCategoryNames() { return null; } - + /** - * Imports a single shadow. Synchronously. The task is NOT switched to background by default. + * Imports a single shadow. Synchronously. The task is NOT switched to background by default. */ public boolean importSingleShadow(String shadowOid, Task task, OperationResult parentResult) throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { - + PrismObject shadow = provisioningService.getObject(ShadowType.class, shadowOid, null, task, parentResult); PrismObject resource = provisioningService.getObject(ResourceType.class, ShadowUtil.getResourceOid(shadow), null, task, parentResult); - + // Create a result handler just for one object. Invoke the handle() method manually. TaskRunResult runResult = new TaskRunResult(); SynchronizeAccountResultHandler resultHandler = createHandler(resource.asObjectable(), shadow, runResult, task, parentResult); @@ -284,19 +284,19 @@ public boolean importSingleShadow(String shadowOid, Task task, OperationResult p } // This is required for proper error reporting resultHandler.setStopOnError(true); - + boolean cont = initializeRun(resultHandler, runResult, task, parentResult); if (!cont) { return false; } - + cont = resultHandler.handle(shadow, parentResult); if (!cont) { return false; } - + finish(resultHandler, runResult, task, parentResult); - + return true; } } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/importer/ImportObjectsFromFileTaskHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/importer/ImportObjectsFromFileTaskHandler.java index 78f008e5ae0..23b6745d31c 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/importer/ImportObjectsFromFileTaskHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/importer/ImportObjectsFromFileTaskHandler.java @@ -65,10 +65,10 @@ public class ImportObjectsFromFileTaskHandler implements TaskHandler { @Autowired(required = true) private ChangeNotificationDispatcher changeNotificationDispatcher; - + @Autowired(required = true) private PrismContext prismContext; - + //private Map handlers; private PrismPropertyDefinition filenamePropertyDefinition; @@ -117,7 +117,7 @@ public void launch(File input, Task task, OperationResult parentResult) { // new PropertyPath(TaskType.F_EXTENSION, filenamePropertyDefinition.getName()), // filenamePropertyDefinition); // objectClassDelta.setValueToReplace(new PrismPropertyValue(input.getAbsolutePath())); -// ((Collection)modifications).add(objectClassDelta); +// ((Collection)modifications).add(objectClassDelta); try { PrismProperty filenameProp = filenamePropertyDefinition.instantiate(); filenameProp.setRealValue(input.getAbsolutePath()); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/importer/ObjectImporter.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/importer/ObjectImporter.java index 3a4bb2b3c05..3d356bb2bab 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/importer/ObjectImporter.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/importer/ObjectImporter.java @@ -96,7 +96,7 @@ public class ObjectImporter { private ModelService modelService; @Autowired(required = true) private Clock clock; - + private Migrator migrator = new Migrator(); // this method is responsible for computing the operation result! @@ -312,7 +312,7 @@ private void importObjectToRepository(PrismObject obje if (options == null) { options = new ImportOptionsType(); } - + if (BooleanUtils.isTrue(options.isKeepOid()) && object.getOid() == null) { // Try to check if there is existing object with the same type and name ObjectQuery query = ObjectQueryUtil.createNameQuery(object); @@ -322,19 +322,19 @@ private void importObjectToRepository(PrismObject obje object.setOid(oid); } } - + try { - String oid = addObject(object, BooleanUtils.isTrue(options.isOverwrite()), + String oid = addObject(object, BooleanUtils.isTrue(options.isOverwrite()), BooleanUtils.isFalse(options.isEncryptProtectedValues()), raw, task, result); - + if (object.canRepresent(TaskType.class)) { taskManager.onTaskCreate(oid, result); } result.recordSuccess(); - } catch (ObjectAlreadyExistsException e) { - if (BooleanUtils.isTrue(options.isOverwrite() && - BooleanUtils.isNotTrue(options.isKeepOid()) && + } catch (ObjectAlreadyExistsException e) { + if (BooleanUtils.isTrue(options.isOverwrite() && + BooleanUtils.isNotTrue(options.isKeepOid()) && object.getOid() == null)) { // This is overwrite, without keep oid, therefore we do not have conflict on OID // this has to be conflict on name. So try to delete the conflicting object and create new one (with a new OID). @@ -383,7 +383,7 @@ private void importObjectToRepository(PrismObject obje private String addObject(PrismObject object, boolean overwrite, boolean noCrypt, boolean raw, Task task, OperationResult parentResult) throws ObjectAlreadyExistsException, SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { - + ObjectDelta delta = ObjectDelta.createAddDelta(object); Collection> deltas = MiscSchemaUtil.createCollection(delta); ModelExecuteOptions options = new ModelExecuteOptions(); @@ -394,9 +394,9 @@ private String addObject(PrismObject object, boolean o if (noCrypt) { options.setNoCrypt(true); } - + modelService.executeChanges(deltas, options, task, parentResult); - + return deltas.iterator().next().getOid(); } @@ -463,7 +463,7 @@ private void validateWithDynamicSchemas(PrismObject ob LOGGER.error("Connector (OID:{}) referenced from the imported resource \"{}\" has schema problems: {}", new Object[]{connectorOid, resourceType.getName(), e.getMessage(), e}); return; } - + Element connectorSchemaElement = ConnectorTypeUtil.getConnectorXsdSchema(connector); PrismSchema connectorSchema; if (connectorSchemaElement == null) { @@ -483,7 +483,7 @@ private void validateWithDynamicSchemas(PrismObject ob result.recordFatalError("Definition of configuration container " + configContainerQName + " not found in the schema of of " + connector); return; } - + try { configurationContainer.applyDefinition(configContainerDef); } catch (SchemaException e) { @@ -499,12 +499,12 @@ private void validateWithDynamicSchemas(PrismObject ob result.recordFatalError("Configuration error in " + resource + " (probably incorrect connector property, see the following error): " + e.getMessage(), e); return; } - + // Also check integrity of the resource schema checkSchema(resourceType.getSchema(), "resource", result); result.computeStatus("Dynamic schema error"); - + } else if (object.canRepresent(ShadowType.class)) { // TODO @@ -581,6 +581,6 @@ private void generateIdentifiers(PrismObject object, R } } } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/integrity/ObjectIntegrityCheckTaskHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/integrity/ObjectIntegrityCheckTaskHandler.java index 13bc72f23c0..7c670eade4c 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/integrity/ObjectIntegrityCheckTaskHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/integrity/ObjectIntegrityCheckTaskHandler.java @@ -78,7 +78,7 @@ protected ObjectIntegrityCheckResultHandler createHandler(TaskRunResult runResul "check object integrity", "check object integrity", taskManager, prismContext, repositoryService, systemObjectCache, opResult); } - + @Override protected boolean initializeRun(ObjectIntegrityCheckResultHandler handler, TaskRunResult runResult, Task task, OperationResult opResult) { diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/integrity/ShadowIntegrityCheckTaskHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/integrity/ShadowIntegrityCheckTaskHandler.java index e10fbd901b8..925ae1169b8 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/integrity/ShadowIntegrityCheckTaskHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/integrity/ShadowIntegrityCheckTaskHandler.java @@ -74,7 +74,7 @@ public class ShadowIntegrityCheckTaskHandler extends AbstractSearchIterativeTask @Autowired private SynchronizationService synchronizationService; - + @Autowired private SystemObjectCache systemObjectCache; @@ -97,7 +97,7 @@ protected ShadowIntegrityCheckResultHandler createHandler(TaskRunResult runResul "check shadow integrity", "check shadow integrity", taskManager, prismContext, provisioningService, matchingRuleRegistry, repositoryService, synchronizationService, systemObjectCache, opResult); } - + @Override protected boolean initializeRun(ShadowIntegrityCheckResultHandler handler, TaskRunResult runResult, Task task, OperationResult opResult) { diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/AbstractConstruction.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/AbstractConstruction.java index 43172bd26dc..0fc79414030 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/AbstractConstruction.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/AbstractConstruction.java @@ -85,7 +85,7 @@ public LensContext getLensContext() { public void setLensContext(LensContext lensContext) { this.lensContext = lensContext; } - + public T getConstructionType() { return constructionType; } @@ -117,7 +117,7 @@ void setPrismContext(PrismContext prismContext) { public String getDescription() { return constructionType.getDescription(); } - + public boolean isWeak() { return constructionType.getStrength() == ConstructionStrengthType.WEAK; } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/AssignmentPathImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/AssignmentPathImpl.java index 21f51c9002d..27227c86b58 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/AssignmentPathImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/AssignmentPathImpl.java @@ -34,21 +34,21 @@ * */ public class AssignmentPathImpl implements AssignmentPath { - + private final List segments = new ArrayList<>(); public AssignmentPathImpl() { } - + @Override public List getSegments() { return segments; } - + public void add(AssignmentPathSegmentImpl segment) { segments.add(segment); } - + public void removeLast(AssignmentPathSegmentImpl segment) { AssignmentPathSegmentImpl last = last(); if (last == null) { @@ -64,7 +64,7 @@ public void removeLast(AssignmentPathSegmentImpl segment) { public AssignmentPathSegmentImpl first() { return segments.get(0); } - + @Override public boolean isEmpty() { return segments.isEmpty(); @@ -95,7 +95,7 @@ public AssignmentPathSegmentImpl beforeLast(int n) { return segments.get(segments.size()-1-n); } } - + @Override public int countTargetOccurrences(ObjectType target) { if (target == null) { @@ -163,7 +163,7 @@ public String debugDump(int indent) { } return sb.toString(); } - + @Override public void shortDump(StringBuilder sb) { ObjectType previousTarget = null; diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/AssignmentPathSegmentImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/AssignmentPathSegmentImpl.java index 7ae5e3883a8..8e8742b8953 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/AssignmentPathSegmentImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/AssignmentPathSegmentImpl.java @@ -332,7 +332,7 @@ public ObjectType getTarget() { public void setTarget(ObjectType target) { this.target = target; } - + @Override public ObjectType getSource() { return source; @@ -393,7 +393,7 @@ public ObjectType getOrderOneObject() { public void setOrderOneObject(ObjectType varThisObject) { this.varThisObject = varThisObject; } - + public boolean isProcessMembership() { return processMembership; } @@ -468,7 +468,7 @@ private static boolean isMatchingConstraint(OrderConstraintsType orderConstraint return XsdTypeMapper.isMatchingMultiplicity(evaluationOrderInt, orderMin, orderMax); } } - + @Override public boolean isDelegation() { return ObjectTypeUtil.isDelegationRelation(relation); @@ -518,7 +518,7 @@ public String toString() { sb.append(")"); return sb.toString(); } - + @Override public void shortDump(StringBuilder sb) { evaluationOrder.shortDump(sb); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/AssignmentPathVariables.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/AssignmentPathVariables.java index 986bd6472a2..b6f7fcb3aec 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/AssignmentPathVariables.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/AssignmentPathVariables.java @@ -82,5 +82,5 @@ public PrismObject getImmediateRole() { public void setImmediateRole(PrismObject immediateRole) { this.immediateRole = immediateRole; } - + } 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 b403515a6cf..1924b3a9fd9 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 @@ -134,13 +134,13 @@ public class ChangeExecutor { @Autowired private ModelObjectResolver objectResolver; - + @Autowired private OperationalDataManager metadataManager; @Autowired private PolicyRuleProcessor policyRuleProcessor; - + @Autowired private CredentialsProcessor credentialsProcessor; @@ -182,7 +182,7 @@ public boolean executeChanges(LensContext context, Tas OperationResult subResult = result.createSubresult( OPERATION_EXECUTE_FOCUS + "." + focusContext.getObjectTypeClass().getSimpleName()); - + try { // Will remove credential deltas or hash them focusDelta = credentialsProcessor.transformFocusExectionDelta(context, focusDelta); @@ -545,7 +545,7 @@ private void updateLinks( LOGGER.trace("Updating situation after shadow was linked."); updateSituationInShadow(task, SynchronizationSituationType.LINKED, focusObjectContext, projCtx, result); - } else { + } else { // Link should NOT exist if (!focusContext.isDelete()) { @@ -586,7 +586,7 @@ private void updateLinks( projOid); updateSituationInShadow(task, null, focusObjectContext, projCtx, result); } - // Not linked, that's OK + // Not linked, that's OK } } @@ -1060,29 +1060,29 @@ private ProvisioningOperationOptions copyFromModelOptions(ModelExecuteOptions op provisioningOptions.setOverwrite(options.getOverwrite()); return provisioningOptions; } - - private ProvisioningOperationOptions getProvisioningOptions(LensContext context, + + private ProvisioningOperationOptions getProvisioningOptions(LensContext context, ModelExecuteOptions modelOptions) { if (modelOptions == null && context != null) { modelOptions = context.getOptions(); } ProvisioningOperationOptions provisioningOptions = copyFromModelOptions(modelOptions); - + if (context != null && context.getChannel() != null) { - + if (context.getChannel().equals(QNameUtil.qNameToUri(SchemaConstants.CHANGE_CHANNEL_RECON))) { // TODO: this is probably wrong. We should not have special case // for recon channel! This should be handled by the provisioning task // setting the right options there. provisioningOptions.setCompletePostponed(false); } - + if (context.getChannel().equals(SchemaConstants.CHANGE_CHANNEL_DISCOVERY_URI)) { // We want to avoid endless loops in error handling. provisioningOptions.setDoNotDiscovery(true); } } - + return provisioningOptions; } @@ -1156,7 +1156,7 @@ private void executeAddition(Object } else if (objectTypeToAdd instanceof NodeType) { throw new UnsupportedOperationException("NodeType cannot be added using model interface"); } else if (ObjectTypes.isManagedByProvisioning(objectTypeToAdd)) { - + ProvisioningOperationOptions provisioningOptions = getProvisioningOptions(context, options); oid = addProvisioningObject(objectToAdd, context, objectContext, provisioningOptions, @@ -1294,7 +1294,7 @@ private void executeModification(Ob } } - + private String addTask(TaskType task, OperationResult result) throws ObjectAlreadyExistsException, ObjectNotFoundException { @@ -1419,7 +1419,7 @@ private OperationProvisioningScript user = context.getFocusContext().getObjectOld(); } } - + LensProjectionContext projectionCtx = (LensProjectionContext) objectContext; PrismObject shadow = null; if (projectionCtx.getObjectNew() != null) { @@ -1429,7 +1429,7 @@ private OperationProvisioningScript } else { shadow = projectionCtx.getObjectOld(); } - + if (shadow == null) { //put at least something shadow = resourceObject.clone(); @@ -1456,7 +1456,7 @@ private OperationProvisioningScriptsType evaluateScript(OperationProvisioningScr OperationResult result) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException { OperationProvisioningScriptsType outScripts = new OperationProvisioningScriptsType(); - + if (resourceScripts != null) { OperationProvisioningScriptsType scripts = resourceScripts.clone(); for (OperationProvisioningScriptType script : scripts.getScript()) { @@ -1489,23 +1489,23 @@ private OperationProvisioningScriptsType evaluateScript(OperationProvisioningScr return outScripts; } - + private boolean evaluateScriptCondition(OperationProvisioningScriptType script, ExpressionVariables variables, Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException { ExpressionType condition = script.getCondition(); if (condition == null) { return true; } - + PrismPropertyValue conditionOutput = ExpressionUtil.evaluateCondition(variables, condition, expressionFactory, " condition for provisioning script ", task, result); if (conditionOutput == null) { return true; } - + Boolean conditionOutputValue = conditionOutput.getValue(); - + return BooleanUtils.isNotFalse(conditionOutputValue); - + } private void evaluateScriptArgument(ProvisioningScriptArgumentType argument, @@ -1622,7 +1622,7 @@ private void executeReconciliationS } finally { ModelExpressionThreadLocalHolder.popExpressionEnvironment(); } - + } } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/Clockwork.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/Clockwork.java index caa46f2c585..2d54d66706c 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/Clockwork.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/Clockwork.java @@ -116,14 +116,14 @@ */ @Component public class Clockwork { - + private static final int DEFAULT_NUMBER_OF_RESULTS_TO_KEEP = 5; private static final int DEFAULT_MAX_CONFLICT_RESOLUTION_ATTEMPTS = 1; // synchronize with common-core-3.xsd private static final int DEFAULT_CONFLICT_RESOLUTION_DELAY_UNIT = 5000; // synchronize with common-core-3.xsd private static final Trace LOGGER = TraceManager.getTrace(Clockwork.class); - + // This is ugly // TODO: cleanup @Autowired private Projector projector; @@ -149,9 +149,9 @@ public class Clockwork { @Autowired @Qualifier("cacheRepositoryService") private transient RepositoryService repositoryService; - + private LensDebugListener debugListener; - + public LensDebugListener getDebugListener() { return debugListener; } @@ -348,18 +348,18 @@ private int getMaxClicks(LensContext context, Operatio } public HookOperationMode click(LensContext context, Task task, OperationResult result) throws SchemaException, PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException, ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException { - + // DO NOT CHECK CONSISTENCY of the context here. The context may not be fresh and consistent yet. Project will fix // that. Check consistency afterwards (and it is also checked inside projector several times). - + if (context.getDebugListener() == null) { context.setDebugListener(debugListener); } - + try { - + XMLGregorianCalendar now = clock.currentTimeXMLGregorianCalendar(); - + // We need to determine focus before auditing. Otherwise we will not know user // for the accounts (unless there is a specific delta for it). // This is ugly, but it is the easiest way now (TODO: cleanup). @@ -398,11 +398,11 @@ public HookOperationMode click(LensContext context, Ta } else { LOGGER.trace("Skipping projection because the context is fresh and projection for current wave has already run"); } - + if (!context.isRequestAuthorized()) { authorizeContextRequest(context, task, result); } - + LensUtil.traceContext(LOGGER, "CLOCKWORK (" + state + ")", "before processing", true, context, false); if (InternalsConfig.consistencyChecks) { try { @@ -414,9 +414,9 @@ public HookOperationMode click(LensContext context, Ta if (InternalsConfig.encryptionChecks && !ModelExecuteOptions.isNoCrypt(context.getOptions())) { context.checkEncrypted(); } - + // LOGGER.info("CLOCKWORK: {}: {}", state, context); - + switch (state) { case INITIAL: processInitialToPrimary(context, task, result); @@ -433,11 +433,11 @@ public HookOperationMode click(LensContext context, Ta debugListener.afterSync(context); } return mode; - } + } result.recomputeStatus(); result.cleanupResult(); return invokeHooks(context, task, result); - + } catch (CommunicationException | ConfigurationException | ExpressionEvaluationException | ObjectNotFoundException | PolicyViolationException | SchemaException | SecurityViolationException | RuntimeException | ObjectAlreadyExistsException e) { @@ -445,18 +445,18 @@ public HookOperationMode click(LensContext context, Ta throw e; } } - + /** * Invokes hooks, if there are any. * * @return * - ERROR, if any hook reported error; otherwise returns * - BACKGROUND, if any hook reported switching to background; otherwise - * - FOREGROUND (if all hooks reported finishing on foreground) + * - FOREGROUND (if all hooks reported finishing on foreground) */ private HookOperationMode invokeHooks(LensContext context, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException { // TODO: following two parts should be merged together in later versions - + // Execute configured scripting hooks PrismObject systemConfiguration = systemObjectCache.getSystemConfiguration(result); // systemConfiguration may be null in some tests @@ -517,7 +517,7 @@ private HookOperationMode invokeHooks(LensContext context, Task task, OperationR } } } - + // Execute registered Java hooks HookOperationMode resultMode = HookOperationMode.FOREGROUND; if (hookRegistry != null) { @@ -537,14 +537,14 @@ private HookOperationMode invokeHooks(LensContext context, Task task, OperationR private void evaluateScriptingHook(LensContext context, HookType hookType, - ScriptExpressionEvaluatorType scriptExpressionEvaluatorType, String shortDesc, Task task, OperationResult result) + ScriptExpressionEvaluatorType scriptExpressionEvaluatorType, String shortDesc, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException { - + LOGGER.trace("Evaluating {}", shortDesc); // TODO: it would be nice to cache this // null output definition: this script has no output ScriptExpression scriptExpression = scriptExpressionFactory.createScriptExpression(scriptExpressionEvaluatorType, null, shortDesc); - + ExpressionVariables variables = new ExpressionVariables(); variables.addVariableDefinition(ExpressionConstants.VAR_PRISM_CONTEXT, prismContext); variables.addVariableDefinition(ExpressionConstants.VAR_MODEL_CONTEXT, context); @@ -554,55 +554,55 @@ private void evaluateScriptingHook(LensContext context, HookType hookType, focus = focusContext.getObjectAny(); } variables.addVariableDefinition(ExpressionConstants.VAR_FOCUS, focus); - + Utils.evaluateScript(scriptExpression, context, variables, false, shortDesc, task, result); LOGGER.trace("Finished evaluation of {}", shortDesc); } private void processInitialToPrimary(LensContext context, Task task, OperationResult result) { // Context loaded, nothing special do. Bump state to PRIMARY. - context.setState(ModelState.PRIMARY); + context.setState(ModelState.PRIMARY); } - + private void processPrimaryToSecondary(LensContext context, Task task, OperationResult result) { // Nothing to do now. The context is already recomputed. context.setState(ModelState.SECONDARY); } - + private void processSecondary(LensContext context, Task task, OperationResult result) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException, PolicyViolationException { if (context.getExecutionWave() > context.getMaxWave() + 1) { context.setState(ModelState.FINAL); return; } - + Holder restartRequestedHolder = new Holder<>(); - + LensUtil.partialExecute("execution", - () -> { + () -> { boolean restartRequested = changeExecutor.executeChanges(context, task, result); restartRequestedHolder.setValue(restartRequested); - }, + }, context.getPartialProcessingOptions()::getExecution); - + audit(context, AuditEventStage.EXECUTION, task, result); - + rotContextIfNeeded(context); boolean restartRequested = false; if (restartRequestedHolder.getValue() != null) { restartRequested = restartRequestedHolder.getValue(); } - + if (!restartRequested) { // TODO what if restart is requested indefinitely? context.incrementExecutionWave(); } else { // explicitly rot context? } - + LensUtil.traceContext(LOGGER, "CLOCKWORK (" + context.getState() + ")", "change execution", false, context, false); } - + /** * Force recompute for the next execution wave. Recompute only those contexts that were changed. * This is more intelligent than context.rot() @@ -620,7 +620,7 @@ private void rotContextIfNeeded(LensContext context) t // } ObjectDelta execDelta = projectionContext.getExecutableDelta(); if (isShadowDeltaSignificant(execDelta)) { - + LOGGER.debug("Context rot: projection {} rotten because of executable delta {}", projectionContext, execDelta); projectionContext.setFresh(false); projectionContext.setFullShadow(false); @@ -648,8 +648,8 @@ private void rotContextIfNeeded(LensContext context) t } //remove secondary deltas from other than execution wave - we need to recompute them.. // cleanUpSecondaryDeltas(context); - - + + } if (rot) { context.setFresh(false); @@ -664,7 +664,7 @@ private void rotContextIfNeeded(LensContext context) t // ObjectDeltaWaves executionWaveDeltaList = focusContext.getSecondaryDeltas(); // executionWaveDeltaList.clear(); // } - + private

    boolean isShadowDeltaSignificant(ObjectDelta

    delta) { if (delta == null || delta.isEmpty()) { return false; @@ -678,17 +678,17 @@ private

    boolean isShadowDeltaSignificant(ObjectDelta

    d } return false; } - + private HookOperationMode processFinal(LensContext context, Task task, OperationResult result) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException, PolicyViolationException { auditFinalExecution(context, task, result); logFinalReadable(context, task, result); recordOperationExecution(context, null, task, result); - + HookOperationMode opmode = personaProcessor.processPersonaChanges(context, task, result); if (opmode == HookOperationMode.BACKGROUND) { return opmode; } - + return triggerReconcileAffected(context, task, result); } @@ -970,7 +970,7 @@ private void audit(LensContext context, AuditEventStag auditEvent(context, stage, null, false, task, result); } } - + /** * Make sure that at least one execution is audited if a request was already audited. We don't want * request without execution in the audit logs. @@ -984,7 +984,7 @@ private void auditFinalExecution(LensContext context, } auditEvent(context, AuditEventStage.EXECUTION, null, true, task, result); } - + private void processClockworkException(LensContext context, Exception e, Task task, OperationResult result) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException { LOGGER.trace("Processing clockwork exception {}", e.toString()); @@ -994,9 +994,9 @@ private void processClockworkException(LensContext con reclaimSequences(context, task, result); } - private void auditEvent(LensContext context, AuditEventStage stage, + private void auditEvent(LensContext context, AuditEventStage stage, XMLGregorianCalendar timestamp, boolean alwaysAudit, Task task, OperationResult result) throws SchemaException { - + PrismObject primaryObject; ObjectDelta primaryDelta; if (context.getFocusContext() != null) { @@ -1020,7 +1020,7 @@ private void auditEvent(LensContext context, AuditEven } primaryDelta = projection.getDelta(); } - + AuditEventType eventType; if (primaryDelta == null) { eventType = AuditEventType.SYNCHRONIZATION; @@ -1033,17 +1033,17 @@ private void auditEvent(LensContext context, AuditEven } else { throw new IllegalStateException("Unknown state of delta "+primaryDelta); } - + AuditEventRecord auditRecord = new AuditEventRecord(eventType, stage); - + if (primaryObject != null) { auditRecord.setTarget(primaryObject.clone()); // } else { // throw new IllegalStateException("No primary object in:\n"+context.dump()); } - + auditRecord.setChannel(context.getChannel()); - + if (stage == AuditEventStage.REQUEST) { Collection> clonedDeltas = ObjectDeltaOperation.cloneDeltaCollection(context.getPrimaryChanges()); checkNamesArePresent(clonedDeltas, primaryObject); @@ -1064,15 +1064,15 @@ private void auditEvent(LensContext context, AuditEven } else { throw new IllegalStateException("Unknown audit stage "+stage); } - + if (timestamp != null) { auditRecord.setTimestamp(XmlTypeConverter.toMillis(timestamp)); } - + addRecordMessage(auditRecord, result); - + auditService.audit(auditRecord, task); - + if (stage == AuditEventStage.EXECUTION) { // We need to clean up so these deltas will not be audited again in next wave context.markExecutedDeltasAudited(); @@ -1118,7 +1118,7 @@ private void addRecordMessage(AuditEventRecord auditRecord, OperationResult resu if (!StringUtils.isEmpty(message)) { if (sb.length() != 0) { sb.append("; "); - } + } sb.append(message); } } @@ -1137,7 +1137,7 @@ public static void throwException(Throwable e) throws ObjectAlreadyExistsExcepti throw new SystemException("Unexpected exception "+e.getClass()+" "+e.getMessage(), e); } } - + /** * Logs the entire operation in a human-readable fashion. */ @@ -1145,7 +1145,7 @@ private void logFinalReadable(LensContext context, Tas if (!LOGGER.isDebugEnabled()) { return; } - + // a priori: sync delta boolean hasSyncDelta = false; for (LensProjectionContext projectionContext: context.getProjectionContexts()) { @@ -1154,20 +1154,20 @@ private void logFinalReadable(LensContext context, Tas hasSyncDelta = true; } } - + Collection> executedDeltas = context.getExecutedDeltas(); if (!hasSyncDelta && executedDeltas == null || executedDeltas.isEmpty()) { // Not worth mentioning return; } - + StringBuilder sb = new StringBuilder(); String channel = context.getChannel(); if (channel != null) { sb.append("Channel: ").append(channel).append("\n"); } - - + + if (hasSyncDelta) { sb.append("Triggered by synchronization delta\n"); for (LensProjectionContext projectionContext: context.getProjectionContexts()) { @@ -1194,7 +1194,7 @@ private void logFinalReadable(LensContext context, Tas sb.append("\n"); } } - + // focus primary LensFocusContext focusContext = context.getFocusContext(); if (focusContext != null) { @@ -1206,7 +1206,7 @@ private void logFinalReadable(LensContext context, Tas sb.append("\n"); } } - + // projection primary Collection> projPrimaryDeltas = new ArrayList>(); for (LensProjectionContext projectionContext: context.getProjectionContexts()) { @@ -1223,7 +1223,7 @@ private void logFinalReadable(LensContext context, Tas sb.append("\n"); } } - + if (focusContext != null) { sb.append("Focus: ").append(focusContext.getHumanReadableName()).append("\n"); } @@ -1237,7 +1237,7 @@ private void logFinalReadable(LensContext context, Tas sb.append("\n"); } } - + if (executedDeltas == null || executedDeltas.isEmpty()) { sb.append("Executed: nothing\n"); } else { @@ -1252,17 +1252,17 @@ private void logFinalReadable(LensContext context, Tas sb.append("\n"); } } - + LOGGER.debug("\n###[ CLOCKWORK SUMMARY ]######################################\n{}" + "##############################################################", sb.toString()); } - + private void authorizeContextRequest(LensContext context, Task task, OperationResult parentResult) throws SecurityViolationException, SchemaException, ObjectNotFoundException { OperationResult result = parentResult.createMinorSubresult(Clockwork.class.getName()+".authorizeRequest"); LOGGER.trace("Authorizing request"); try { - + final LensFocusContext focusContext = context.getFocusContext(); OwnerResolver ownerResolver = new LensOwnerResolver<>(context, objectResolver, task, result); if (focusContext != null) { @@ -1273,15 +1273,15 @@ private void authorizeContextRequest(LensContext conte } context.setRequestAuthorized(true); result.recordSuccess(); - + LOGGER.trace("Request authorized"); - + } catch (Throwable e) { result.recordFatalError(e); throw e; } } - + private ObjectSecurityConstraints authorizeElementContext(LensContext context, LensElementContext elementContext, OwnerResolver ownerResolver, boolean isFocus, Task task, OperationResult result) throws SecurityViolationException, SchemaException, ObjectNotFoundException { ObjectDelta primaryDelta = elementContext.getPrimaryDelta(); @@ -1290,8 +1290,8 @@ private ObjectSecurityConstraints a primaryDelta = primaryDelta.clone(); PrismObject object = elementContext.getObjectCurrent(); if (object == null) { - // This may happen when object is being added. - // But also in cases such as assignment of account and modification of + // This may happen when object is being added. + // But also in cases such as assignment of account and modification of // the same account in one operation object = elementContext.getObjectNew(); } @@ -1322,13 +1322,13 @@ private ObjectSecurityConstraints a throw new AuthorizationException("Access denied"); } else { // No explicit decision for assignment modification yet - // process each assignment individually - authorizeAssignmentRequest(context, ModelAuthorizationAction.ASSIGN.getUrl(), + // process each assignment individually + authorizeAssignmentRequest(context, ModelAuthorizationAction.ASSIGN.getUrl(), object, ownerResolver, PlusMinusZero.PLUS, true, task, result); - + // We want to allow unassignment even if there are policies. Otherwise we would not be able to get // rid of that assignment - authorizeAssignmentRequest(context, ModelAuthorizationAction.UNASSIGN.getUrl(), + authorizeAssignmentRequest(context, ModelAuthorizationAction.UNASSIGN.getUrl(), object, ownerResolver,PlusMinusZero.MINUS, false, task, result); } } @@ -1344,7 +1344,7 @@ private ObjectSecurityConstraints a } // Process credential changes explicitly. There is a special authorization for that. - + if (!primaryDelta.isDelete()) { if (primaryDelta.isAdd()) { PrismObject objectToAdd = primaryDelta.getObjectToAdd(); @@ -1387,7 +1387,7 @@ private ObjectSecurityConstraints a // TODO: optimize, avoid evaluating the constraints twice securityEnforcer.authorize(operationUrl, getRequestAuthorizationPhase(context) , object, primaryDelta, null, ownerResolver, result); } - + return securityConstraints; } else { return null; @@ -1424,27 +1424,27 @@ private void authorizeAssignmentRequ ObjectReferenceType targetRef = changedAssignment.getTargetRef(); if (targetRef == null || targetRef.getOid() == null) { if (LOGGER.isDebugEnabled()) { - LOGGER.debug("{} of non-target assignment denied", + LOGGER.debug("{} of non-target assignment denied", assignActionUrl.substring(assignActionUrl.lastIndexOf('#') + 1)); } securityEnforcer.failAuthorization("with assignment", getRequestAuthorizationPhase(context), object, null, null, result); } // We do not worry about performance here too much. The target was already evaluated. This will be retrieved from repo cache anyway. PrismObject target = objectResolver.resolve(targetRef.asReferenceValue(), "resolving assignment target", task, result); - + if (prohibitPolicies) { if (changedAssignment.getPolicyRule() != null || !changedAssignment.getPolicyException().isEmpty() || !changedAssignment.getPolicySituation().isEmpty()) { securityEnforcer.failAuthorization("with assignment because of policies in the assignment", getRequestAuthorizationPhase(context), object, null, target, result); } } - + ObjectDelta assignmentObjectDelta = object.createModifyDelta(); ContainerDelta assignmentDelta = assignmentObjectDelta.createContainerModification(FocusType.F_ASSIGNMENT); // We do not care if this is add or delete. All that matters for authorization is that it is in a delta. assignmentDelta.addValuesToAdd(changedAssignment.asPrismContainerValue().clone()); if (securityEnforcer.isAuthorized(assignActionUrl, getRequestAuthorizationPhase(context), object, assignmentObjectDelta, target, ownerResolver)) { if (LOGGER.isDebugEnabled()) { - LOGGER.debug("{} of target {} to {} allowed with {} authorization", + LOGGER.debug("{} of target {} to {} allowed with {} authorization", assignActionUrl.substring(assignActionUrl.lastIndexOf('#') + 1), target, object, assignActionUrl); } @@ -1454,7 +1454,7 @@ private void authorizeAssignmentRequ if (ObjectTypeUtil.isDelegationRelation(relation)) { if (securityEnforcer.isAuthorized(ModelAuthorizationAction.DELEGATE.getUrl(), getRequestAuthorizationPhase(context), object, assignmentObjectDelta, target, ownerResolver)) { if (LOGGER.isDebugEnabled()) { - LOGGER.debug("{} of target {} to {} allowed with {} authorization", + LOGGER.debug("{} of target {} to {} allowed with {} authorization", assignActionUrl.substring(assignActionUrl.lastIndexOf('#') + 1), target, object, ModelAuthorizationAction.DELEGATE.getUrl()); } @@ -1462,7 +1462,7 @@ private void authorizeAssignmentRequ } } if (LOGGER.isDebugEnabled()) { - LOGGER.debug("{} of target {} to {} denied", + LOGGER.debug("{} of target {} to {} denied", assignActionUrl.substring(assignActionUrl.lastIndexOf('#')), target, object); } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/Construction.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/Construction.java index 1faa654697f..26c6b3b56d4 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/Construction.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/Construction.java @@ -82,7 +82,7 @@ * resource object. It in fact reflects the definition of ConstructionType but * it also contains "live" objects and can evaluate the construction. It also * contains intermediary and side results of the evaluation. - * + * * @author Radovan Semancik * * This class is Serializable but it is not in fact serializable. It @@ -490,7 +490,7 @@ private void evaluateAssociations(Task task, OperationResult result) throw new SchemaException("No outbound section in definition of association " + assocName + " in construction in " + getSource()); } - Mapping, PrismContainerDefinition> assocMapping = + Mapping, PrismContainerDefinition> assocMapping = evaluateAssociation(associationDefinitionType, task, result); if (assocMapping != null) { associationMappings.add(assocMapping); 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 f341c08377b..e780df280d3 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 @@ -28,19 +28,19 @@ * */ public class ConstructionPack implements DebugDumpable { - + private final Collection> constructions = new ArrayList<>(); private boolean forceRecon; private boolean hasValidAssignment = false; - + public boolean isForceRecon() { return forceRecon; } - + public void setForceRecon(boolean forceRecon) { this.forceRecon = forceRecon; } - + public Collection> getConstructions() { return constructions; } @@ -56,7 +56,7 @@ public boolean hasValidAssignment() { public void setHasValidAssignment(boolean hasValidAssignment) { this.hasValidAssignment = hasValidAssignment; } - + public boolean hasStrongConstruction() { for (PrismPropertyValue construction: constructions) { if (!construction.getValue().isWeak()) { @@ -65,7 +65,7 @@ public boolean hasStrongConstruction() { } return false; } - + @Override public String toString() { return "ConstructionPack(" + SchemaDebugUtil.prettyPrint(constructions) + (forceRecon ? ", forceRecon" : "") + ")"; diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ContextFactory.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ContextFactory.java index 839460ff20e..3c0e6af4813 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ContextFactory.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ContextFactory.java @@ -52,16 +52,16 @@ */ @Component public class ContextFactory { - + @Autowired(required = true) PrismContext prismContext; @Autowired(required = true) private ProvisioningService provisioningService; - + @Autowired(required = true) Protector protector; - + public LensContext createContext( Collection> deltas, ModelExecuteOptions options, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException { ObjectDelta focusDelta = null; @@ -76,7 +76,7 @@ public LensContext createContext( if (confDelta != null) { throw new IllegalArgumentException("Mixed configuration and focus deltas in one executeChanges invocation"); } - + focusClass = (Class) typeClass; if (!delta.isAdd() && delta.getOid() == null) { throw new IllegalArgumentException("Delta "+delta+" does not have an OID"); @@ -95,7 +95,7 @@ public LensContext createContext( if (confDelta != null) { throw new IllegalArgumentException("Mixed configuration and projection deltas in one executeChanges invocation"); } - + projectionDeltas.add((ObjectDelta) delta); } else { if (confDelta != null) { @@ -104,11 +104,11 @@ public LensContext createContext( confDelta = delta; } } - + if (confDelta != null) { focusClass = (Class) confDelta.getObjectTypeClass(); } - + if (focusClass == null) { focusClass = determineFocusClass(); } @@ -116,30 +116,30 @@ public LensContext createContext( context.setChannel(task.getChannel()); context.setOptions(options); context.setDoReconciliationForAllProjections(ModelExecuteOptions.isReconcile(options)); - + if (confDelta != null) { LensFocusContext focusContext = context.createFocusContext(); focusContext.setPrimaryDelta((ObjectDelta) confDelta); - + } else { - + if (focusDelta != null) { LensFocusContext focusContext = context.createFocusContext(); focusContext.setPrimaryDelta(focusDelta); } - + for (ObjectDelta projectionDelta: projectionDeltas) { LensProjectionContext projectionContext = context.createProjectionContext(); if (context.isDoReconciliationForAllProjections()) { projectionContext.setDoReconciliation(true); } projectionContext.setPrimaryDelta(projectionDelta); - - // We are little bit more liberal regarding projection deltas. + + // We are little bit more liberal regarding projection deltas. // If the deltas represent shadows we tolerate missing attribute definitions. // We try to add the definitions by calling provisioning provisioningService.applyDefinition(projectionDelta, task, result); - + if (projectionDelta instanceof ShadowDiscriminatorObjectDelta) { ShadowDiscriminatorObjectDelta shadowDelta = (ShadowDiscriminatorObjectDelta)projectionDelta; projectionContext.setResourceShadowDiscriminator(shadowDelta.getDiscriminator()); @@ -149,18 +149,18 @@ public LensContext createContext( } } } - + } // This forces context reload before the next projection context.rot("context initialization"); - + if (InternalsConfig.consistencyChecks) context.checkConsistence(); - + return context; } - - + + public LensContext createRecomputeContext( PrismObject object, ModelExecuteOptions options, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException { Class typeClass = object.getCompileTimeClass(); @@ -176,7 +176,7 @@ public LensContext createRecompu context.setLazyAuditRequest(true); return context; } - + public LensContext createRecomputeFocusContext( Class focusType, PrismObject focus, ModelExecuteOptions options, Task task, OperationResult result) { LensContext syncContext = new LensContext(focusType, @@ -188,7 +188,7 @@ public LensContext createRecomputeFocusContext( syncContext.setDoReconciliationForAllProjections(ModelExecuteOptions.isReconcile(options)); return syncContext; } - + public LensContext createRecomputeProjectionContext( PrismObject shadow, ModelExecuteOptions options, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException { provisioningService.applyDefinition(shadow, task, result); @@ -201,17 +201,17 @@ public LensContext createRecomputeProjectionContext( syncContext.setChannel(QNameUtil.qNameToUri(SchemaConstants.CHANGE_CHANNEL_RECOMPUTE)); return syncContext; } - + /** * Creates empty lens context for synchronization purposes, filling in only the very basic metadata (such as channel). */ public LensContext createSyncContext(Class focusClass, ResourceObjectShadowChangeDescription change) { - + LensContext context = new LensContext(focusClass, prismContext, provisioningService); context.setChannel(change.getSourceChannel()); return context; } - + public static Class determineFocusClass() { // TODO !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! return (Class) UserType.class; @@ -231,7 +231,7 @@ private static Class checkProjectionClass(Class old public static boolean isFocalClass(Class aClass) { return FocusType.class.isAssignableFrom(aClass); } - + public boolean isProjectionClass(Class aClass) { return ShadowType.class.isAssignableFrom(aClass); } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/EvaluatedAssignmentImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/EvaluatedAssignmentImpl.java index 3157167f698..1dc39b967dd 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/EvaluatedAssignmentImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/EvaluatedAssignmentImpl.java @@ -47,13 +47,13 @@ import static com.evolveum.midpoint.prism.PrismContainerValue.asContainerable; /** - * Evaluated assignment that contains all constructions and authorizations from the assignment + * Evaluated assignment that contains all constructions and authorizations from the assignment * itself and all the applicable inducements from all the roles referenced from the assignment. - * + * * @author Radovan Semancik */ public class EvaluatedAssignmentImpl implements EvaluatedAssignment { - + private static final Trace LOGGER = TraceManager.getTrace(EvaluatedAssignmentImpl.class); @NotNull private final ItemDeltaItem,PrismContainerDefinition> assignmentIdi; @@ -156,50 +156,50 @@ public Collection> getConstructionSet(PlusMinusZero whichSet) { default: throw new IllegalArgumentException("whichSet: " + whichSet); } } - + public void addConstruction(Construction contruction, PlusMinusZero whichSet) { switch (whichSet) { - case ZERO: + case ZERO: constructionTriple.addToZeroSet(contruction); break; - case PLUS: + case PLUS: constructionTriple.addToPlusSet(contruction); break; - case MINUS: + case MINUS: constructionTriple.addToMinusSet(contruction); break; - default: + default: throw new IllegalArgumentException("whichSet: " + whichSet); } } - + @NotNull public DeltaSetTriple> getPersonaConstructionTriple() { return personaConstructionTriple; } - + public void addPersonaConstruction(PersonaConstruction personaContruction, PlusMinusZero whichSet) { switch (whichSet) { - case ZERO: + case ZERO: personaConstructionTriple.addToZeroSet(personaContruction); break; - case PLUS: + case PLUS: personaConstructionTriple.addToPlusSet(personaContruction); break; - case MINUS: + case MINUS: personaConstructionTriple.addToMinusSet(personaContruction); break; - default: + default: throw new IllegalArgumentException("whichSet: " + whichSet); } } - + @NotNull @Override public DeltaSetTriple getRoles() { return roles; } - + public void addRole(EvaluatedAssignmentTargetImpl role, PlusMinusZero mode) { roles.addToSet(mode, role); } @@ -212,7 +212,7 @@ public Collection getOrgRefVals() { public void addOrgRefVal(PrismReferenceValue org) { orgRefVals.add(org); } - + @NotNull public Collection getMembershipRefVals() { return membershipRefVals; @@ -236,16 +236,16 @@ public void addDelegationRefVal(PrismReferenceValue org) { public Collection getAuthorizations() { return authorizations; } - + public void addAuthorization(Authorization authorization) { authorizations.add(authorization); } - + @NotNull public Collection getAdminGuiConfigurations() { return adminGuiConfigurations; } - + public void addAdminGuiConfiguration(AdminGuiConfigurationType adminGuiConfiguration) { adminGuiConfigurations.add(adminGuiConfiguration); } @@ -312,7 +312,7 @@ public void evaluateConstructions(ObjectDeltaObject focusOdo, PrismObject focusOdo, Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException { evaluateConstructions(focusOdo, null, task, result); } - + public void setPresentInCurrentObject(boolean presentInCurrentObject) { this.presentInCurrentObject = presentInCurrentObject; } @@ -335,7 +335,7 @@ public boolean isPresentInOldObject() { public Collection getFocusPolicyRules() { return focusPolicyRules; } - + public void addFocusPolicyRule(EvaluatedPolicyRule policyRule) { focusPolicyRules.add(policyRule); } @@ -409,14 +409,14 @@ public void triggerConstraint(@Nullable EvaluatedPolicyRule rule, EvaluatedPolic rule, trigger); } } - + if (!hasException) { LensUtil.triggerConstraint(rule, trigger, policySituations); } } private boolean processRuleExceptions(EvaluatedAssignmentImpl evaluatedAssignment, EvaluatedPolicyRule rule, EvaluatedPolicyRuleTrigger trigger) { - boolean hasException = false; + boolean hasException = false; for (PolicyExceptionType policyException: evaluatedAssignment.getAssignmentType().getPolicyException()) { if (policyException.getRuleName().equals(rule.getName())) { LensUtil.processRuleWithException(rule, trigger, policySituations, policyException); @@ -427,7 +427,7 @@ private boolean processRuleExceptions(EvaluatedAssignmentImpl evaluatedAssign } return hasException; } - + @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); @@ -511,7 +511,7 @@ public String toString() { return "EvaluatedAssignment(target=" + target + "; constr=" + constructionTriple + "; org="+orgRefVals+"; autz="+authorizations+"; "+focusMappings.size()+" focus mappings; "+ focusPolicyRules .size()+" rules)"; } - + public String toHumanReadableString() { if (target != null) { return "EvaluatedAssignment(" + target + ")"; diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/EvaluatedAssignmentTargetCache.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/EvaluatedAssignmentTargetCache.java index 291b23860b4..9a330e939a9 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/EvaluatedAssignmentTargetCache.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/EvaluatedAssignmentTargetCache.java @@ -36,13 +36,13 @@ * */ public class EvaluatedAssignmentTargetCache implements DebugDumpable { - + private static final Trace LOGGER = TraceManager.getTrace(EvaluatedAssignmentTargetCache.class); // Triple. Target processed for addition is not necessarily reusable for deletion // This is indexed by OID and relation only private DeltaTriple> processedKeys; - + // Triple. Target processed for addition is not necessarily reusable for deletion // This is indexed by OID, relation and order private DeltaTriple> processedOrderKeys; @@ -52,7 +52,7 @@ public EvaluatedAssignmentTargetCache() { processedOrderKeys = new DeltaTriple<>(() -> new HashSet<>()); processedKeys = new DeltaTriple<>(() -> new HashSet<>()); } - + public void reset() { processedOrderKeys.foreach(set -> set.clear()); processedKeys.foreach(set -> set.clear()); @@ -67,12 +67,12 @@ public void recordProcessing(AssignmentPathSegmentImpl segment, PlusMinusZero mo return; } processedOrderKeys.get(mode).add(new OrderKey(segment)); - + if (targetType.getOid() != null) { processedKeys.get(mode).add(new Key(segment)); } } - + private boolean isCacheable(AbstractRoleType targetType) { IdempotenceType idempotence = targetType.getIdempotence(); return idempotence != null && idempotence != IdempotenceType.NONE; @@ -109,11 +109,11 @@ public boolean canSkip(AssignmentPathSegmentImpl segment, PlusMinusZero mode) { return processedOrderKeys.get(mode).contains(new OrderKey(segment)); } } - + private class Key { private String targetOid; private QName relation; - + public Key(AssignmentPathSegmentImpl segment) { super(); this.targetOid = segment.getTarget().getOid(); @@ -170,17 +170,17 @@ private EvaluatedAssignmentTargetCache getOuterType() { public String toString() { return "Key(" + content() + ")"; } - - + + protected String content() { return targetOid + "[" + relation + "]"; } } - + private class OrderKey extends Key { private EvaluationOrder evaluationOrder; - + public OrderKey(AssignmentPathSegmentImpl segment) { super(segment); this.evaluationOrder = segment.getEvaluationOrder(); @@ -228,7 +228,7 @@ private EvaluatedAssignmentTargetCache getOuterType() { public String toString() { return "OrderKey("+ content() + ": order=" + evaluationOrder + ")"; } - + } @Override @@ -242,5 +242,5 @@ public String debugDump(int indent) { processedOrderKeys.debugDumpNoTitle(sb, indent + 2); return sb.toString(); } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/EvaluatedAssignmentTargetImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/EvaluatedAssignmentTargetImpl.java index 7da4e0ceca2..f9ae6c4faaa 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/EvaluatedAssignmentTargetImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/EvaluatedAssignmentTargetImpl.java @@ -29,7 +29,7 @@ * */ public class EvaluatedAssignmentTargetImpl implements EvaluatedAssignmentTarget { - + final PrismObject target; private final boolean evaluateConstructions; @NotNull private final AssignmentPathImpl assignmentPath; // TODO reconsider (maybe we should store only some lightweight information here) @@ -99,12 +99,12 @@ public Collection getExclusions() { FocusType focusType = target.asObjectable(); if (focusType instanceof AbstractRoleType) { AbstractRoleType roleType = (AbstractRoleType)focusType; - + // legacy (very old) for (ExclusionPolicyConstraintType exclusionType: roleType.getExclusion()) { exclusions.add(exclusionType); } - + // legacy PolicyConstraintsType constraints = roleType.getPolicyConstraints(); if (constraints != null) { @@ -114,7 +114,7 @@ public Collection getExclusions() { } } } - return exclusions; + return exclusions; } @Override diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/EvaluatedPolicyRuleImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/EvaluatedPolicyRuleImpl.java index 9e370d6b1e2..5ea5fe70aed 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/EvaluatedPolicyRuleImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/EvaluatedPolicyRuleImpl.java @@ -68,7 +68,7 @@ private ObjectType computeDirectOwner() { public String getName() { return policyRuleType.getName(); } - + @Override public PolicyRuleType getPolicyRule() { return policyRuleType; @@ -120,7 +120,7 @@ void addTrigger(EvaluatedPolicyRuleTrigger trigger) { public Collection getPolicyExceptions() { return policyExceptions; } - + void addPolicyException(PolicyExceptionType exception) { policyExceptions.add(exception); } @@ -129,14 +129,14 @@ void addPolicyException(PolicyExceptionType exception) { public PolicyActionsType getActions() { return policyRuleType.getPolicyActions(); } - + @Override public String getPolicySituation() { // TODO default situations depending on getTriggeredConstraintKinds if (policyRuleType.getPolicySituation() != null) { return policyRuleType.getPolicySituation(); } - + if (!triggers.isEmpty()) { EvaluatedPolicyRuleTrigger firstTrigger = triggers.iterator().next(); if (firstTrigger instanceof EvaluatedSituationTrigger) { @@ -151,7 +151,7 @@ public String getPolicySituation() { return predefinedSituation.getUrl(); } } - + PolicyConstraintsType policyConstraints = getPolicyConstraints(); if (policyConstraints.getExclusion() != null) { return PredefinedPolicySituation.EXCLUSION_VIOLATION.getUrl(); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/EvaluationOrderImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/EvaluationOrderImpl.java index 92c343275a6..9a0e63ff0f4 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/EvaluationOrderImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/EvaluationOrderImpl.java @@ -81,7 +81,7 @@ public int getSummaryOrder() { } return rv; } - + @Override public EvaluationOrder advance(QName relation) { checkConsistence(); @@ -183,14 +183,14 @@ public int hashCode() { public String toString() { return "EvaluationOrder(" + shortDump() + ")"; } - + @Override public String shortDump() { StringBuilder sb = new StringBuilder(); shortDump(sb); return sb.toString(); } - + @Override public void shortDump(StringBuilder sb) { for (Entry entry: orderMap.entrySet()) { diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/FailableLensFunction.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/FailableLensFunction.java index 72c4faa52e7..809586ae00f 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/FailableLensFunction.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/FailableLensFunction.java @@ -28,7 +28,7 @@ */ @FunctionalInterface public interface FailableLensFunction { - + R apply(T param) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException; } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ItemValueWithOrigin.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ItemValueWithOrigin.java index 135ffb9b684..d3985478f84 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ItemValueWithOrigin.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ItemValueWithOrigin.java @@ -36,11 +36,11 @@ * */ public class ItemValueWithOrigin implements DebugDumpable { - + private V itemValue; private PrismValueDeltaSetTripleProducer mapping; private Construction construction; - + public ItemValueWithOrigin(V propertyValue, PrismValueDeltaSetTripleProducer mapping, Construction accountConstruction) { super(); @@ -58,11 +58,11 @@ public V getItemValue() { public void setItemValue(V value) { this.itemValue = value; } - + public PrismValueDeltaSetTripleProducer getMapping() { return mapping; } - + public Construction getConstruction() { return construction; } @@ -74,7 +74,7 @@ public ObjectType getSource() { public boolean isValid() { return construction == null || construction.isValid(); } - + public boolean equalsRealValue(V pvalue, ValueMatcher valueMatcher) throws SchemaException { if (itemValue == null) { return false; @@ -83,11 +83,11 @@ public boolean equalsRealValue(V pvalue, ValueMatcher valueMatcher) throw return itemValue.equalsRealValue(pvalue); } else { // this must be a property, otherwise there would be no matcher - return valueMatcher.match(((PrismPropertyValue)itemValue).getValue(), + return valueMatcher.match(((PrismPropertyValue)itemValue).getValue(), ((PrismPropertyValue)pvalue).getValue()); } } - + public ItemValueWithOrigin clone() { ItemValueWithOrigin clone = new ItemValueWithOrigin<>(itemValue, mapping, construction); copyValues(clone); @@ -103,7 +103,7 @@ protected void copyValues(ItemValueWithOrigin clone) { } clone.construction = this.construction; } - + public static DeltaSetTriple> createOutputTriple(PrismValueDeltaSetTripleProducer mapping) { PrismValueDeltaSetTriple outputTriple = mapping.getOutputTriple(); if (outputTriple == null) { diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensContext.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensContext.java index 1f313358973..77b53656e3e 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensContext.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensContext.java @@ -57,7 +57,7 @@ public class LensContext implements ModelContext { private static final long serialVersionUID = -778283437426659540L; private static final String DOT_CLASS = LensContext.class.getName() + "."; - + private static final Trace LOGGER = TraceManager.getTrace(LensContext.class); private ModelState state = ModelState.INITIAL; @@ -123,12 +123,12 @@ public class LensContext implements ModelContext { * True if we want to reconcile all accounts in this context. */ private boolean doReconciliationForAllProjections = false; - + /** * If set to true then all operations are considered to be * in execution phase - for the purpose of authorizations and auditing. * This is used in case that the whole operation (context) is a - * secondary change, e.g. in case that persona is provisioned. + * secondary change, e.g. in case that persona is provisioned. */ private boolean executionPhaseOnly = false; @@ -418,7 +418,7 @@ public void setChannel(String channelUri) { public void setChannel(QName channelQName) { this.channel = QNameUtil.qNameToUri(channelQName); } - + public boolean isDoReconciliationForAllProjections() { return doReconciliationForAllProjections; } @@ -426,7 +426,7 @@ public boolean isDoReconciliationForAllProjections() { public void setDoReconciliationForAllProjections(boolean doReconciliationForAllProjections) { this.doReconciliationForAllProjections = doReconciliationForAllProjections; } - + public boolean isReconcileFocus() { return doReconciliationForAllProjections || ModelExecuteOptions.isReconcileFocus(options); } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensContextPlaceholder.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensContextPlaceholder.java index 6772397f68a..081a387e194 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensContextPlaceholder.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensContextPlaceholder.java @@ -23,7 +23,7 @@ /** * This class does nothing. It just takes place when no real Lens Context is available. * @see ModelExpressionThreadLocalHolder - * + * * @author semancik * */ @@ -52,6 +52,6 @@ public String debugDump(int indent, boolean showTriples) { sb.append("LensContextPlaceholder"); return sb.toString(); } - - + + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensDebugListener.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensDebugListener.java index 5b1a48c72e8..d23f8d59935 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensDebugListener.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensDebugListener.java @@ -20,32 +20,32 @@ /** * Interface used to intercept the SyncContext as it passes through the computation. - * + * * It is mostly used in tests. - * + * * EXPERIMENTAL - * + * * @author Radovan Semancik * */ public interface LensDebugListener { - + public void beforeSync(LensContext context); public void afterSync(LensContext context); - + public void beforeProjection(LensContext context); - + public void afterProjection(LensContext context); - + /** * May be used to gather profiling data, etc. */ public void afterMappingEvaluation(LensContext context, Mapping evaluatedMapping); - + // /** // * For all scripts expect for mappings. // * May be used to gather profiling data, etc. -// */ +// */ // public void afterScriptEvaluation(LensContext context, ScriptExpression scriptExpression); } 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 49edc329e13..b17024a6dfa 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 @@ -61,7 +61,7 @@ public abstract class LensElementContext implements ModelElementContext { private static final long serialVersionUID = 1649567559396392861L; - + private static final Trace LOGGER = TraceManager.getTrace(LensElementContext.class); private PrismObject objectOld; @@ -73,24 +73,24 @@ public abstract class LensElementContext implements ModelE private String oid = null; private int iteration; private String iterationToken; - + /** * Initial intent regarding the account. It indicated what the initiator of the operation WANTS TO DO with the - * context. + * context. * If set to null then the decision is left to "the engine". Null is also a typical value * when the context is created. It may be pre-set under some circumstances, e.g. if an account is being unlinked. */ private SynchronizationIntent synchronizationIntent; - + private transient boolean isFresh = false; - + private LensContext lensContext; - + private transient PrismObjectDefinition objectDefinition = null; - + transient private Collection policyRules = new ArrayList<>(); transient private Collection policySituations = new ArrayList<>(); - + public LensElementContext(Class objectTypeClass, LensContext lensContext) { super(); Validate.notNull(objectTypeClass, "Object class is null"); @@ -98,7 +98,7 @@ public LensElementContext(Class objectTypeClass, LensContext getLensContext() { return lensContext; } - + protected PrismContext getNotNullPrismContext() { return getLensContext().getNotNullPrismContext(); } @@ -135,24 +135,24 @@ protected PrismContext getNotNullPrismContext() { public Class getObjectTypeClass() { return objectTypeClass; } - + public boolean canRepresent(Class type) { return type.isAssignableFrom(objectTypeClass); } - + public PrismContext getPrismContext() { return lensContext.getPrismContext(); } - + @Override public PrismObject getObjectOld() { return objectOld; } - + public void setObjectOld(PrismObject objectOld) { this.objectOld = objectOld; } - + public PrismObject getObjectCurrent() { return objectCurrent; } @@ -160,7 +160,7 @@ public PrismObject getObjectCurrent() { public void setObjectCurrent(PrismObject objectCurrent) { this.objectCurrent = objectCurrent; } - + public PrismObject getObjectAny() { if (objectNew != null) { return objectNew; @@ -170,12 +170,12 @@ public PrismObject getObjectAny() { } return objectOld; } - + /** * Sets current and possibly also old object. This method is used with * freshly loaded object. The object is set as current object. * If the old object was not initialized yet (and if it should be initialized) - * then the object is also set as old object. + * then the object is also set as old object. */ public void setLoadedObject(PrismObject object) { setObjectCurrent(object); @@ -188,11 +188,11 @@ public void setLoadedObject(PrismObject object) { public PrismObject getObjectNew() { return objectNew; } - + public void setObjectNew(PrismObject objectNew) { this.objectNew = objectNew; } - + @Override public ObjectDelta getPrimaryDelta() { return primaryDelta; @@ -228,11 +228,11 @@ public ObjectDelta getFixedPrimaryDelta() { // Object does exist. Let's ignore the delta - see description above. return null; } - + public void setPrimaryDelta(ObjectDelta primaryDelta) { this.primaryDelta = primaryDelta; } - + public void addPrimaryDelta(ObjectDelta delta) throws SchemaException { if (primaryDelta == null) { primaryDelta = delta; @@ -240,7 +240,7 @@ public void addPrimaryDelta(ObjectDelta delta) throws SchemaException { primaryDelta.merge(delta); } } - + public void swallowToPrimaryDelta(ItemDelta itemDelta) throws SchemaException { if (primaryDelta == null) { primaryDelta = new ObjectDelta(getObjectTypeClass(), ChangeType.MODIFY, getPrismContext()); @@ -248,7 +248,7 @@ public void swallowToPrimaryDelta(ItemDelta itemDelta) throws SchemaExcepti } primaryDelta.swallow(itemDelta); } - + public abstract void swallowToSecondaryDelta(ItemDelta itemDelta) throws SchemaException; public boolean isAdd() { @@ -260,7 +260,7 @@ public boolean isAdd() { } return false; } - + public boolean isModify() { if (ObjectDelta.isModify(getPrimaryDelta())) { return true; @@ -290,13 +290,13 @@ public SimpleOperationName getOperation() { } return SimpleOperationName.MODIFY; } - + @NotNull @Override public List> getExecutedDeltas() { return executedDeltas; } - + List> getExecutedDeltas(Boolean audited) { if (audited == null) { return executedDeltas; @@ -309,13 +309,13 @@ List> getExecutedDeltas(Boolean audited) { } return deltas; } - + public void markExecutedDeltasAudited() { for(LensObjectDeltaOperation executedDelta: executedDeltas) { executedDelta.setAudited(true); } } - + public void addToExecutedDeltas(LensObjectDeltaOperation executedDelta) { executedDeltas.add(executedDelta.clone()); // must be cloned because e.g. for ADD deltas the object gets modified afterwards } @@ -333,7 +333,7 @@ public ObjectDelta getFixedDelta() throws SchemaException { } public boolean wasAddExecuted() { - + for (LensObjectDeltaOperation executedDeltaOperation : getExecutedDeltas()){ ObjectDelta executedDelta = executedDeltaOperation.getObjectDelta(); if (!executedDelta.isAdd()){ @@ -342,10 +342,10 @@ public boolean wasAddExecuted() { return true; } } - + return false; } - + abstract public ObjectDeltaObject getObjectDeltaObject() throws SchemaException; @Override @@ -355,7 +355,7 @@ public String getOid() { } return oid; } - + public String determineOid() { if (getObjectOld() != null && getObjectOld().getOid() != null) { return getObjectOld().getOid(); @@ -374,7 +374,7 @@ public String determineOid() { } return null; } - + /** * Sets oid to the field but also to the deltas (if applicable). */ @@ -387,8 +387,8 @@ public void setOid(String oid) { objectNew.setOid(oid); } } - - public PrismObjectDefinition getObjectDefinition() { + + public PrismObjectDefinition getObjectDefinition() { if (objectDefinition == null) { if (objectOld != null) { objectDefinition = objectOld.getDefinition(); @@ -402,7 +402,7 @@ public PrismObjectDefinition getObjectDefinition() { } return objectDefinition; } - + public boolean isFresh() { return isFresh; } @@ -418,7 +418,7 @@ public Collection getPolicyRules() { public void addPolicyRule(EvaluatedPolicyRule policyRule) { this.policyRules.add(policyRule); } - + public void triggerConstraint(EvaluatedPolicyRule rule, EvaluatedPolicyRuleTrigger trigger) throws PolicyViolationException { LensUtil.triggerConstraint(rule, trigger, policySituations); } @@ -440,11 +440,11 @@ public void recompute() throws SchemaException { } objectNew = delta.computeChangedObject(base); } - + public void checkConsistence() { checkConsistence(null); } - + public void checkConsistence(String contextDesc) { if (getObjectOld() != null) { checkConsistence(getObjectOld(), "old "+getElementDesc() , contextDesc); @@ -459,7 +459,7 @@ public void checkConsistence(String contextDesc) { checkConsistence(getObjectNew(), "new "+getElementDesc(), contextDesc); } } - + protected void checkConsistence(ObjectDelta delta, boolean requireOid, String contextDesc) { try { delta.checkConsistence(requireOid, true, true, ConsistencyCheckScope.THOROUGH); @@ -476,7 +476,7 @@ protected void checkConsistence(ObjectDelta delta, boolean requireOid, String protected boolean isRequireSecondardyDeltaOid() { return primaryDelta == null; } - + protected void checkConsistence(PrismObject object, String elementDesc, String contextDesc) { String desc = elementDesc+" in "+this + (contextDesc == null ? "" : " in " +contextDesc); try { @@ -494,7 +494,7 @@ protected void checkConsistence(PrismObject object, String elementDesc, Strin ShadowUtil.checkConsistence((PrismObject) object, desc); } } - + /** * Cleans up the contexts by removing some of the working state. */ @@ -514,7 +514,7 @@ public void normalize() { primaryDelta.normalize(); } } - + public void adopt(PrismContext prismContext) throws SchemaException { if (objectNew != null) { prismContext.adopt(objectNew); @@ -530,9 +530,9 @@ public void adopt(PrismContext prismContext) throws SchemaException { } // TODO: object definition? } - + public abstract LensElementContext clone(LensContext lensContext); - + protected void copyValues(LensElementContext clone, LensContext lensContext) { clone.lensContext = lensContext; // This is de-facto immutable @@ -547,7 +547,7 @@ protected void copyValues(LensElementContext clone, LensContext lensContext) clone.iteration = this.iteration; clone.iterationToken = this.iterationToken; } - + protected ObjectDelta cloneDelta(ObjectDelta thisDelta) { if (thisDelta == null) { return null; @@ -613,11 +613,11 @@ public void retrieveFromLensElementContextType(LensElementContextType lensElemen } this.oid = lensElementContextType.getOid(); - + this.iteration = lensElementContextType.getIteration() != null ? lensElementContextType.getIteration() : 0; this.iterationToken = lensElementContextType.getIterationToken(); this.synchronizationIntent = SynchronizationIntent.fromSynchronizationIntentType(lensElementContextType.getSynchronizationIntent()); - + // note: objectTypeClass is already converted (used in the constructor) } @@ -661,7 +661,7 @@ public void checkEncrypted() { CryptoUtil.checkEncrypted(primaryDelta); } } - + public boolean operationMatches(ChangeTypeType operation) { switch (operation) { case ADD: @@ -673,9 +673,9 @@ public boolean operationMatches(ChangeTypeType operation) { } throw new IllegalArgumentException("Unknown operaiton "+operation); } - + protected abstract String getElementDefaultDesc(); - + protected String getElementDesc() { PrismObject object = getObjectNew(); if (object == null) { @@ -689,15 +689,15 @@ protected String getElementDesc() { } return object.toDebugType(); } - + protected String getDebugDumpTitle() { return StringUtils.capitalize(getElementDesc()); } - + protected String getDebugDumpTitle(String suffix) { return getDebugDumpTitle()+" "+suffix; } - + public abstract String getHumanReadableName(); } 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 fe99cc6004a..edbb19f4b07 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 @@ -44,18 +44,18 @@ public class LensFocusContext extends LensElementContext secondaryDeltas = new ObjectDeltaWaves<>(); - + transient private SecurityPolicyType securityPolicy; transient private ObjectPolicyConfigurationType objectPolicyConfigurationType; - + private int getProjectionWave() { return getLensContext().getProjectionWave(); } - + private int getExecutionWave() { return getLensContext().getProjectionWave(); } - + public SecurityPolicyType getSecurityPolicy() { return securityPolicy; } @@ -89,16 +89,16 @@ public ObjectDelta getProjectionWavePrimaryDelta() throws SchemaException { return secondaryDeltas.getMergedDeltas(getFixedPrimaryDelta(), getProjectionWave()); } } - + public boolean isDelete() { return getPrimaryDelta() != null && getPrimaryDelta().isDelete(); } - + public boolean isAdd() { return getPrimaryDelta() != null && getPrimaryDelta().isAdd(); } - + @Override public ObjectDelta getSecondaryDelta() { try { @@ -108,7 +108,7 @@ public ObjectDelta getSecondaryDelta() { throw new SystemException("Unexpected delta merging problem: "+e.getMessage(), e); } } - + public ObjectDelta getSecondaryDelta(int wave) { return secondaryDeltas.get(wave); } @@ -116,11 +116,11 @@ public ObjectDelta getSecondaryDelta(int wave) { public ObjectDeltaWaves getSecondaryDeltas() { return secondaryDeltas; } - + public ObjectDelta getProjectionWaveSecondaryDelta() throws SchemaException { return getWaveSecondaryDelta(getProjectionWave()); } - + public ObjectDelta getWaveSecondaryDelta(int wave) throws SchemaException { return secondaryDeltas.get(wave); } @@ -138,39 +138,39 @@ public void setSecondaryDelta(ObjectDelta secondaryDelta) { public void setSecondaryDelta(ObjectDelta secondaryDelta, int wave) { this.secondaryDeltas.set(wave, secondaryDelta); } - + public void setProjectionWaveSecondaryDelta(ObjectDelta secondaryDelta) { this.secondaryDeltas.set(getProjectionWave(), secondaryDelta); } - + public void swallowToProjectionWaveSecondaryDelta(ItemDelta propDelta) throws SchemaException { - + ObjectDelta secondaryDelta = getProjectionWaveSecondaryDelta(); - + if (secondaryDelta == null) { - secondaryDelta = new ObjectDelta(getObjectTypeClass(), ChangeType.MODIFY, getPrismContext()); + secondaryDelta = new ObjectDelta(getObjectTypeClass(), ChangeType.MODIFY, getPrismContext()); secondaryDelta.setOid(getOid()); setProjectionWaveSecondaryDelta(secondaryDelta); } else if (secondaryDelta.containsModification(propDelta, true, true)) { return; } - + secondaryDelta.swallow(propDelta); } - + public void swallowToSecondaryDelta(ItemDelta propDelta) throws SchemaException { ObjectDelta secondaryDelta = getSecondaryDelta(0); if (secondaryDelta == null) { - secondaryDelta = new ObjectDelta(getObjectTypeClass(), ChangeType.MODIFY, getPrismContext()); + secondaryDelta = new ObjectDelta(getObjectTypeClass(), ChangeType.MODIFY, getPrismContext()); secondaryDelta.setOid(getOid()); setSecondaryDelta(secondaryDelta, 0); } else if (secondaryDelta.containsModification(propDelta, true, true)) { return; } - + secondaryDelta.swallow(propDelta); } - + public boolean alreadyHasDelta(ItemDelta itemDelta) { ObjectDelta primaryDelta = getPrimaryDelta(); if (primaryDelta != null && primaryDelta.containsModification(itemDelta, true, true)) { @@ -207,7 +207,7 @@ public boolean hasAnyDelta() { public ObjectDelta getProjectionWaveDelta() throws SchemaException { return getWaveDelta(getProjectionWave()); } - + public ObjectDelta getWaveDelta(int wave) throws SchemaException { if (wave == 0) { // Primary delta is executed only in the first wave (wave 0) @@ -234,7 +234,7 @@ public ObjectDelta getAggregatedWaveDelta(int wave) throws SchemaException { LOGGER.trace("Aggregated wave delta for wave {} = {}", wave, result != null ? result.debugDump() : "(null)"); return result; } - + public ObjectDelta getWaveExecutableDelta(int wave) throws SchemaException { if (wave == 0) { if (getFixedPrimaryDelta() != null && getFixedPrimaryDelta().isAdd()) { @@ -245,11 +245,11 @@ public ObjectDelta getWaveExecutableDelta(int wave) throws SchemaException { } } return delta; - } + } } return getWaveDelta(wave); } - + @Override public void cleanup() { // Clean up only delta in current wave. The deltas in previous waves are already done. @@ -266,7 +266,7 @@ public void normalize() { secondaryDeltas.normalize(); } } - + // @Override // public void reset() { // super.reset(); @@ -280,11 +280,11 @@ public void adopt(PrismContext prismContext) throws SchemaException { secondaryDeltas.adopt(prismContext); } } - + public void clearIntermediateResults() { // Nothing to do } - + public void applyProjectionWaveSecondaryDeltas(Collection> itemDeltas) throws SchemaException { ObjectDelta wavePrimaryDelta = getProjectionWavePrimaryDelta(); ObjectDelta waveSecondaryDelta = getProjectionWaveSecondaryDelta(); @@ -303,7 +303,7 @@ public void applyProjectionWaveSecondaryDeltas(Collection> itemDe } } } - + @Override public LensFocusContext clone(LensContext lensContext) { LensFocusContext clone = new LensFocusContext(getObjectTypeClass(), lensContext); @@ -331,7 +331,7 @@ public String dump(boolean showTriples) { public String debugDump(int indent) { return debugDump(indent, true); } - + public String debugDump(int indent, boolean showTriples) { StringBuilder sb = new StringBuilder(); DebugUtil.indentDebugDump(sb, indent); @@ -345,7 +345,7 @@ public String debugDump(int indent, boolean showTriples) { sb.append(", iteration=").append(getIteration()).append(" (").append(getIterationToken()).append(")"); } sb.append(", syncIntent=").append(getSynchronizationIntent()); - + sb.append("\n"); DebugUtil.debugDumpWithLabel(sb, getDebugDumpTitle("old"), getObjectOld(), indent+1); @@ -354,7 +354,7 @@ public String debugDump(int indent, boolean showTriples) { sb.append("\n"); DebugUtil.debugDumpWithLabel(sb, getDebugDumpTitle("new"), getObjectNew(), indent+1); - + sb.append("\n"); DebugUtil.debugDumpWithLabel(sb, getDebugDumpTitle("primary delta"), getPrimaryDelta(), indent+1); @@ -367,7 +367,7 @@ public String debugDump(int indent, boolean showTriples) { sb.append("\n"); sb.append(secondaryDeltas.debugDump(indent + 2)); } - + sb.append("\n"); DebugUtil.debugDumpWithLabel(sb, getDebugDumpTitle("executed deltas"), getExecutedDeltas(), indent+1); @@ -383,7 +383,7 @@ protected String getElementDefaultDesc() { public String toString() { return "LensFocusContext(" + getObjectTypeClass().getSimpleName() + ":" + getOid() + ")"; } - + public String getHumanReadableName() { StringBuilder sb = new StringBuilder(); sb.append("focus("); @@ -468,5 +468,5 @@ public void checkConsistence(String desc) { } } } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensObjectDeltaOperation.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensObjectDeltaOperation.java index 14d5f0315e6..ce274effef5 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensObjectDeltaOperation.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensObjectDeltaOperation.java @@ -35,7 +35,7 @@ public class LensObjectDeltaOperation extends ObjectDeltaOperation implements Serializable { private boolean audited = false; - + public LensObjectDeltaOperation() { super(); } @@ -51,7 +51,7 @@ public boolean isAudited() { public void setAudited(boolean audited) { this.audited = audited; } - + @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); @@ -60,7 +60,7 @@ public String debugDump(int indent) { DebugUtil.debugDumpWithLabel(sb, "audited", audited, indent + 1); return sb.toString(); } - + @Override protected String getDebugDumpClassName() { return "LensObjectDeltaOperation"; diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensOwnerResolver.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensOwnerResolver.java index f20bd121cb9..92b642fd771 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensOwnerResolver.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensOwnerResolver.java @@ -46,14 +46,14 @@ * */ public class LensOwnerResolver implements OwnerResolver { - + private static final Trace LOGGER = TraceManager.getTrace(LensOwnerResolver.class); - + private LensContext context; private ObjectResolver objectResolver; private Task task; private OperationResult result; - + public LensOwnerResolver(LensContext context, ObjectResolver objectResolver, Task task, OperationResult result) { super(); @@ -86,7 +86,7 @@ public PrismObject resolveOwner } else if (object.canRepresent(UserType.class)) { ObjectQuery query = QueryBuilder.queryFor(UserType.class, context.getPrismContext()) .item(FocusType.F_PERSONA_REF).ref(object.getOid()).build(); - List> owners = new ArrayList<>(); + List> owners = new ArrayList<>(); try { objectResolver.searchIterative(UserType.class, query, null, (o,result) -> owners.add(o), owners, result); } catch (ObjectNotFoundException | CommunicationException | ConfigurationException @@ -99,7 +99,7 @@ public PrismObject resolveOwner } if (owners.size() > 1) { LOGGER.warn("More than one owner of {}: {}", object, owners); - } + } return (PrismObject) owners.get(0); } else if (object.canRepresent(AbstractRoleType.class)) { ObjectReferenceType ownerRef = ((AbstractRoleType)(object.asObjectable())).getOwnerRef(); 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 f796bebd001..12b4b59fdf7 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 @@ -65,22 +65,22 @@ * */ public class LensProjectionContext extends LensElementContext implements ModelProjectionContext { - + private ObjectDelta syncDelta; private ObjectDelta secondaryDelta; - + /** * If set to true: absolute state of this projection was detected by the synchronization. * This is mostly for debugging and visibility. It is not used by projection logic. */ private boolean syncAbsoluteTrigger = false; - + /** * The wave in which this resource should be processed. Initial value of -1 means "undetermined". */ private int wave = -1; - + /** * Indicates that the wave computation is still in progress. */ @@ -90,9 +90,9 @@ public class LensProjectionContext extends LensElementContext implem * Definition of account type. */ private ResourceShadowDiscriminator resourceShadowDiscriminator; - + private boolean fullShadow = false; - + /** * True if the account is assigned to the user by a valid assignment. It may be false for accounts that are either * found to be illegal by live sync, were unassigned from user, etc. @@ -100,18 +100,18 @@ public class LensProjectionContext extends LensElementContext implem */ private boolean isAssigned; private boolean isAssignedOld; - + /** * True if the account should be part of the synchronization. E.g. outbound expression should be applied to it. */ private boolean isActive; - + /** * True if there is a valid assignment for this projection and/or the policy allows such projection to exist. */ private Boolean isLegal = null; private Boolean isLegalOld = null; - + private boolean isExists; /** @@ -124,13 +124,13 @@ public class LensProjectionContext extends LensElementContext implem * True if we want to reconcile account in this context. */ private boolean doReconciliation; - + /** * false if the context should be not taken into the account while synchronizing changes from other resource */ private boolean canProject = true; - - + + /** * Synchronization situation as it was originally detected by the synchronization code (SynchronizationService). @@ -144,12 +144,12 @@ public class LensProjectionContext extends LensElementContext implem * The synchronization decision is used instead. */ private SynchronizationSituationType synchronizationSituationResolved = null; - + /** * Delta set triple for accounts. Specifies which accounts should be added, removed or stay as they are. * It tells almost nothing about attributes directly although the information about attributes are inside * each account construction (in a form of ValueConstruction that contains attribute delta triples). - * + * * Intermediary computation result. It is stored to allow re-computing of account constructions during * iterative computations. * @@ -164,7 +164,7 @@ public class LensProjectionContext extends LensElementContext implem * Target: ConsolidationProcessor / ReconciliationProcessor (via squeezed structures) */ private transient Construction outboundConstruction; - + /** * Postprocessed triples from the above two properties. * Source: ConsolidationProcessor @@ -178,14 +178,14 @@ public class LensProjectionContext extends LensElementContext implem // Cached copy, to avoid constructing it over and over again private transient PrismObjectDefinition shadowDefinition = null; - + private transient RefinedObjectClassDefinition structuralObjectClassDefinition; private transient Collection auxiliaryObjectClassDefinitions; private transient CompositeRefinedObjectClassDefinition compositeObjectClassDefinition; - + private ValuePolicyType accountPasswordPolicy; - + /** * Resource that hosts this projection. */ @@ -198,7 +198,7 @@ public class LensProjectionContext extends LensElementContext implem * TODO implement as non-transient. */ transient private boolean toBeArchived; - + transient private String humanReadableName; LensProjectionContext(LensContext lensContext, ResourceShadowDiscriminator resourceAccountType) { @@ -293,11 +293,11 @@ public void setDoReconciliation(boolean doReconciliation) { public ResourceShadowDiscriminator getResourceShadowDiscriminator() { return resourceShadowDiscriminator; } - + public void setResourceShadowDiscriminator(ResourceShadowDiscriminator resourceShadowDiscriminator) { this.resourceShadowDiscriminator = resourceShadowDiscriminator; } - + public boolean compareResourceShadowDiscriminator(ResourceShadowDiscriminator rsd, boolean compareOrder) { Validate.notNull(rsd.getResourceOid()); if (resourceShadowDiscriminator == null) { @@ -331,7 +331,7 @@ public boolean compareResourceShadowDiscriminator(ResourceShadowDiscriminator rs return true; } - + public boolean isThombstone() { if (resourceShadowDiscriminator == null) { return false; @@ -346,7 +346,7 @@ public void addAccountSyncDelta(ObjectDelta delta) throws SchemaExce syncDelta.merge(delta); } } - + public boolean isAdd() { if (synchronizationPolicyDecision == SynchronizationPolicyDecision.ADD) { return true; @@ -355,7 +355,7 @@ public boolean isAdd() { } return super.isAdd(); } - + public boolean isModify() { if (synchronizationPolicyDecision == SynchronizationPolicyDecision.KEEP) { return true; @@ -376,7 +376,7 @@ public boolean isDelete() { } return super.isDelete(); } - + public ResourceType getResource() { return resource; } @@ -384,7 +384,7 @@ public ResourceType getResource() { public void setResource(ResourceType resource) { this.resource = resource; } - + @Override public PrismObjectDefinition getObjectDefinition() { if (shadowDefinition == null) { @@ -421,7 +421,7 @@ public boolean isActive() { public void setActive(boolean isActive) { this.isActive = isActive; } - + public Boolean isLegal() { return isLegal; } @@ -475,7 +475,7 @@ public void setSynchronizationSituationResolved( public boolean isFullShadow() { return fullShadow; } - + /** * Returns true if full shadow is available, either loaded or in a create delta. */ @@ -489,7 +489,7 @@ public boolean hasFullShadow() { public void setFullShadow(boolean fullShadow) { this.fullShadow = fullShadow; } - + public ShadowKindType getKind() { ResourceShadowDiscriminator discr = getResourceShadowDiscriminator(); if (discr != null) { @@ -506,7 +506,7 @@ public ShadowKindType getKind() { } return ShadowKindType.ACCOUNT; } - + public PrismValueDeltaSetTriple> getConstructionDeltaSetTriple() { return constructionDeltaSetTriple; } @@ -515,7 +515,7 @@ public void setConstructionDeltaSetTriple( PrismValueDeltaSetTriple> constructionDeltaSetTriple) { this.constructionDeltaSetTriple = constructionDeltaSetTriple; } - + public Construction getOutboundConstruction() { return outboundConstruction; } @@ -531,7 +531,7 @@ public Map,Prism public void setSqueezedAttributes(Map,PrismPropertyDefinition>>> squeezedAttributes) { this.squeezedAttributes = squeezedAttributes; } - + public Map,PrismContainerDefinition>>> getSqueezedAssociations() { return squeezedAssociations; } @@ -564,18 +564,18 @@ public ResourceObjectTypeDefinitionType getResourceObjectTypeDefinitionType() { ResourceObjectTypeDefinitionType def = ResourceTypeUtil.getResourceObjectTypeDefinitionType(resource, discr.getKind(), discr.getIntent()); return def; } - + private ResourceSchema getResourceSchema() throws SchemaException { return RefinedResourceSchemaImpl.getResourceSchema(resource, getNotNullPrismContext()); } - + public RefinedResourceSchema getRefinedResourceSchema() throws SchemaException { if (resource == null) { return null; } return RefinedResourceSchemaImpl.getRefinedSchema(resource, LayerType.MODEL, getNotNullPrismContext()); } - + public RefinedObjectClassDefinition getStructuralObjectClassDefinition() throws SchemaException { if (structuralObjectClassDefinition == null) { RefinedResourceSchema refinedSchema = getRefinedResourceSchema(); @@ -593,7 +593,7 @@ public Collection getAuxiliaryObjectClassDefinitio } return auxiliaryObjectClassDefinitions; } - + public void refreshAuxiliaryObjectClassDefinitions() throws SchemaException { RefinedResourceSchema refinedSchema = getRefinedResourceSchema(); if (refinedSchema == null) { @@ -612,7 +612,7 @@ public void refreshAuxiliaryObjectClassDefinitions() throws SchemaException { } compositeObjectClassDefinition = null; } - + public CompositeRefinedObjectClassDefinition getCompositeObjectClassDefinition() throws SchemaException { if (compositeObjectClassDefinition == null) { RefinedObjectClassDefinition structuralObjectClassDefinition = getStructuralObjectClassDefinition(); @@ -635,7 +635,7 @@ private void addAuxiliaryObjectClassNames(List auxiliaryObjectClassQNames } } } - + public RefinedAttributeDefinition findAttributeDefinition(QName attrName) throws SchemaException { RefinedAttributeDefinition attrDef = getStructuralObjectClassDefinition().findAttributeDefinition(attrName); if (attrDef != null) { @@ -662,57 +662,57 @@ public Collection getDependencies() { } return dependencies; } - + public ValuePolicyType getAccountPasswordPolicy() { return accountPasswordPolicy; } - + public void setCanProject(boolean canProject) { this.canProject = canProject; } - + public boolean isCanProject() { return canProject; } - + public void setAccountPasswordPolicy(ValuePolicyType accountPasswordPolicy) { this.accountPasswordPolicy = accountPasswordPolicy; } - + public AssignmentPolicyEnforcementType getAssignmentPolicyEnforcementType() { // TODO: per-resource assignment enforcement ResourceType resource = getResource(); ProjectionPolicyType globalAccountSynchronizationSettings = null; if (resource != null){ globalAccountSynchronizationSettings = resource.getProjection(); - } - + } + if (globalAccountSynchronizationSettings == null) { globalAccountSynchronizationSettings = getLensContext().getAccountSynchronizationSettings(); } AssignmentPolicyEnforcementType globalAssignmentPolicyEnforcement = MiscSchemaUtil.getAssignmentPolicyEnforcementType(globalAccountSynchronizationSettings); return globalAssignmentPolicyEnforcement; } - + public boolean isLegalize(){ ResourceType resource = getResource(); ProjectionPolicyType globalAccountSynchronizationSettings = null; if (resource != null){ globalAccountSynchronizationSettings = resource.getProjection(); - } - + } + if (globalAccountSynchronizationSettings == null) { globalAccountSynchronizationSettings = getLensContext().getAccountSynchronizationSettings(); } - + if (globalAccountSynchronizationSettings == null){ return false; } - + if (globalAccountSynchronizationSettings.isLegalize() == null){ return false; } - + return globalAccountSynchronizationSettings.isLegalize(); } @@ -744,7 +744,7 @@ public void recompute() throws SchemaException { setObjectNew(base); return; } - + if (base == null && accDelta.isModify()) { RefinedObjectClassDefinition rOCD = getCompositeObjectClassDefinition(); if (rOCD != null) { @@ -754,13 +754,13 @@ public void recompute() throws SchemaException { setObjectNew(accDelta.computeChangedObject(base)); } - + public void clearIntermediateResults() { //constructionDeltaSetTriple = null; outboundConstruction = null; squeezedAttributes = null; } - + /** * Distribute the resource that's in the context into all the prism objects (old, new) and deltas. * The resourceRef will not just contain the OID but also full resource object. This may optimize handling @@ -778,7 +778,7 @@ public void distributeResource() { distributeResourceDelta(getPrimaryDelta(), resource); distributeResourceDelta(getSecondaryDelta(), resource); } - + private void distributeResourceObject(PrismObject object, PrismObject resource) { if (object == null) { return; @@ -819,7 +819,7 @@ private void distributeResourceValues(Collection values, Pr distributeResourceValue(pval, resource); } } - + /** * Returns delta suitable for execution. The primary and secondary deltas may not make complete sense all by themselves. * E.g. they may both be MODIFY deltas even in case that the account should be created. The deltas begin to make sense @@ -839,12 +839,12 @@ public ObjectDelta getExecutableDelta() throws SchemaException { RefinedObjectClassDefinition rObjectClassDef = getCompositeObjectClassDefinition(); if (rObjectClassDef == null) { - throw new IllegalStateException("Definition for account type " + getResourceShadowDiscriminator() + throw new IllegalStateException("Definition for account type " + getResourceShadowDiscriminator() + " not found in the context, but it should be there"); } PrismObject newAccount = (PrismObject) rObjectClassDef.createBlankShadow(); addDelta.setObjectToAdd(newAccount); - + if (origDelta != null) { addDelta.merge(origDelta); } @@ -911,7 +911,7 @@ public void checkConsistence(String contextDesc, boolean fresh, boolean force) { } } } - + @Override protected void checkConsistence(PrismObject object, String elementDesc, String contextDesc) { super.checkConsistence(object, elementDesc, contextDesc); @@ -934,7 +934,7 @@ protected void checkConsistence(PrismObject object, String elementDe } } } - + protected boolean isRequireSecondardyDeltaOid() { if (synchronizationPolicyDecision == SynchronizationPolicyDecision.ADD || synchronizationPolicyDecision == SynchronizationPolicyDecision.BROKEN || @@ -947,7 +947,7 @@ protected boolean isRequireSecondardyDeltaOid() { } return super.isRequireSecondardyDeltaOid(); } - + @Override public void cleanup() { secondaryDelta = null; @@ -958,7 +958,7 @@ public void cleanup() { isAssignedOld = false; // ??? [med] isActive = false; } - + @Override public void normalize() { super.normalize(); @@ -1012,7 +1012,7 @@ public LensProjectionContext clone(LensContext lensContext copyValues(clone, lensContext); return clone; } - + protected void copyValues(LensProjectionContext clone, LensContext lensContext) { super.copyValues(clone, lensContext); // do NOT clone transient values such as accountConstructionDeltaSetTriple @@ -1038,7 +1038,7 @@ private Map,Pris if (squeezedAttributes == null) { return null; } - Map,PrismPropertyDefinition>>> clonedMap + Map,PrismPropertyDefinition>>> clonedMap = new HashMap,PrismPropertyDefinition>>>(); Cloner,PrismPropertyDefinition>> cloner = new Cloner,PrismPropertyDefinition>>() { @Override @@ -1051,7 +1051,7 @@ public ItemValueWithOrigin,PrismPropertyDefinition> clo } return clonedMap; } - + /** * Returns true if the projection has any value for specified attribute. */ @@ -1155,12 +1155,12 @@ private String getHumanReadableIdentifier() { public String debugDump() { return debugDump(0); } - + @Override public String debugDump(int indent) { return debugDump(indent, true); } - + public String debugDump(int indent, boolean showTriples) { StringBuilder sb = new StringBuilder(); SchemaDebugUtil.indentDebugDump(sb, indent); @@ -1202,7 +1202,7 @@ public String debugDump(int indent, boolean showTriples) { } sb.append("\n"); DebugUtil.debugDumpWithLabel(sb, getDebugDumpTitle("old"), getObjectOld(), indent + 1); - + sb.append("\n"); DebugUtil.debugDumpWithLabel(sb, getDebugDumpTitle("current"), getObjectCurrent(), indent + 1); @@ -1217,24 +1217,24 @@ public String debugDump(int indent, boolean showTriples) { sb.append("\n"); DebugUtil.debugDumpWithLabel(sb, getDebugDumpTitle("sync delta"), getSyncDelta(), indent + 1); - + sb.append("\n"); DebugUtil.debugDumpWithLabel(sb, getDebugDumpTitle("executed deltas"), getExecutedDeltas(), indent+1); if (showTriples) { - + sb.append("\n"); DebugUtil.debugDumpWithLabel(sb, getDebugDumpTitle("constructionDeltaSetTriple"), constructionDeltaSetTriple, indent + 1); - + sb.append("\n"); DebugUtil.debugDumpWithLabel(sb, getDebugDumpTitle("outbound account construction"), outboundConstruction, indent + 1); - + sb.append("\n"); DebugUtil.debugDumpWithLabel(sb, getDebugDumpTitle("squeezed attributes"), squeezedAttributes, indent + 1); - + sb.append("\n"); DebugUtil.debugDumpWithLabel(sb, getDebugDumpTitle("squeezed associations"), squeezedAssociations, indent + 1); - + sb.append("\n"); DebugUtil.debugDumpWithLabel(sb, getDebugDumpTitle("squeezed auxiliary object classes"), squeezedAuxiliaryObjectClasses, indent + 1); @@ -1252,7 +1252,7 @@ public String debugDump(int indent, boolean showTriples) { protected String getElementDefaultDesc() { return "projection"; } - + @Override public String toString() { return "LensProjectionContext(" + (getObjectTypeClass() == null ? "null" : getObjectTypeClass().getSimpleName()) + ":" + getOid() + @@ -1389,7 +1389,7 @@ public String getResourceOid() { return null; } } - + public ResourceObjectVolatilityType getVolatility() throws SchemaException { RefinedObjectClassDefinition structuralObjectClassDefinition = getStructuralObjectClassDefinition(); if (structuralObjectClassDefinition == null) { diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensUtil.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensUtil.java index 21b3f7531ef..dff02ac358a 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensUtil.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensUtil.java @@ -91,10 +91,10 @@ * */ public class LensUtil { - + private static final Trace LOGGER = TraceManager.getTrace(LensUtil.class); - - public static void traceContext(Trace logger, String activity, String phase, + + public static void traceContext(Trace logger, String activity, String phase, boolean important, LensContext context, boolean showTriples) throws SchemaException { if (logger.isTraceEnabled()) { logger.trace("Lens context:\n"+ @@ -133,7 +133,7 @@ public static ResourceType getResourceReadOnly(LensContex } return resourceType; } - + public static String refineProjectionIntent(ShadowKindType kind, String intent, ResourceType resource, PrismContext prismContext) throws SchemaException { RefinedResourceSchema refinedSchema = RefinedResourceSchemaImpl.getRefinedSchema(resource, LayerType.MODEL, prismContext); RefinedObjectClassDefinition rObjClassDef = refinedSchema.getRefinedDefinition(kind, intent); @@ -142,7 +142,7 @@ public static String refineProjectionIntent(ShadowKindType kind, String intent, } return rObjClassDef.getIntent(); } - + public static LensProjectionContext getProjectionContext(LensContext context, PrismObject equivalentAccount, ProvisioningService provisioningService, PrismContext prismContext, Task task, OperationResult result) throws ObjectNotFoundException, @@ -153,7 +153,7 @@ public static LensProjectionContext getProjectionContext(L kind, equivalentAccountType.getIntent(), provisioningService, prismContext, task, result); } - + public static LensProjectionContext getProjectionContext(LensContext context, String resourceOid, ShadowKindType kind, String intent, ProvisioningService provisioningService, PrismContext prismContext, @@ -164,7 +164,7 @@ public static LensProjectionContext getProjectionContext(L ResourceShadowDiscriminator rsd = new ResourceShadowDiscriminator(resourceOid, kind, refinedIntent); return context.findProjectionContext(rsd); } - + public static LensProjectionContext getOrCreateProjectionContext(LensContext context, ResourceShadowDiscriminator rsd) { LensProjectionContext accountSyncContext = context.findProjectionContext(rsd); @@ -176,12 +176,12 @@ public static LensProjectionContext getOrCreateProjection accountSyncContext.setDoReconciliation(context.isDoReconciliationForAllProjections()); return accountSyncContext; } - + public static LensProjectionContext createAccountContext(LensContext context, ResourceShadowDiscriminator rsd){ return new LensProjectionContext(context, rsd); } - - + + /** * Consolidate the mappings of a single item to a delta. It takes the convenient structure of ItemValueWithOrigin triple. * It produces the delta considering the mapping exclusion, authoritativeness and strength. @@ -189,29 +189,29 @@ public static LensProjectionContext createAccountContext( * filterExistingValues: if true, then values that already exist in the item are not added (and those that don't exist are not removed) */ @NotNull - public static > + public static > ItemDelta consolidateTripleToDelta( - ItemPath itemPath, DeltaSetTriple triple, D itemDefinition, + ItemPath itemPath, DeltaSetTriple triple, D itemDefinition, ItemDelta aprioriItemDelta, PrismContainer itemContainer, ValueMatcher valueMatcher, Comparator comparator, - boolean addUnchangedValues, boolean filterExistingValues, boolean isExclusiveStrong, + boolean addUnchangedValues, boolean filterExistingValues, boolean isExclusiveStrong, String contextDescription, boolean applyWeak) throws ExpressionEvaluationException, PolicyViolationException, SchemaException { - + ItemDelta itemDelta = itemDefinition.createEmptyDelta(itemPath); - + Item itemExisting = null; if (itemContainer != null) { itemExisting = itemContainer.findItem(itemPath); } - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Consolidating {} triple:\n{}\nApriori Delta:\n{}\nExisting item:\n{}", itemPath, triple.debugDump(1), DebugUtil.debugDump(aprioriItemDelta, 1), DebugUtil.debugDump(itemExisting, 1)); } - + Collection allValues = collectAllValues(triple, valueMatcher); - + final MutableBoolean itemHasStrongMutable = new MutableBoolean(false); SimpleVisitor visitor = pvwo -> { if (pvwo.getMapping().getStrength() == MappingStrengthType.STRONG) { @@ -220,11 +220,11 @@ ItemDelta consolidateTripleToDelta( }; triple.simpleAccept(visitor); boolean ignoreNormalMappings = itemHasStrongMutable.booleanValue() && isExclusiveStrong; - + // We will process each value individually. I really mean each value. This whole method deals with // a single item (e.g. attribute). But this loop iterates over every potential value of that item. for (V value : allValues) { - + LOGGER.trace(" consolidating value: {}", value); // Check what to do with the value using the usual "triple routine". It means that if a value is // in zero set than we need no delta, plus set means add delta and minus set means delete delta. @@ -235,12 +235,12 @@ ItemDelta consolidateTripleToDelta( collectPvwosFromSet(value, triple.getPlusSet(), valueMatcher); Collection> minusPvwos = collectPvwosFromSet(value, triple.getMinusSet(), valueMatcher); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("PVWOs for value {}:\nzero = {}\nplus = {}\nminus = {}", value, zeroPvwos, plusPvwos, minusPvwos); } - + boolean zeroHasStrong = false; if (!zeroPvwos.isEmpty()) { for (ItemValueWithOrigin pvwo : zeroPvwos) { @@ -250,7 +250,7 @@ ItemDelta consolidateTripleToDelta( } } } - + if (zeroHasStrong && aprioriItemDelta != null && aprioriItemDelta.isValueToDelete(value, true)) { throw new PolicyViolationException("Attempt to delete value "+value+" from item "+itemPath +" but that value is mandated by a strong mapping (in "+contextDescription+")"); @@ -361,7 +361,7 @@ ItemDelta consolidateTripleToDelta( value, itemPath, contextDescription); continue; } - + if (weakOnly && !applyWeak && (itemExisting == null || itemExisting.isEmpty())){ // There is a weak mapping on a property, but we do not have full account available, so skipping deletion of the value is better way LOGGER.trace("Value {} mapping is weak and the full account could not be fetched, skipping deletion in {}", @@ -377,7 +377,7 @@ ItemDelta consolidateTripleToDelta( value, itemPath, contextDescription); itemDelta.addValueToDelete((V)value.clone()); } - + if (!zeroPvwos.isEmpty()) { boolean weakOnly = true; boolean hasStrong = false; @@ -396,7 +396,7 @@ ItemDelta consolidateTripleToDelta( hasAuthoritative = true; } } - + if (aprioriItemDelta != null && aprioriItemDelta.isReplace()) { // Any strong mappings in the zero set needs to be re-applied as otherwise the replace will destroy it if (hasStrong) { @@ -408,7 +408,7 @@ ItemDelta consolidateTripleToDelta( } } } - + Item itemNew = null; if (itemContainer != null) { itemNew = itemContainer.findItem(itemPath); @@ -430,18 +430,18 @@ ItemDelta consolidateTripleToDelta( LOGGER.trace("Existing values for item {} in {}, weak mapping processing skipped", new Object[]{itemPath, contextDescription}); } - + if (itemExisting != null) { List existingValues = itemExisting.getValues(); if (existingValues != null) { itemDelta.setEstimatedOldValues(PrismValue.cloneCollection(existingValues)); } } - + return itemDelta; - + } - + private static boolean hasValue(Item item, ItemDelta itemDelta) throws SchemaException { if (item == null || item.isEmpty()) { if (itemDelta != null && itemDelta.addsAnyValue()) { @@ -459,7 +459,7 @@ private static boolean hasValue } } } - + private static Collection addWeakValues(Collection> pvwos, OriginType origin, boolean applyWeak) { Collection values = new ArrayList(); for (ItemValueWithOrigin pvwo: pvwos) { @@ -471,7 +471,7 @@ private static Collection ad } return values; } - + private static boolean hasValue(Item existingUserItem, V newValue, ValueMatcher valueMatcher, Comparator comparator) { if (existingUserItem == null) { return false; @@ -482,7 +482,7 @@ private static boolean hasValue return existingUserItem.contains(newValue, true, comparator); } } - + private static Collection collectAllValues (DeltaSetTriple> triple, ValueMatcher valueMatcher) throws SchemaException { Collection allValues = new HashSet<>(); @@ -506,7 +506,7 @@ private static void collectA } else { boolean found = false; for (V valueFromAllvalues: allValues) { - if (valueMatcher.match(((PrismPropertyValue)valueFromAllvalues).getValue(), + if (valueMatcher.match(((PrismPropertyValue)valueFromAllvalues).getValue(), ((PrismPropertyValue)pval).getValue())) { found = true; break; @@ -518,7 +518,7 @@ private static void collectA } } } - + private static Collection> collectPvwosFromSet(V pvalue, Collection> deltaSet, ValueMatcher valueMatcher) throws SchemaException { Collection> pvwos = new ArrayList<>(); @@ -542,9 +542,9 @@ public static PropertyDelta createActivationTimestampDelta } else { throw new IllegalArgumentException("Unknown activation status "+status); } - + PrismPropertyDefinition timestampDef = activationDefinition.findPropertyDefinition(timestampPropertyName); - PropertyDelta timestampDelta + PropertyDelta timestampDelta = timestampDef.createEmptyDelta(new ItemPath(FocusType.F_ACTIVATION, timestampPropertyName)); timestampDelta.setValueToReplace(new PrismPropertyValue(now, origin, null)); return timestampDelta; @@ -608,9 +608,9 @@ public static Object getIterationTokenVariableValue(LensProjectionContext accCtx ItemDeltaItem,PrismPropertyDefinition> idi = new ItemDeltaItem<>(propOld, propDelta, propNew); return idi; } - + /** - * Extracts the delta from this projection context and also from all other projection contexts that have + * Extracts the delta from this projection context and also from all other projection contexts that have * equivalent discriminator. */ public static PropertyDelta findAPrioriDelta(LensContext context, @@ -631,9 +631,9 @@ public static PropertyDelta findAPrioriDelta(LensCo } return aPrioriDelta; } - + /** - * Extracts the delta from this projection context and also from all other projection contexts that have + * Extracts the delta from this projection context and also from all other projection contexts that have * equivalent discriminator. */ public static ObjectDelta findAPrioriDelta(LensContext context, @@ -651,7 +651,7 @@ public static ObjectDelta findAPrioriDelta } return aPrioriDelta; } - + /** * Returns a list of context that have equivalent discriminator with the reference context. Ordered by "order" in the * discriminator. @@ -692,8 +692,8 @@ public static boolean hasLowerOrderContext(LensContext } return false; } - - public static boolean hasDependentContext(LensContext context, + + public static boolean hasDependentContext(LensContext context, LensProjectionContext targetProjectionContext) { for (LensProjectionContext projectionContext: context.getProjectionContexts()) { for (ResourceObjectTypeDependencyType dependency: projectionContext.getDependencies()) { @@ -704,13 +704,13 @@ public static boolean hasDependentContext(LensContext } return false; } - + public static boolean isDependencyTargetContext(LensProjectionContext sourceProjContext, LensProjectionContext targetProjectionContext, ResourceObjectTypeDependencyType dependency) { - ResourceShadowDiscriminator refDiscr = new ResourceShadowDiscriminator(dependency, + ResourceShadowDiscriminator refDiscr = new ResourceShadowDiscriminator(dependency, sourceProjContext.getResource().getOid(), sourceProjContext.getKind()); return targetProjectionContext.compareResourceShadowDiscriminator(refDiscr, false); } - + public static LensProjectionContext findLowerOrderContext(LensContext context, LensProjectionContext refProjCtx) { int minOrder = -1; @@ -727,7 +727,7 @@ public static LensProjectionContext findLowerOrderContext } return foundCtx; } - + public static void setContextOid(LensContext context, LensElementContext objectContext, String oid) { objectContext.setOid(oid); @@ -756,7 +756,7 @@ public static PrismObjectDefinition getFocusDefinition( Class typeClass = focusContext.getObjectTypeClass(); return context.getPrismContext().getSchemaRegistry().findObjectDefinitionByCompileTimeClass(typeClass); } - + public static int determineMaxIterations(IterationSpecificationType iterationSpecType) { if (iterationSpecType != null) { return iterationSpecType.getMaxIterations(); @@ -764,11 +764,11 @@ public static int determineMaxIterations(IterationSpecificationType iterationSpe return 0; } } - - public static String formatIterationToken(LensContext context, - LensElementContext accountContext, IterationSpecificationType iterationType, - int iteration, ExpressionFactory expressionFactory, ExpressionVariables variables, - Task task, OperationResult result) + + public static String formatIterationToken(LensContext context, + LensElementContext accountContext, IterationSpecificationType iterationType, + int iteration, ExpressionFactory expressionFactory, ExpressionVariables variables, + Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException { if (iterationType == null) { return formatIterationTokenDefault(iteration); @@ -780,7 +780,7 @@ public static String formatIterationToken(LensContext PrismPropertyDefinition outputDefinition = new PrismPropertyDefinitionImpl<>(ExpressionConstants.VAR_ITERATION_TOKEN, DOMUtil.XSD_STRING, context.getPrismContext()); Expression,PrismPropertyDefinition> expression = expressionFactory.makeExpression(tokenExpressionType, outputDefinition , "iteration token expression in "+accountContext.getHumanReadableName(), task, result); - + Collection> sources = new ArrayList<>(); PrismPropertyDefinitionImpl inputDefinition = new PrismPropertyDefinitionImpl<>(ExpressionConstants.VAR_ITERATION, DOMUtil.XSD_INT, context.getPrismContext()); @@ -790,8 +790,8 @@ public static String formatIterationToken(LensContext ItemDeltaItem,PrismPropertyDefinition> idi = new ItemDeltaItem<>(input); Source,PrismPropertyDefinition> iterationSource = new Source<>(idi, ExpressionConstants.VAR_ITERATION); sources.add(iterationSource); - - ExpressionEvaluationContext expressionContext = new ExpressionEvaluationContext(sources , variables, + + ExpressionEvaluationContext expressionContext = new ExpressionEvaluationContext(sources , variables, "iteration token expression in "+accountContext.getHumanReadableName(), task, result); PrismValueDeltaSetTriple> outputTriple = ModelExpressionThreadLocalHolder.evaluateExpressionInContext(expression, expressionContext, task, result); Collection> outputValues = outputTriple.getNonNegativeValues(); @@ -807,18 +807,18 @@ public static String formatIterationToken(LensContext } return realValue; } - + public static String formatIterationTokenDefault(int iteration) { if (iteration == 0) { return ""; } return Integer.toString(iteration); } - - public static boolean evaluateIterationCondition(LensContext context, - LensElementContext accountContext, IterationSpecificationType iterationType, - int iteration, String iterationToken, boolean beforeIteration, - ExpressionFactory expressionFactory, ExpressionVariables variables, Task task, OperationResult result) + + public static boolean evaluateIterationCondition(LensContext context, + LensElementContext accountContext, IterationSpecificationType iterationType, + int iteration, String iterationToken, boolean beforeIteration, + ExpressionFactory expressionFactory, ExpressionVariables variables, Task task, OperationResult result) throws ExpressionEvaluationException, SchemaException, ObjectNotFoundException { if (iterationType == null) { return true; @@ -839,10 +839,10 @@ public static boolean evaluateIterationCondition(LensCont ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_BOOLEAN, context.getPrismContext()); Expression,PrismPropertyDefinition> expression = expressionFactory.makeExpression(expressionType, outputDefinition , desc, task, result); - + variables.addVariableDefinition(ExpressionConstants.VAR_ITERATION, iteration); variables.addVariableDefinition(ExpressionConstants.VAR_ITERATION_TOKEN, iterationToken); - + ExpressionEvaluationContext expressionContext = new ExpressionEvaluationContext(null , variables, desc, task, result); PrismValueDeltaSetTriple> outputTriple = ModelExpressionThreadLocalHolder.evaluateExpressionInContext(expression, expressionContext, context, null, task, result); Collection> outputValues = outputTriple.getNonNegativeValues(); @@ -859,7 +859,7 @@ public static boolean evaluateIterationCondition(LensCont return realValue; } - + /** * Used for assignments and similar objects that do not have separate lifecycle. */ @@ -887,7 +887,7 @@ public static AssignmentPathVariables computeAssignmentPathVariables(AssignmentP } AssignmentPathVariables vars = new AssignmentPathVariables(); vars.setAssignmentPath(assignmentPath.clone()); - + Iterator iterator = assignmentPath.getSegments().iterator(); while (iterator.hasNext()) { AssignmentPathSegmentImpl segment = iterator.next(); @@ -903,7 +903,7 @@ public static AssignmentPathVariables computeAssignmentPathVariables(AssignmentP magicAssignmentIdi = vars.getMagicAssignment(); mergeExtension(magicAssignmentIdi, segmentAssignmentIdi); } - + // Collect extension values from the source object extension ObjectType segmentSource = segment.getSource(); if (segmentSource != null) { @@ -912,16 +912,16 @@ public static AssignmentPathVariables computeAssignmentPathVariables(AssignmentP // immediate assignment (use assignment from previous iteration) vars.setImmediateAssignment(vars.getThisAssignment()); - + // this assignment ItemDeltaItem,PrismContainerDefinition> thisAssignment = segmentAssignmentIdi.clone(); vars.setThisAssignment(thisAssignment); - + if (iterator.hasNext() && segmentSource instanceof AbstractRoleType) { vars.setImmediateRole((PrismObject) segmentSource.asPrismObject()); } } - + AssignmentPathSegmentImpl focusAssignmentSegment = assignmentPath.first(); vars.setFocusAssignment(focusAssignmentSegment.getAssignmentIdi().clone()); @@ -959,7 +959,7 @@ private static void mergeExtension(ItemDeltaItem,PrismContainerDefinition> dstItem, Item,PrismContainerDefinition> srcItem) throws SchemaException { if (srcItem == null || dstItem == null) { @@ -968,19 +968,19 @@ private static void mergeExtension(Item,Pris PrismContainer srcExtension = ((PrismContainer)srcItem).findContainer(AssignmentType.F_EXTENSION); mergeExtensionContainers(dstItem, srcExtension); } - + private static void mergeExtension(ItemDeltaItem,PrismContainerDefinition> destIdi, PrismObject srcObject) throws SchemaException { if (srcObject == null) { return; } - + PrismContainer srcExtension = srcObject.findContainer(ObjectType.F_EXTENSION); - + mergeExtensionContainers(destIdi.getItemNew(), srcExtension); mergeExtensionContainers(destIdi.getItemOld(), srcExtension); } - + private static void mergeExtensionContainers(Item,PrismContainerDefinition> dstItem, PrismContainer srcExtension) throws SchemaException { if (dstItem == null) { return; @@ -1007,14 +1007,14 @@ private static void mergeExtension(PrismContainer magicExtension, } } } - + public static Mapping.Builder addAssignmentPathVariables(Mapping.Builder builder, AssignmentPathVariables assignmentPathVariables) { ExpressionVariables expressionVariables = new ExpressionVariables(); Utils.addAssignmentPathVariables(assignmentPathVariables, expressionVariables); return builder.addVariableDefinitions(expressionVariables.getMap()); } - - public static void checkContextSanity(LensContext context, String activityDescription, + + public static void checkContextSanity(LensContext context, String activityDescription, OperationResult result) throws SchemaException, PolicyViolationException { LensFocusContext focusContext = context.getFocusContext(); if (focusContext != null) { @@ -1036,7 +1036,7 @@ private static void checkObjectPolicy(LensFocusContext } PrismObject focusObjectNew = focusContext.getObjectNew(); ObjectDelta focusDelta = focusContext.getDelta(); - + for (PropertyConstraintType propertyConstraintType: objectPolicyConfigurationType.getPropertyConstraint()) { ItemPath itemPath = propertyConstraintType.getPath().getItemPath(); if (BooleanUtils.isTrue(propertyConstraintType.isOidBound())) { @@ -1070,7 +1070,7 @@ private static void checkObjectPolicy(LensFocusContext } } } - + // Deprecated if (BooleanUtils.isTrue(objectPolicyConfigurationType.isOidNameBoundMode())) { if (focusDelta != null) { @@ -1098,12 +1098,12 @@ public static PrismContainer createAssignmentSingleValueContaine // Make it appear to be single-value. Therefore paths without segment IDs will work. return assignmentType.asPrismContainerValue().asSingleValuedContainer(SchemaConstantsGenerated.C_ASSIGNMENT); } - + public static AssignmentType getAssignmentType(ItemDeltaItem,PrismContainerDefinition> assignmentIdi, boolean old) { return PrismContainerValue.asContainerable(assignmentIdi.getSingleValue(old)); } - - + + public static String getChannel(LensContext context, Task task) { if (context != null && context.getChannel() != null){ return context.getChannel(); @@ -1112,7 +1112,7 @@ public static String getChannel(LensContext context, T } return null; } - + public static void setDeltaOldValue(LensElementContext ctx, ItemDelta itemDelta) { if (itemDelta.getEstimatedOldValues() != null) { return; @@ -1132,7 +1132,7 @@ public static void setDeltaOldValue(LensElementContext } } } - + public static void setDeltaOldValue(LensElementContext ctx, ObjectDelta objectDelta) { if (objectDelta == null) { return; @@ -1215,14 +1215,14 @@ public static void triggerConstraint(@Nullable EvaluatedPolicyRule rule, Evaluat } } - + public static void processRuleWithException(EvaluatedPolicyRule rule, EvaluatedPolicyRuleTrigger trigger, Collection policySituations, PolicyExceptionType policyException) { LOGGER.debug("Policy rule {} would be triggered, but there is an exception for it. Not trigerring", rule==null?null:rule.getName()); - + if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Policy rule {} would be triggered, but there is an exception for it:\nTrigger:\n{}\nException:\n{}", + LOGGER.trace("Policy rule {} would be triggered, but there is an exception for it:\nTrigger:\n{}\nException:\n{}", rule==null?null:rule.getName(), trigger.debugDump(1), policyException); } @@ -1233,14 +1233,14 @@ public static void processRuleWithException(EvaluatedPolicyRule rule, EvaluatedP } - + public static void partialExecute(String componentName, ProjectorComponentRunnable runnable, Supplier optionSupplier) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, PolicyViolationException, ExpressionEvaluationException, ObjectAlreadyExistsException { partialExecute(componentName, runnable, optionSupplier, null); } - - public static void partialExecute(String componentName, ProjectorComponentRunnable runnable, + + public static void partialExecute(String componentName, ProjectorComponentRunnable runnable, Supplier optionSupplier, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, PolicyViolationException, ExpressionEvaluationException, ObjectAlreadyExistsException { @@ -1260,7 +1260,7 @@ public static void partialExecute(String componentName, ProjectorComponentRunnab } throw e; } - + } } @@ -1285,7 +1285,7 @@ public static void checkMaxIterations(int iteration, int maxIterations, String c throw new ObjectAlreadyExistsException(sb.toString()); } } - + public static boolean needsFullShadowForCredentialProcessing(LensProjectionContext projCtx) throws SchemaException { RefinedObjectClassDefinition refinedProjDef = projCtx.getStructuralObjectClassDefinition(); if (refinedProjDef == null) { @@ -1303,10 +1303,10 @@ public static boolean needsFullShadowForCredentialProcessing(LensProjectionConte } return false; } - + public static boolean isPasswordReturnedByDefault(LensProjectionContext projCtx) { CredentialsCapabilityType credentialsCapabilityType = ResourceTypeUtil.getEffectiveCapability(projCtx.getResource(), CredentialsCapabilityType.class); return CapabilityUtil.isPasswordReturnedByDefault(credentialsCapabilityType); } - + } 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 a6ce96e375a..22996facd85 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 @@ -35,7 +35,7 @@ * */ public class ObjectDeltaWaves implements List>, DebugDumpable, Serializable { - + private List> waves = new ArrayList>(); /** @@ -93,9 +93,9 @@ public void checkConsistence(boolean requireOid, String shortDesc) { } catch (IllegalStateException e) { throw new IllegalStateException(e.getMessage()+"; in "+shortDesc+", wave "+wave, e); } - } + } } - + public void normalize() { if (waves != null) { for (ObjectDelta wave: waves) { @@ -105,11 +105,11 @@ public void normalize() { } } } - + public ObjectDeltaWaves clone() { ObjectDeltaWaves clone = new ObjectDeltaWaves(); copyValues(clone); - return clone; + return clone; } protected void copyValues(ObjectDeltaWaves clone) { @@ -121,7 +121,7 @@ protected void copyValues(ObjectDeltaWaves clone) { } } } - + public void adopt(PrismContext prismContext) throws SchemaException { for (ObjectDelta thisWave: this.waves) { if (thisWave != null) { @@ -132,7 +132,7 @@ public void adopt(PrismContext prismContext) throws SchemaException { // DELEGATED METHODS (with small tweaks) - + /* (non-Javadoc) * @see java.util.List#size() */ @@ -326,9 +326,9 @@ public ListIterator> listIterator(int index) { public List> subList(int fromIndex, int toIndex) { return waves.subList(fromIndex, toIndex); } - + // DUMP - + @Override public String debugDump() { return debugDump(0); @@ -342,17 +342,17 @@ public String dump(boolean showTriples) { public String debugDump(int indent) { return debugDump(indent, true); } - + public String debugDump(int indent, boolean showTriples) { StringBuilder sb = new StringBuilder(); DebugUtil.indentDebugDump(sb, indent); sb.append("ObjectDeltaWaves:"); - + if (waves.isEmpty()) { sb.append(" empty"); return sb.toString(); } - + if (waves.size() == 1) { sb.append(" single wave\n"); if (waves.get(0) != null) { @@ -376,7 +376,7 @@ public String debugDump(int indent, boolean showTriples) { } } } - + return sb.toString(); } @@ -439,6 +439,6 @@ public void checkEncrypted(String shortDesc) { } catch (IllegalStateException e) { throw new IllegalStateException(e.getMessage()+"; in "+shortDesc+", wave "+wave, e); } - } + } } } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/OperationalDataManager.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/OperationalDataManager.java index 6850fa2b761..41690c8420c 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/OperationalDataManager.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/OperationalDataManager.java @@ -59,55 +59,55 @@ */ @Component public class OperationalDataManager { - + private static final Trace LOGGER = TraceManager.getTrace(OperationalDataManager.class); - + @Autowired(required = false) private ActivationComputer activationComputer; - + // for inserting workflow-related metadata to changed object @Autowired(required = false) private WorkflowManager workflowManager; @Autowired(required = true) private PrismContext prismContext; - + public void applyRequestMetadata(LensContext context, XMLGregorianCalendar now, Task task, OperationResult result) throws SchemaException { - + MetadataType requestMetadata = new MetadataType(); applyRequestMetadata(context, requestMetadata, now, task); context.setRequestMetadata(requestMetadata); - + } - + public void applyMetadataAdd(LensContext context, - PrismObject objectToAdd, XMLGregorianCalendar now, Task task, OperationResult result) + PrismObject objectToAdd, XMLGregorianCalendar now, Task task, OperationResult result) throws SchemaException { - + T objectType = objectToAdd.asObjectable(); MetadataType metadataType = objectType.getMetadata(); if (metadataType == null) { metadataType = new MetadataType(); objectType.setMetadata(metadataType); } - + transplantRequestMetadata(context, metadataType); - + applyCreateMetadata(context, metadataType, now, task); - + if (workflowManager != null) { metadataType.getCreateApproverRef().addAll(workflowManager.getApprovedBy(task, result)); } - + if (objectToAdd.canRepresent(FocusType.class)) { applyAssignmentMetadataObject((LensContext) context, objectToAdd, now, task, result); } - + } - + public void applyMetadataModify(ObjectDelta objectDelta, - LensElementContext objectContext, Class objectTypeClass, + LensElementContext objectContext, Class objectTypeClass, XMLGregorianCalendar now, Task task, LensContext context, OperationResult result) throws SchemaException { String channel = LensUtil.getChannel(context, task); @@ -166,36 +166,36 @@ public void applyMetadataModify(Obj } if (FocusType.class.isAssignableFrom(objectTypeClass)) { - applyAssignmentMetadataDelta((LensContext) context, + applyAssignmentMetadataDelta((LensContext) context, (ObjectDelta)objectDelta, now, task, result); } } - + private void applyAssignmentMetadataObject(LensContext context, PrismObject objectToAdd, XMLGregorianCalendar now, Task task, OperationResult result) throws SchemaException { - + PrismContainer assignmentContainer = objectToAdd.findContainer(FocusType.F_ASSIGNMENT); if (assignmentContainer != null) { for (PrismContainerValue assignmentContainerValue: assignmentContainer.getValues()) { applyAssignmentValueMetadataAdd(context, assignmentContainerValue, "ADD", now, task, result); } } - + } - + private void applyAssignmentMetadataDelta(LensContext context, ObjectDelta objectDelta, XMLGregorianCalendar now, Task task, OperationResult result) throws SchemaException { if (objectDelta == null || objectDelta.isDelete()) { return; } - + if (objectDelta.isAdd()) { applyAssignmentMetadataObject(context, objectDelta.getObjectToAdd(), now, task, result); - + } else { - + for (ItemDelta itemDelta: objectDelta.getModifications()) { if (itemDelta.getPath().equivalent(SchemaConstants.PATH_ASSIGNMENT)) { ContainerDelta assignmentDelta = (ContainerDelta)itemDelta; @@ -212,24 +212,24 @@ private void applyAssignmentMetadataDelta(LensContext c } // TODO: assignment modification } - + } - + } - + private void applyAssignmentValueMetadataAdd(LensContext context, PrismContainerValue assignmentContainerValue, String desc, XMLGregorianCalendar now, Task task, OperationResult result) throws SchemaException { - + AssignmentType assignmentType = assignmentContainerValue.asContainerable(); MetadataType metadataType = assignmentType.getMetadata(); if (metadataType == null) { metadataType = new MetadataType(); assignmentType.setMetadata(metadataType); } - + transplantRequestMetadata(context, metadataType); - + // This applies the effective status only to assginments that are completely new (whole container is added/replaced) // The effectiveStatus of existing assignments is processes in FocusProcessor.processAssignmentActivation() // We cannot process that here. Because this code is not even triggered when there is no delta. So recompute will not work. @@ -242,9 +242,9 @@ private void applyAssignmentValueMetadataAdd(LensContext void applyRequestMetadata(LensContext context, metaData.setRequestorRef(ObjectTypeUtil.createObjectRef(task.getOwner())); } } - + private void transplantRequestMetadata(LensContext context, MetadataType metaData) { MetadataType requestMetadata = context.getRequestMetadata(); if (requestMetadata == null) { @@ -266,13 +266,13 @@ private void transplantRequestMetadata(LensContext con metaData.setRequestTimestamp(requestMetadata.getRequestTimestamp()); metaData.setRequestorRef(requestMetadata.getRequestorRef()); } - + public MetadataType createCreateMetadata(LensContext context, XMLGregorianCalendar now, Task task) { MetadataType metaData = new MetadataType(); applyCreateMetadata(context, metaData, now, task); return metaData; } - + private void applyCreateMetadata(LensContext context, MetadataType metaData, XMLGregorianCalendar now, Task task) { String channel = LensUtil.getChannel(context, task); metaData.setCreateChannel(channel); @@ -281,8 +281,8 @@ private void applyCreateMetadata(LensContext context, metaData.setCreatorRef(ObjectTypeUtil.createObjectRef(task.getOwner())); } } - - public Collection> createModifyMetadataDeltas(LensContext context, + + public Collection> createModifyMetadataDeltas(LensContext context, ItemPath metadataPath, PrismObjectDefinition def, XMLGregorianCalendar now, Task task) { Collection> deltas = new ArrayList<>(); String channel = LensUtil.getChannel(context, task); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/PersonaProcessor.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/PersonaProcessor.java index b2c6b7e2510..acfecb83250 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/PersonaProcessor.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/PersonaProcessor.java @@ -68,45 +68,45 @@ /** * Runs persona-related changes after the primary operation is all done. Executed directly from clockwork. - * + * * Not entirely clean solution. Ideally, this should be somehow integrated in the clockwork process (nested contexts). * But should be good enough for now. - * + * * @author semancik */ @Component public class PersonaProcessor { - + private static final Trace LOGGER = TraceManager.getTrace(PersonaProcessor.class); - + @Autowired(required=true) private ConstructionProcessor constructionProcessor; - + @Autowired(required=true) private ObjectTemplateProcessor objectTemplateProcessor; - + @Autowired(required=true) private ObjectResolver objectResolver; - + @Autowired @Qualifier("cacheRepositoryService") private transient RepositoryService repositoryService; - + @Autowired(required = true) private ContextFactory contextFactory; - + @Autowired(required = true) private Clockwork clockwork; - + @Autowired(required=true) private Clock clock; - + @Autowired(required=true) private PrismContext prismContext; - + @SuppressWarnings({ "unchecked", "rawtypes" }) public HookOperationMode processPersonaChanges(LensContext context, Task task, OperationResult result) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException, PolicyViolationException { - + LensFocusContext focusContext = context.getFocusContext(); if (focusContext == null) { return HookOperationMode.FOREGROUND; @@ -115,7 +115,7 @@ public HookOperationMode processPersonaChanges(LensContex // We can do this only for FocusType. return HookOperationMode.FOREGROUND; } - + if (focusContext.isDelete()) { // Special case. Simply delete all the existing personas. // TODO: maybe we need to do this before actual focus delete? @@ -123,18 +123,18 @@ public HookOperationMode processPersonaChanges(LensContex // TODO return HookOperationMode.FOREGROUND; } - + return processPersonaChangesFocus((LensContext) context, task, result); } - + public HookOperationMode processPersonaChangesFocus(LensContext context, Task task, OperationResult result) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException, PolicyViolationException { DeltaSetTriple> evaluatedAssignmentTriple = (DeltaSetTriple)context.getEvaluatedAssignmentTriple(); if (evaluatedAssignmentTriple == null || evaluatedAssignmentTriple.isEmpty()) { return HookOperationMode.FOREGROUND; } - + DeltaSetTriple activePersonaKeyTriple = new DeltaSetTriple<>(); - + ComplexConstructionConsumer> consumer = new ComplexConstructionConsumer>() { @Override @@ -154,7 +154,7 @@ public void onUnchangedValid(PersonaKey key, String desc) { @Override public void onUnchangedInvalid(PersonaKey key, String desc) { - + } @Override @@ -167,21 +167,21 @@ public void after(PersonaKey key, String desc, DeltaMapTriple>> constructionMapTriple) { } - + }; - - DeltaMapTriple>> constructionMapTriple = - constructionProcessor.processConstructions(context, evaluatedAssignmentTriple, + + DeltaMapTriple>> constructionMapTriple = + constructionProcessor.processConstructions(context, evaluatedAssignmentTriple, evaluatedAssignment -> evaluatedAssignment.getPersonaConstructionTriple(), construction -> new PersonaKey(construction.getConstructionType()), consumer, task, result); - + LOGGER.trace("activePersonaKeyTriple:\n{}", activePersonaKeyTriple.debugDumpLazily()); - + List existingPersonas = readExistingPersonas(context, task, result); LOGGER.trace("existingPersonas:\n{}", existingPersonas); - + for (PersonaKey key: activePersonaKeyTriple.getNonNegativeValues()) { FocusType existingPersona = findPersona(existingPersonas, key); LOGGER.trace("existingPersona: {}", existingPersona); @@ -205,22 +205,22 @@ public void after(PersonaKey key, String desc, personaModify(context, key, construction, existingPersona.asPrismObject(), task, result); } } - + for (PersonaKey key: activePersonaKeyTriple.getMinusSet()) { FocusType existingPersona = findPersona(existingPersonas, key); if (existingPersona != null) { personaDelete(context, key, existingPersona, task, result); } } - + return HookOperationMode.FOREGROUND; } - - + + public List readExistingPersonas(LensContext context, Task task, OperationResult result) { LensFocusContext focusContext = context.getFocusContext(); PrismObject focus = focusContext.getObjectNew(); - + List personas = new ArrayList<>(); String desc = "personaRef in "+focus; for (ObjectReferenceType personaRef: focus.asObjectable().getPersonaRef()) { @@ -232,7 +232,7 @@ public List readExistingPersonas(LensContext // But go on... } } - + return personas; } @@ -259,82 +259,82 @@ private boolean personaMatches(FocusType persona, PersonaKey key) { } return true; } - - public void personaAdd(LensContext context, PersonaKey key, PersonaConstruction construction, - Task task, OperationResult result) + + public void personaAdd(LensContext context, PersonaKey key, PersonaConstruction construction, + Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, PolicyViolationException, ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException { PrismObject focus = context.getFocusContext().getObjectNew(); LOGGER.debug("Adding persona {} for {} using construction {}", key, focus, construction); PersonaConstructionType constructionType = construction.getConstructionType(); ObjectReferenceType objectMappingRef = constructionType.getObjectMappingRef(); ObjectTemplateType objectMappingType = objectResolver.resolve(objectMappingRef, ObjectTemplateType.class, null, "object mapping in persona construction in "+focus, task, result); - + QName targetType = constructionType.getTargetType(); PrismObjectDefinition objectDef = prismContext.getSchemaRegistry().findObjectDefinitionByType(targetType); PrismObject target = objectDef.instantiate(); - + FocusTypeUtil.setSubtype(target, constructionType.getTargetSubtype()); - + // pretend ADD focusOdo. We need to push all the items through the object template ObjectDeltaObject focusOdo = new ObjectDeltaObject<>(null, focus.createAddDelta(), focus); ObjectDelta targetDelta = target.createAddDelta(); - + String contextDesc = "object mapping "+objectMappingType+ " for persona construction for "+focus; XMLGregorianCalendar now = clock.currentTimeXMLGregorianCalendar(); - - Collection> itemDeltas = objectTemplateProcessor.processObjectMapping(context, objectMappingType, + + Collection> itemDeltas = objectTemplateProcessor.processObjectMapping(context, objectMappingType, focusOdo, target, targetDelta, contextDesc, now, task, result); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("itemDeltas:\n{}", DebugUtil.debugDump(itemDeltas)); } - + for (ItemDelta itemDelta: itemDeltas) { itemDelta.applyTo(target); } - + LOGGER.trace("Creating persona:\n{}", target.debugDumpLazily()); - + executePersonaDelta(targetDelta, task, result); - + link(context, target.asObjectable(), result); } - - public void personaModify(LensContext context, PersonaKey key, PersonaConstruction construction, - PrismObject existingPersona, Task task, OperationResult result) + + public void personaModify(LensContext context, PersonaKey key, PersonaConstruction construction, + PrismObject existingPersona, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, PolicyViolationException, ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException { PrismObject focus = context.getFocusContext().getObjectNew(); LOGGER.debug("Modifying persona {} for {} using construction {}", key, focus, construction); PersonaConstructionType constructionType = construction.getConstructionType(); ObjectReferenceType objectMappingRef = constructionType.getObjectMappingRef(); ObjectTemplateType objectMappingType = objectResolver.resolve(objectMappingRef, ObjectTemplateType.class, null, "object mapping in persona construction in "+focus, task, result); - + ObjectDeltaObject focusOdo = context.getFocusContext().getObjectDeltaObject(); String contextDesc = "object mapping "+objectMappingType+ " for persona construction for "+focus; XMLGregorianCalendar now = clock.currentTimeXMLGregorianCalendar(); - - Collection> itemDeltas = objectTemplateProcessor.processObjectMapping(context, objectMappingType, + + Collection> itemDeltas = objectTemplateProcessor.processObjectMapping(context, objectMappingType, focusOdo, existingPersona, null, contextDesc, now, task, result); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("itemDeltas:\n{}", DebugUtil.debugDump(itemDeltas)); } - + ObjectDelta targetDelta = existingPersona.createModifyDelta(); for (ItemDelta itemDelta: itemDeltas) { targetDelta.addModification(itemDelta); } - + executePersonaDelta(targetDelta, task, result); } - - public void personaDelete(LensContext context, PersonaKey key, FocusType existingPersona, Task task, OperationResult result) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { + + public void personaDelete(LensContext context, PersonaKey key, FocusType existingPersona, Task task, OperationResult result) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { PrismObject focus = context.getFocusContext().getObjectOld(); LOGGER.debug("Deleting persona {} for {}: ", key, focus, existingPersona); ObjectDelta targetDelta = existingPersona.asPrismObject().createDeleteDelta(); executePersonaDelta(targetDelta, task, result); - + unlink(context, existingPersona, result); } @@ -344,20 +344,20 @@ private void link(LensContext context, FocusType perso refValue.setOid(persona.getOid()); refValue.setTargetType(persona.asPrismObject().getDefinition().getTypeName()); delta.addModificationAddReference(FocusType.F_PERSONA_REF, refValue); - + repositoryService.modifyObject(delta.getObjectTypeClass(), delta.getOid(), delta.getModifications(), result); } - + private void unlink(LensContext context, FocusType persona, OperationResult result) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { ObjectDelta delta = context.getFocusContext().getObjectNew().createModifyDelta(); PrismReferenceValue refValue = new PrismReferenceValue(); refValue.setOid(persona.getOid()); refValue.setTargetType(persona.asPrismObject().getDefinition().getTypeName()); delta.addModificationDeleteReference(FocusType.F_PERSONA_REF, refValue); - + repositoryService.modifyObject(delta.getObjectTypeClass(), delta.getOid(), delta.getModifications(), result); } - + private void executePersonaDelta(ObjectDelta delta, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, PolicyViolationException, ExpressionEvaluationException, ObjectAlreadyExistsException, SecurityViolationException { Collection> deltas = MiscSchemaUtil.createCollection(delta); LensContext context = contextFactory.createContext(deltas, null, task, result); @@ -368,7 +368,7 @@ private void executePersonaDelta(ObjectDelta delta, Ta } class PersonaKey implements HumanReadableDescribable { - + private QName type; private List subtypes; @@ -377,7 +377,7 @@ public PersonaKey(PersonaConstructionType constructionType) { this.type = constructionType.getTargetType(); this.subtypes = constructionType.getTargetSubtype(); } - + public QName getType() { return type; } @@ -433,7 +433,7 @@ public String toString() { private PersonaProcessor getOuterType() { return PersonaProcessor.this; } - + } } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ProjectorComponentRunnable.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ProjectorComponentRunnable.java index 296b46c0a24..a20226a39ae 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ProjectorComponentRunnable.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ProjectorComponentRunnable.java @@ -26,13 +26,13 @@ /** * Runnable with proper set of exceptions that fit running of projector components. - * + * * @author semancik */ @FunctionalInterface public interface ProjectorComponentRunnable { - - void run() throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, + + void run() throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, PolicyViolationException, ExpressionEvaluationException, ObjectAlreadyExistsException; } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/SimpleOperationName.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/SimpleOperationName.java index f696814a5fe..4f74bfbd6a4 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/SimpleOperationName.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/SimpleOperationName.java @@ -20,11 +20,11 @@ * */ public enum SimpleOperationName { - + ADD("add"), MODIFY("modify"), DELETE("delete"); - + private final String value; private SimpleOperationName(String value) { diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/SynchronizationIntent.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/SynchronizationIntent.java index 14034dca0b7..0baca592cb6 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/SynchronizationIntent.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/SynchronizationIntent.java @@ -23,27 +23,27 @@ * */ public enum SynchronizationIntent { - + /** * New account that should be added (and linked) */ ADD, - + /** * Existing account that should be deleted (and unlinked) */ DELETE, - + /** * Existing account that is kept as it is (remains linked). */ KEEP, - + /** * Existing account that should be unlinked (but NOT deleted) */ UNLINK, - + /** * Existing account that belongs to the user and needs to be synchronized. * This may include deleting, archiving or disabling the account. diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/UndefinedEvaluationOrderImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/UndefinedEvaluationOrderImpl.java index d8a432fe0b2..9c98a55db47 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/UndefinedEvaluationOrderImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/UndefinedEvaluationOrderImpl.java @@ -38,7 +38,7 @@ public class UndefinedEvaluationOrderImpl implements EvaluationOrder { public int getSummaryOrder() { return -1; // TODO } - + @Override public EvaluationOrder advance(QName relation) { return this; @@ -101,7 +101,7 @@ public String debugDump(int indent) { public String toString() { return "EvaluationOrder(" + shortDump() + ")"; } - + @Override public void shortDump(StringBuilder sb) { sb.append("UNDEFINED"); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ActivationProcessor.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ActivationProcessor.java index 70125d9fe31..0a769b559a8 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ActivationProcessor.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ActivationProcessor.java @@ -76,7 +76,7 @@ /** * The processor that takes care of user activation mapping to an account (outbound direction). - * + * * @author Radovan Semancik */ @Component @@ -88,7 +88,7 @@ public class ActivationProcessor { private static final QName LEGAL_PROPERTY_NAME = new QName(SchemaConstants.NS_C, "legal"); private static final QName ASSIGNED_PROPERTY_NAME = new QName(SchemaConstants.NS_C, "assigned"); private static final QName FOCUS_EXISTS_PROPERTY_NAME = new QName(SchemaConstants.NS_C, "focusExists"); - + private PrismObjectDefinition userDefinition; private PrismContainerDefinition activationDefinition; @@ -97,23 +97,23 @@ public class ActivationProcessor { @Autowired(required=true) private MappingEvaluator mappingEvaluator; - + @Autowired(required=true) private MidpointFunctions midpointFunctions; public void processActivation(LensContext context, LensProjectionContext projectionContext, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException, CommunicationException, ConfigurationException, SecurityViolationException { - + LensFocusContext focusContext = context.getFocusContext(); if (focusContext != null && !FocusType.class.isAssignableFrom(focusContext.getObjectTypeClass())) { // We can do this only for focal object. return; } - + processActivationFocal((LensContext)context, projectionContext, now, task, result); } - - private void processActivationFocal(LensContext context, + + private void processActivationFocal(LensContext context, LensProjectionContext projectionContext, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException, CommunicationException, ConfigurationException, SecurityViolationException { LensFocusContext focusContext = context.getFocusContext(); if (focusContext == null) { @@ -125,13 +125,13 @@ private void processActivationFocal(LensContext context processActivationUserFuture(context, projectionContext, now, task, result); } - public void processActivationUserCurrent(LensContext context, LensProjectionContext projCtx, + public void processActivationUserCurrent(LensContext context, LensProjectionContext projCtx, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException, CommunicationException, ConfigurationException, SecurityViolationException { String projCtxDesc = projCtx.toHumanReadableString(); SynchronizationPolicyDecision decision = projCtx.getSynchronizationPolicyDecision(); SynchronizationIntent synchronizationIntent = projCtx.getSynchronizationIntent(); - + if (decision == SynchronizationPolicyDecision.BROKEN) { LOGGER.trace("Broken projection {}, skipping further activation processing", projCtxDesc); return; @@ -139,13 +139,13 @@ public void processActivationUserCurrent(LensContext co if (decision != null) { throw new IllegalStateException("Decision "+decision+" already present for projection "+projCtxDesc); } - + if (synchronizationIntent == SynchronizationIntent.UNLINK) { projCtx.setSynchronizationPolicyDecision(SynchronizationPolicyDecision.UNLINK); LOGGER.trace("Evaluated decision for {} to {} because of unlink synchronization intent, skipping further activation processing", projCtxDesc, SynchronizationPolicyDecision.UNLINK); return; } - + if (projCtx.isThombstone()) { if (shouldKeepThombstone(projCtx)) { // Let's keep thombstones linked until they expire. So we do not have shadows without owners. @@ -158,22 +158,22 @@ public void processActivationUserCurrent(LensContext co } return; } - + if (synchronizationIntent == SynchronizationIntent.DELETE || projCtx.isDelete()) { // TODO: is this OK? projCtx.setSynchronizationPolicyDecision(SynchronizationPolicyDecision.DELETE); LOGGER.trace("Evaluated decision for {} to {}, skipping further activation processing", projCtxDesc, SynchronizationPolicyDecision.DELETE); return; } - - boolean shadowShouldExist = evaluateExistenceMapping(context, projCtx, now, true, task, result); + boolean shadowShouldExist = evaluateExistenceMapping(context, projCtx, now, true, task, result); + LOGGER.trace("Evaluated intended existence of projection {} to {}", projCtxDesc, shadowShouldExist); - + // Let's reconcile the existence intent (shadowShouldExist) and the synchronization intent in the context LensProjectionContext lowerOrderContext = LensUtil.findLowerOrderContext(context, projCtx); - + if (synchronizationIntent == null || synchronizationIntent == SynchronizationIntent.SYNCHRONIZE) { if (shadowShouldExist) { projCtx.setActive(true); @@ -211,7 +211,7 @@ public void processActivationUserCurrent(LensContext co LensUtil.moveTriggers(projCtx, context.getFocusContext()); } } - + } else if (synchronizationIntent == SynchronizationIntent.ADD) { if (shadowShouldExist) { projCtx.setActive(true); @@ -224,7 +224,7 @@ public void processActivationUserCurrent(LensContext co } else { throw new PolicyViolationException("Request to add projection "+projCtxDesc+" but the activation policy decided that it should not exist"); } - + } else if (synchronizationIntent == SynchronizationIntent.KEEP) { if (shadowShouldExist) { projCtx.setActive(true); @@ -236,27 +236,27 @@ public void processActivationUserCurrent(LensContext co } else { throw new PolicyViolationException("Request to keep projection "+projCtxDesc+" but the activation policy decided that it should not exist"); } - + } else { throw new IllegalStateException("Unknown sync intent "+synchronizationIntent); } - + LOGGER.trace("Evaluated decision for projection {} to {}", projCtxDesc, decision); - + projCtx.setSynchronizationPolicyDecision(decision); - + PrismObject focusNew = context.getFocusContext().getObjectNew(); if (focusNew == null) { // This must be a user delete or something similar. No point in proceeding LOGGER.trace("focusNew is null, skipping activation processing of {}", projCtxDesc); return; } - + if (decision == SynchronizationPolicyDecision.UNLINK || decision == SynchronizationPolicyDecision.DELETE) { LOGGER.trace("Decision is {}, skipping activation properties processing for {}", decision, projCtxDesc); return; } - + ResourceObjectTypeDefinitionType resourceAccountDefType = projCtx.getResourceObjectTypeDefinitionType(); if (resourceAccountDefType == null) { LOGGER.trace("No refined object definition, therefore also no activation outbound definition, skipping activation processing for account " + projCtxDesc); @@ -267,7 +267,7 @@ public void processActivationUserCurrent(LensContext co LOGGER.trace("No activation definition in projection {}, skipping activation properties processing", projCtxDesc); return; } - + ActivationCapabilityType capActivation = ResourceTypeUtil.getEffectiveCapability(projCtx.getResource(), ActivationCapabilityType.class); if (capActivation == null) { LOGGER.trace("Skipping activation status and validity processing because {} has no activation capability", projCtx.getResource()); @@ -278,11 +278,11 @@ public void processActivationUserCurrent(LensContext co ActivationValidityCapabilityType capValidFrom = CapabilityUtil.getEffectiveActivationValidFrom(capActivation); ActivationValidityCapabilityType capValidTo = CapabilityUtil.getEffectiveActivationValidTo(capActivation); ActivationLockoutStatusCapabilityType capLockoutStatus = CapabilityUtil.getEffectiveActivationLockoutStatus(capActivation); - + if (capStatus != null) { evaluateActivationMapping(context, projCtx, activationType.getAdministrativeStatus(), - SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, + SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, capActivation, now, true, ActivationType.F_ADMINISTRATIVE_STATUS.getLocalPart(), task, result); } else { LOGGER.trace("Skipping activation administrative status processing because {} does not have activation administrative status capability", projCtx.getResource()); @@ -295,10 +295,10 @@ public void processActivationUserCurrent(LensContext co LOGGER.trace("Skipping activation validFrom processing because {} does not have activation validFrom capability nor outbound mapping with explicit target", projCtx.getResource()); } else { evaluateActivationMapping(context, projCtx, activationType.getValidFrom(), - SchemaConstants.PATH_ACTIVATION_VALID_FROM, SchemaConstants.PATH_ACTIVATION_VALID_FROM, + SchemaConstants.PATH_ACTIVATION_VALID_FROM, SchemaConstants.PATH_ACTIVATION_VALID_FROM, null, now, true, ActivationType.F_VALID_FROM.getLocalPart(), task, result); } - + ResourceBidirectionalMappingType validToMappingType = activationType.getValidTo(); if (validToMappingType == null || validToMappingType.getOutbound() == null) { LOGGER.trace("Skipping activation validTo processing because {} does not have appropriate outbound mapping", projCtx.getResource()); @@ -306,19 +306,19 @@ public void processActivationUserCurrent(LensContext co LOGGER.trace("Skipping activation validTo processing because {} does not have activation validTo capability nor outbound mapping with explicit target", projCtx.getResource()); } else { evaluateActivationMapping(context, projCtx, activationType.getValidTo(), - SchemaConstants.PATH_ACTIVATION_VALID_TO, SchemaConstants.PATH_ACTIVATION_VALID_TO, + SchemaConstants.PATH_ACTIVATION_VALID_TO, SchemaConstants.PATH_ACTIVATION_VALID_TO, null, now, true, ActivationType.F_VALID_TO.getLocalPart(), task, result); } - + if (capLockoutStatus != null) { evaluateActivationMapping(context, projCtx, activationType.getLockoutStatus(), - SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, + SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, capActivation, now, true, ActivationType.F_LOCKOUT_STATUS.getLocalPart(), task, result); } else { LOGGER.trace("Skipping activation lockout status processing because {} does not have activation lockout status capability", projCtx.getResource()); } - + } private boolean shouldKeepThombstone(LensProjectionContext projCtx) { @@ -333,15 +333,15 @@ private boolean shouldKeepThombstone(LensProjectionContext projCtx) { return false; } - public void processActivationMetadata(LensContext context, LensProjectionContext accCtx, + public void processActivationMetadata(LensContext context, LensProjectionContext accCtx, XMLGregorianCalendar now, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException { ObjectDelta projDelta = accCtx.getDelta(); if (projDelta == null) { return; } - + PropertyDelta statusDelta = projDelta.findPropertyDelta(SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS); - + if (statusDelta != null && !statusDelta.isDelete()) { // we have to determine if the status really changed @@ -387,32 +387,32 @@ public void processActivationMetadata(LensContext conte } } } - + } - + public void processActivationUserFuture(LensContext context, LensProjectionContext accCtx, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException, CommunicationException, ConfigurationException, SecurityViolationException { String accCtxDesc = accCtx.toHumanReadableString(); SynchronizationPolicyDecision decision = accCtx.getSynchronizationPolicyDecision(); SynchronizationIntent synchronizationIntent = accCtx.getSynchronizationIntent(); - - if (accCtx.isThombstone() || decision == SynchronizationPolicyDecision.BROKEN - || decision == SynchronizationPolicyDecision.IGNORE + + if (accCtx.isThombstone() || decision == SynchronizationPolicyDecision.BROKEN + || decision == SynchronizationPolicyDecision.IGNORE || decision == SynchronizationPolicyDecision.UNLINK || decision == SynchronizationPolicyDecision.DELETE) { return; } - + accCtx.recompute(); - + evaluateExistenceMapping(context, accCtx, now, false, task, result); - + PrismObject focusNew = context.getFocusContext().getObjectNew(); if (focusNew == null) { // This must be a user delete or something similar. No point in proceeding LOGGER.trace("focusNew is null, skipping activation processing of {}", accCtxDesc); return; } - + ResourceObjectTypeDefinitionType resourceAccountDefType = accCtx.getResourceObjectTypeDefinitionType(); if (resourceAccountDefType == null) { return; @@ -421,7 +421,7 @@ public void processActivationUserFuture(LensContext con if (activationType == null) { return; } - + ActivationCapabilityType capActivation = ResourceTypeUtil.getEffectiveCapability(accCtx.getResource(), ActivationCapabilityType.class); if (capActivation == null) { return; @@ -430,42 +430,42 @@ public void processActivationUserFuture(LensContext con ActivationStatusCapabilityType capStatus = CapabilityUtil.getEffectiveActivationStatus(capActivation); ActivationValidityCapabilityType capValidFrom = CapabilityUtil.getEffectiveActivationValidFrom(capActivation); ActivationValidityCapabilityType capValidTo = CapabilityUtil.getEffectiveActivationValidTo(capActivation); - + if (capStatus != null) { - + evaluateActivationMapping(context, accCtx, activationType.getAdministrativeStatus(), - SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, - capActivation, now, false, ActivationType.F_ADMINISTRATIVE_STATUS.getLocalPart(), task, result); + SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, + capActivation, now, false, ActivationType.F_ADMINISTRATIVE_STATUS.getLocalPart(), task, result); } if (capValidFrom != null) { evaluateActivationMapping(context, accCtx, activationType.getAdministrativeStatus(), - SchemaConstants.PATH_ACTIVATION_VALID_FROM, SchemaConstants.PATH_ACTIVATION_VALID_FROM, + SchemaConstants.PATH_ACTIVATION_VALID_FROM, SchemaConstants.PATH_ACTIVATION_VALID_FROM, null, now, false, ActivationType.F_VALID_FROM.getLocalPart(), task, result); } - + if (capValidTo != null) { evaluateActivationMapping(context, accCtx, activationType.getAdministrativeStatus(), - SchemaConstants.PATH_ACTIVATION_VALID_TO, SchemaConstants.PATH_ACTIVATION_VALID_TO, + SchemaConstants.PATH_ACTIVATION_VALID_TO, SchemaConstants.PATH_ACTIVATION_VALID_TO, null, now, false, ActivationType.F_VALID_FROM.getLocalPart(), task, result); } - + } - + private boolean evaluateExistenceMapping(final LensContext context, final LensProjectionContext projCtx, final XMLGregorianCalendar now, final boolean current, Task task, final OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException { final String projCtxDesc = projCtx.toHumanReadableString(); - + final Boolean legal = projCtx.isLegal(); if (legal == null) { throw new IllegalStateException("Null 'legal' for "+projCtxDesc); } - + LOGGER.trace("Evaluating intended existence of projection {}; legal={}", projCtxDesc, legal); - + ResourceObjectTypeDefinitionType resourceAccountDefType = projCtx.getResourceObjectTypeDefinitionType(); if (resourceAccountDefType == null) { return legal; @@ -483,7 +483,7 @@ private boolean evaluateExistenceMapping(final LensContext // "default mapping" return legal; } - + MappingEvaluatorParams, PrismPropertyDefinition, ShadowType, F> params = new MappingEvaluatorParams<>(); params.setMappingTypes(outbound); params.setMappingDesc("outbound existence mapping in projection " + projCtxDesc); @@ -493,11 +493,11 @@ private boolean evaluateExistenceMapping(final LensContext params.setTargetContext(projCtx); params.setFixTarget(true); params.setContext(context); - + params.setInitializer(builder -> { // Source: legal - ItemDeltaItem,PrismPropertyDefinition> legalSourceIdi = getLegalIdi(projCtx); - Source,PrismPropertyDefinition> legalSource + ItemDeltaItem,PrismPropertyDefinition> legalSourceIdi = getLegalIdi(projCtx); + Source,PrismPropertyDefinition> legalSource = new Source<>(legalSourceIdi, ExpressionConstants.VAR_LEGAL); builder.defaultSource(legalSource); @@ -507,11 +507,11 @@ private boolean evaluateExistenceMapping(final LensContext builder.addSource(assignedSource); // Source: focusExists - ItemDeltaItem,PrismPropertyDefinition> focusExistsSourceIdi = getFocusExistsIdi(context.getFocusContext()); - Source,PrismPropertyDefinition> focusExistsSource + ItemDeltaItem,PrismPropertyDefinition> focusExistsSourceIdi = getFocusExistsIdi(context.getFocusContext()); + Source,PrismPropertyDefinition> focusExistsSource = new Source<>(focusExistsSourceIdi, ExpressionConstants.VAR_FOCUS_EXISTS); builder.addSource(focusExistsSource); - + // Variable: focus builder.addVariableDefinition(ExpressionConstants.VAR_FOCUS, context.getFocusContext().getObjectDeltaObject()); @@ -528,7 +528,7 @@ private boolean evaluateExistenceMapping(final LensContext builder.originObject(projCtx.getResource()); return builder; }); - + final MutableBoolean output = new MutableBoolean(false); params.setProcessor((mappingOutputPath,outputStruct) -> { PrismValueDeltaSetTriple> outputTriple = outputStruct.getOutputTriple(); @@ -537,11 +537,11 @@ private boolean evaluateExistenceMapping(final LensContext output.setValue(legal); return false; } - + Collection> nonNegativeValues = outputTriple.getNonNegativeValues(); - - // MID-3507: this is probably the bug. The processor is executed after every mapping. - // The processing will die on the error if one mapping returns a value and the other mapping returns null + + // MID-3507: this is probably the bug. The processor is executed after every mapping. + // The processing will die on the error if one mapping returns a value and the other mapping returns null // (e.g. because the condition is false). This should be fixed. if (nonNegativeValues == null || nonNegativeValues.isEmpty()) { throw new ExpressionEvaluationException("Activation existence expression resulted in null or empty value for projection " + projCtxDesc); @@ -549,12 +549,12 @@ private boolean evaluateExistenceMapping(final LensContext if (nonNegativeValues.size() > 1) { throw new ExpressionEvaluationException("Activation existence expression resulted in too many values ("+nonNegativeValues.size()+") for projection " + projCtxDesc); } - + output.setValue(nonNegativeValues.iterator().next().getValue()); - + return false; }); - + PrismPropertyDefinitionImpl shadowExistsDef = new PrismPropertyDefinitionImpl<>( SHADOW_EXISTS_PROPERTY_NAME, DOMUtil.XSD_BOOLEAN, prismContext); @@ -562,50 +562,50 @@ private boolean evaluateExistenceMapping(final LensContext shadowExistsDef.setMaxOccurs(1); params.setTargetItemDefinition(shadowExistsDef); mappingEvaluator.evaluateMappingSetProjection(params, task, result); - + return (boolean) output.getValue(); } - - private void evaluateActivationMapping(final LensContext context, - final LensProjectionContext projCtx, ResourceBidirectionalMappingType bidirectionalMappingType, + + private void evaluateActivationMapping(final LensContext context, + final LensProjectionContext projCtx, ResourceBidirectionalMappingType bidirectionalMappingType, final ItemPath focusPropertyPath, final ItemPath projectionPropertyPath, - final ActivationCapabilityType capActivation, XMLGregorianCalendar now, final boolean current, + final ActivationCapabilityType capActivation, XMLGregorianCalendar now, final boolean current, String desc, final Task task, final OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException { - + MappingInitializer,PrismPropertyDefinition> initializer = builder -> { // Source: administrativeStatus, validFrom or validTo ItemDeltaItem,PrismPropertyDefinition> sourceIdi = context.getFocusContext().getObjectDeltaObject().findIdi(focusPropertyPath); - + if (capActivation != null && focusPropertyPath.equals(SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS)) { ActivationValidityCapabilityType capValidFrom = CapabilityUtil.getEffectiveActivationValidFrom(capActivation); ActivationValidityCapabilityType capValidTo = CapabilityUtil.getEffectiveActivationValidTo(capActivation); - + // Source: computedShadowStatus ItemDeltaItem,PrismPropertyDefinition> computedIdi; if (capValidFrom != null && capValidTo != null) { // "Native" validFrom and validTo, directly use administrativeStatus computedIdi = context.getFocusContext().getObjectDeltaObject().findIdi(focusPropertyPath); - + } else { // Simulate validFrom and validTo using effectiveStatus computedIdi = context.getFocusContext().getObjectDeltaObject().findIdi(SchemaConstants.PATH_ACTIVATION_EFFECTIVE_STATUS); - + } - + Source,PrismPropertyDefinition> computedSource = new Source<>(computedIdi, ExpressionConstants.VAR_INPUT); - + builder.defaultSource(computedSource); - + Source,PrismPropertyDefinition> source = new Source<>(sourceIdi, ExpressionConstants.VAR_ADMINISTRATIVE_STATUS); builder.addSource(source); - + } else { Source,PrismPropertyDefinition> source = new Source<>(sourceIdi, ExpressionConstants.VAR_INPUT); builder.defaultSource(source); } - + // Source: legal ItemDeltaItem,PrismPropertyDefinition> legalIdi = getLegalIdi(projCtx); Source,PrismPropertyDefinition> legalSource = new Source<>(legalIdi, ExpressionConstants.VAR_LEGAL); @@ -617,25 +617,25 @@ private void evaluateActivationMapping(final LensContex builder.addSource(assignedSource); // Source: focusExists - ItemDeltaItem,PrismPropertyDefinition> focusExistsSourceIdi = getFocusExistsIdi(context.getFocusContext()); - Source,PrismPropertyDefinition> focusExistsSource + ItemDeltaItem,PrismPropertyDefinition> focusExistsSourceIdi = getFocusExistsIdi(context.getFocusContext()); + Source,PrismPropertyDefinition> focusExistsSource = new Source<>(focusExistsSourceIdi, ExpressionConstants.VAR_FOCUS_EXISTS); builder.addSource(focusExistsSource); - + return builder; }; - + evaluateOutboundMapping(context, projCtx, bidirectionalMappingType, focusPropertyPath, projectionPropertyPath, initializer, now, current, desc + " outbound activation mapping", task, result); - + } - private void evaluateOutboundMapping(final LensContext context, - final LensProjectionContext projCtx, ResourceBidirectionalMappingType bidirectionalMappingType, + private void evaluateOutboundMapping(final LensContext context, + final LensProjectionContext projCtx, ResourceBidirectionalMappingType bidirectionalMappingType, final ItemPath focusPropertyPath, final ItemPath projectionPropertyPath, - final MappingInitializer,PrismPropertyDefinition> initializer, + final MappingInitializer,PrismPropertyDefinition> initializer, XMLGregorianCalendar now, final boolean evaluateCurrent, String desc, final Task task, final OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException { - + if (bidirectionalMappingType == null) { LOGGER.trace("No '{}' definition in projection {}, skipping", desc, projCtx.toHumanReadableString()); return; @@ -645,20 +645,20 @@ private void evaluateOutboundMapping(final LensContext< LOGGER.trace("No outbound definition in '{}' definition in projection {}, skipping", desc, projCtx.toHumanReadableString()); return; } - + String projCtxDesc = projCtx.toHumanReadableString(); PrismObject shadowNew = projCtx.getObjectNew(); - MappingInitializer,PrismPropertyDefinition> internalInitializer = + MappingInitializer,PrismPropertyDefinition> internalInitializer = builder -> { builder.addVariableDefinitions(Utils.getDefaultExpressionVariables(context, projCtx).getMap()); - + builder.originType(OriginType.OUTBOUND); builder.originObject(projCtx.getResource()); - + initializer.initialize(builder); - + return builder; }; @@ -719,7 +719,7 @@ private ItemDeltaItem,PrismPr LensFocusContext lensFocusContext) throws SchemaException { Boolean existsOld = null; Boolean existsNew = null; - + if (lensFocusContext != null) { if (lensFocusContext.isDelete()) { existsOld = true; @@ -732,15 +732,15 @@ private ItemDeltaItem,PrismPr existsNew = true; } } - + PrismPropertyDefinitionImpl existsDef = new PrismPropertyDefinitionImpl<>(FOCUS_EXISTS_PROPERTY_NAME, DOMUtil.XSD_BOOLEAN, prismContext); existsDef.setMinOccurs(1); existsDef.setMaxOccurs(1); PrismProperty existsProp = existsDef.instantiate(); - + existsProp.add(new PrismPropertyValue(existsNew)); - + if (existsOld == existsNew) { return new ItemDeltaItem,PrismPropertyDefinition>(existsProp); } else { @@ -751,30 +751,30 @@ private ItemDeltaItem,PrismPr return new ItemDeltaItem,PrismPropertyDefinition>(existsPropOld, existsDelta, existsProp); } } - + @SuppressWarnings({ "unchecked", "rawtypes" }) - public void processLifecycle(LensContext context, LensProjectionContext projCtx, + public void processLifecycle(LensContext context, LensProjectionContext projCtx, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException, CommunicationException, ConfigurationException, SecurityViolationException { - + LensFocusContext focusContext = context.getFocusContext(); if (focusContext != null && !FocusType.class.isAssignableFrom(focusContext.getObjectTypeClass())) { // We can do this only for focal object. LOGGER.trace("Skipping lifecycle evaluation because focus is not FocusType"); return; } - + processLifecycleFocus((LensContext)context, projCtx, now, task, result); } - - private void processLifecycleFocus(LensContext context, LensProjectionContext projCtx, + + private void processLifecycleFocus(LensContext context, LensProjectionContext projCtx, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException, CommunicationException, ConfigurationException, SecurityViolationException { - + LensFocusContext focusContext = context.getFocusContext(); if (focusContext == null) { LOGGER.trace("Skipping lifecycle evaluation because there is no focus"); return; } - + ResourceObjectLifecycleDefinitionType lifecycleDef = null; ResourceObjectTypeDefinitionType resourceAccountDefType = projCtx.getResourceObjectTypeDefinitionType(); if (resourceAccountDefType != null) { @@ -784,31 +784,31 @@ private void processLifecycleFocus(LensContext context, if (lifecycleDef != null) { lifecycleStateMappingType = lifecycleDef.getLifecycleState(); } - + if (lifecycleStateMappingType == null || lifecycleStateMappingType.getOutbound() == null) { - + if (!projCtx.isAdd()) { LOGGER.trace("Skipping lifecycle evaluation because this is not add operation (default expression)"); return; } - + PrismObject focusNew = focusContext.getObjectNew(); if (focusNew == null) { LOGGER.trace("Skipping lifecycle evaluation because there is no new focus (default expression)"); return; } - + PrismObject projectionNew = projCtx.getObjectNew(); if (projectionNew == null) { LOGGER.trace("Skipping lifecycle evaluation because there is no new projection (default expression)"); return; } - + String lifecycle = midpointFunctions.computeProjectionLifecycle( focusNew.asObjectable(), projectionNew.asObjectable(), projCtx.getResource()); - + LOGGER.trace("Computed projection lifecycle (default expression): {}", lifecycle); - + if (lifecycle != null) { PrismPropertyDefinition propDef = projCtx.getObjectDefinition().findPropertyDefinition(SchemaConstants.PATH_LIFECYCLE_STATE); PropertyDelta lifeCycleDelta = propDef.createEmptyDelta(SchemaConstants.PATH_LIFECYCLE_STATE); @@ -817,17 +817,17 @@ private void processLifecycleFocus(LensContext context, lifeCycleDelta.setValuesToReplace(pval); projCtx.swallowToSecondaryDelta(lifeCycleDelta); } - + } else { - + LOGGER.trace("Computing projection lifecycle (mapping): {}", lifecycleStateMappingType); evaluateActivationMapping(context, projCtx, lifecycleStateMappingType, - SchemaConstants.PATH_LIFECYCLE_STATE, SchemaConstants.PATH_LIFECYCLE_STATE, + SchemaConstants.PATH_LIFECYCLE_STATE, SchemaConstants.PATH_LIFECYCLE_STATE, null, now, true, ObjectType.F_LIFECYCLE_STATE.getLocalPart(), task, result); } - + } - + private PrismObjectDefinition getUserDefinition() { if (userDefinition == null) { userDefinition = prismContext.getSchemaRegistry() @@ -835,7 +835,7 @@ private PrismObjectDefinition getUserDefinition() { } return userDefinition; } - + private PrismContainerDefinition getActivationDefinition() { if (activationDefinition == null) { PrismObjectDefinition userDefinition = getUserDefinition(); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/AssignmentProcessor.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/AssignmentProcessor.java index 1a0b3eabfe7..7d05638bd16 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/AssignmentProcessor.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/AssignmentProcessor.java @@ -90,17 +90,17 @@ /** * Assignment processor is recomputing user assignments. It recomputes all the assignments whether they are direct - * or indirect (roles). - * + * or indirect (roles). + * * Processor does not do the complete recompute. Only the account "existence" is recomputed. I.e. the processor determines * what accounts should be added, deleted or kept as they are. The result is marked in account context SynchronizationPolicyDecision. * This step does not create any deltas. It recomputes the attributes to delta set triples but does not "refine" them to deltas yet. * It cannot create deltas as other mapping may interfere, e.g. outbound mappings. These needs to be computed before we can * create the final deltas (because there may be mapping exclusions, interference of weak mappings, etc.) - * + * * The result of assignment processor are intermediary data in the context such as LensContext.evaluatedAssignmentTriple and * LensProjectionContext.accountConstructionDeltaSetTriple. - * + * * @author Radovan Semancik */ @Component @@ -112,7 +112,7 @@ public class AssignmentProcessor { @Autowired private ObjectResolver objectResolver; - + @Autowired private SystemObjectCache systemObjectCache; @@ -121,22 +121,22 @@ public class AssignmentProcessor { @Autowired private MappingFactory mappingFactory; - + @Autowired private MappingEvaluator mappingEvaluator; - + @Autowired(required=true) private ActivationComputer activationComputer; - + @Autowired(required=true) private ProvisioningService provisioningService; - + @Autowired(required=true) private ConstructionProcessor constructionProcessor; - + @Autowired private ObjectTemplateProcessor objectTemplateProcessor; - + @Autowired private PolicyRuleProcessor policyRuleProcessor; @@ -144,7 +144,7 @@ public class AssignmentProcessor { /** * Processing all the assignments to determine which projections should be added, deleted or kept as they are. - * Generic method for all projection types (theoretically). + * Generic method for all projection types (theoretically). */ @SuppressWarnings("unchecked") public void processAssignmentsProjections(LensContext context, XMLGregorianCalendar now, @@ -162,17 +162,17 @@ public void processAssignmentsProjections(LensContext // //do not execute assignment if the execution was triggered by compensation mechanism and limitPropagation is set // return; // } - + OperationResult result = parentResult.createSubresult(AssignmentProcessor.class.getName() + ".processAssignmentsProjections"); - + try { processAssignmentsProjectionsWithFocus((LensContext)context, now, task, result); - } catch (SchemaException | ObjectNotFoundException | ExpressionEvaluationException | PolicyViolationException | + } catch (SchemaException | ObjectNotFoundException | ExpressionEvaluationException | PolicyViolationException | CommunicationException | ConfigurationException | SecurityViolationException | RuntimeException | Error e) { result.recordFatalError(e); throw e; } - + OperationResultStatus finalStatus = OperationResultStatus.SUCCESS; String message = null; int errors = 0; @@ -191,35 +191,35 @@ public void processAssignmentsProjections(LensContext result.setMessage(message); result.cleanupResult(); } - + /** * Processing focus-projection assignments (including roles). */ @SuppressWarnings({ "rawtypes", "unchecked" }) - private void processAssignmentsProjectionsWithFocus(LensContext context, XMLGregorianCalendar now, + private void processAssignmentsProjectionsWithFocus(LensContext context, XMLGregorianCalendar now, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, PolicyViolationException, CommunicationException, ConfigurationException, SecurityViolationException { - + // PREPARE ASSIGNMENT DELTA - + LensFocusContext focusContext = context.getFocusContext(); ObjectDelta focusDelta = focusContext.getDelta(); - + if (focusDelta != null && focusDelta.isDelete()) { processFocusDelete(context, result); return; } checkAssignmentDeltaSanity(context); - - + + // ASSIGNMENT EVALUATION - + // Initializing assignment evaluator. This will be used later to process all the assignments including the nested // assignments (roles). AssignmentEvaluator assignmentEvaluator = createAssignmentEvaluator(context, now); ObjectType source = determineSource(focusContext); - + AssignmentTripleEvaluator assignmentTripleEvaluator = new AssignmentTripleEvaluator<>(); assignmentTripleEvaluator.setActivationComputer(activationComputer); assignmentTripleEvaluator.setAssignmentEvaluator(assignmentEvaluator); @@ -229,30 +229,30 @@ private void processAssignmentsProjectionsWithFocus(LensCo assignmentTripleEvaluator.setResult(result); assignmentTripleEvaluator.setSource(source); assignmentTripleEvaluator.setTask(task); - + // Normal processing. The enforcement policy requires that assigned accounts should be added, so we need to figure out // which assignments were added. Do a complete recompute for all the enforcement modes. We can do that because this does // not create deltas, it just creates the triples. So we can decide what to do later when we convert triples to deltas. - + // Evaluates all assignments and sorts them to triple: added, removed and untouched assignments. // This is where most of the assignment-level action happens. DeltaSetTriple> evaluatedAssignmentTriple = assignmentTripleEvaluator.processAllAssignments(); policyRuleProcessor.addGlobalPoliciesToAssignments(context, evaluatedAssignmentTriple, task, result); context.setEvaluatedAssignmentTriple((DeltaSetTriple)evaluatedAssignmentTriple); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("evaluatedAssignmentTriple:\n{}", evaluatedAssignmentTriple.debugDump()); } - + // PROCESSING POLICIES policyRuleProcessor.processPolicies(context, evaluatedAssignmentTriple, result); - + boolean needToReevaluateAssignments = policyRuleProcessor.processPruning(context, evaluatedAssignmentTriple, result); - + if (needToReevaluateAssignments) { LOGGER.debug("Re-evaluating assignments because exclusion pruning rule was triggered"); - + assignmentTripleEvaluator.reset(); evaluatedAssignmentTriple = assignmentTripleEvaluator.processAllAssignments(); context.setEvaluatedAssignmentTriple((DeltaSetTriple)evaluatedAssignmentTriple); @@ -262,21 +262,21 @@ private void processAssignmentsProjectionsWithFocus(LensCo if (LOGGER.isTraceEnabled()) { LOGGER.trace("re-evaluatedAssignmentTriple:\n{}", evaluatedAssignmentTriple.debugDump()); } - + policyRuleProcessor.processPolicies(context, evaluatedAssignmentTriple, result); } //policyRuleProcessor.storeAssignmentPolicySituation(context, evaluatedAssignmentTriple, result); // PROCESSING FOCUS - + Map>> focusOutputTripleMap = new HashMap<>(); collectFocusTripleFromMappings(evaluatedAssignmentTriple.getPlusSet(), focusOutputTripleMap, PlusMinusZero.PLUS); collectFocusTripleFromMappings(evaluatedAssignmentTriple.getMinusSet(), focusOutputTripleMap, PlusMinusZero.MINUS); collectFocusTripleFromMappings(evaluatedAssignmentTriple.getZeroSet(), focusOutputTripleMap, PlusMinusZero.ZERO); ObjectDeltaObject focusOdo = focusContext.getObjectDeltaObject(); Collection> focusDeltas = objectTemplateProcessor.computeItemDeltas(focusOutputTripleMap, null, - focusOdo.getObjectDelta(), focusOdo.getNewObject(), focusContext.getObjectDefinition(), + focusOdo.getObjectDelta(), focusOdo.getNewObject(), focusContext.getObjectDefinition(), "focus mappings in assignments of "+focusContext.getHumanReadableName()); LOGGER.trace("Computed focus deltas: {}", focusDeltas); focusContext.applyProjectionWaveSecondaryDeltas(focusDeltas); @@ -285,7 +285,7 @@ private void processAssignmentsProjectionsWithFocus(LensCo if (context.getPartialProcessingOptions().getProjection() != PartialProcessingTypeType.SKIP) { // PROCESSING PROJECTIONS - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Projection processing start, evaluatedAssignmentTriple:\n{}", evaluatedAssignmentTriple.debugDump(1)); } @@ -466,7 +466,7 @@ public void after(ResourceShadowDiscriminator rat, String desc, construction -> getConstructionMapKey(context, construction, task, result), consumer, task, result); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Projection processing done"); } @@ -475,9 +475,9 @@ public void after(ResourceShadowDiscriminator rat, String desc, finishLegalDecisions(context); } } - - + + private ResourceShadowDiscriminator getConstructionMapKey(LensContext context, Construction construction, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { String resourceOid = construction.getResource(task, result).getOid(); String intent = construction.getIntent(); @@ -533,17 +533,17 @@ private ObjectType determineSource(LensFocusContext fo return focusContext.getObjectNew().asObjectable(); } - - - private void evaluateConstructions(LensContext context, + + + private void evaluateConstructions(LensContext context, DeltaSetTriple> evaluatedAssignmentTriple, Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException { evaluateConstructions(context, evaluatedAssignmentTriple.getZeroSet(), task, result); evaluateConstructions(context, evaluatedAssignmentTriple.getPlusSet(), task, result); evaluateConstructions(context, evaluatedAssignmentTriple.getMinusSet(), task, result); } - - private void evaluateConstructions(LensContext context, + + private void evaluateConstructions(LensContext context, Collection> evaluatedAssignments, Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException { if (evaluatedAssignments == null) { return; @@ -576,8 +576,8 @@ private void evaluateConstructions(LensContext context, // This is a role assignment or something like that. Just throw the original exception for now. throw ex; } - ResourceShadowDiscriminator rad = new ResourceShadowDiscriminator(resourceOid, - FocusTypeUtil.determineConstructionKind(evaluatedAssignment.getAssignmentType()), + ResourceShadowDiscriminator rad = new ResourceShadowDiscriminator(resourceOid, + FocusTypeUtil.determineConstructionKind(evaluatedAssignment.getAssignmentType()), FocusTypeUtil.determineConstructionIntent(evaluatedAssignment.getAssignmentType())); LensProjectionContext accCtx = context.findProjectionContext(rad); if (accCtx != null) { @@ -612,7 +612,7 @@ private Collection> getConstructions(Constructi } return accountConstructionPack.getConstructions(); } - + private boolean isForceRecon(ConstructionPack accountConstructionPack) { if (accountConstructionPack == null) { return false; @@ -621,20 +621,20 @@ private boolean isForceRecon(ConstructionPack accountConstructionPack) { } /** - * Set 'legal' flag for the accounts that does not have it already + * Set 'legal' flag for the accounts that does not have it already */ private void finishLegalDecisions(LensContext context) throws PolicyViolationException, SchemaException { for (LensProjectionContext projectionContext: context.getProjectionContexts()) { - + String desc = projectionContext.toHumanReadableString(); - + if (projectionContext.isLegal() != null) { // already have decision LOGGER.trace("Projection {} legal={} (predetermined)", desc, projectionContext.isLegal()); propagateLegalDecisionToHigherOrders(context, projectionContext); continue; } - + if (projectionContext.isLegalize()){ LOGGER.trace("Projection {} legal: legalized", desc); createAssignmentDelta(context, projectionContext); @@ -642,11 +642,11 @@ private void finishLegalDecisions(LensContext context) projectionContext.setAssignedOld(false); projectionContext.setLegal(true); projectionContext.setLegalOld(false); - + } else { - + AssignmentPolicyEnforcementType enforcementType = projectionContext.getAssignmentPolicyEnforcementType(); - + if (enforcementType == AssignmentPolicyEnforcementType.FULL) { LOGGER.trace("Projection {} illegal: no assignment in FULL enforcement", desc); // What is not explicitly allowed is illegal in FULL enforcement mode @@ -658,7 +658,7 @@ private void finishLegalDecisions(LensContext context) throw new PolicyViolationException("Attempt to add projection "+projectionContext.toHumanReadableString() +" while the synchronization enforcement policy is FULL and the projection is not assigned"); } - + } else if (enforcementType == AssignmentPolicyEnforcementType.NONE && !projectionContext.isThombstone()) { if (projectionContext.isAdd()) { LOGGER.trace("Projection {} legal: added in NONE policy", desc); @@ -674,13 +674,13 @@ private void finishLegalDecisions(LensContext context) projectionContext.setLegal(projectionContext.isExists()); projectionContext.setLegalOld(projectionContext.isExists()); } - + } else if (enforcementType == AssignmentPolicyEnforcementType.POSITIVE && !projectionContext.isThombstone()) { // Everything that is not yet dead is legal in POSITIVE enforcement mode LOGGER.trace("Projection {} legal: not dead in POSITIVE policy", desc); projectionContext.setLegal(true); projectionContext.setLegalOld(true); - + } else if (enforcementType == AssignmentPolicyEnforcementType.RELATIVE && !projectionContext.isThombstone() && projectionContext.isLegal() == null && projectionContext.isLegalOld() == null) { // RELATIVE mode and nothing has changed. Maintain status quo. Pretend that it is legal. @@ -689,14 +689,14 @@ private void finishLegalDecisions(LensContext context) projectionContext.setLegalOld(true); } } - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Finishing legal decision for {}, thombstone {}, enforcement mode {}, legalize {}: {} -> {}", projectionContext.toHumanReadableString(), projectionContext.isThombstone(), projectionContext.getAssignmentPolicyEnforcementType(), projectionContext.isLegalize(), projectionContext.isLegalOld(), projectionContext.isLegal()); } - + propagateLegalDecisionToHigherOrders(context, projectionContext); } } @@ -728,7 +728,7 @@ private void createAssignmentDelta(LensContext context, PrismContainerDefinition containerDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(focusClass).findContainerDefinition(FocusType.F_ASSIGNMENT); assignmentDelta.applyDefinition(containerDefinition); context.getFocusContext().swallowToProjectionWaveSecondaryDelta(assignmentDelta); - + } public void processOrgAssignments(LensContext context, OperationResult result) throws SchemaException, PolicyViolationException { @@ -750,7 +750,7 @@ public void processOrgAssignments(LensContext context, } } setReferences(focusContext, ObjectType.F_PARENT_ORG_REF, shouldBeParentOrgRefs); - + ObjectDelta focusPrimaryDelta = focusContext.getPrimaryDelta(); if (focusPrimaryDelta != null) { ReferenceDelta parentOrgRefDelta = focusPrimaryDelta.findReferenceModification(ObjectType.F_PARENT_ORG_REF); @@ -764,7 +764,7 @@ public void processOrgAssignments(LensContext context, } } try { - + parentOrgRefDelta.validateValues( (plusMinusZero,val) -> { switch (plusMinusZero) { @@ -781,7 +781,7 @@ public void processOrgAssignments(LensContext context, break; } }, parentOrgRefCurrentValues); - + } catch (TunnelException e) { throw (PolicyViolationException)e.getCause(); } @@ -806,15 +806,15 @@ public void checkForAssignmentConflicts(LensContext co } } } - + public void processAssignmentsAccountValues(LensProjectionContext accountContext, OperationResult result) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException { - + // TODO: reevaluate constructions // This should re-evaluate all the constructions. They are evaluated already, evaluated in the assignment step before. // But if there is any iteration counter that it will not be taken into account - + } private String dumpAccountMap(Map accountMap) { @@ -842,7 +842,7 @@ private boolean accountExists(LensContext context, Res } return true; } - + private void markPolicyDecision(LensProjectionContext accountSyncContext, SynchronizationPolicyDecision decision) { if (accountSyncContext.getSynchronizationPolicyDecision() == null) { accountSyncContext.setSynchronizationPolicyDecision(decision); @@ -856,7 +856,7 @@ public void removeIgnoredContexts(LensContext context) Iterator projectionIterator = projectionContexts.iterator(); while (projectionIterator.hasNext()) { LensProjectionContext projectionContext = projectionIterator.next(); - + if (projectionContext.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.IGNORE) { projectionIterator.remove(); } @@ -867,13 +867,13 @@ private XM Collection> evaluatedAssignments, Map>> outputTripleMap, PlusMinusZero plusMinusZero) throws SchemaException { - + XMLGregorianCalendar nextRecomputeTime = null; - + for (EvaluatedAssignmentImpl ea: evaluatedAssignments) { Collection> focusMappings = (Collection)ea.getFocusMappings(); for (Mapping mapping: focusMappings) { - + ItemPath itemPath = mapping.getOutputPath(); DeltaSetTriple> outputTriple = ItemValueWithOrigin.createOutputTriple(mapping); if (outputTriple == null) { @@ -896,10 +896,10 @@ private XM } } } - + return nextRecomputeTime; } - + public void processMembershipAndDelegatedRefs(LensContext context, OperationResult result) throws SchemaException { LensFocusContext focusContext = context.getFocusContext(); @@ -975,7 +975,7 @@ private void addReferences(Collection extractedReferences, } } } - + private AssignmentEvaluator createAssignmentEvaluator(LensContext context, XMLGregorianCalendar now) throws SchemaException { return new AssignmentEvaluator.Builder() @@ -993,5 +993,5 @@ private AssignmentEvaluator createAssignmentEvaluator(L .systemConfiguration(context.getSystemConfiguration()) .build(); } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/AssignmentTripleEvaluator.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/AssignmentTripleEvaluator.java index b8ebf4ba0c6..075f78d5768 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/AssignmentTripleEvaluator.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/AssignmentTripleEvaluator.java @@ -48,14 +48,14 @@ /** * Evaluates all assignments and sorts them to triple: added, removed and untouched assignments. - * + * * @author semancik * */ public class AssignmentTripleEvaluator { - + private static final Trace LOGGER = TraceManager.getTrace(AssignmentTripleEvaluator.class); - + private LensContext context; private ObjectType source; private AssignmentEvaluator assignmentEvaluator; @@ -64,7 +64,7 @@ public class AssignmentTripleEvaluator { private XMLGregorianCalendar now; private Task task; private OperationResult result; - + public LensContext getContext() { return context; } @@ -132,25 +132,25 @@ public void setResult(OperationResult result) { public void reset() { assignmentEvaluator.reset(); } - + public DeltaSetTriple> processAllAssignments() throws SchemaException, ExpressionEvaluationException, PolicyViolationException { - + LensFocusContext focusContext = context.getFocusContext(); - + ObjectDelta focusDelta = focusContext.getDelta(); - + ContainerDelta assignmentDelta = getExecutionWaveAssignmentDelta(focusContext); assignmentDelta.expand(focusContext.getObjectCurrent()); LOGGER.trace("Assignment delta:\n{}", assignmentDelta.debugDump()); - + SmartAssignmentCollection assignmentCollection = new SmartAssignmentCollection<>(); assignmentCollection.collect(focusContext.getObjectCurrent(), focusContext.getObjectOld(), assignmentDelta); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Assignment collection:\n{}", assignmentCollection.debugDump(1)); } - + // Iterate over all the assignments. I mean really all. This is a union of the existing and changed assignments // therefore it contains all three types of assignments (plus, minus and zero). As it is an union each assignment // will be processed only once. Inside the loop we determine whether it was added, deleted or remains unchanged. @@ -162,10 +162,10 @@ public DeltaSetTriple> processAllAssignments() throws for (SmartAssignmentElement assignmentElement : assignmentCollection) { processAssignment(evaluatedAssignmentTriple, focusDelta, assignmentDelta, assignmentElement); } - + return evaluatedAssignmentTriple; } - + private void processAssignment(DeltaSetTriple> evaluatedAssignmentTriple, ObjectDelta focusDelta, ContainerDelta assignmentDelta, SmartAssignmentElement assignmentElement) throws SchemaException, ExpressionEvaluationException, PolicyViolationException { @@ -196,12 +196,12 @@ private void processAssignment(DeltaSetTriple> evalua if (assignmentItemDeltas != null && !assignmentItemDeltas.isEmpty()) { // Small changes inside assignment, but otherwise the assignment stays as it is (not added or deleted) subItemDeltas = assignmentItemDeltas; - + // The subItemDeltas above will handle some changes. But not other. // E.g. a replace of the whole construction will not be handled properly. // Therefore we force recon to sort it out. forceRecon = true; - + isAssignmentChanged = true; PrismContainer assContNew = focusContext.getObjectNew().findContainer(FocusType.F_ASSIGNMENT); assignmentCValNew = assContNew.getValue(assignmentCVal.getId()); @@ -211,9 +211,9 @@ private void processAssignment(DeltaSetTriple> evalua // The following code is using collectToAccountMap() to collect the account constructions to one of the three "delta" // sets (zero, plus, minus). It is handling several situations that needs to be handled specially. // It is also collecting assignments to evaluatedAssignmentTriple. - + if (focusDelta != null && focusDelta.isDelete()) { - + // USER DELETE // If focus (user) is being deleted that all the assignments are to be gone. Including those that // were not changed explicitly. @@ -227,7 +227,7 @@ private void processAssignment(DeltaSetTriple> evalua evaluatedAssignment.setPresentInCurrentObject(presentInCurrent); evaluatedAssignment.setPresentInOldObject(presentInOld); collectToMinus(evaluatedAssignmentTriple, evaluatedAssignment, forceRecon); - + } else { if (assignmentDelta.isReplace()) { @@ -276,15 +276,15 @@ private void processAssignment(DeltaSetTriple> evalua LOGGER.error("Whoops. Unexpected things happen. Assignment is neither current, old nor new (replace delta)\n{}", assignmentElement.debugDump(1)); throw new SystemException("Whoops. Unexpected things happen. Assignment is neither current, old nor new (replace delta)."); } - + } else { - // ADD/DELETE of entire assignment or small changes inside existing assignments + // ADD/DELETE of entire assignment or small changes inside existing assignments // This is the usual situation. // Just sort assignments to sets: unchanged (zero), added (plus), removed (minus) if (isAssignmentChanged) { // There was some change - + boolean isAdd = assignmentDelta.isValueToAdd(assignmentCVal, true); boolean isDelete = assignmentDelta.isValueToDelete(assignmentCVal, true); if (isAdd & !isDelete) { @@ -326,13 +326,13 @@ private void processAssignment(DeltaSetTriple> evalua evaluatedAssignment.setPresentInCurrentObject(presentInCurrent); evaluatedAssignment.setPresentInOldObject(presentInOld); collectToMinus(evaluatedAssignmentTriple, evaluatedAssignment, forceRecon); - + } else { // Small change inside an assignment // The only thing that we need to worry about is assignment validity change. That is a cause // of provisioning/deprovisioning of the projections. So check that explicitly. Other changes are // not significant, i.e. reconciliation can handle them. - boolean isValidOld = LensUtil.isAssignmentValid(focusContext.getObjectOld().asObjectable(), + boolean isValidOld = LensUtil.isAssignmentValid(focusContext.getObjectOld().asObjectable(), assignmentCValOld.asContainerable(), now, activationComputer); boolean isValid = LensUtil.isAssignmentValid(focusContext.getObjectNew().asObjectable(), assignmentCValNew.asContainerable(), now, activationComputer); @@ -380,7 +380,7 @@ private void processAssignment(DeltaSetTriple> evalua collectToMinus(evaluatedAssignmentTriple, evaluatedAssignment, true); } } - + } else { // No change in assignment if (LOGGER.isTraceEnabled()) { @@ -466,7 +466,7 @@ private Collection> getExecutionW new IdItemPathSegment(id))); } - private void collectToZero(DeltaSetTriple> evaluatedAssignmentTriple, + private void collectToZero(DeltaSetTriple> evaluatedAssignmentTriple, EvaluatedAssignmentImpl evaluatedAssignment, boolean forceRecon) { if (forceRecon) { evaluatedAssignment.setForceRecon(true); @@ -474,7 +474,7 @@ private void collectToZero(DeltaSetTriple void collectToPlus(DeltaSetTriple> evaluatedAssignmentTriple, + private void collectToPlus(DeltaSetTriple> evaluatedAssignmentTriple, EvaluatedAssignmentImpl evaluatedAssignment, boolean forceRecon) { if (forceRecon) { evaluatedAssignment.setForceRecon(true); @@ -482,7 +482,7 @@ private void collectToPlus(DeltaSetTriple void collectToMinus(DeltaSetTriple> evaluatedAssignmentTriple, + private void collectToMinus(DeltaSetTriple> evaluatedAssignmentTriple, EvaluatedAssignmentImpl evaluatedAssignment, boolean forceRecon) { if (forceRecon) { evaluatedAssignment.setForceRecon(true); @@ -491,13 +491,13 @@ private void collectToMinus(DeltaSetTriple EvaluatedAssignmentImpl evaluateAssignment(ItemDeltaItem,PrismContainerDefinition> assignmentIdi, - PlusMinusZero mode, boolean evaluateOld, LensContext context, ObjectType source, AssignmentEvaluator assignmentEvaluator, + PlusMinusZero mode, boolean evaluateOld, LensContext context, ObjectType source, AssignmentEvaluator assignmentEvaluator, String assignmentPlacementDesc, Task task, OperationResult parentResult) throws SchemaException, ExpressionEvaluationException, PolicyViolationException { OperationResult result = parentResult.createMinorSubresult(AssignmentProcessor.class.getSimpleName()+".evaluateAssignment"); result.addParam("assignmentDescription", assignmentPlacementDesc); try{ - // Evaluate assignment. This follows to the assignment targets, follows to the inducements, - // evaluates all the expressions, etc. + // Evaluate assignment. This follows to the assignment targets, follows to the inducements, + // evaluates all the expressions, etc. EvaluatedAssignmentImpl evaluatedAssignment = assignmentEvaluator.evaluate(assignmentIdi, mode, evaluateOld, source, assignmentPlacementDesc, task, result); context.rememberResources(evaluatedAssignment.getResources(task, result)); result.recordSuccess(); @@ -526,8 +526,8 @@ private EvaluatedAssignmentImpl evaluateAssignment(Item // This is a role assignment or something like that. Just throw the original exception for now. throw ex; } - ResourceShadowDiscriminator rad = new ResourceShadowDiscriminator(resourceOid, - FocusTypeUtil.determineConstructionKind(assignmentType), + ResourceShadowDiscriminator rad = new ResourceShadowDiscriminator(resourceOid, + FocusTypeUtil.determineConstructionKind(assignmentType), FocusTypeUtil.determineConstructionIntent(assignmentType)); LensProjectionContext accCtx = context.findProjectionContext(rad); if (accCtx != null) { @@ -543,7 +543,7 @@ private EvaluatedAssignmentImpl evaluateAssignment(Item throw e; } } - + /** * Returns delta of user assignments, both primary and secondary (merged together). * The returned object is (kind of) immutable. Changing it may do strange things (but most likely the changes will be lost). @@ -557,16 +557,16 @@ private ContainerDelta getExecutionWaveAss return createEmptyAssignmentDelta(focusContext); } ContainerDelta assignmentDelta = focusDelta.findContainerDelta(new ItemPath(FocusType.F_ASSIGNMENT)); - if (assignmentDelta == null) { + if (assignmentDelta == null) { return createEmptyAssignmentDelta(focusContext); } return assignmentDelta; } - + private ContainerDelta createEmptyAssignmentDelta(LensFocusContext focusContext) { return new ContainerDelta<>(getAssignmentContainerDefinition(focusContext), prismContext); } - + private PrismContainerDefinition getAssignmentContainerDefinition(LensFocusContext focusContext) { return focusContext.getObjectDefinition().findContainerDefinition(FocusType.F_ASSIGNMENT); } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ComplexConstructionConsumer.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ComplexConstructionConsumer.java index 99e1820b166..6565a7926ca 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ComplexConstructionConsumer.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ComplexConstructionConsumer.java @@ -24,16 +24,16 @@ * */ public interface ComplexConstructionConsumer { - + boolean before(K key); void onAssigned(K key, String desc); - + void onUnchangedValid(K key, String desc); - + void onUnchangedInvalid(K key, String desc); - + void onUnassigned(K key, String desc); - + void after(K key, String desc, DeltaMapTriple> constructionMapTriple); } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ConsolidationProcessor.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ConsolidationProcessor.java index bf85c6755fc..b4d12d90636 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ConsolidationProcessor.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ConsolidationProcessor.java @@ -94,18 +94,18 @@ public class ConsolidationProcessor { public static final String PROCESS_CONSOLIDATION = ConsolidationProcessor.class.getName() + ".consolidateValues"; private static final Trace LOGGER = TraceManager.getTrace(ConsolidationProcessor.class); - + private PrismContainerDefinition associationDefinition; - + @Autowired private ContextLoader contextLoader; - + @Autowired private MatchingRuleRegistry matchingRuleRegistry; @Autowired PrismContext prismContext; - + /** * Converts delta set triples to a secondary account deltas. */ @@ -151,14 +151,14 @@ private ObjectDelta consolidateValuesToModifyD LensProjectionContext projCtx, boolean addUnchangedValues, Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, PolicyViolationException { - + // "Squeeze" all the relevant mappings into a data structure that we can process conveniently. We want to have all the // (meta)data about relevant for a specific attribute in one data structure, not spread over several account constructions. - Map,PrismPropertyDefinition>>> squeezedAttributes = - sqeeze(projCtx, construction -> (Collection)construction.getAttributeMappings()); + Map,PrismPropertyDefinition>>> squeezedAttributes = + sqeeze(projCtx, construction -> (Collection)construction.getAttributeMappings()); projCtx.setSqueezedAttributes(squeezedAttributes); - - Map,PrismContainerDefinition>>> squeezedAssociations = + + Map,PrismContainerDefinition>>> squeezedAssociations = sqeeze(projCtx, construction -> construction.getAssociationMappings()); projCtx.setSqueezedAssociations(squeezedAssociations); @@ -168,8 +168,8 @@ private ObjectDelta consolidateValuesToModifyD if (!squeezedAssociations.isEmpty()) { fillInAssociationNames(squeezedAssociations); } - - MappingExtractor,PrismPropertyDefinition,F> auxiliaryObjectClassExtractor = + + MappingExtractor,PrismPropertyDefinition,F> auxiliaryObjectClassExtractor = construction -> { PrismValueDeltaSetTripleProducer,PrismPropertyDefinition> prod = new PrismValueDeltaSetTripleProducer,PrismPropertyDefinition>() { @Override @@ -211,19 +211,19 @@ public boolean isSourceless() { col.add(prod); return col; }; - - Map,PrismPropertyDefinition>>> squeezedAuxiliaryObjectClasses = - sqeeze(projCtx, auxiliaryObjectClassExtractor); + + Map,PrismPropertyDefinition>>> squeezedAuxiliaryObjectClasses = + sqeeze(projCtx, auxiliaryObjectClassExtractor); projCtx.setSqueezedAuxiliaryObjectClasses(squeezedAuxiliaryObjectClasses); - + ResourceShadowDiscriminator discr = projCtx.getResourceShadowDiscriminator(); ObjectDelta objectDelta = new ObjectDelta(ShadowType.class, ChangeType.MODIFY, prismContext); objectDelta.setOid(projCtx.getOid()); - + // Do not automatically load the full projection now. Even if we have weak mapping. // That may be a waste of resources if the weak mapping results in no change anyway. // Let's be very very lazy about fetching the account from the resource. - if (!projCtx.hasFullShadow() && + if (!projCtx.hasFullShadow() && (hasActiveWeakMapping(squeezedAttributes, projCtx) || hasActiveWeakMapping(squeezedAssociations, projCtx) || (hasActiveStrongMapping(squeezedAttributes, projCtx) || hasActiveStrongMapping(squeezedAssociations, projCtx)))) { // Full account was not yet loaded. This will cause problems as @@ -233,7 +233,7 @@ public boolean isSourceless() { // of all // account's attributes.Therefore load the account now, but with // doNotDiscovery options.. - + // We also need to get account if there are strong mappings. Strong mappings // should always be applied. So reading the account now will indirectly // trigger reconciliation which makes sure that the strong mappings are @@ -242,36 +242,36 @@ public boolean isSourceless() { // By getting accounts from provisioning, there might be a problem with // resource availability. We need to know, if the account was read full // or we have only the shadow from the repository. If we have only - // shadow, the weak mappings may applied even if they should not be. + // shadow, the weak mappings may applied even if they should not be. contextLoader.loadFullShadow(context, projCtx, "weak or strong mapping", task, result); if (projCtx.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.BROKEN) { return null; } } - + boolean completeAccount = projCtx.hasFullShadow(); - + ObjectDelta existingDelta = projCtx.getDelta(); - + // AUXILIARY OBJECT CLASSES ItemPath auxiliaryObjectClassItemPath = new ItemPath(ShadowType.F_AUXILIARY_OBJECT_CLASS); PrismPropertyDefinition auxiliaryObjectClassPropertyDef = projCtx.getObjectDefinition().findPropertyDefinition(auxiliaryObjectClassItemPath); PropertyDelta auxiliaryObjectClassAPrioriDelta = null; RefinedResourceSchema refinedSchema = projCtx.getRefinedResourceSchema(); - List auxOcNames = new ArrayList<>(); - List auxOcDefs = new ArrayList<>(); + List auxOcNames = new ArrayList<>(); + List auxOcDefs = new ArrayList<>(); ObjectDelta projDelta = projCtx.getDelta(); if (projDelta != null) { auxiliaryObjectClassAPrioriDelta = projDelta.findPropertyDelta(auxiliaryObjectClassItemPath); } for (Entry, PrismPropertyDefinition>>> entry : squeezedAuxiliaryObjectClasses.entrySet()) { DeltaSetTriple, PrismPropertyDefinition>> ivwoTriple = entry.getValue(); - + LOGGER.trace("CONSOLIDATE auxiliary object classes ({})", new Object[]{ discr }); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Auxiliary object class triple:\n{}",ivwoTriple.debugDump()); } - + for (ItemValueWithOrigin,PrismPropertyDefinition> ivwo: ivwoTriple.getAllValues()) { QName auxObjectClassName = ivwo.getItemValue().getValue(); if (auxOcNames.contains(auxObjectClassName)) { @@ -286,17 +286,17 @@ public boolean isSourceless() { } auxOcDefs.add(auxOcDef); } - + ItemDelta, PrismPropertyDefinition> itemDelta = LensUtil.consolidateTripleToDelta( auxiliaryObjectClassItemPath, ivwoTriple, auxiliaryObjectClassPropertyDef, - auxiliaryObjectClassAPrioriDelta, projCtx.getObjectNew(), null, null, addUnchangedValues, completeAccount, false, + auxiliaryObjectClassAPrioriDelta, projCtx.getObjectNew(), null, null, addUnchangedValues, completeAccount, false, discr.toHumanReadableDescription(), false); PropertyDelta propDelta = (PropertyDelta)itemDelta; - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Auxiliary object class delta:\n{}",propDelta.debugDump()); } - + if (!propDelta.isEmpty()) { objectDelta.addModification(propDelta); } @@ -310,7 +310,7 @@ public boolean isSourceless() { RefinedObjectClassDefinition rOcDef = new CompositeRefinedObjectClassDefinitionImpl( structuralObjectClassDefinition, auxOcDefs); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Object class definition for {} consolidation:\n{}", discr, rOcDef.debugDump()); } @@ -321,7 +321,7 @@ public boolean isSourceless() { for (Map.Entry,PrismPropertyDefinition>>> entry : squeezedAttributes.entrySet()) { QName attributeName = entry.getKey(); DeltaSetTriple,PrismPropertyDefinition>> triple = entry.getValue(); - PropertyDelta propDelta = consolidateAttribute(rOcDef, discr, existingDelta, projCtx, + PropertyDelta propDelta = consolidateAttribute(rOcDef, discr, existingDelta, projCtx, addUnchangedValues, completeAccount, attributeName, (DeltaSetTriple)triple); if (propDelta != null) { objectDelta.addModification(propDelta); @@ -332,13 +332,13 @@ public boolean isSourceless() { for (Entry,PrismContainerDefinition>>> entry : squeezedAssociations.entrySet()) { QName associationName = entry.getKey(); DeltaSetTriple,PrismContainerDefinition>> triple = entry.getValue(); - ContainerDelta containerDelta = consolidateAssociation(rOcDef, discr, existingDelta, projCtx, + ContainerDelta containerDelta = consolidateAssociation(rOcDef, discr, existingDelta, projCtx, addUnchangedValues, completeAccount, associationName, triple); if (containerDelta != null) { objectDelta.addModification(containerDelta); } } - + return objectDelta; } @@ -363,23 +363,23 @@ private PropertyDelta consolidateAttribute(RefinedOb ResourceShadowDiscriminator discr, ObjectDelta existingDelta, LensProjectionContext projCtx, boolean addUnchangedValues, boolean completeShadow, QName itemName, DeltaSetTriple,PrismPropertyDefinition>> triple) throws SchemaException, ExpressionEvaluationException, PolicyViolationException { - + if (triple == null || triple.isEmpty()) { return null; } - + RefinedAttributeDefinition attributeDefinition = triple.getAnyValue().getConstruction().findAttributeDefinition(itemName); - - ItemPath itemPath = new ItemPath(ShadowType.F_ATTRIBUTES, itemName); - + + ItemPath itemPath = new ItemPath(ShadowType.F_ATTRIBUTES, itemName); + if (attributeDefinition.isIgnored(LayerType.MODEL)) { LOGGER.trace("Skipping processing mappings for attribute {} because it is ignored", itemName); return null; } ValueMatcher valueMatcher = ValueMatcher.createMatcher(attributeDefinition, matchingRuleRegistry); - - return (PropertyDelta) consolidateItem(rOcDef, discr, existingDelta, projCtx, addUnchangedValues, completeShadow, + + return (PropertyDelta) consolidateItem(rOcDef, discr, existingDelta, projCtx, addUnchangedValues, completeShadow, attributeDefinition.isExlusiveStrong(), itemPath, attributeDefinition, triple, valueMatcher, null, "attribute "+itemName); } @@ -387,27 +387,27 @@ private ContainerDelta consolidate ResourceShadowDiscriminator discr, ObjectDelta existingDelta, LensProjectionContext projCtx, boolean addUnchangedValues, boolean completeShadow, QName associationName, DeltaSetTriple,PrismContainerDefinition>> triple) throws SchemaException, ExpressionEvaluationException, PolicyViolationException { - + ItemPath itemPath = new ItemPath(ShadowType.F_ASSOCIATION); PrismContainerDefinition asspcContainerDef = getAssociationDefinition(); RefinedAssociationDefinition associationDef = rOcDef.findAssociationDefinition(associationName); - + Comparator> comparator = new Comparator>() { - + @Override public int compare(PrismContainerValue o1, PrismContainerValue o2) { - + if (o1 == null && o2 == null){ LOGGER.trace("Comparing {} and {}: 0 (A)", o1, o2); return 0; - } - + } + if (o1 == null || o2 == null){ LOGGER.trace("Comparing {} and {}: 2 (B)", o1, o2); return 1; } - + PrismReference ref1 = o1.findReference(ShadowAssociationType.F_SHADOW_REF); PrismReference ref2 = o2.findReference(ShadowAssociationType.F_SHADOW_REF); @@ -420,22 +420,22 @@ public int compare(PrismContainerValue o1, LOGGER.trace("Comparing {} and {}: 0 (C)", o1, o2); return 0; } - + LOGGER.trace("Comparing {} and {}: 1 (D)", o1, o2); return 1; } }; - + ContainerDelta delta = (ContainerDelta) consolidateItem(rOcDef, discr, existingDelta, - projCtx, addUnchangedValues, completeShadow, associationDef.isExclusiveStrong(), itemPath, + projCtx, addUnchangedValues, completeShadow, associationDef.isExclusiveStrong(), itemPath, asspcContainerDef, triple, null, comparator, "association "+associationName); - + if (delta != null) { setAssociationName(delta.getValuesToAdd(), associationName); setAssociationName(delta.getValuesToDelete(), associationName); setAssociationName(delta.getValuesToReplace(), associationName); } - + return delta; } @@ -458,9 +458,9 @@ private PrismContainerDefinition getAssociationDefinition private ItemDelta consolidateItem(RefinedObjectClassDefinition rOcDef, ResourceShadowDiscriminator discr, ObjectDelta existingDelta, LensProjectionContext projCtx, - boolean addUnchangedValues, boolean completeShadow, boolean isExclusiveStrong, - ItemPath itemPath, D itemDefinition, DeltaSetTriple> triple, - ValueMatcher valueMatcher, Comparator comparator, String itemDesc) + boolean addUnchangedValues, boolean completeShadow, boolean isExclusiveStrong, + ItemPath itemPath, D itemDefinition, DeltaSetTriple> triple, + ValueMatcher valueMatcher, Comparator comparator, String itemDesc) throws SchemaException, ExpressionEvaluationException, PolicyViolationException { boolean forceAddUnchangedValues = false; @@ -473,20 +473,20 @@ private ItemDelta consolida // lost forceAddUnchangedValues = true; } - + LOGGER.trace("CONSOLIDATE {}\n({}) completeShadow={}, addUnchangedValues={}, forceAddUnchangedValues={}", itemDesc, discr, completeShadow, addUnchangedValues, forceAddUnchangedValues); - + // Use this common utility method to do the computation. It does most of the work. ItemDelta itemDelta = LensUtil.consolidateTripleToDelta( - itemPath, (DeltaSetTriple)triple, itemDefinition, existingItemDelta, projCtx.getObjectNew(), + itemPath, (DeltaSetTriple)triple, itemDefinition, existingItemDelta, projCtx.getObjectNew(), valueMatcher, comparator, addUnchangedValues || forceAddUnchangedValues, completeShadow, isExclusiveStrong, discr.toHumanReadableDescription(), completeShadow); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Consolidated delta (before sync filter) for {}:\n{}",discr,itemDelta==null?"null":itemDelta.debugDump()); } - + if (existingItemDelta != null && existingItemDelta.isReplace()) { // We cannot filter out any values if there is an replace delta. The replace delta cleans all previous // state and all the values needs to be passed on @@ -505,7 +505,7 @@ private ItemDelta consolida // two replace deltas and therefore some information may be lost itemDelta.simplify(); } - + // Validate the delta. i.e. make sure it conforms to schema (that it does not have more values than allowed, etc.) if (existingItemDelta != null) { // Let's make sure that both the previous delta and this delta makes sense @@ -513,12 +513,12 @@ private ItemDelta consolida mergedDelta.merge(itemDelta); mergedDelta.validate(); } else { - itemDelta.validate(); + itemDelta.validate(); } - + return itemDelta; } - + return null; } @@ -578,7 +578,7 @@ private boolean hasActiveWeakMap } return false; } - + private boolean hasActiveStrongMapping( Map>> squeezedAttributes, LensProjectionContext accCtx) throws SchemaException { for (Map.Entry>> entry : squeezedAttributes.entrySet()) { @@ -598,14 +598,14 @@ private boolean hasActiveStrongM private void consolidateValuesModifyProjection(LensContext context, LensProjectionContext accCtx, Task task, OperationResult result) - throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, + throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, PolicyViolationException { boolean addUnchangedValues = false; if (accCtx.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.ADD) { addUnchangedValues = true; } - + ObjectDelta modifyDelta = consolidateValuesToModifyDelta(context, accCtx, addUnchangedValues, task, result); if (modifyDelta == null || modifyDelta.isEmpty()) { return; @@ -618,7 +618,7 @@ private void consolidateValuesModifyProjection(LensContext } } - private ItemDelta consolidateItemWithSync(LensProjectionContext accCtx, ItemDelta delta, + private ItemDelta consolidateItemWithSync(LensProjectionContext accCtx, ItemDelta delta, ValueMatcher valueMatcher) { if (delta == null) { return null; @@ -628,7 +628,7 @@ private ItemDelta consolida } return delta; } - + /** * This method checks {@link com.evolveum.midpoint.prism.delta.PropertyDelta} created during consolidation with * account sync deltas. If changes from property delta are in account sync deltas than they must be removed, @@ -638,7 +638,7 @@ private ItemDelta consolida * @param delta new delta created during consolidation process * @return method return updated delta, or null if delta was empty after filtering (removing unnecessary values). */ - private PropertyDelta consolidatePropertyWithSync(LensProjectionContext accCtx, PropertyDelta delta, + private PropertyDelta consolidatePropertyWithSync(LensProjectionContext accCtx, PropertyDelta delta, ValueMatcher valueMatcher) { if (delta == null) { return null; @@ -800,7 +800,7 @@ private vo sqeezeAttributesFromConstruction(squeezedMap, construction.getValue(), extractor, enforcement); } } - + private void sqeezeAttributesFromAccountConstructionSetNonminusToPlus( Map>> squeezedMap, Collection>> constructionSet, MappingExtractor extractor, @@ -812,7 +812,7 @@ private vo sqeezeAttributesFromConstructionNonminusToPlus(squeezedMap, construction.getValue(), extractor, enforcement); } } - + private void sqeezeAttributesFromConstructionSetNonminusToMinus( Map>> squeezedMap, Collection>> constructionSet, MappingExtractor extractor, @@ -859,7 +859,7 @@ private vo } } } - + private void sqeezeAttributesFromConstructionNonminusToPlus( Map>> squeezedMap, Construction construction, MappingExtractor extractor, AssignmentPolicyEnforcementType enforcement) { @@ -891,7 +891,7 @@ private vo continue; } QName name = mapping.getMappingQName(); - DeltaSetTriple> squeezeTriple + DeltaSetTriple> squeezeTriple = getSqueezeMapTriple(squeezedMap, name); if (enforcement == AssignmentPolicyEnforcementType.POSITIVE) { convertSqueezeSet(vcTriple.getZeroSet(), squeezeTriple.getZeroSet(), mapping, construction); @@ -948,5 +948,5 @@ private De } return triple; } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ConstructionProcessor.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ConstructionProcessor.java index b3d580e65fb..feea66947d2 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ConstructionProcessor.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ConstructionProcessor.java @@ -49,44 +49,44 @@ */ @Component public class ConstructionProcessor { - + private static final Trace LOGGER = TraceManager.getTrace(ConstructionProcessor.class); - - public - DeltaMapTriple> processConstructions(LensContext context, - DeltaSetTriple> evaluatedAssignmentTriple, + + public + DeltaMapTriple> processConstructions(LensContext context, + DeltaSetTriple> evaluatedAssignmentTriple, Function,DeltaSetTriple> constructionTripleExtractor, FailableLensFunction keyGenerator, ComplexConstructionConsumer consumer, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { - - // We will be collecting the evaluated account constructions into these three maps. + + // We will be collecting the evaluated account constructions into these three maps. // It forms a kind of delta set triple for the account constructions. DeltaMapTriple> constructionMapTriple = new DeltaMapTriple<>(); - collectToConstructionMaps(context, evaluatedAssignmentTriple, constructionMapTriple, + collectToConstructionMaps(context, evaluatedAssignmentTriple, constructionMapTriple, constructionTripleExtractor, keyGenerator, task, result); - + if (LOGGER.isTraceEnabled()) { // Dump the maps LOGGER.trace("constructionMapTriple:\n{}", constructionMapTriple.debugDump()); } - + // Now we are processing constructions from all the three sets once again. We will create projection contexts - // for them if not yet created. Now we will do the usual routing for converting the delta triples to deltas. + // for them if not yet created. Now we will do the usual routing for converting the delta triples to deltas. // I.e. zero means unchanged, plus means added, minus means deleted. That will be recorded in the SynchronizationPolicyDecision. // We will also collect all the construction triples to projection context. These will be used later for computing // actual attribute deltas (in consolidation processor). for (K key : constructionMapTriple.unionKeySets()) { - + boolean cont = consumer.before(key); if (!cont) { continue; } - + String desc = key.toHumanReadableDescription(); ConstructionPack zeroConstructionPack = constructionMapTriple.getZeroMap().get(key); ConstructionPack plusConstructionPack = constructionMapTriple.getPlusMap().get(key); - + if (LOGGER.isTraceEnabled()) { if (zeroConstructionPack == null) { LOGGER.trace("ZERO construction pack: null"); @@ -106,7 +106,7 @@ DeltaMapTriple> processConstructions(LensContext conte // SITUATION: The construction is ASSIGNED if (plusConstructionPack != null && plusConstructionPack.hasStrongConstruction()) { - + if (plusConstructionPack.hasValidAssignment()) { LOGGER.trace("Construction {}: assigned (valid)", desc); consumer.onAssigned(key, desc); @@ -117,40 +117,40 @@ DeltaMapTriple> processConstructions(LensContext conte // Just ignore it, do not even create projection context LOGGER.trace("Construction {} ignoring: assigned (invalid)", desc); } - + // SITUATION: The projection should exist (is valid), there is NO CHANGE in assignments } else if (zeroConstructionPack != null && zeroConstructionPack.hasValidAssignment() && zeroConstructionPack.hasStrongConstruction()) { - + LOGGER.trace("Construction {}: unchanged (valid)", desc); consumer.onUnchangedValid(key, desc); - + // SITUATION: The projection is both ASSIGNED and UNASSIGNED - } else if (constructionMapTriple.getPlusMap().containsKey(key) && constructionMapTriple.getMinusMap().containsKey(key) && + } else if (constructionMapTriple.getPlusMap().containsKey(key) && constructionMapTriple.getMinusMap().containsKey(key) && plusConstructionPack.hasStrongConstruction()) { // Account was removed and added in the same operation. This is the case if e.g. one role is // removed and another is added and they include the same account. // Keep original account state - + ConstructionPack plusPack = constructionMapTriple.getPlusMap().get(key); ConstructionPack minusPack = constructionMapTriple.getMinusMap().get(key); - + if (plusPack.hasValidAssignment() && minusPack.hasValidAssignment()) { - + LOGGER.trace("Construction {}: both assigned and unassigned (valid)", desc); consumer.onUnchangedValid(key, desc); - + } else if (!plusPack.hasValidAssignment() && !minusPack.hasValidAssignment()) { // Just ignore it, do not even create projection context LOGGER.trace("Construction {} ignoring: both assigned and unassigned (invalid)", desc); - + } else if (plusPack.hasValidAssignment() && !minusPack.hasValidAssignment()) { // Assignment became valid. Same as if it was assigned. LOGGER.trace("Construction {}: both assigned and unassigned (invalid->valid)", desc); consumer.onAssigned(key, desc); - + } else if (!plusPack.hasValidAssignment() && minusPack.hasValidAssignment()) { // Assignment became invalid. Same as if it was unassigned. - + LOGGER.trace("Construction {}: both assigned and unassigned (valid->invalid)", desc); consumer.onUnassigned(key, desc); @@ -160,55 +160,55 @@ DeltaMapTriple> processConstructions(LensContext conte // SITUATION: The projection is UNASSIGNED } else if (constructionMapTriple.getMinusMap().containsKey(key)) { - + LOGGER.trace("Construction {}: unassigned", desc); consumer.onUnassigned(key, desc); - + // SITUATION: The projection should exist (invalid), there is NO CHANGE in assignments } else if (constructionMapTriple.getZeroMap().containsKey(key) && !constructionMapTriple.getZeroMap().get(key).hasValidAssignment()) { - + LOGGER.trace("Construction {}: unchanged (invalid)", desc); consumer.onUnchangedInvalid(key, desc); - - // This is a legal state: projection was assigned, but it only has weak construction (no strong) + + // This is a legal state: projection was assigned, but it only has weak construction (no strong) // We do not need to do anything. But we want to log the message // and we do not want the "looney" error below. } else if (plusConstructionPack != null && !plusConstructionPack.hasStrongConstruction()) { - + // Just ignore it, do not even create projection context LOGGER.trace("Construction {} ignoring: assigned (weak only)", desc); - + // This is a legal state: projection is unchanged, but it only has weak construction (no strong) // We do not need to do anything. But we want to log the message // and we do not want the "looney" error below. } else if (zeroConstructionPack != null && !zeroConstructionPack.hasStrongConstruction()) { - + // Just ignore it, do not even create projection context LOGGER.trace("Construction {} ignoring: unchanged (weak only)", desc); - + } else { throw new IllegalStateException("Construction " + desc + " went looney"); } consumer.after(key, desc, constructionMapTriple); } - + return constructionMapTriple; } - + public void collectToConstructionMaps(LensContext context, - DeltaSetTriple> evaluatedAssignmentTriple, + DeltaSetTriple> evaluatedAssignmentTriple, DeltaMapTriple> constructionMapTriple, Function,DeltaSetTriple> constructionTripleExtractor, FailableLensFunction keyGenerator, - Task task, OperationResult result) + Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { - + collectToConstructionMapFromEvaluatedAssignments(context, evaluatedAssignmentTriple.getZeroSet(), constructionMapTriple, constructionTripleExtractor, keyGenerator, PlusMinusZero.ZERO, task, result); collectToConstructionMapFromEvaluatedAssignments(context, evaluatedAssignmentTriple.getPlusSet(), constructionMapTriple, constructionTripleExtractor, keyGenerator, PlusMinusZero.PLUS, task, result); collectToConstructionMapFromEvaluatedAssignments(context, evaluatedAssignmentTriple.getMinusSet(), constructionMapTriple, constructionTripleExtractor, keyGenerator, PlusMinusZero.MINUS, task, result); } - + private void collectToConstructionMapFromEvaluatedAssignments(LensContext context, Collection> evaluatedAssignments, DeltaMapTriple> constructionMapTriple, Function,DeltaSetTriple> constructionTripleExtractor, FailableLensFunction keyGenerator, PlusMinusZero mode, Task task, @@ -223,25 +223,25 @@ private void collectToC collectToConstructionMapFromEvaluatedConstructions(context, evaluatedAssignment, constructionTriple.getMinusSet(), constructionMapTriple, keyGenerator, mode, PlusMinusZero.MINUS, task, result); } } - + private void collectToConstructionMapFromEvaluatedConstructions(LensContext context, EvaluatedAssignmentImpl evaluatedAssignment, Collection evaluatedConstructions, DeltaMapTriple> constructionMapTriple, - FailableLensFunction keyGenerator, + FailableLensFunction keyGenerator, PlusMinusZero mode1, PlusMinusZero mode2, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { - + for (T construction : evaluatedConstructions) { - + PlusMinusZero mode = PlusMinusZero.compute(mode1, mode2); Map> constructionMap = constructionMapTriple.getMap(mode); if (constructionMap == null) { continue; } - + K key = keyGenerator.apply(construction); - + ConstructionPack constructionPack; if (constructionMap.containsKey(key)) { constructionPack = constructionMap.get(key); @@ -249,7 +249,7 @@ private void collectToC constructionPack = new ConstructionPack<>(); constructionMap.put(key, constructionPack); } - + constructionPack.add(new PrismPropertyValue<>(construction)); if (evaluatedAssignment.isValid()) { constructionPack.setHasValidAssignment(true); @@ -257,7 +257,7 @@ private void collectToC if (evaluatedAssignment.isForceRecon()) { constructionPack.setForceRecon(true); } - + } } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ContextLoader.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ContextLoader.java index a4bd723abc5..32653c97e11 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ContextLoader.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ContextLoader.java @@ -86,8 +86,8 @@ /** * Context loader loads the missing parts of the context. The context enters the projector with just the minimum information. * Context loader gets missing data such as accounts. It gets them from the repository or provisioning as necessary. It follows - * the account links in user (accountRef) and user deltas. - * + * the account links in user (accountRef) and user deltas. + * * @author Radovan Semancik * */ @@ -97,50 +97,50 @@ public class ContextLoader { @Autowired(required = true) @Qualifier("cacheRepositoryService") private transient RepositoryService cacheRepositoryService; - + @Autowired private SystemObjectCache systemObjectCache; @Autowired private ProvisioningService provisioningService; @Autowired private SecurityHelper securityHelper; @Autowired private PrismContext prismContext; - + private static final Trace LOGGER = TraceManager.getTrace(ContextLoader.class); - - public void load(LensContext context, String activityDescription, - Task task, OperationResult result) - throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, + + public void load(LensContext context, String activityDescription, + Task task, OperationResult result) + throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, PolicyViolationException, ExpressionEvaluationException { context.checkAbortRequested(); context.recompute(); - + for (LensProjectionContext projectionContext: context.getProjectionContexts()) { preprocessProjectionContext(context, projectionContext, task, result); } - + if (consistencyChecks) context.checkConsistence(); - + determineFocusContext((LensContext)context, result); - + LensFocusContext focusContext = context.getFocusContext(); if (focusContext != null) { loadObjectCurrent(context, result); - + context.recomputeFocus(); - + loadFromSystemConfig(context, task, result); - + if (FocusType.class.isAssignableFrom(context.getFocusClass())) { // this also removes the accountRef deltas loadLinkRefs((LensContext)context, task, result); LOGGER.trace("loadLinkRefs done"); } - + // Some cleanup if (focusContext.getPrimaryDelta() != null && focusContext.getPrimaryDelta().isModify() && focusContext.getPrimaryDelta().isEmpty()) { focusContext.setPrimaryDelta(null); } - + for (LensProjectionContext projectionContext: context.getProjectionContexts()) { if (projectionContext.getSynchronizationIntent() != null) { // Accounts with explicitly set intent are never rotten. These are explicitly requested actions @@ -148,36 +148,36 @@ public void load(LensContext context, String activityD projectionContext.setFresh(true); } } - + setPrimaryDeltaOldValue(focusContext); - + } else { // Projection contexts are not rotten in this case. There is no focus so there is no way to refresh them. for (LensProjectionContext projectionContext: context.getProjectionContexts()) { projectionContext.setFresh(true); } } - + removeRottenContexts(context); - + if (consistencyChecks) context.checkConsistence(); - + for (LensProjectionContext projectionContext: context.getProjectionContexts()) { context.checkAbortRequested(); finishLoadOfProjectionContext(context, projectionContext, task, result); } - + if (consistencyChecks) context.checkConsistence(); - + context.recompute(); - + if (consistencyChecks) { fullCheckConsistence(context); } - + LensUtil.traceContext(LOGGER, activityDescription, "after load", false, context, false); } - + /** * Removes projection contexts that are not fresh. @@ -219,17 +219,17 @@ private void removeRottenContexts(LensContext context) } } } - - + + /** - * Make sure that the projection context is loaded as approppriate. + * Make sure that the projection context is loaded as approppriate. */ public void makeSureProjectionIsLoaded(LensContext context, LensProjectionContext projectionContext, Task task, OperationResult result) throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { preprocessProjectionContext(context, projectionContext, task, result); finishLoadOfProjectionContext(context, projectionContext, task, result); } - + /** * Make sure that the context is OK and consistent. It means that is has a resource, it has correctly processed * discriminator, etc. @@ -289,8 +289,8 @@ private void preprocessProjectionContext(LensContext c } } } - - /** + + /** * try to load focus context from the projections, e.g. by determining account owners */ public void determineFocusContext(LensContext context, @@ -327,7 +327,7 @@ public void determineFocusContext(LensContext context, focusContext.setLoadedObject(object); } } - + private void loadObjectCurrent(LensContext context, OperationResult result) throws SchemaException, ObjectNotFoundException { LensFocusContext focusContext = context.getFocusContext(); if (focusContext == null) { @@ -360,14 +360,14 @@ private void loadObjectCurrent(LensContext context, Op // Always load a complete object here, including the not-returned-by-default properties. // This is temporary measure to make sure that the mappings will have all they need. // See MID-2635 - Collection> options = + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE)); PrismObject object = cacheRepositoryService.getObject(focusContext.getObjectTypeClass(), userOid, options, result); focusContext.setLoadedObject(object); focusContext.setFresh(true); LOGGER.trace("Focal object loaded: {}", object); } - + private void setPrimaryDeltaOldValue(LensElementContext ctx) throws SchemaException, ObjectNotFoundException { if (ctx.getPrimaryDelta() != null && ctx.getObjectOld() != null && ctx.isModify()) { PrismObject objectOld = ctx.getObjectOld(); @@ -376,7 +376,7 @@ private void setPrimaryDeltaOldValue(LensElementContext void loadFromSystemConfig(LensContext context, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ConfigurationException, ExpressionEvaluationException, PolicyViolationException { PrismObject systemConfiguration = systemObjectCache.getSystemConfiguration(result); @@ -392,29 +392,29 @@ private void loadFromSystemConfig(LensContext context, if (context.getFocusContext().getObjectPolicyConfigurationType() == null) { List subTypes = FocusTypeUtil.determineSubTypes(object); ObjectPolicyConfigurationType policyConfigurationType = - ModelUtils.determineObjectPolicyConfiguration(context.getFocusContext().getObjectTypeClass(), subTypes, + ModelUtils.determineObjectPolicyConfiguration(context.getFocusContext().getObjectTypeClass(), subTypes, systemConfigurationType); LOGGER.trace("Selected policy configuration: {}", policyConfigurationType); context.getFocusContext().setObjectPolicyConfigurationType(policyConfigurationType); } } - + if (context.getFocusTemplate() == null) { PrismObject focusTemplate = determineFocusTemplate(context, result); if (focusTemplate != null) { context.setFocusTemplate(focusTemplate.asObjectable()); } } - + if (context.getAccountSynchronizationSettings() == null) { ProjectionPolicyType globalAccountSynchronizationSettings = systemConfigurationType.getGlobalAccountSynchronizationSettings(); LOGGER.trace("Applying globalAccountSynchronizationSettings to context: {}", globalAccountSynchronizationSettings); context.setAccountSynchronizationSettings(globalAccountSynchronizationSettings); } - + loadSecurityPolicy(context, task, result); } - + @SuppressWarnings("unchecked") private void loadSecurityPolicy(LensContext context, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, @@ -429,7 +429,7 @@ private void loadSecurityPolicy(LensContext context, } SecurityPolicyType securityPolicy = focusContext.getSecurityPolicy(); if (securityPolicy == null) { - securityPolicy = securityHelper.locateSecurityPolicy((PrismObject)focusContext.getObjectAny(), + securityPolicy = securityHelper.locateSecurityPolicy((PrismObject)focusContext.getObjectAny(), context.getSystemConfiguration(), task, result); if (securityPolicy == null) { // store empty policy to avoid repeated lookups @@ -460,7 +460,7 @@ private PrismObject determineFocusTem LOGGER.trace("No default object template (no templateRef)"); return null; } - + PrismObject template = cacheRepositoryService.getObject(ObjectTemplateType.class, templateRef.getOid(), null, result); return template; } @@ -483,20 +483,20 @@ private void loadLinkRefs(LensContext context, Task tas } if (consistencyChecks) context.checkConsistence(); - + loadLinkRefsFromDelta(context, userCurrent, focusContext.getPrimaryDelta(), task, result); LOGGER.trace("loadLinkRefsFromDelta done"); - + if (consistencyChecks) context.checkConsistence(); loadProjectionContextsSync(context, task, result); LOGGER.trace("loadProjectionContextsSync done"); - + if (consistencyChecks) context.checkConsistence(); } /** - * Does not overwrite existing account contexts, just adds new ones. + * Does not overwrite existing account contexts, just adds new ones. */ private void loadLinkRefsFromFocus(LensContext context, PrismObject focus, Task task, OperationResult result) throws ObjectNotFoundException, @@ -513,14 +513,14 @@ private void loadLinkRefsFromFocus(LensContext context, throw new SchemaException("Null or empty OID in link reference in " + focus); } LensProjectionContext existingAccountContext = findAccountContext(oid, context); - + if (!canBeLoaded(context, existingAccountContext)){ continue; } - + if (existingAccountContext != null) { // TODO: do we need to reload the account inside here? yes we need - + existingAccountContext.setFresh(true); continue; } @@ -555,7 +555,7 @@ private void loadLinkRefsFromFocus(LensContext context, } if (accountContext.isDoReconciliation()) { // Do not load old account now. It will get loaded later in the - // reconciliation step. + // reconciliation step. continue; } accountContext.setLoadedObject(shadow); @@ -569,7 +569,7 @@ private void loadLinkRefsFromDelta(LensContext context, if (focusPrimaryDelta == null) { return; } - + ReferenceDelta linkRefDelta; if (focusPrimaryDelta.getChangeType() == ChangeType.ADD) { PrismReference linkRef = focusPrimaryDelta.getObjectToAdd().findReference( @@ -589,14 +589,14 @@ private void loadLinkRefsFromDelta(LensContext context, // delete, all existing account are already marked for delete return; } - + if (linkRefDelta.isReplace()) { // process "replace" by distributing values to delete and add linkRefDelta = (ReferenceDelta) linkRefDelta.clone(); PrismReference linkRef = focus.findReference(FocusType.F_LINK_REF); linkRefDelta.distributeReplace(linkRef == null ? null : linkRef.getValues()); } - + if (linkRefDelta.getValuesToAdd() != null) { for (PrismReferenceValue refVal : linkRefDelta.getValuesToAdd()) { String oid = refVal.getOid(); @@ -685,7 +685,7 @@ private void loadLinkRefsFromDelta(LensContext context, accountContext.setFresh(true); } } - + if (linkRefDelta.getValuesToDelete() != null) { for (PrismReferenceValue refVal : linkRefDelta.getValuesToDelete()) { String oid = refVal.getOid(); @@ -720,7 +720,7 @@ private void loadLinkRefsFromDelta(LensContext context, LOGGER.warn("Deleting accountRef of " + focus + " that points to non-existing OID " + oid); } - + } } if (accountContext != null) { @@ -733,10 +733,10 @@ private void loadLinkRefsFromDelta(LensContext context, } accountContext.setFresh(true); } - + } } - + // remove the accountRefs without oid. These will get into the way now. // The accounts // are in the context now and will be linked at the end of the process @@ -769,14 +769,14 @@ private void loadProjectionContextsSync(LensContext co } String oid = syncDelta.getOid(); PrismObject shadow = null; - + if (syncDelta.getChangeType() == ChangeType.ADD) { shadow = syncDelta.getObjectToAdd().clone(); projCtx.setLoadedObject(shadow); projCtx.setExists(true); - + } else { - + if (oid == null) { throw new IllegalArgumentException("No OID in sync delta in " + projCtx); } @@ -786,17 +786,17 @@ private void loadProjectionContextsSync(LensContext co option.setDoNotDiscovery(true); option.setPointInTimeType(PointInTimeType.FUTURE); Collection> options = SelectorOptions.createCollection(option); - + try { - + shadow = provisioningService.getObject(ShadowType.class, oid, options, task, result); - + } catch (ObjectNotFoundException e) { LOGGER.trace("Loading shadow {} from sync delta failed: not found", oid); projCtx.setExists(false); projCtx.setObjectCurrent(null); } - + // We will not set old account if the delta is delete. The // account does not really exists now. // (but the OID and resource will be set from the repo @@ -810,7 +810,7 @@ private void loadProjectionContextsSync(LensContext co projCtx.setExists(true); } } - + // Make sure OID is set correctly projCtx.setOid(oid); // Make sure that resource is also resolved @@ -836,7 +836,7 @@ private boolean canBeLoaded(LensContext context, LensP } return true; } - + private LensProjectionContext getOrCreateAccountContext(LensContext context, PrismObject projection, Task task, OperationResult result) throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, PolicyViolationException, ExpressionEvaluationException { @@ -845,9 +845,9 @@ private LensProjectionContext getOrCreateAccountContext(Le if (resourceOid == null) { throw new SchemaException("The " + projection + " has null resource reference OID"); } - + LensProjectionContext projectionContext = context.findProjectionContextByOid(accountType.getOid()); - + if (projectionContext == null) { String intent = ShadowUtil.getIntent(accountType); ShadowKindType kind = ShadowUtil.getKind(accountType); @@ -859,7 +859,7 @@ private LensProjectionContext getOrCreateAccountContext(Le } ResourceShadowDiscriminator rsd = new ResourceShadowDiscriminator(resourceOid, kind, intent, thombstone); projectionContext = LensUtil.getOrCreateProjectionContext(context, rsd); - + if (projectionContext.getOid() == null) { projectionContext.setOid(projection.getOid()); } else if (projection.getOid() != null && !projectionContext.getOid().equals(projection.getOid())) { @@ -877,7 +877,7 @@ private LensProjectionContext getOrCreateAccountContext(Le PrismObject newShadow = provisioningService.getObject(ShadowType.class, projection.getOid(), opts, task, result); // Obviously, two projections with the same discriminator exists if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Projection {} already exists in context\nExisting:\n{}\nNew:\n{}", new Object[]{rsd, + LOGGER.trace("Projection {} already exists in context\nExisting:\n{}\nNew:\n{}", new Object[]{rsd, existingShadow.debugDump(1), newShadow.debugDump(1)}); } throw new PolicyViolationException("Projection "+rsd+" already exists in context (existing "+existingShadow+", new "+projection); @@ -903,13 +903,13 @@ private LensProjectionContext getOrCreateAccountContext(Le } return projectionContext; } - + private void markShadowDead(String oid, OperationResult result) { if (oid == null) { // nothing to mark return; } - Collection> modifications = MiscSchemaUtil.createCollection(PropertyDelta.createReplaceDelta(prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(ShadowType.class), + Collection> modifications = MiscSchemaUtil.createCollection(PropertyDelta.createReplaceDelta(prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(ShadowType.class), ShadowType.F_DEAD, true)); try { cacheRepositoryService.modifyObject(ShadowType.class, oid, modifications, result); @@ -956,7 +956,7 @@ private LensProjectionContext findAccountContext(String a return null; } - + private LensProjectionContext getOrCreateEmptyThombstoneProjectionContext(LensContext context, String missingShadowOid) { LensProjectionContext projContext = context.findProjectionContextByOid(missingShadowOid); @@ -964,28 +964,28 @@ private LensProjectionContext getOrCreateEmptyThombstoneP projContext = context.createProjectionContext(null); projContext.setOid(missingShadowOid); } - + if (projContext.getResourceShadowDiscriminator() == null) { projContext.setResourceShadowDiscriminator(new ResourceShadowDiscriminator(null, null, null, true)); } else { projContext.getResourceShadowDiscriminator().setThombstone(true); } - + projContext.setFullShadow(false); projContext.setObjectCurrent(null); - + return projContext; } - + /** * Check reconcile flag in account sync context and set accountOld * variable if it's not set (from provisioning), load resource (if not set already), etc. */ - private void finishLoadOfProjectionContext(LensContext context, + private void finishLoadOfProjectionContext(LensContext context, LensProjectionContext projContext, Task task, OperationResult result) throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { - + String projectionHumanReadableName = projContext.getHumanReadableName(); if (projContext.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.BROKEN) { @@ -1005,7 +1005,7 @@ private void finishLoadOfProjectionContext(LensContext // The current object is useless here. So lets just wipe it so it will get loaded projContext.setObjectCurrent(null); } - + // Load current object boolean thombstone = false; PrismObject projectionObject = projContext.getObjectCurrent(); @@ -1018,7 +1018,7 @@ private void finishLoadOfProjectionContext(LensContext } else { if (projectionObjectOid == null) { projContext.setExists(false); - if (projContext.getResourceShadowDiscriminator() == null || projContext.getResourceShadowDiscriminator().getResourceOid() == null) { + if (projContext.getResourceShadowDiscriminator() == null || projContext.getResourceShadowDiscriminator().getResourceOid() == null) { throw new SystemException( "Projection "+projectionHumanReadableName+" with null OID, no representation and no resource OID in account sync context "+projContext); } @@ -1030,7 +1030,7 @@ private void finishLoadOfProjectionContext(LensContext // Avoid discovery loops rootOptions.setDoNotDiscovery(true); } - } else { + } else { rootOptions.setNoFetch(true); } rootOptions.setAllowNotFound(true); @@ -1038,7 +1038,7 @@ private void finishLoadOfProjectionContext(LensContext if (LOGGER.isTraceEnabled()) { LOGGER.trace("Loading shadow {} for projection {}, options={}", projectionObjectOid, projectionHumanReadableName, options); } - + try { PrismObject objectOld = provisioningService.getObject( projContext.getObjectTypeClass(), projectionObjectOid, options, task, result); @@ -1066,22 +1066,22 @@ private void finishLoadOfProjectionContext(LensContext projContext.setFullShadow(false); } projectionObject = objectOld; - + } catch (ObjectNotFoundException ex) { // This does not mean BROKEN. The projection was there, but it gone now. What we really want here // is a thombstone projection. thombstone = true; projContext.setFullShadow(false); LOGGER.warn("Could not find object with oid {}. The projection context {} is marked as thombstone.", projectionObjectOid, projectionHumanReadableName); - - - } catch (CommunicationException | SchemaException | ConfigurationException | SecurityViolationException + + + } catch (CommunicationException | SchemaException | ConfigurationException | SecurityViolationException | RuntimeException | Error e) { - - LOGGER.warn("Problem while getting object with oid {}. Projection context {} is marked as broken: {}: {}", + + LOGGER.warn("Problem while getting object with oid {}. Projection context {} is marked as broken: {}: {}", projectionObjectOid, projectionHumanReadableName, e.getClass().getSimpleName(), e.getMessage()); projContext.setSynchronizationPolicyDecision(SynchronizationPolicyDecision.BROKEN); - + ResourceType resourceType = projContext.getResource(); if (resourceType == null) { throw e; @@ -1108,7 +1108,7 @@ private void finishLoadOfProjectionContext(LensContext } } } - + } projContext.setFresh(true); } @@ -1118,8 +1118,8 @@ private void finishLoadOfProjectionContext(LensContext projContext.setExists(true); } } - - + + // Determine Resource ResourceType resourceType = projContext.getResource(); String resourceOid = null; @@ -1135,7 +1135,7 @@ private void finishLoadOfProjectionContext(LensContext } else { resourceOid = resourceType.getOid(); } - + // Determine discriminator ResourceShadowDiscriminator discr = projContext.getResourceShadowDiscriminator(); if (discr == null) { @@ -1154,13 +1154,13 @@ private void finishLoadOfProjectionContext(LensContext discr.setThombstone(thombstone); } } - + // Load resource if (resourceType == null && resourceOid != null) { resourceType = LensUtil.getResourceReadOnly(context, resourceOid, provisioningService, task, result); projContext.setResource(resourceType); } - + //Determine refined schema and password policies for account type RefinedObjectClassDefinition structuralObjectClassDef = projContext.getStructuralObjectClassDefinition(); if (structuralObjectClassDef != null) { @@ -1182,7 +1182,7 @@ private void finishLoadOfProjectionContext(LensContext } else { LOGGER.trace("No structural object class definition, skipping determining password policy"); } - + //set limitation, e.g. if this projection context should be recomputed and processed by projector if (ModelExecuteOptions.isLimitPropagation(context.getOptions())){ if (context.getTriggeredResourceOid() != null){ @@ -1191,10 +1191,10 @@ private void finishLoadOfProjectionContext(LensContext } } } - + setPrimaryDeltaOldValue(projContext); } - + private boolean needToReload(LensContext context, LensProjectionContext projContext) { ResourceShadowDiscriminator discr = projContext.getResourceShadowDiscriminator(); @@ -1216,7 +1216,7 @@ private boolean needToReload(LensContext context, } return false; } - + private void fullCheckConsistence(LensContext context) { context.checkConsistence(); for (LensProjectionContext projectionContext: context.getProjectionContexts()) { @@ -1228,7 +1228,7 @@ private void fullCheckConsistence(LensContext context) } } } - + public void loadFullShadow(LensContext context, LensProjectionContext projCtx, String reason, Task task, OperationResult result) throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { if (projCtx.isFullShadow()) { @@ -1251,7 +1251,7 @@ public void loadFullShadow(LensContext context, LensPr return; } } - + GetOperationOptions getOptions = GetOperationOptions.createAllowNotFound(); getOptions.setPointInTimeType(PointInTimeType.FUTURE); if (SchemaConstants.CHANGE_CHANNEL_DISCOVERY_URI.equals(context.getChannel())) { @@ -1261,7 +1261,7 @@ public void loadFullShadow(LensContext context, LensPr } else { LOGGER.trace("Loading full resource object {} from provisioning (discovery enabled), reason: {}, channel: {}", projCtx, reason, context.getChannel()); } - try { + try { Collection> options = SelectorOptions.createCollection(getOptions); applyAttributesToGet(projCtx, options); PrismObject objectCurrent = provisioningService.getObject(ShadowType.class, @@ -1275,14 +1275,14 @@ public void loadFullShadow(LensContext context, LensPr // TODO: this probably need to be fixed in the consistency mechanism // TODO: the following line is a temporary fix projCtx.setOid(objectCurrent.getOid()); - + } catch (ObjectNotFoundException ex) { LOGGER.trace("Load of full resource object {} ended with ObjectNotFoundException (options={})", projCtx, getOptions); if (projCtx.isDelete()){ //this is OK, shadow was deleted, but we will continue in processing with old shadow..and set it as full so prevent from other full loading projCtx.setFullShadow(true); } else { - + boolean compensated = false; if (!GetOperationOptions.isDoNotDiscovery(getOptions)) { // The account might have been re-created by the discovery. @@ -1331,9 +1331,9 @@ public void loadFullShadow(LensContext context, LensPr } } } - + } - + if (!compensated) { LOGGER.trace("ObjectNotFound error is not compensated, setting context to thombstone"); projCtx.getResourceShadowDiscriminator().setThombstone(true); @@ -1342,10 +1342,10 @@ public void loadFullShadow(LensContext context, LensPr } } } - + projCtx.recompute(); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Loaded full resource object:\n{}", projCtx.debugDump(1)); } @@ -1358,5 +1358,5 @@ private void applyAttributesToGet(LensProjectionContext projCtx, Collection void resetWaves(LensContext context) throws PolicyViolationException { } - + public void sortProjectionsToWaves(LensContext context) throws PolicyViolationException { // Create a snapshot of the projection collection at the beginning of computation. // The collection may be changed during computation (projections may be added). We do not want to process // these added projections. They are already processed inside the computation. // This also avoids ConcurrentModificationException LensProjectionContext[] projectionArray = context.getProjectionContexts().toArray(new LensProjectionContext[0]); - + // Reset incomplete flag for those contexts that are not yet computed for (LensProjectionContext projectionContext: context.getProjectionContexts()) { if (projectionContext.getWave() < 0) { projectionContext.setWaveIncomplete(true); } } - + for (LensProjectionContext projectionContext: projectionArray) { determineProjectionWave(context, projectionContext, null, null); projectionContext.setWaveIncomplete(false); } - + if (LOGGER.isTraceEnabled()) { StringBuilder sb = new StringBuilder(); for (LensProjectionContext projectionContext: context.getProjectionContexts()) { @@ -85,7 +85,7 @@ public void sortProjectionsToWaves(LensContext context context.getProjectionWave(), context.getExecutionWave(), sb.toString()); } } - + public int computeMaxWaves(LensContext context) { if (context.getPartialProcessingOptions().getInbound() != PartialProcessingTypeType.SKIP) { // Let's do one extra wave with no accounts in it. This time we expect to get the results of the execution to the user @@ -96,7 +96,7 @@ public int computeMaxWaves(LensContext context) { } } - private LensProjectionContext determineProjectionWave(LensContext context, + private LensProjectionContext determineProjectionWave(LensContext context, LensProjectionContext projectionContext, ResourceObjectTypeDependencyType inDependency, List depPath) throws PolicyViolationException { if (!projectionContext.isWaveIncomplete()) { // This was already processed @@ -111,8 +111,8 @@ private LensProjectionContext determineProjectionWave(Len return determineProjectionWaveProvision(context, projectionContext, inDependency, depPath); } } - - private LensProjectionContext determineProjectionWaveProvision(LensContext context, + + private LensProjectionContext determineProjectionWaveProvision(LensContext context, LensProjectionContext projectionContext, ResourceObjectTypeDependencyType inDependency, List depPath) throws PolicyViolationException { if (depPath == null) { depPath = new ArrayList(); @@ -130,7 +130,7 @@ private LensProjectionContext determineProjectionWaveProv } checkForCircular(depPath, outDependency); depPath.add(outDependency); - ResourceShadowDiscriminator refDiscr = new ResourceShadowDiscriminator(outDependency, + ResourceShadowDiscriminator refDiscr = new ResourceShadowDiscriminator(outDependency, projectionContext.getResource().getOid(), projectionContext.getKind()); LensProjectionContext dependencyProjectionContext = findDependencyTargetContext(context, projectionContext, outDependency); // if (LOGGER.isTraceEnabled()) { @@ -165,7 +165,7 @@ private LensProjectionContext determineProjectionWaveProv } depPath.remove(outDependency); } - LensProjectionContext resultAccountContext = projectionContext; + LensProjectionContext resultAccountContext = projectionContext; if (projectionContext.getWave() >=0 && projectionContext.getWave() != determinedWave) { // Wave for this context was set during the run of this method (it was not set when we // started, we checked at the beginning). Therefore this context must have been visited again. @@ -181,15 +181,15 @@ private LensProjectionContext determineProjectionWaveProv resultAccountContext.setWave(determinedWave); return resultAccountContext; } - - private LensProjectionContext determineProjectionWaveDeprovision(LensContext context, + + private LensProjectionContext determineProjectionWaveDeprovision(LensContext context, LensProjectionContext projectionContext, ResourceObjectTypeDependencyType inDependency, List depPath) throws PolicyViolationException { if (depPath == null) { depPath = new ArrayList(); } int determinedWave = 0; int determinedOrder = 0; - + // This needs to go in the reverse. We need to figure out who depends on us. for (DependencyAndSource ds: findReverseDependecies(context, projectionContext)) { LensProjectionContext dependencySourceContext = ds.sourceProjectionContext; @@ -204,7 +204,7 @@ private LensProjectionContext determineProjectionWaveDepr } checkForCircular(depPath, outDependency); depPath.add(outDependency); - ResourceShadowDiscriminator refDiscr = new ResourceShadowDiscriminator(outDependency, + ResourceShadowDiscriminator refDiscr = new ResourceShadowDiscriminator(outDependency, projectionContext.getResource().getOid(), projectionContext.getKind()); dependencySourceContext = determineProjectionWave(context, dependencySourceContext, outDependency, depPath); if (dependencySourceContext.getWave() + 1 > determinedWave) { @@ -218,7 +218,7 @@ private LensProjectionContext determineProjectionWaveDepr depPath.remove(outDependency); } - LensProjectionContext resultAccountContext = projectionContext; + LensProjectionContext resultAccountContext = projectionContext; if (projectionContext.getWave() >=0 && projectionContext.getWave() != determinedWave) { // Wave for this context was set during the run of this method (it was not set when we // started, we checked at the beginning). Therefore this context must have been visited again. @@ -231,8 +231,8 @@ private LensProjectionContext determineProjectionWaveDepr resultAccountContext.setWave(determinedWave); return resultAccountContext; } - - private Collection findReverseDependecies(LensContext context, + + private Collection findReverseDependecies(LensContext context, LensProjectionContext targetProjectionContext) throws PolicyViolationException { Collection deps = new ArrayList<>(); for (LensProjectionContext projectionContext: context.getProjectionContexts()) { @@ -248,7 +248,7 @@ private Collection findReverseDepend return deps; } - + private void checkForCircular(List depPath, ResourceObjectTypeDependencyType outDependency) throws PolicyViolationException { for (ResourceObjectTypeDependencyType pathElement: depPath) { @@ -290,7 +290,7 @@ private boolean isHigerOrder(ResourceObjectTypeDependencyType a, */ private LensProjectionContext findDependencyTargetContext( LensContext context, LensProjectionContext sourceProjContext, ResourceObjectTypeDependencyType dependency) { - ResourceShadowDiscriminator refDiscr = new ResourceShadowDiscriminator(dependency, + ResourceShadowDiscriminator refDiscr = new ResourceShadowDiscriminator(dependency, sourceProjContext.getResource().getOid(), sourceProjContext.getKind()); LensProjectionContext selected = null; for (LensProjectionContext projectionContext: context.getProjectionContexts()) { @@ -311,24 +311,24 @@ private LensProjectionContext findDependencyTargetContext } return selected; } - + // private boolean isDependencyTargetContext(LensProjectionContext sourceProjContext, LensProjectionContext targetProjectionContext, ResourceObjectTypeDependencyType dependency) { -// ResourceShadowDiscriminator refDiscr = new ResourceShadowDiscriminator(dependency, +// ResourceShadowDiscriminator refDiscr = new ResourceShadowDiscriminator(dependency, // sourceProjContext.getResource().getOid(), sourceProjContext.getKind()); // return targetProjectionContext.compareResourceShadowDiscriminator(refDiscr, false); // } - + private LensProjectionContext createAnotherContext(LensContext context, LensProjectionContext origProjectionContext, ResourceShadowDiscriminator discr) throws PolicyViolationException { - - + + LensProjectionContext otherCtx = context.createProjectionContext(discr); otherCtx.setResource(origProjectionContext.getResource()); // Force recon for the new context. This is a primitive way how to avoid phantom changes. otherCtx.setDoReconciliation(true); return otherCtx; } - + private LensProjectionContext createAnotherContext(LensContext context, LensProjectionContext origProjectionContext, int determinedOrder) throws PolicyViolationException { ResourceShadowDiscriminator origDiscr = origProjectionContext.getResourceShadowDiscriminator(); @@ -337,18 +337,18 @@ private LensProjectionContext createAnotherContext(LensCo LensProjectionContext otherCtx = createAnotherContext(context, origProjectionContext, discr); return otherCtx; } - + /** * Check that the dependencies are still satisfied. Also check for high-ordes vs low-order operation consistency - * and stuff like that. + * and stuff like that. */ - public boolean checkDependencies(LensContext context, + public boolean checkDependencies(LensContext context, LensProjectionContext projContext, OperationResult result) throws PolicyViolationException { if (projContext.isDelete()) { // It is OK if we depend on something that is not there if we are being removed ... for now return true; } - + if (projContext.getOid() == null || projContext.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.ADD) { // Check for lower-order contexts LensProjectionContext lowerOrderContext = null; @@ -379,10 +379,10 @@ public boolean checkDependencies(LensContext context, projContext.setSynchronizationPolicyDecision(SynchronizationPolicyDecision.DELETE); } } - } - + } + for (ResourceObjectTypeDependencyType dependency: projContext.getDependencies()) { - ResourceShadowDiscriminator refRat = new ResourceShadowDiscriminator(dependency, + ResourceShadowDiscriminator refRat = new ResourceShadowDiscriminator(dependency, projContext.getResource().getOid(), projContext.getKind()); LOGGER.trace("LOOKING FOR {}", refRat); LensProjectionContext dependencyAccountContext = context.findProjectionContext(refRat); @@ -395,7 +395,7 @@ public boolean checkDependencies(LensContext context, " dependent on " + refRat.toHumanReadableDescription() + ": No context in dependency check"); } else if (strictness == ResourceObjectTypeDependencyStrictnessType.LAX) { // independent object not in the context, just ignore it - LOGGER.trace("Unsatisfied lax dependency of account " + + LOGGER.trace("Unsatisfied lax dependency of account " + projContext.getResourceShadowDiscriminator().toHumanReadableDescription() + " dependent on " + refRat.toHumanReadableDescription() + "; dependency skipped"); } else if (strictness == ResourceObjectTypeDependencyStrictnessType.RELAXED) { @@ -430,21 +430,21 @@ public boolean checkDependencies(LensContext context, } return true; } - + public void preprocessDependencies(LensContext context){ - + //in the first wave we do not have enough information to preprocess contexts if (context.getExecutionWave() == 0){ return; } - + for (LensProjectionContext projContext : context.getProjectionContexts()){ if (!projContext.isCanProject()){ continue; } - + for (ResourceObjectTypeDependencyType dependency: projContext.getDependencies()) { - ResourceShadowDiscriminator refRat = new ResourceShadowDiscriminator(dependency, + ResourceShadowDiscriminator refRat = new ResourceShadowDiscriminator(dependency, projContext.getResource().getOid(), projContext.getKind()); LOGGER.trace("LOOKING FOR {}", refRat); LensProjectionContext dependencyAccountContext = context.findProjectionContext(refRat); @@ -469,26 +469,26 @@ public void preprocessDependencies(LensContext context } } - + /** * Finally checks for all the dependencies. Some dependencies cannot be checked during wave computations as - * we might not have all activation decisions yet. + * we might not have all activation decisions yet. */ public void checkDependenciesFinal(LensContext context, OperationResult result) throws PolicyViolationException { - + for (LensProjectionContext accountContext: context.getProjectionContexts()) { checkDependencies(context, accountContext, result); } - + for (LensProjectionContext accountContext: context.getProjectionContexts()) { - if (accountContext.isDelete() + if (accountContext.isDelete() || accountContext.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.UNLINK) { // It is OK if we depend on something that is not there if we are being removed // but we still need to check if others depends on me for (LensProjectionContext projectionContext: context.getProjectionContexts()) { if (projectionContext.isDelete() || projectionContext.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.UNLINK - || projectionContext.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.BROKEN + || projectionContext.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.BROKEN || projectionContext.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.IGNORE) { // If someone who is being deleted depends on us then it does not really matter continue; @@ -508,33 +508,33 @@ public void checkDependenciesFinal(LensContext context } } } - + } } } - + private boolean wasProvisioned(LensProjectionContext accountContext, int executionWave) { int accountWave = accountContext.getWave(); if (accountWave >= executionWave) { // This had no chance to be provisioned yet, so we assume it will be provisioned return true; } - if (accountContext.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.BROKEN + if (accountContext.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.BROKEN || accountContext.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.IGNORE) { return false; } - - + + PrismObject objectCurrent = accountContext.getObjectCurrent(); if (objectCurrent != null && objectCurrent.asObjectable().getFailedOperationType() != null) { // There is unfinished operation in the shadow. We cannot continue. return false; - } - + } + if (accountContext.isExists()) { return true; } - + if (accountContext.isAdd()) { List> executedDeltas = accountContext.getExecutedDeltas(); if (executedDeltas == null || executedDeltas.isEmpty()) { @@ -548,17 +548,17 @@ private boolean wasProvisioned(LensProjectionContext acco } return true; } - + return false; } - + private boolean wasExecuted(LensProjectionContext accountContext){ if (accountContext.isAdd()) { - + if (accountContext.getOid() == null){ return false; } - + List> executedDeltas = accountContext.getExecutedDeltas(); if (executedDeltas == null || executedDeltas.isEmpty()) { return false; @@ -571,6 +571,6 @@ class DependencyAndSource { ResourceObjectTypeDependencyType dependency; LensProjectionContext sourceProjectionContext; } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/FocusConstraintsChecker.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/FocusConstraintsChecker.java index f814548031f..274e91d2e09 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/FocusConstraintsChecker.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/FocusConstraintsChecker.java @@ -48,7 +48,7 @@ public class FocusConstraintsChecker { private static ThreadLocal cacheThreadLocal = new ThreadLocal<>(); - + private static final Trace LOGGER = TraceManager.getTrace(FocusConstraintsChecker.class); private static final Trace PERFORMANCE_ADVISOR = TraceManager.getPerformanceAdvisorTrace(); @@ -61,7 +61,7 @@ public class FocusConstraintsChecker { public FocusConstraintsChecker() { } - + public PrismContext getPrismContext() { return prismContext; } @@ -73,11 +73,11 @@ public void setPrismContext(PrismContext prismContext) { public LensContext getContext() { return context; } - + public void setContext(LensContext context) { this.context = context; } - + public RepositoryService getRepositoryService() { return repositoryService; } @@ -89,7 +89,7 @@ public void setRepositoryService(RepositoryService repositoryService) { public boolean isSatisfiesConstraints() { return satisfiesConstraints; } - + public String getMessages() { return messageBuilder.toString(); } @@ -98,14 +98,14 @@ public PrismObject getConflictingObject() { return conflictingObject; } public void check(PrismObject objectNew, OperationResult result) throws SchemaException { - + if (objectNew == null) { // This must be delete LOGGER.trace("No new object. Therefore it satisfies constraints"); satisfiesConstraints = true; return; } - + // Hardcode to name ... for now PolyStringType name = objectNew.asObjectable().getName(); if (Cache.isOk(name)) { @@ -117,19 +117,19 @@ public void check(PrismObject objectNew, OperationResult result) throws Schem } } } - + private boolean checkPropertyUniqueness(PrismObject objectNew, ItemPath propPath, LensContext context, OperationResult result) throws SchemaException { - + PrismProperty property = objectNew.findProperty(propPath); if (property == null || property.isEmpty()) { throw new SchemaException("No property "+propPath+" in new object "+objectNew+", cannot check uniqueness"); } String oid = objectNew.getOid(); - + ObjectQuery query = QueryBuilder.queryFor(objectNew.getCompileTimeClass(), prismContext) .itemAs(property) .build(); - + List> foundObjects = repositoryService.searchObjects(objectNew.getCompileTimeClass(), query, null, result); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Uniqueness check of {}, property {} resulted in {} results, using query:\n{}", @@ -142,8 +142,8 @@ private boolean checkPropertyUniqueness(PrismObject objectNew, ItemPath p LOGGER.trace("Found more than one object with property "+propPath+" = " + property); message("Found more than one object with property "+propPath+" = " + property); return false; - } - + } + LOGGER.trace("Comparing {} and {}", foundObjects.get(0).getOid(), oid); boolean match = foundObjects.get(0).getOid().equals(oid); if (!match) { @@ -156,10 +156,10 @@ private boolean checkPropertyUniqueness(PrismObject objectNew, ItemPath p conflictingObject = foundObjects.get(0); } - + return match; } - + private void message(String message) { if (messageBuilder.length() != 0) { messageBuilder.append(", "); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/FocusProcessor.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/FocusProcessor.java index 90bb3645e1c..75acdbecb22 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/FocusProcessor.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/FocusProcessor.java @@ -105,9 +105,9 @@ /** * Processor to handle everything about focus: values, assignments, etc. - * + * * @author Radovan Semancik - * + * */ @Component public class FocusProcessor { @@ -116,16 +116,16 @@ public class FocusProcessor { private PrismContainerDefinition activationDefinition; private PrismPropertyDefinition failedLoginsDefinition; - + @Autowired private InboundProcessor inboundProcessor; - + @Autowired private AssignmentProcessor assignmentProcessor; - + @Autowired private ObjectTemplateProcessor objectTemplateProcessor; - + @Autowired private MappingFactory mappingFactory; @@ -134,23 +134,23 @@ public class FocusProcessor { @Autowired private CredentialsProcessor credentialsProcessor; - + @Autowired private ModelObjectResolver modelObjectResolver; - + @Autowired private ActivationComputer activationComputer; - + @Autowired private ExpressionFactory expressionFactory; @Autowired @Qualifier("cacheRepositoryService") private transient RepositoryService cacheRepositoryService; - + @Autowired private MappingEvaluator mappingHelper; - + @Autowired private OperationalDataManager metadataManager; @@ -165,15 +165,15 @@ void processFocus(LensContext con if (focusContext == null) { return; } - + if (!FocusType.class.isAssignableFrom(focusContext.getObjectTypeClass())) { // We can do this only for FocusType objects. return; } - + processFocusFocus((LensContext)context, activityDescription, now, task, result); } - + private void processFocusFocus(LensContext context, String activityDescription, XMLGregorianCalendar now, Task task, OperationResult result) throws ObjectNotFoundException, @@ -192,7 +192,7 @@ private void processFocusFocus(LensContext context, Str int iteration = focusContext.getIteration(); String iterationToken = focusContext.getIterationToken(); boolean wasResetIterationCounter = false; - + PrismObject focusCurrent = focusContext.getObjectCurrent(); if (focusCurrent != null && iterationToken == null) { Integer focusIteration = focusCurrent.asObjectable().getIteration(); @@ -201,19 +201,19 @@ private void processFocusFocus(LensContext context, Str } iterationToken = focusCurrent.asObjectable().getIterationToken(); } - + while (true) { - + ObjectPolicyConfigurationType objectPolicyConfigurationType = focusContext.getObjectPolicyConfigurationType(); applyObjectPolicyConstraints(focusContext, objectPolicyConfigurationType); - - ExpressionVariables variablesPreIteration = Utils.getDefaultExpressionVariables(focusContext.getObjectNew(), + + ExpressionVariables variablesPreIteration = Utils.getDefaultExpressionVariables(focusContext.getObjectNew(), null, null, null, context.getSystemConfiguration(), focusContext); if (iterationToken == null) { - iterationToken = LensUtil.formatIterationToken(context, focusContext, + iterationToken = LensUtil.formatIterationToken(context, focusContext, iterationSpecificationType, iteration, expressionFactory, variablesPreIteration, task, result); } - + // We have to remember the token and iteration in the context. // The context can be recomputed several times. But we always want // to use the same iterationToken if possible. If there is a random @@ -224,18 +224,18 @@ private void processFocusFocus(LensContext context, Str focusContext.setIteration(iteration); focusContext.setIterationToken(iterationToken); LOGGER.trace("Focus {} processing, iteration {}, token '{}'", focusContext.getHumanReadableName(), iteration, iterationToken); - + String conflictMessage; - if (!LensUtil.evaluateIterationCondition(context, focusContext, + if (!LensUtil.evaluateIterationCondition(context, focusContext, iterationSpecificationType, iteration, iterationToken, true, expressionFactory, variablesPreIteration, task, result)) { - + conflictMessage = "pre-iteration condition was false"; LOGGER.debug("Skipping iteration {}, token '{}' for {} because the pre-iteration condition was false", iteration, iterationToken, focusContext.getHumanReadableName()); } else { - + // INBOUND - + if (consistencyChecks) context.checkConsistence(); LensUtil.partialExecute("inbound", @@ -248,31 +248,31 @@ private void processFocusFocus(LensContext context, Str if (consistencyChecks) context.checkConsistence(); }, partialProcessingOptions::getInbound); - - + + // ACTIVATION - + LensUtil.partialExecute("focusActivation", () -> processActivationBeforeAssignments(context, now, result), partialProcessingOptions::getFocusActivation); - - + + // OBJECT TEMPLATE (before assignments) - + LensUtil.partialExecute("objectTemplateBeforeAssignments", () -> objectTemplateProcessor.processTemplate(context, ObjectTemplateMappingEvaluationPhaseType.BEFORE_ASSIGNMENTS, now, task, result), partialProcessingOptions::getObjectTemplateBeforeAssignments); - - + + // process activation again. Object template might have changed it. context.recomputeFocus(); LensUtil.partialExecute("focusActivation", () -> processActivationBeforeAssignments(context, now, result), partialProcessingOptions::getFocusActivation); - + // ASSIGNMENTS - + LensUtil.partialExecute("assignments", () -> assignmentProcessor.processAssignmentsProjections(context, now, task, result), partialProcessingOptions::getAssignments); @@ -287,11 +287,11 @@ private void processFocusFocus(LensContext context, Str partialProcessingOptions::getAssignmentsMembershipAndDelegate); context.recompute(); - + LensUtil.partialExecute("assignmentsConflicts", () -> assignmentProcessor.checkForAssignmentConflicts(context, result), partialProcessingOptions::getAssignmentsConflicts); - + // OBJECT TEMPLATE (after assignments) LensUtil.partialExecute("objectTemplateAfterAssignments", @@ -307,20 +307,20 @@ private void processFocusFocus(LensContext context, Str LensUtil.partialExecute("focusActivation", () -> processActivationAfterAssignments(context, now, result), partialProcessingOptions::getFocusActivation); - + // CREDENTIALS (including PASSWORD POLICY) - + LensUtil.partialExecute("focusCredentials", () -> credentialsProcessor.processFocusCredentials(context, now, task, result), partialProcessingOptions::getFocusCredentials); - + // We need to evaluate this as a last step. We need to make sure we have all the // focus deltas so we can properly trigger the rules. LensUtil.partialExecute("focusPolicyRules", () -> evaluateFocusPolicyRules(context, activityDescription, now, task, result), partialProcessingOptions::getFocusPolicyRules); - + // Processing done, check for success if (resetOnRename && !wasResetIterationCounter && willResetIterationCounter(focusContext)) { @@ -336,7 +336,7 @@ private void processFocusFocus(LensContext context, Str continue; } } - + PrismObject previewObjectNew = focusContext.getObjectNew(); if (previewObjectNew == null) { // this must be delete @@ -349,7 +349,7 @@ private void processFocusFocus(LensContext context, Str " in iteration "+iteration+", we cannot process an object without a name"); } } - + // Check if iteration constraints are OK FocusConstraintsChecker checker = new FocusConstraintsChecker<>(); checker.setPrismContext(prismContext); @@ -358,10 +358,10 @@ private void processFocusFocus(LensContext context, Str checker.check(previewObjectNew, result); if (checker.isSatisfiesConstraints()) { LOGGER.trace("Current focus satisfies uniqueness constraints. Iteration {}, token '{}'", iteration, iterationToken); - ExpressionVariables variablesPostIteration = Utils.getDefaultExpressionVariables(focusContext.getObjectNew(), - null, null, null, context.getSystemConfiguration(), focusContext); - if (LensUtil.evaluateIterationCondition(context, focusContext, - iterationSpecificationType, iteration, iterationToken, false, expressionFactory, variablesPostIteration, + ExpressionVariables variablesPostIteration = Utils.getDefaultExpressionVariables(focusContext.getObjectNew(), + null, null, null, context.getSystemConfiguration(), focusContext); + if (LensUtil.evaluateIterationCondition(context, focusContext, + iterationSpecificationType, iteration, iterationToken, false, expressionFactory, variablesPostIteration, task, result)) { // stop the iterations break; @@ -375,7 +375,7 @@ private void processFocusFocus(LensContext context, Str checker.getConflictingObject(), iteration, maxIterations); conflictMessage = checker.getMessages(); } - + if (!wasResetIterationCounter) { wasResetIterationCounter = true; if (iteration != 0) { @@ -387,17 +387,17 @@ private void processFocusFocus(LensContext context, Str } } } - + // Next iteration iteration++; iterationToken = null; LensUtil.checkMaxIterations(iteration, maxIterations, conflictMessage, focusContext.getHumanReadableName()); cleanupContext(focusContext); } - + addIterationTokenDeltas(focusContext, iteration, iterationToken); if (consistencyChecks) context.checkConsistence(); - + } private void evaluateFocusPolicyRules(LensContext context, String activityDescription, @@ -422,21 +422,21 @@ private void triggerAssignmentFocusPolicyRules(LensContext } } } - + private void triggerGlobalRules(LensContext context) throws SchemaException, PolicyViolationException { PrismObject systemConfiguration = context.getSystemConfiguration(); if (systemConfiguration == null) { return; } LensFocusContext focusContext = context.getFocusContext(); - + // We need to consider object before modification here. We need to prohibit the modification, so we // cannot look at modified object. PrismObject focus = focusContext.getObjectCurrent(); if (focus == null) { focus = focusContext.getObjectNew(); } - + for (GlobalPolicyRuleType globalPolicyRule: systemConfiguration.asObjectable().getGlobalPolicyRule()) { ObjectSelectorType focusSelector = globalPolicyRule.getFocusSelector(); if (cacheRepositoryService.selectorMatches(focusSelector, focus, LOGGER, "Global policy rule "+globalPolicyRule.getName()+": ")) { @@ -462,7 +462,7 @@ private void triggerRule(LensFocusContext focusContext, } } - private boolean modificationConstraintMatches(LensFocusContext focusContext, EvaluatedPolicyRule policyRule, + private boolean modificationConstraintMatches(LensFocusContext focusContext, EvaluatedPolicyRule policyRule, ModificationPolicyConstraintType modificationConstraintType) throws SchemaException { if (!operationMatches(focusContext, modificationConstraintType.getOperation())) { LOGGER.trace("Rule {} operation not applicable", policyRule.getName()); @@ -510,13 +510,13 @@ private void applyObjectPolicyConstraints(LensFocusContext if (objectPolicyConfigurationType == null) { return; } - + final PrismObject focusNew = focusContext.getObjectNew(); if (focusNew == null) { // This is delete. Nothing to do. return; } - + for (PropertyConstraintType propertyConstraintType: objectPolicyConfigurationType.getPropertyConstraint()) { ItemPath itemPath = propertyConstraintType.getPath().getItemPath(); if (BooleanUtils.isTrue(propertyConstraintType.isOidBound())) { @@ -539,13 +539,13 @@ private void applyObjectPolicyConstraints(LensFocusContext propDelta.setValueToReplace(new PrismPropertyValue(new PolyString(newValue), OriginType.USER_POLICY, null)); } else { throw new SchemaException("Unsupported type "+propDef.getTypeName()+" for property "+itemPath+" in "+focusDefinition+" as specified in object policy, only string and polystring properties are supported for OID-bound mode"); - } + } focusContext.swallowToSecondaryDelta(propDelta); focusContext.recompute(); } } } - + // Deprecated if (BooleanUtils.isTrue(objectPolicyConfigurationType.isOidNameBoundMode())) { // Generate the name now - unless it is already present @@ -582,7 +582,7 @@ private boolean willResetIterationCounter(LensFocusContext PropertyDelta nameDelta = focusDelta.findPropertyDelta(new ItemPath(FocusType.F_NAME)); return nameDelta != null; } - + /** * Remove the intermediate results of values processing such as secondary deltas. */ @@ -591,54 +591,54 @@ private void cleanupContext(LensFocusContext focusConte // and it does not depend on iteration LOGGER.trace("Cleaning up focus context"); focusContext.setProjectionWaveSecondaryDelta(null); - + focusContext.clearIntermediateResults(); focusContext.recompute(); } - private void processActivationBeforeAssignments(LensContext context, XMLGregorianCalendar now, - OperationResult result) + private void processActivationBeforeAssignments(LensContext context, XMLGregorianCalendar now, + OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException { processActivationBasic(context, now, result); } - - private void processActivationAfterAssignments(LensContext context, XMLGregorianCalendar now, - OperationResult result) + + private void processActivationAfterAssignments(LensContext context, XMLGregorianCalendar now, + OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException { processActivationBasic(context, now, result); processAssignmentActivation(context, now, result); } - - private void processActivationBasic(LensContext context, XMLGregorianCalendar now, - OperationResult result) + + private void processActivationBasic(LensContext context, XMLGregorianCalendar now, + OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException { LensFocusContext focusContext = context.getFocusContext(); - + if (focusContext.isDelete()) { LOGGER.trace("Skipping processing of focus activation: focus delete"); return; } - + processActivationAdministrativeAndValidity(focusContext, now, result); - + if (focusContext.canRepresent(UserType.class)) { processActivationLockout((LensFocusContext) focusContext, now, result); } } - - private void processActivationAdministrativeAndValidity(LensFocusContext focusContext, XMLGregorianCalendar now, - OperationResult result) - throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException { - + + private void processActivationAdministrativeAndValidity(LensFocusContext focusContext, XMLGregorianCalendar now, + OperationResult result) + throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException { + TimeIntervalStatusType validityStatusNew = null; TimeIntervalStatusType validityStatusCurrent = null; XMLGregorianCalendar validityChangeTimestamp = null; - + String lifecycleStateNew = null; String lifecycleStateCurrent = null; ActivationType activationNew = null; ActivationType activationCurrent = null; - + PrismObject focusNew = focusContext.getObjectNew(); if (focusNew != null) { F focusTypeNew = focusNew.asObjectable(); @@ -649,7 +649,7 @@ private void processActivationAdministrativeAndValidity(Le } lifecycleStateNew = focusTypeNew.getLifecycleState(); } - + PrismObject focusCurrent = focusContext.getObjectCurrent(); if (focusCurrent != null) { F focusCurrentType = focusCurrent.asObjectable(); @@ -659,11 +659,11 @@ private void processActivationAdministrativeAndValidity(Le } lifecycleStateCurrent = focusCurrentType.getLifecycleState(); } - + if (validityStatusCurrent == validityStatusNew) { // No change, (almost) no work if (validityStatusNew != null && activationNew.getValidityStatus() == null) { - // There was no validity change. But the status is not recorded. So let's record it so it can be used in searches. + // There was no validity change. But the status is not recorded. So let's record it so it can be used in searches. recordValidityDelta(focusContext, validityStatusNew, now); } else { LOGGER.trace("Skipping validity processing because there was no change ({} -> {})", validityStatusCurrent, validityStatusNew); @@ -672,14 +672,14 @@ private void processActivationAdministrativeAndValidity(Le LOGGER.trace("Validity change {} -> {}", validityStatusCurrent, validityStatusNew); recordValidityDelta(focusContext, validityStatusNew, now); } - + ActivationStatusType effectiveStatusNew = activationComputer.getEffectiveStatus(lifecycleStateNew, activationNew, validityStatusNew); ActivationStatusType effectiveStatusCurrent = activationComputer.getEffectiveStatus(lifecycleStateCurrent, activationCurrent, validityStatusCurrent); - + if (effectiveStatusCurrent == effectiveStatusNew) { // No change, (almost) no work if (effectiveStatusNew != null && (activationNew == null || activationNew.getEffectiveStatus() == null)) { - // There was no effective status change. But the status is not recorded. So let's record it so it can be used in searches. + // There was no effective status change. But the status is not recorded. So let's record it so it can be used in searches. recordEffectiveStatusDelta(focusContext, effectiveStatusNew, now); } else { if (focusContext.getPrimaryDelta() != null && focusContext.getPrimaryDelta().hasItemDelta(SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS)) { @@ -688,7 +688,7 @@ private void processActivationAdministrativeAndValidity(Le // some of the mappings will use effectiveStatus as a source, therefore there has to be a delta for the mapping to work correctly recordEffectiveStatusDelta(focusContext, effectiveStatusNew, now); } else { - //check computed effective status current with the saved one - e.g. there can be some inconsistencies so we need to check and force the change.. in other cases, effectvie status will be stored with + //check computed effective status current with the saved one - e.g. there can be some inconsistencies so we need to check and force the change.. in other cases, effectvie status will be stored with // incorrect value. Maybe another option is to not compute effectiveStatusCurrent if there is an existing (saved) effective status in the user.. TODO if (activationCurrent != null && activationCurrent.getEffectiveStatus() != null) { ActivationStatusType effectiveStatusSaved = activationCurrent.getEffectiveStatus(); @@ -703,14 +703,14 @@ private void processActivationAdministrativeAndValidity(Le LOGGER.trace("Effective status change {} -> {}", effectiveStatusCurrent, effectiveStatusNew); recordEffectiveStatusDelta(focusContext, effectiveStatusNew, now); } - - + + } - - private void processActivationLockout(LensFocusContext focusContext, XMLGregorianCalendar now, - OperationResult result) - throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException { - + + private void processActivationLockout(LensFocusContext focusContext, XMLGregorianCalendar now, + OperationResult result) + throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException { + ObjectDelta focusPrimaryDelta = focusContext.getPrimaryDelta(); if (focusPrimaryDelta != null) { PropertyDelta lockoutStatusDelta = focusContext.getPrimaryDelta().findPropertyDelta(SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS); @@ -730,13 +730,13 @@ private void processActivationLockout(LensFocusContext focusNew = focusContext.getObjectNew(); if (focusNew != null) { activationNew = focusNew.asObjectable().getActivation(); @@ -744,7 +744,7 @@ private void processActivationLockout(LensFocusContext focusCurrent = focusContext.getObjectCurrent(); if (focusCurrent != null) { activationCurrent = focusCurrent.asObjectable().getActivation(); @@ -752,36 +752,36 @@ private void processActivationLockout(LensFocusContext {})", lockoutStatusCurrent, lockoutStatusNew); return; } - + LOGGER.trace("Lockout change {} -> {}", lockoutStatusCurrent, lockoutStatusNew); - + if (lockoutStatusNew == LockoutStatusType.NORMAL) { - + CredentialsType credentialsTypeNew = focusNew.asObjectable().getCredentials(); if (credentialsTypeNew != null) { resetFailedLogins(focusContext, credentialsTypeNew.getPassword(), SchemaConstants.PATH_CREDENTIALS_PASSWORD_FAILED_LOGINS); resetFailedLogins(focusContext, credentialsTypeNew.getNonce(), SchemaConstants.PATH_CREDENTIALS_NONCE_FAILED_LOGINS); resetFailedLogins(focusContext, credentialsTypeNew.getSecurityQuestions(), SchemaConstants.PATH_CREDENTIALS_SECURITY_QUESTIONS_FAILED_LOGINS); } - + if (activationNew != null && activationNew.getLockoutExpirationTimestamp() != null) { PrismContainerDefinition activationDefinition = getActivationDefinition(); PrismPropertyDefinition lockoutExpirationTimestampDef = activationDefinition.findPropertyDefinition(ActivationType.F_LOCKOUT_EXPIRATION_TIMESTAMP); - PropertyDelta lockoutExpirationTimestampDelta + PropertyDelta lockoutExpirationTimestampDelta = lockoutExpirationTimestampDef.createEmptyDelta(new ItemPath(UserType.F_ACTIVATION, ActivationType.F_LOCKOUT_EXPIRATION_TIMESTAMP)); lockoutExpirationTimestampDelta.setValueToReplace(); focusContext.swallowToProjectionWaveSecondaryDelta(lockoutExpirationTimestampDelta); } } - + } - + private void resetFailedLogins(LensFocusContext focusContext, AbstractCredentialType credentialTypeNew, ItemPath path) throws SchemaException{ if (credentialTypeNew != null) { Integer failedLogins = credentialTypeNew.getFailedLogins(); @@ -793,13 +793,13 @@ private void resetFailedLogins(LensFocusContext focusContext, Abstract } } } - + private void recordValidityDelta(LensFocusContext focusContext, TimeIntervalStatusType validityStatusNew, XMLGregorianCalendar now) throws SchemaException { PrismContainerDefinition activationDefinition = getActivationDefinition(); - + PrismPropertyDefinition validityStatusDef = activationDefinition.findPropertyDefinition(ActivationType.F_VALIDITY_STATUS); - PropertyDelta validityStatusDelta + PropertyDelta validityStatusDelta = validityStatusDef.createEmptyDelta(new ItemPath(UserType.F_ACTIVATION, ActivationType.F_VALIDITY_STATUS)); if (validityStatusNew == null) { validityStatusDelta.setValueToReplace(); @@ -807,36 +807,36 @@ private void recordValidityDelta(LensFocusContext focu validityStatusDelta.setValueToReplace(new PrismPropertyValue<>(validityStatusNew, OriginType.USER_POLICY, null)); } focusContext.swallowToProjectionWaveSecondaryDelta(validityStatusDelta); - + PrismPropertyDefinition validityChangeTimestampDef = activationDefinition.findPropertyDefinition(ActivationType.F_VALIDITY_CHANGE_TIMESTAMP); - PropertyDelta validityChangeTimestampDelta + PropertyDelta validityChangeTimestampDelta = validityChangeTimestampDef.createEmptyDelta(new ItemPath(UserType.F_ACTIVATION, ActivationType.F_VALIDITY_CHANGE_TIMESTAMP)); validityChangeTimestampDelta.setValueToReplace(new PrismPropertyValue<>(now, OriginType.USER_POLICY, null)); focusContext.swallowToProjectionWaveSecondaryDelta(validityChangeTimestampDelta); } - - private void recordEffectiveStatusDelta(LensFocusContext focusContext, + + private void recordEffectiveStatusDelta(LensFocusContext focusContext, ActivationStatusType effectiveStatusNew, XMLGregorianCalendar now) throws SchemaException { PrismContainerDefinition activationDefinition = getActivationDefinition(); - + // We always want explicit delta for effective status even if there is no real change // we want to propagate enable/disable events to all the resources, even if we are enabling // already enabled user (some resources may be disabled) // This may produce duplicate delta, but that does not matter too much. The duplicate delta // will be filtered out later. PrismPropertyDefinition effectiveStatusDef = activationDefinition.findPropertyDefinition(ActivationType.F_EFFECTIVE_STATUS); - PropertyDelta effectiveStatusDelta + PropertyDelta effectiveStatusDelta = effectiveStatusDef.createEmptyDelta(new ItemPath(UserType.F_ACTIVATION, ActivationType.F_EFFECTIVE_STATUS)); effectiveStatusDelta.setValueToReplace(new PrismPropertyValue(effectiveStatusNew, OriginType.USER_POLICY, null)); if (!focusContext.alreadyHasDelta(effectiveStatusDelta)){ focusContext.swallowToProjectionWaveSecondaryDelta(effectiveStatusDelta); } - + // It is not enough to check alreadyHasDelta(). The change may happen in previous waves // and the secondary delta may no longer be here. When it comes to disableTimestamp we even // cannot rely on natural filtering of already executed deltas as the timestamp here may - // be off by several milliseconds. So explicitly check for the change here. + // be off by several milliseconds. So explicitly check for the change here. PrismObject objectCurrent = focusContext.getObjectCurrent(); if (objectCurrent != null) { PrismProperty effectiveStatusPropCurrent = objectCurrent.findProperty(SchemaConstants.PATH_ACTIVATION_EFFECTIVE_STATUS); @@ -845,14 +845,14 @@ private void recordEffectiveStatusDelta(LensFocusContext< return; } } - + PropertyDelta timestampDelta = LensUtil.createActivationTimestampDelta(effectiveStatusNew, now, activationDefinition, OriginType.USER_POLICY); if (!focusContext.alreadyHasDelta(timestampDelta)) { focusContext.swallowToProjectionWaveSecondaryDelta(timestampDelta); } } - - + + private PrismContainerDefinition getActivationDefinition() { if (activationDefinition == null) { ComplexTypeDefinition focusDefinition = prismContext.getSchemaRegistry().findComplexTypeDefinition(FocusType.COMPLEX_TYPE); @@ -860,7 +860,7 @@ private PrismContainerDefinition getActivationDefinition() { } return activationDefinition; } - + private PrismPropertyDefinition getFailedLoginsDefinition() { if (failedLoginsDefinition == null) { PrismObjectDefinition userDef = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); @@ -868,7 +868,7 @@ private PrismPropertyDefinition getFailedLoginsDefinition() { } return failedLoginsDefinition; } - + /** * Adds deltas for iteration and iterationToken to the focus if needed. */ @@ -884,22 +884,22 @@ private void addIterationTokenDeltas(LensFocusContext f } } PrismObjectDefinition objDef = focusContext.getObjectDefinition(); - + PrismPropertyValue iterationVal = new PrismPropertyValue(iteration); iterationVal.setOriginType(OriginType.USER_POLICY); - PropertyDelta iterationDelta = PropertyDelta.createReplaceDelta(objDef, + PropertyDelta iterationDelta = PropertyDelta.createReplaceDelta(objDef, FocusType.F_ITERATION, iterationVal); focusContext.swallowToSecondaryDelta(iterationDelta); - + PrismPropertyValue iterationTokenVal = new PrismPropertyValue(iterationToken); iterationTokenVal.setOriginType(OriginType.USER_POLICY); - PropertyDelta iterationTokenDelta = PropertyDelta.createReplaceDelta(objDef, + PropertyDelta iterationTokenDelta = PropertyDelta.createReplaceDelta(objDef, FocusType.F_ITERATION_TOKEN, iterationTokenVal); focusContext.swallowToSecondaryDelta(iterationTokenDelta); - + } - - private void processAssignmentActivation(LensContext context, XMLGregorianCalendar now, + + private void processAssignmentActivation(LensContext context, XMLGregorianCalendar now, OperationResult result) throws SchemaException { DeltaSetTriple> evaluatedAssignmentTriple = context.getEvaluatedAssignmentTriple(); if (evaluatedAssignmentTriple == null) { @@ -945,6 +945,6 @@ private void processAssignmentActivation(LensContext co } } } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/InboundProcessor.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/InboundProcessor.java index c8bac8abed2..ce1fc525e3c 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/InboundProcessor.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/InboundProcessor.java @@ -70,22 +70,22 @@ public class InboundProcessor { @Autowired private PrismContext prismContext; - + @Autowired private FilterManager filterManager; - + @Autowired private MappingFactory mappingFactory; - + @Autowired private ContextLoader contextLoader; - + @Autowired private CredentialsProcessor credentialsProcessor; - + @Autowired private MappingEvaluator mappingEvaluator; - + @Autowired private Protector protector; @@ -140,7 +140,7 @@ private void processInboundFocal(LensContext context, T continue; } ObjectDelta aPrioriDelta = getAPrioriDelta(context, projectionContext); - + if (!projectionContext.isDoReconciliation() && aPrioriDelta == null && !LensUtil.hasDependentContext(context, projectionContext) && !projectionContext.isFullShadow()) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Skipping processing of inbound expressions for projection {}: no full shadow, no reconciliation, no a priori delta and no dependent context", @@ -180,7 +180,7 @@ private void processInboundMappingsForProjection(LensConte LensProjectionContext projContext, RefinedObjectClassDefinition projectionDefinition, ObjectDelta aPrioriProjectionDelta, Task task, XMLGregorianCalendar now, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, ConfigurationException, CommunicationException, SecurityViolationException { - + if (aPrioriProjectionDelta == null && projContext.getObjectCurrent() == null) { LOGGER.trace("Nothing to process in inbound, both a priori delta and current account were null."); return; @@ -195,7 +195,7 @@ private void processInboundMappingsForProjection(LensConte return; } } - + for (QName accountAttributeName : projectionDefinition.getNamesOfAttributesWithInboundExpressions()) { boolean cont = processAttributeInbound(accountAttributeName, aPrioriProjectionDelta, projContext, projectionDefinition, context, now, task, result); if (!cont) { @@ -209,25 +209,25 @@ private void processInboundMappingsForProjection(LensConte } processSpecialPropertyInbound(projectionDefinition.getPasswordInbound(), SchemaConstants.PATH_PASSWORD_VALUE, SchemaConstants.PATH_PASSWORD_VALUE, context.getFocusContext().getObjectNew(), projContext, projectionDefinition, context, now, task, result); - + processSpecialPropertyInbound(projectionDefinition.getActivationBidirectionalMappingType(ActivationType.F_ADMINISTRATIVE_STATUS), SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, - context.getFocusContext().getObjectNew(), projContext, projectionDefinition, context, now, task, result); + context.getFocusContext().getObjectNew(), projContext, projectionDefinition, context, now, task, result); processSpecialPropertyInbound(projectionDefinition.getActivationBidirectionalMappingType(ActivationType.F_VALID_FROM), SchemaConstants.PATH_ACTIVATION_VALID_FROM, context.getFocusContext().getObjectNew(), projContext, projectionDefinition, context, now, task, result); processSpecialPropertyInbound(projectionDefinition.getActivationBidirectionalMappingType(ActivationType.F_VALID_TO), SchemaConstants.PATH_ACTIVATION_VALID_TO, context.getFocusContext().getObjectNew(), projContext, projectionDefinition, context, now, task, result); - + processAuxiliaryObjectClassInbound(aPrioriProjectionDelta, projContext, projectionDefinition, context, now, task, result); } - + private boolean processAttributeInbound(QName accountAttributeName, ObjectDelta aPrioriProjectionDelta, final LensProjectionContext projContext, RefinedObjectClassDefinition projectionDefinition, final LensContext context, - XMLGregorianCalendar now, Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, ConfigurationException { - + XMLGregorianCalendar now, Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, ConfigurationException { + PrismObject projCurrent = projContext.getObjectCurrent(); PrismObject projNew = projContext.getObjectNew(); - + final PropertyDelta attributeAPrioriDelta; if (aPrioriProjectionDelta != null) { attributeAPrioriDelta = aPrioriProjectionDelta.findPropertyDelta(new ItemPath(SchemaConstants.C_ATTRIBUTES), accountAttributeName); @@ -241,37 +241,37 @@ private boolean processAttributeInbound(QName accountAttri } RefinedAttributeDefinition attrDef = projectionDefinition.findAttributeDefinition(accountAttributeName); - + if (attrDef.isIgnored(LayerType.MODEL)) { LOGGER.trace("Skipping inbound for attribute {} in {} because the attribute is ignored", PrettyPrinter.prettyPrint(accountAttributeName), projContext.getResourceShadowDiscriminator()); return true; } - + List inboundMappingTypes = attrDef.getInboundMappingTypes(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Processing inbound for {} in {}; ({} mappings)", PrettyPrinter.prettyPrint(accountAttributeName), projContext.getResourceShadowDiscriminator(), inboundMappingTypes.size()); } - + PropertyLimitations limitations = attrDef.getLimitations(LayerType.MODEL); if (limitations != null) { PropertyAccessType access = limitations.getAccess(); if (access != null) { if (access.isRead() == null || !access.isRead()) { - LOGGER.warn("Inbound mapping for non-readable attribute {} in {}, skipping", + LOGGER.warn("Inbound mapping for non-readable attribute {} in {}, skipping", accountAttributeName, projContext.getHumanReadableName()); return true; } } } - + if (inboundMappingTypes.isEmpty()) { return true; } - + for (MappingType inboundMappingType : inboundMappingTypes) { - + // There are two processing options: // // * If we have a delta as an input we will proceed in relative mode, applying mappings on the delta. @@ -310,17 +310,17 @@ private boolean processAttributeInbound(QName accountAttri LOGGER.trace("Processing inbound from a priori delta: {}", aPrioriProjectionDelta); focusItemDelta = evaluateInboundMapping(context, inboundMappingType, accountAttributeName, null, attributeAPrioriDelta, focus, projNew, projContext.getResource(), task, result); - + } else if (projCurrent != null) { - + projCurrent = loadFullShadowIfNeeded(projContext, projCurrent, context, now, task, result); if (projCurrent == null) { return false; } - + PrismProperty oldAccountProperty = projCurrent.findProperty(new ItemPath(ShadowType.F_ATTRIBUTES, accountAttributeName)); LOGGER.trace("Processing inbound from account sync absolute state (currentAccount): {}", oldAccountProperty); - focusItemDelta = evaluateInboundMapping(context, inboundMappingType, accountAttributeName, oldAccountProperty, null, + focusItemDelta = evaluateInboundMapping(context, inboundMappingType, accountAttributeName, oldAccountProperty, null, focus, projNew, projContext.getResource(), task, result); } @@ -334,14 +334,14 @@ private boolean processAttributeInbound(QName accountAttri LOGGER.trace("Created delta (from inbound expression for {} on {}) was null or empty.", accountAttributeName, projContext.getResource()); } } - + return true; } - + private void processAuxiliaryObjectClassInbound( ObjectDelta aPrioriProjectionDelta, final LensProjectionContext projContext, RefinedObjectClassDefinition projectionDefinition, final LensContext context, - XMLGregorianCalendar now, Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, ConfigurationException { + XMLGregorianCalendar now, Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, ConfigurationException { ResourceBidirectionalMappingAndDefinitionType auxiliaryObjectClassMappings = projectionDefinition.getAuxiliaryObjectClassMappings(); if (auxiliaryObjectClassMappings == null) { @@ -355,10 +355,10 @@ private void processAuxiliaryObjectClassInbound( if (inboundMappingTypes.isEmpty()) { return; } - + PrismObject projCurrent = projContext.getObjectCurrent(); PrismObject projNew = projContext.getObjectNew(); - + final PropertyDelta attributeAPrioriDelta; if (aPrioriProjectionDelta != null) { attributeAPrioriDelta = aPrioriProjectionDelta.findPropertyDelta(ShadowType.F_AUXILIARY_OBJECT_CLASS); @@ -369,8 +369,8 @@ private void processAuxiliaryObjectClassInbound( } } else { attributeAPrioriDelta = null; - } - + } + // Make we always have full shadow when dealing with auxiliary object classes. // Unlike structural object class the auxiliary object classes may have changed // on the resource @@ -378,7 +378,7 @@ private void processAuxiliaryObjectClassInbound( if (projCurrent == null) { return; } - + PrismObject focus; if (context.getFocusContext().getObjectCurrent() != null) { focus = context.getFocusContext().getObjectCurrent(); @@ -387,12 +387,12 @@ private void processAuxiliaryObjectClassInbound( } for (MappingType inboundMappingType : inboundMappingTypes) { - + ItemDelta focusItemDelta = null; - + PrismProperty oldAccountProperty = projCurrent.findProperty(ShadowType.F_AUXILIARY_OBJECT_CLASS); LOGGER.trace("Processing inbound from account sync absolute state (currentAccount): {}", oldAccountProperty); - focusItemDelta = evaluateInboundMapping(context, inboundMappingType, ShadowType.F_AUXILIARY_OBJECT_CLASS, oldAccountProperty, + focusItemDelta = evaluateInboundMapping(context, inboundMappingType, ShadowType.F_AUXILIARY_OBJECT_CLASS, oldAccountProperty, null, focus, projNew, projContext.getResource(), task, result); if (focusItemDelta != null && !focusItemDelta.isEmpty()) { @@ -448,7 +448,7 @@ private PrismObject loadProjection(LensContext } private boolean hasAnyStrongMapping(RefinedObjectClassDefinition objectDefinition) { - + for (QName attributeName : objectDefinition.getNamesOfAttributesWithInboundExpressions()) { RefinedAttributeDefinition attributeDefinition = objectDefinition.findAttributeDefinition(attributeName); for (MappingType inboundMapping : attributeDefinition.getInboundMappingTypes()){ @@ -457,7 +457,7 @@ private boolean hasAnyStrongMapping(RefinedObjectClassDefinition objectDefinitio } } } - + return false; } @@ -465,7 +465,7 @@ private boolean hasAnyStrongMapping(RefinedObjectClassDefinition objectDefinitio * A priori delta is a delta that was executed in a previous "step". That means it is either delta from a previous * wave or a sync delta (in wave 0). */ - private ObjectDelta getAPrioriDelta(LensContext context, + private ObjectDelta getAPrioriDelta(LensContext context, LensProjectionContext accountContext) throws SchemaException { int wave = context.getProjectionWave(); if (wave == 0) { @@ -502,23 +502,23 @@ private boolean checkWeakSkip(Mapping inbound, Prism } return false; } - - private ItemDelta evaluateInboundMapping(final LensContext context, - MappingType inboundMappingType, + + private ItemDelta evaluateInboundMapping(final LensContext context, + MappingType inboundMappingType, QName accountAttributeName, PrismProperty oldAccountProperty, PropertyDelta attributeAPrioriDelta, PrismObject focusNew, PrismObject account, ResourceType resource, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, ConfigurationException { if (oldAccountProperty != null && oldAccountProperty.hasRaw()) { throw new SystemException("Property "+oldAccountProperty+" has raw parsing state, such property cannot be used in inbound expressions"); } - + Mapping.Builder builder = mappingFactory.createMappingBuilder(inboundMappingType, "inbound expression for "+accountAttributeName+" in "+resource); - + if (!builder.isApplicableToChannel(context.getChannel())) { return null; } - + Source,PrismPropertyDefinition> defaultSource = new Source<>(oldAccountProperty, attributeAPrioriDelta, null, ExpressionConstants.VAR_INPUT); defaultSource.recompute(); Mapping mapping = builder.defaultSource(defaultSource) @@ -532,12 +532,12 @@ private .originType(OriginType.INBOUND) .originObject(resource) .build(); - + if (checkWeakSkip(mapping, focusNew)) { LOGGER.trace("Skipping because of mapping is weak and focus property has already a value"); return null; } - + ItemPath targetFocusItemPath = mapping.getOutputPath(); if (ItemPath.isNullOrEmpty(targetFocusItemPath)) { throw new ConfigurationException("Empty target path in "+mapping.getContextDescription()); @@ -552,22 +552,22 @@ private throw new SchemaException("No definition for focus property "+targetFocusItemPath+", cannot process inbound expression in "+resource); } final ItemDelta outputFocusItemDelta = targetItemDef.createEmptyDelta(targetFocusItemPath); - + mappingEvaluator.evaluateMapping(mapping, context, task, result); - + PrismValueDeltaSetTriple triple = mapping.getOutputTriple(); // Meaning of the resulting triple: // values in PLUS set will be added (valuesToAdd in delta) // values in MINUS set will be removed (valuesToDelete in delta) // values in ZERO set will be compared with existing values in user property // the differences will be added to delta - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Inbound mapping for {} returned triple:\n{}", accountAttributeName, triple == null ? "null" : triple.debugDump()); } - + if (triple != null) { - + if (triple.hasPlusSet()) { boolean alreadyReplaced = false; @@ -577,7 +577,7 @@ private if (targetFocusItem != null && targetFocusItem.hasRealValue(value)) { continue; } - + //if property is not multi value replace existing attribute if (targetFocusItem != null && !targetFocusItem.getDefinition().isMultiValue() && !targetFocusItem.isEmpty()) { Collection replace = new ArrayList(); @@ -607,7 +607,7 @@ private } } } - + Item shouldBeItem = targetItemDef.instantiate(); shouldBeItem.addAll(PrismValue.cloneCollection(triple.getZeroSet())); shouldBeItem.addAll(PrismValue.cloneCollection(triple.getPlusSet())); @@ -657,11 +657,11 @@ private //if user property doesn't exist we have to add it (as delta), because inbound say so outputFocusItemDelta.addValuesToAdd(shouldBeItem.getClonedValues()); } - + } else { // triple == null - + // the mapping is not applicable. Nothing to do. - + } // if no changes were generated return null @@ -676,12 +676,12 @@ private StringPolicyResolver createStringPolicyResolver(f public void setOutputPath(ItemPath outputPath) { this.outputPath = outputPath; } - + @Override public void setOutputDefinition(ItemDefinition outputDefinition) { this.outputDefinition = outputDefinition; } - + @Override public StringPolicyType resolve() { if (!outputDefinition.getName().equals(PasswordType.F_VALUE)) { @@ -712,13 +712,13 @@ private PrismPropertyValue filterValue(PrismPropertyValue propertyValu return filteredValue; } - + /** - * Processing for special (fixed-schema) properties such as credentials and activation. - * @throws ObjectNotFoundException + * Processing for special (fixed-schema) properties such as credentials and activation. + * @throws ObjectNotFoundException */ private void processSpecialPropertyInbound(ResourceBidirectionalMappingType biMappingType, ItemPath sourceTargetPath, - PrismObject newUser, LensProjectionContext projCtx, + PrismObject newUser, LensProjectionContext projCtx, RefinedObjectClassDefinition rOcDef, LensContext context, XMLGregorianCalendar now, Task task, OperationResult opResult) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException { if (biMappingType == null) { @@ -728,8 +728,8 @@ private void processSpecialPropertyInbound(ResourceBidirec } // private void processSpecialPropertyInbound(MappingType inboundMappingType, ItemPath sourcePath, -// PrismObject newUser, LensProjectionContext accContext, -// RefinedObjectClassDefinition accountDefinition, LensContext context, +// PrismObject newUser, LensProjectionContext accContext, +// RefinedObjectClassDefinition accountDefinition, LensContext context, // OperationResult opResult) throws SchemaException { // if (inboundMappingType == null) { // return; @@ -740,11 +740,11 @@ private void processSpecialPropertyInbound(ResourceBidirec // } /** - * Processing for special (fixed-schema) properties such as credentials and activation. - * @throws ObjectNotFoundException - * @throws ExpressionEvaluationException + * Processing for special (fixed-schema) properties such as credentials and activation. + * @throws ObjectNotFoundException + * @throws ExpressionEvaluationException */ - private void processSpecialPropertyInbound(Collection inboundMappingTypes, + private void processSpecialPropertyInbound(Collection inboundMappingTypes, final ItemPath sourcePath, final ItemPath targetPath, final PrismObject newUser, final LensProjectionContext projContext, RefinedObjectClassDefinition projectionDefinition, final LensContext context, @@ -753,7 +753,7 @@ private void processSpecialPropertyInbound(Collection userPrimaryDelta = context.getFocusContext().getPrimaryDelta(); PropertyDelta primaryPropDelta = null; if (userPrimaryDelta != null) { @@ -772,8 +772,8 @@ private void processSpecialPropertyInbound(Collection { if (projContext.getObjectNew() == null) { projContext.recompute(); @@ -811,18 +811,18 @@ private void processSpecialPropertyInbound(Collection processor = + + MappingOutputProcessor processor = (mappingOutputPath, outputStruct) -> { PrismValueDeltaSetTriple outputTriple = outputStruct.getOutputTriple(); if (outputTriple == null){ LOGGER.trace("Mapping for property {} evaluated to null. Skipping inboud processing for that property.", sourcePath); return false; } - + ObjectDelta userSecondaryDeltaInt = context.getFocusContext().getProjectionWaveSecondaryDelta(); if (userSecondaryDeltaInt != null) { PropertyDelta delta = userSecondaryDeltaInt.findPropertyDelta(targetPath); @@ -831,11 +831,11 @@ private void processSpecialPropertyInbound(Collection focusDefinition = context.getFocusContext().getObjectDefinition(); PrismProperty result = focusDefinition.findPropertyDefinition(targetPath).instantiate(); result.addAll(PrismValue.cloneCollection(outputTriple.getNonNegativeValues())); - + PrismProperty targetPropertyNew = newUser.findOrCreateProperty(targetPath); PropertyDelta delta; if (ProtectedStringType.COMPLEX_TYPE.equals(targetPropertyNew.getDefinition().getTypeName())) { @@ -866,7 +866,7 @@ private void processSpecialPropertyInbound(Collection params = new MappingEvaluatorParams<>(); params.setMappingTypes(inboundMappingTypes); params.setMappingDesc("inbound mapping for " + sourcePath + " in " + projContext.getResource()); @@ -881,13 +881,13 @@ private void processSpecialPropertyInbound(Collection> outputTriple = mappingEvaluatorHelper.evaluateMappingSetProjection( // inboundMappingTypes, "inbound mapping for " + sourcePath + " in " + accContext.getResource(), now, initializer, targetPropertyNew, primaryPropDelta, newUser, true, strongMappingWasUsed, context, accContext, task, opResult); - + } - + // private Collection getMappingApplicableToChannel( // Collection inboundMappingTypes, String description, String channelUri) { // Collection inboundMappings = new ArrayList(); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingEvaluator.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingEvaluator.java index d5313ba1473..5fd799078e8 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingEvaluator.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingEvaluator.java @@ -102,9 +102,9 @@ */ @Component public class MappingEvaluator { - + private static final Trace LOGGER = TraceManager.getTrace(MappingEvaluator.class); - + @Autowired private MappingFactory mappingFactory; @Autowired private CredentialsProcessor credentialsProcessor; @Autowired private ContextLoader contextLoader; @@ -115,7 +115,7 @@ public vo Mapping mapping, LensContext lensContext, Task task, OperationResult parentResult) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException { evaluateMapping(mapping, lensContext, null, task, parentResult); } - + public void evaluateMapping( Mapping mapping, LensContext lensContext, LensProjectionContext projContext, Task task, OperationResult parentResult) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException { ExpressionEnvironment env = new ExpressionEnvironment<>(); @@ -150,33 +150,33 @@ public vo } } } - + // TODO: unify OutboundProcessor.evaluateMapping() with MappingEvaluator.evaluateOutboundMapping(...) - public void evaluateOutboundMapping(final LensContext context, + public void evaluateOutboundMapping(final LensContext context, final LensProjectionContext projCtx, List outboundMappings, final ItemPath focusPropertyPath, final ItemPath projectionPropertyPath, - final MappingInitializer,PrismPropertyDefinition> initializer, MappingOutputProcessor> processor, + final MappingInitializer,PrismPropertyDefinition> initializer, MappingOutputProcessor> processor, XMLGregorianCalendar now, final boolean evaluateCurrent, boolean evaluateWeak, String desc, final Task task, final OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException { - + String projCtxDesc = projCtx.toHumanReadableString(); PrismObject shadowNew = projCtx.getObjectNew(); - MappingInitializer,PrismPropertyDefinition> internalInitializer = + MappingInitializer,PrismPropertyDefinition> internalInitializer = builder -> { builder.addVariableDefinitions(Utils.getDefaultExpressionVariables(context, projCtx).getMap()); - + builder.originType(OriginType.OUTBOUND); builder.originObject(projCtx.getResource()); - + initializer.initialize(builder); - + return builder; }; MappingLoader loader = new ProjectionMappingLoader<>(context, projCtx, contextLoader); - + MappingEvaluatorParams, PrismPropertyDefinition, ShadowType, F> params = new MappingEvaluatorParams<>(); params.setMappingTypes(outboundMappings); params.setMappingDesc(desc + " in projection " + projCtxDesc); @@ -197,34 +197,34 @@ public void evaluateOutboundMapping(final LensContext void evaluateMappingSetProjection( MappingEvaluatorParams params, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException { - + String mappingDesc = params.getMappingDesc(); LensElementContext targetContext = params.getTargetContext(); PrismObjectDefinition targetObjectDefinition = targetContext.getObjectDefinition(); ItemPath defaultTargetItemPath = params.getDefaultTargetItemPath(); - - Map> outputTripleMap = new HashMap<>(); + + Map> outputTripleMap = new HashMap<>(); XMLGregorianCalendar nextRecomputeTime = null; Collection mappingTypes = params.getMappingTypes(); Collection> mappings = new ArrayList<>(mappingTypes.size()); for (MappingType mappingType: mappingTypes) { - + Mapping.Builder mappingBuilder = mappingFactory.createMappingBuilder(mappingType, mappingDesc); String mappingName = null; if (mappingType.getName() != null) { mappingName = mappingType.getName(); } - + if (!mappingBuilder.isApplicableToChannel(params.getContext().getChannel())) { LOGGER.trace("Mapping {} not applicable to channel, skipping {}", mappingName, params.getContext().getChannel()); continue; } - + mappingBuilder.now(params.getNow()); if (defaultTargetItemPath != null && targetObjectDefinition != null) { D defaultTargetItemDef = targetObjectDefinition.findItemDefinition(defaultTargetItemPath); @@ -235,17 +235,17 @@ public mapping = mappingBuilder.build(); Boolean timeConstraintValid = mapping.evaluateTimeConstraintValid(task, result); - + if (params.getEvaluateCurrent() != null) { if (params.getEvaluateCurrent() && !timeConstraintValid) { LOGGER.trace("Mapping {} is non-current, but evulating current mappings, skipping {}", mappingName, params.getContext().getChannel()); @@ -256,27 +256,27 @@ public aPrioriTargetObject = params.getAPrioriTargetObject(); - + LOGGER.trace("Going to process {} mappings for {}", mappings.size(), mappingDesc); - + for (Mapping mapping: mappings) { - + if (mapping.getStrength() == MappingStrengthType.WEAK) { // Evaluate weak mappings in a second run. continue; } - + ItemPath mappingOutputPath = mapping.getOutputPath(); if (params.isFixTarget() && mappingOutputPath != null && defaultTargetItemPath != null && !mappingOutputPath.equivalent(defaultTargetItemPath)) { throw new ExpressionEvaluationException("Target cannot be overridden in "+mappingDesc); } - + if (params.getAPrioriTargetDelta() != null && mappingOutputPath != null) { ItemDelta aPrioriItemDelta = params.getAPrioriTargetDelta().findItemDelta(mappingOutputPath); if (mapping.getStrength() != MappingStrengthType.STRONG) { @@ -285,15 +285,15 @@ public mappingOutputTriple = mapping.getOutputTriple(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Output triple of mapping {}\n{}", mapping.getContextDescription(), mappingOutputTriple==null?null:mappingOutputTriple.debugDump(1)); } - + if (isMeaningful(mappingOutputTriple)) { MappingOutputStruct mappingOutputStruct = outputTripleMap.get(mappingOutputPath); @@ -301,10 +301,10 @@ public (); outputTripleMap.put(mappingOutputPath, mappingOutputStruct); } - + if (mapping.getStrength() == MappingStrengthType.STRONG) { mappingOutputStruct.setStrongMappingWasUsed(true); - + // if (!hasFullTargetObject && params.getTargetLoader() != null) { // if (!params.getTargetLoader().isLoaded()) { // aPrioriTargetObject = params.getTargetLoader().load(task, result); @@ -320,34 +320,34 @@ public mapping: mappings) { - + if (mapping.getStrength() != MappingStrengthType.WEAK) { continue; } - + ItemPath mappingOutputPath = mapping.getOutputPath(); if (params.isFixTarget() && mappingOutputPath != null && defaultTargetItemPath != null && !mappingOutputPath.equivalent(defaultTargetItemPath)) { throw new ExpressionEvaluationException("Target cannot be overridden in "+mappingDesc); } - + MappingOutputStruct mappingOutputStruct = outputTripleMap.get(mappingOutputPath); if (mappingOutputStruct == null) { mappingOutputStruct = new MappingOutputStruct<>(); outputTripleMap.put(mappingOutputPath, mappingOutputStruct); } - + PrismValueDeltaSetTriple outputTriple = mappingOutputStruct.getOutputTriple(); if (outputTriple != null) { // Previous mapping produced output. We do not need to evaluate weak mapping. @@ -357,20 +357,20 @@ public aPrioriTargetItem = null; if (aPrioriTargetObject != null && mappingOutputPath != null) { aPrioriTargetItem = aPrioriTargetObject.findItem(mappingOutputPath); } if (hasNoValue(aPrioriTargetItem)) { - + mappingOutputStruct.setWeakMappingWasUsed(true); - + evaluateMapping(mapping, params.getContext(), task, result); - + PrismValueDeltaSetTriple mappingOutputTriple = mapping.getOutputTriple(); if (mappingOutputTriple != null) { - + // This may be counter-intuitive to load object after the mapping is executed // But the mapping may not be activated (e.g. condition is false). And in that // case we really do not want to trigger object loading. @@ -388,38 +388,38 @@ public processor = params.getProcessor(); for (Entry> outputTripleMapEntry: outputTripleMap.entrySet()) { ItemPath mappingOutputPath = outputTripleMapEntry.getKey(); MappingOutputStruct mappingOutputStruct = outputTripleMapEntry.getValue(); PrismValueDeltaSetTriple outputTriple = mappingOutputStruct.getOutputTriple(); - + boolean defaultProcessing = true; - + if (processor != null) { LOGGER.trace("Executing processor to process mapping evaluation results: {}", processor); defaultProcessing = processor.process(mappingOutputPath, mappingOutputStruct); - } - + } + if (defaultProcessing) { - + if (outputTriple == null) { LOGGER.trace("{} expression resulted in null triple for {}, skipping", mappingDesc, targetContext); continue; } - + ItemDefinition targetItemDefinition = null; if (mappingOutputPath != null) { targetItemDefinition = targetObjectDefinition.findItemDefinition(mappingOutputPath); @@ -430,56 +430,56 @@ public targetItemDelta = targetItemDefinition.createEmptyDelta(mappingOutputPath); - + Item aPrioriTargetItem = null; if (aPrioriTargetObject != null) { aPrioriTargetItem = aPrioriTargetObject.findItem(mappingOutputPath); } - + // WARNING // Following code seems to be wrong. It is not very relativisic. It seems to always // go for replace. // It seems that it is only used for activation mappings (outbout and inbound). As // these are quite special single-value properties then it seems to work fine // (with the exception of MID-3418). Todo: make it more relativistic: MID-3419 - + if (targetContext.isAdd()) { - + Collection nonNegativeValues = outputTriple.getNonNegativeValues(); if (nonNegativeValues == null || nonNegativeValues.isEmpty()) { LOGGER.trace("{} resulted in null or empty value for {}, skipping", mappingDesc, targetContext); continue; } targetItemDelta.setValuesToReplace(PrismValue.cloneCollection(nonNegativeValues)); - + } else { - + // if we have fresh information (full shadow) AND the mapping used to derive the information was strong, // we will consider all values (zero & plus sets) -- otherwise, we take only the "plus" (i.e. changed) set - + // the first case is necessary, because in some situations (e.g. when mapping is changed) // the evaluator sees no differences w.r.t. real state, even if there is a difference // - and we must have a way to push new information onto the resource - + Collection valuesToReplace; - + if (hasFullTargetObject && mappingOutputStruct.isStrongMappingWasUsed()) { valuesToReplace = outputTriple.getNonNegativeValues(); } else { valuesToReplace = outputTriple.getPlusSet(); } - + if (LOGGER.isTraceEnabled()) { - LOGGER.trace("{}: hasFullTargetObject={}, isStrongMappingWasUsed={}, valuesToReplace={}", - new Object[]{mappingDesc, hasFullTargetObject, + LOGGER.trace("{}: hasFullTargetObject={}, isStrongMappingWasUsed={}, valuesToReplace={}", + new Object[]{mappingDesc, hasFullTargetObject, mappingOutputStruct.isStrongMappingWasUsed(), valuesToReplace}); } - + if (valuesToReplace != null && !valuesToReplace.isEmpty()) { - + // if what we want to set is the same as is already in the shadow, we skip that // (we insist on having full shadow, to be sure we work with current data) - + if (hasFullTargetObject && targetContext.isFresh() && aPrioriTargetItem != null) { Collection valuesPresent = aPrioriTargetItem.getValues(); if (PrismValue.equalsRealValues(valuesPresent, valuesToReplace)) { @@ -488,29 +488,29 @@ public mapping: mappings) { XMLGregorianCalendar mappingNextRecomputeTime = mapping.getNextRecomputeTime(); if (mappingNextRecomputeTime != null) { @@ -519,9 +519,9 @@ public triggerContDef = targetObjectDefinition.findContainerDefinition(ObjectType.F_TRIGGER); ContainerDelta triggerDelta = triggerContDef.createEmptyDelta(new ItemPath(ObjectType.F_TRIGGER)); @@ -556,7 +556,7 @@ private boolean isMeaningful(PrismValueDeltaSetTriple // this means: no value produced return true; } - if (mappingOutputTriple.getMinusSet() != null && + if (mappingOutputTriple.getMinusSet() != null && (mappingOutputTriple.getZeroSet() == null || mappingOutputTriple.getZeroSet().isEmpty()) && (mappingOutputTriple.getPlusSet() == null || mappingOutputTriple.getPlusSet().isEmpty())) { // Minus deltas are always meaningful, even with hashing (see below) @@ -564,7 +564,7 @@ private boolean isMeaningful(PrismValueDeltaSetTriple return true; } if (hasNoOrHashedValuesOnly(mappingOutputTriple.getMinusSet()) && hasNoOrHashedValuesOnly(mappingOutputTriple.getZeroSet()) && hasNoOrHashedValuesOnly(mappingOutputTriple.getPlusSet())) { - // Used to skip application of mapping that produces only hashed protected values. + // Used to skip application of mapping that produces only hashed protected values. // Those values are useless, e.g. to set new password. If we would consider them as // meaningful then a normal mapping with such values may prohibit application of // a weak mapping. We want weak mapping in this case, e.g. to set a randomly-generated password. @@ -591,14 +591,14 @@ private boolean hasNoOrHashedValuesOnly(Collection set } return true; } - + private boolean hasNoValue(Item aPrioriTargetItem) { - return aPrioriTargetItem == null + return aPrioriTargetItem == null || (aPrioriTargetItem.isEmpty() && !aPrioriTargetItem.isIncomplete()); } public Mapping createFocusMapping(final MappingFactory mappingFactory, - final LensContext context, final MappingType mappingType, ObjectType originObject, + final LensContext context, final MappingType mappingType, ObjectType originObject, ObjectDeltaObject focusOdo, AssignmentPathVariables assignmentPathVariables, PrismObject configuration, XMLGregorianCalendar now, String contextDesc, Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException { Integer iteration = null; @@ -615,10 +615,10 @@ private boolean hasNoValue(Item aPrioriTargetItem) { return createFocusMapping(mappingFactory, context, mappingType, originObject, focusOdo, focusOdo.getAnyObject(), assignmentPathVariables, iteration, iterationToken, configuration, now, contextDesc, task, result); } - + public Mapping createFocusMapping( - final MappingFactory mappingFactory, final LensContext context, final MappingType mappingType, ObjectType originObject, - ObjectDeltaObject focusOdo, PrismObject defaultTargetObject, AssignmentPathVariables assignmentPathVariables, + final MappingFactory mappingFactory, final LensContext context, final MappingType mappingType, ObjectType originObject, + ObjectDeltaObject focusOdo, PrismObject defaultTargetObject, AssignmentPathVariables assignmentPathVariables, Integer iteration, String iterationToken, PrismObject configuration, XMLGregorianCalendar now, String contextDesc, final Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException { @@ -705,10 +705,10 @@ public StringPolicyType resolve() { // no output element, i.e. this is a "validation mapping" return mapping; } - + if (defaultTargetObject != null) { Item existingTargetItem = (Item) defaultTargetObject.findItem(itemPath); - if (existingTargetItem != null && !existingTargetItem.isEmpty() + if (existingTargetItem != null && !existingTargetItem.isEmpty() && mapping.getStrength() == MappingStrengthType.WEAK) { LOGGER.trace("Mapping {} is weak and target already has a value {}, skipping.", mapping, existingTargetItem); return null; diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingEvaluatorParams.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingEvaluatorParams.java index 5e434810a3e..951baa1ca61 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingEvaluatorParams.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingEvaluatorParams.java @@ -36,7 +36,7 @@ * */ public class MappingEvaluatorParams { - + private Collection mappingTypes; private String mappingDesc; private XMLGregorianCalendar now; @@ -56,35 +56,35 @@ public class MappingEvaluatorParams getMappingTypes() { return mappingTypes; } - + public void setMappingTypes(Collection mappingTypes) { this.mappingTypes = mappingTypes; } - + public String getMappingDesc() { return mappingDesc; } - + public void setMappingDesc(String mappingDesc) { this.mappingDesc = mappingDesc; } - + public XMLGregorianCalendar getNow() { return now; } - + public void setNow(XMLGregorianCalendar now) { this.now = now; } - + public MappingInitializer getInitializer() { return initializer; } - + public void setInitializer(MappingInitializer initializer) { this.initializer = initializer; } @@ -100,35 +100,35 @@ public void setTargetLoader(MappingLoader targetLoader) { public MappingOutputProcessor getProcessor() { return processor; } - + public void setProcessor(MappingOutputProcessor processor) { this.processor = processor; } - + public PrismObject getAPrioriTargetObject() { return aPrioriTargetObject; } - + public void setAPrioriTargetObject(PrismObject aPrioriTargetObject) { this.aPrioriTargetObject = aPrioriTargetObject; } - + public ObjectDelta getAPrioriTargetDelta() { return aPrioriTargetDelta; } - + public void setAPrioriTargetDelta(ObjectDelta aPrioriTargetDelta) { this.aPrioriTargetDelta = aPrioriTargetDelta; } - + public LensElementContext getTargetContext() { return targetContext; } - + public void setTargetContext(LensElementContext targetContext) { this.targetContext = targetContext; } - + public ObjectDeltaObject getSourceContext() { return sourceContext; } @@ -140,11 +140,11 @@ public void setSourceContext(ObjectDeltaObject sourceContext) { public Boolean getEvaluateCurrent() { return evaluateCurrent; } - + public void setEvaluateCurrent(Boolean evaluateCurrent) { this.evaluateCurrent = evaluateCurrent; } - + public boolean isEvaluateWeak() { return evaluateWeak; } @@ -156,7 +156,7 @@ public void setEvaluateWeak(boolean evaluateWeak) { public LensContext getContext() { return context; } - + public void setContext(LensContext context) { this.context = context; } @@ -192,5 +192,5 @@ public D getTargetItemDefinition() { public void setTargetItemDefinition(D targetItemDefinition) { this.targetItemDefinition = targetItemDefinition; } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingExtractor.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingExtractor.java index cd9b32f9420..7886a9469e9 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingExtractor.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingExtractor.java @@ -27,6 +27,6 @@ public interface MappingExtractor { Collection> getMappings(Construction construction); - - + + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingInitializer.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingInitializer.java index 8af11745ee0..e37e972bade 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingInitializer.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingInitializer.java @@ -28,5 +28,5 @@ public interface MappingInitializer { Mapping.Builder initialize(Mapping.Builder mapping) throws SchemaException; - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingLoader.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingLoader.java index ab3f94931ef..113c21a1c6c 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingLoader.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingLoader.java @@ -31,9 +31,9 @@ * */ public interface MappingLoader { - + boolean isLoaded(); - + PrismObject load(String loadReason, Task task, OperationResult result) throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException; } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingOutputProcessor.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingOutputProcessor.java index e60b1b3ccdf..1d39bd85161 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingOutputProcessor.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingOutputProcessor.java @@ -29,11 +29,11 @@ public interface MappingOutputProcessor { /** - * + * * @return if true is returned then the detaul processing will take place * after the processor is finished. If false then the defaul processing * will be skipped. */ boolean process(ItemPath mappingOutputPath, MappingOutputStruct outputStruct) throws SchemaException, ExpressionEvaluationException; - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingOutputStruct.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingOutputStruct.java index d11a04e9f26..2dd422317b4 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingOutputStruct.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/MappingOutputStruct.java @@ -31,7 +31,7 @@ public class MappingOutputStruct { public PrismValueDeltaSetTriple getOutputTriple() { return outputTriple; } - + public void setOutputTriple(PrismValueDeltaSetTriple outputTriple) { this.outputTriple = outputTriple; } @@ -51,5 +51,5 @@ public boolean isWeakMappingWasUsed() { public void setWeakMappingWasUsed(boolean weakMappingWasUsed) { this.weakMappingWasUsed = weakMappingWasUsed; } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ObjectTemplateProcessor.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ObjectTemplateProcessor.java index d39ab016c08..c542dfcd290 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ObjectTemplateProcessor.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ObjectTemplateProcessor.java @@ -91,9 +91,9 @@ /** * Processor to handle object template. - * + * * @author Radovan Semancik - * + * */ @Component public class ObjectTemplateProcessor { @@ -108,11 +108,11 @@ public class ObjectTemplateProcessor { @Autowired private ModelObjectResolver modelObjectResolver; - + @Autowired @Qualifier("cacheRepositoryService") private transient RepositoryService cacheRepositoryService; - + @Autowired private MappingEvaluator mappingEvaluator; @@ -120,9 +120,9 @@ public class ObjectTemplateProcessor { private MatchingRuleRegistry matchingRuleRegistry; /** - * Process focus template: application of object template where focus is both source and target. + * Process focus template: application of object template where focus is both source and target. */ - public void processTemplate(LensContext context, ObjectTemplateMappingEvaluationPhaseType phase, + public void processTemplate(LensContext context, ObjectTemplateMappingEvaluationPhaseType phase, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException, ObjectAlreadyExistsException { LensFocusContext focusContext = context.getFocusContext(); @@ -130,42 +130,42 @@ public void processTemplate(LensContext context, Object LOGGER.trace("Skipping processing of object template: focus delete"); return; } - + ObjectTemplateType objectTemplate = context.getFocusTemplate(); if (objectTemplate == null) { // No applicable template LOGGER.trace("Skipping processing of object template: no object template"); return; } - + int iteration = focusContext.getIteration(); String iterationToken = focusContext.getIterationToken(); ObjectDeltaObject focusOdo = focusContext.getObjectDeltaObject(); PrismObjectDefinition focusDefinition = getObjectDefinition(focusContext.getObjectTypeClass()); - + LOGGER.trace("Applying {} to {}, iteration {} ({}), phase {}", objectTemplate, focusContext.getObjectNew(), iteration, iterationToken, phase); - + Map>> outputTripleMap = new HashMap<>(); Map itemDefinitionsMap = collectItemDefinitionsFromTemplate(objectTemplate, objectTemplate.toString(), task, result); - XMLGregorianCalendar nextRecomputeTime = collectTripleFromTemplate(context, objectTemplate, phase, + XMLGregorianCalendar nextRecomputeTime = collectTripleFromTemplate(context, objectTemplate, phase, focusOdo, focusOdo.getNewObject(), outputTripleMap, iteration, iterationToken, now, objectTemplate.toString(), task, result); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("outputTripleMap before item delta computation:\n{}", DebugUtil.debugDumpMapMultiLine(outputTripleMap)); } String contextDesc = "object template "+objectTemplate+ " for focus "+focusOdo.getAnyObject(); - Collection> itemDeltas = computeItemDeltas(outputTripleMap, itemDefinitionsMap, focusOdo.getObjectDelta(), focusOdo.getNewObject(), + Collection> itemDeltas = computeItemDeltas(outputTripleMap, itemDefinitionsMap, focusOdo.getObjectDelta(), focusOdo.getNewObject(), focusDefinition, contextDesc); - + focusContext.applyProjectionWaveSecondaryDeltas(itemDeltas); - + if (nextRecomputeTime != null) { - + boolean alreadyHasTrigger = false; PrismObject objectCurrent = focusContext.getObjectCurrent(); if (objectCurrent != null) { @@ -177,7 +177,7 @@ public void processTemplate(LensContext context, Object } } } - + if (!alreadyHasTrigger) { PrismObjectDefinition objectDefinition = focusContext.getObjectDefinition(); PrismContainerDefinition triggerContDef = objectDefinition.findContainerDefinition(ObjectType.F_TRIGGER); @@ -187,44 +187,44 @@ public void processTemplate(LensContext context, Object TriggerType triggerType = triggerCVal.asContainerable(); triggerType.setTimestamp(nextRecomputeTime); triggerType.setHandlerUri(RecomputeTriggerHandler.HANDLER_URI); - + focusContext.swallowToProjectionWaveSecondaryDelta(triggerDelta); } } } - + /** * Processing object mapping: application of object template where focus is the source and another object is the target. * Used to map focus to personas. */ - public Collection> processObjectMapping(LensContext context, + public Collection> processObjectMapping(LensContext context, ObjectTemplateType objectMappingType, ObjectDeltaObject focusOdo, PrismObject target, ObjectDelta targetAPrioriDelta, String contextDesc, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException, ObjectAlreadyExistsException { LensFocusContext focusContext = context.getFocusContext(); - + int iteration = 0; String iterationToken = null; PrismObjectDefinition focusDefinition = getObjectDefinition(focusContext.getObjectTypeClass()); - + LOGGER.trace("Applying object mapping {} from {} to {}, iteration {} ({})", objectMappingType, focusContext.getObjectNew(), target, iteration, iterationToken); - + Map>> outputTripleMap = new HashMap<>(); - Map itemDefinitionsMap = collectItemDefinitionsFromTemplate(objectMappingType, + Map itemDefinitionsMap = collectItemDefinitionsFromTemplate(objectMappingType, objectMappingType.toString(), task, result); collectTripleFromTemplate(context, objectMappingType, null, focusOdo, target, outputTripleMap, iteration, iterationToken, now, objectMappingType.toString(), task, result); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("outputTripleMap before item delta computation:\n{}", DebugUtil.debugDumpMapMultiLine(outputTripleMap)); } Collection> itemDeltas = computeItemDeltas(outputTripleMap, itemDefinitionsMap, targetAPrioriDelta, target, focusDefinition, contextDesc); - + return itemDeltas; } @@ -261,16 +261,16 @@ private Map collectItemDefinitionsFr Collection> computeItemDeltas(Map>> outputTripleMap, @Nullable Map itemDefinitionsMap, ObjectDelta targetObjectAPrioriDelta, PrismObject targetObject, PrismObjectDefinition focusDefinition, String contextDesc) throws ExpressionEvaluationException, PolicyViolationException, SchemaException { - + Collection> itemDeltas = new ArrayList<>(); - + LOGGER.trace("Computing deltas in {}, focusDelta:\n{}", contextDesc, targetObjectAPrioriDelta); boolean addUnchangedValues = false; if (targetObjectAPrioriDelta != null && targetObjectAPrioriDelta.isAdd()) { addUnchangedValues = true; } - + for (Entry>> entry: outputTripleMap.entrySet()) { ItemPath itemPath = entry.getKey(); DeltaSetTriple> outputTriple = entry.getValue(); @@ -291,17 +291,17 @@ Collection> computeIte ItemDelta itemDelta = LensUtil.consolidateTripleToDelta(itemPath, (DeltaSetTriple)outputTriple, itemDefinition, aprioriItemDelta, targetObject, null, null, addUnchangedValues, filterExistingValues, false, contextDesc, true); - - + + // Do a quick version of reconciliation. There is not much to reconcile as both the source and the target - // is focus. But there are few cases to handle, such as strong mappings, and sourceless normal mappings. + // is focus. But there are few cases to handle, such as strong mappings, and sourceless normal mappings. Collection> zeroSet = outputTriple.getZeroSet(); Item itemNew = null; if (targetObject != null) { itemNew = targetObject.findItem(itemPath); } for (ItemValueWithOrigin zeroSetIvwo: zeroSet) { - + PrismValueDeltaSetTripleProducer mapping = zeroSetIvwo.getMapping(); if ((mapping.getStrength() == null || mapping.getStrength() == MappingStrengthType.NORMAL)) { if (aprioriItemDelta != null && !aprioriItemDelta.isEmpty()) { @@ -310,25 +310,25 @@ Collection> computeIte if (!mapping.isSourceless()) { continue; } - LOGGER.trace("Adding zero values from normal mapping {}, a-priori delta: {}, isSourceless: {}", + LOGGER.trace("Adding zero values from normal mapping {}, a-priori delta: {}, isSourceless: {}", mapping, aprioriItemDelta, mapping.isSourceless()); } else if (mapping.getStrength() == MappingStrengthType.WEAK) { if ((itemNew != null && !itemNew.isEmpty()) || (itemDelta != null && itemDelta.addsAnyValue())) { continue; } - LOGGER.trace("Adding zero values from weak mapping {}, itemNew: {}, itemDelta: {}", + LOGGER.trace("Adding zero values from weak mapping {}, itemNew: {}, itemDelta: {}", mapping, itemNew, itemDelta); } else { LOGGER.trace("Adding zero values from strong mapping {}", mapping); } - + PrismValue valueFromZeroSet = zeroSetIvwo.getItemValue(); if (itemNew == null || !itemNew.containsRealValue(valueFromZeroSet)) { LOGGER.trace("Reconciliation will add value {} for item {}. Existing item: {}", valueFromZeroSet, itemPath, itemNew); itemDelta.addValuesToAdd(valueFromZeroSet.clone()); } } - + if (isNonTolerant) { if (itemDelta.isDelete()) { @@ -364,7 +364,7 @@ Collection> computeIte } PrismUtil.setDeltaOldValue(targetObject, itemDelta); } - + itemDelta.simplify(); itemDelta.validate(contextDesc); itemDeltas.add(itemDelta); @@ -380,22 +380,22 @@ private ItemDelta getAprioriItemDelta(ObjectDelta focus } private XMLGregorianCalendar collectTripleFromTemplate(LensContext context, - ObjectTemplateType objectTemplateType, ObjectTemplateMappingEvaluationPhaseType phase, + ObjectTemplateType objectTemplateType, ObjectTemplateMappingEvaluationPhaseType phase, ObjectDeltaObject focusOdo, PrismObject target, Map>> outputTripleMap, int iteration, String iterationToken, XMLGregorianCalendar now, String contextDesc, Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, PolicyViolationException { - + LOGGER.trace("Collecting triples from {}", objectTemplateType); - + XMLGregorianCalendar nextRecomputeTime = null; - + // Process includes for (ObjectReferenceType includeRef: objectTemplateType.getIncludeRef()) { PrismObject includeObject = includeRef.asReferenceValue().getObject(); if (includeObject == null) { - ObjectTemplateType includeObjectType = modelObjectResolver.resolve(includeRef, ObjectTemplateType.class, + ObjectTemplateType includeObjectType = modelObjectResolver.resolve(includeRef, ObjectTemplateType.class, null, "include reference in "+objectTemplateType + " in " + contextDesc, task, result); includeObject = includeObjectType.asPrismObject(); // Store resolved object for future use (e.g. next waves). @@ -403,8 +403,8 @@ private XMLGregorianCalendar collectT } LOGGER.trace("Including template {}", includeObject); ObjectTemplateType includeObjectType = includeObject.asObjectable(); - XMLGregorianCalendar includeNextRecomputeTime = collectTripleFromTemplate(context, includeObjectType, phase, - focusOdo, target, + XMLGregorianCalendar includeNextRecomputeTime = collectTripleFromTemplate(context, includeObjectType, phase, + focusOdo, target, outputTripleMap, iteration, iterationToken, now, "include "+includeObject+" in "+objectTemplateType + " in " + contextDesc, task, result); if (includeNextRecomputeTime != null) { @@ -413,11 +413,11 @@ private XMLGregorianCalendar collectT } } } - + // Process own mappings List mappings = collectMappings(objectTemplateType); List sortedMappings = sortMappingsByDependencies(mappings); - XMLGregorianCalendar templateNextRecomputeTime = collectTripleFromMappings(sortedMappings, phase, context, objectTemplateType, + XMLGregorianCalendar templateNextRecomputeTime = collectTripleFromMappings(sortedMappings, phase, context, objectTemplateType, focusOdo, target, outputTripleMap, iteration, iterationToken, now, contextDesc, task, result); if (templateNextRecomputeTime != null) { @@ -425,7 +425,7 @@ private XMLGregorianCalendar collectT nextRecomputeTime = templateNextRecomputeTime; } } - + return nextRecomputeTime; } @@ -528,9 +528,9 @@ private updatedFocusOdo = getUpdatedFocusOdo(context, focusOdo, outputTripleMap, mappingType, contextDesc); // for mapping chaining - Mapping mapping = mappingEvaluator.createFocusMapping(mappingFactory, context, mappingType, objectTemplateType, + Mapping mapping = mappingEvaluator.createFocusMapping(mappingFactory, context, mappingType, objectTemplateType, updatedFocusOdo, target, null, iteration, iterationToken, context.getSystemConfiguration(), now, contextDesc, task, result); if (mapping == null) { continue; } - + Boolean timeConstraintValid = mapping.evaluateTimeConstraintValid(task, result); - + if (timeConstraintValid != null && !timeConstraintValid) { // Delayed mapping. Just schedule recompute time XMLGregorianCalendar mappingNextRecomputeTime = mapping.getNextRecomputeTime(); @@ -564,7 +564,7 @@ private ObjectDeltaObject getUpdatedFocusOdo(LensContex private PrismObjectDefinition getObjectDefinition(Class focusClass) { return prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(focusClass); } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/OutboundProcessor.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/OutboundProcessor.java index 3743ced0af3..0e2d8b07bfd 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/OutboundProcessor.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/OutboundProcessor.java @@ -68,7 +68,7 @@ /** * Processor that evaluates values of the outbound mappings. It does not create the deltas yet. It just collects the * evaluated mappings in account context. - * + * * @author Radovan Semancik */ @Component @@ -79,7 +79,7 @@ public class OutboundProcessor { private PrismContainerDefinition associationContainerDefinition; @Autowired private PrismContext prismContext; - @Autowired private MappingFactory mappingFactory; + @Autowired private MappingFactory mappingFactory; @Autowired private MappingEvaluator mappingEvaluator; @Autowired private ContextLoader contextLoader; @@ -102,41 +102,41 @@ public void processOutbound(LensContext context, LensPr LOGGER.error("Definition for {} not found in the context, but it should be there, dumping context:\n{}", discr, context.debugDump()); throw new IllegalStateException("Definition for " + discr + " not found in the context, but it should be there"); } - + ObjectDeltaObject focusOdo = context.getFocusContext().getObjectDeltaObject(); ObjectDeltaObject projectionOdo = projCtx.getObjectDeltaObject(); - + Construction outboundConstruction = new Construction<>(null, projCtx.getResource()); outboundConstruction.setRefinedObjectClassDefinition(rOcDef); - + Collection auxiliaryObjectClassDefinitions = rOcDef.getAuxiliaryObjectClassDefinitions(); if (auxiliaryObjectClassDefinitions != null) { for (RefinedObjectClassDefinition auxiliaryObjectClassDefinition: auxiliaryObjectClassDefinitions) { outboundConstruction.addAuxiliaryObjectClassDefinition(auxiliaryObjectClassDefinition); } } - + String operation = projCtx.getOperation().getValue(); for (QName attributeName : rOcDef.getNamesOfAttributesWithOutboundExpressions()) { RefinedAttributeDefinition refinedAttributeDefinition = rOcDef.findAttributeDefinition(attributeName); - + final MappingType outboundMappingType = refinedAttributeDefinition.getOutboundMappingType(); if (outboundMappingType == null) { continue; } - + if (refinedAttributeDefinition.isIgnored(LayerType.MODEL)) { LOGGER.trace("Skipping processing outbound mapping for attribute {} because it is ignored", attributeName); continue; } - + MappingStrengthType strength = outboundMappingType.getStrength(); if (!projCtx.isDelete() && !projCtx.isFullShadow() && (strength == MappingStrengthType.STRONG || strength == MappingStrengthType.WEAK)) { contextLoader.loadFullShadow(context, projCtx, "strong/weak outbound mapping", task, result); projectionOdo = projCtx.getObjectDeltaObject(); } - + Mapping.Builder,RefinedAttributeDefinition> builder = mappingFactory.createMappingBuilder(outboundMappingType, "outbound mapping for " + PrettyPrinter.prettyPrint(refinedAttributeDefinition.getName()) + " in " + projCtx.getResource()); @@ -144,42 +144,42 @@ public void processOutbound(LensContext context, LensPr .originType(OriginType.OUTBOUND); Mapping,RefinedAttributeDefinition> evaluatedMapping = evaluateMapping(builder, attributeName, refinedAttributeDefinition, focusOdo, projectionOdo, operation, rOcDef, null, context, projCtx, task, result); - + if (evaluatedMapping != null) { outboundConstruction.addAttributeMapping(evaluatedMapping); } } - + for (QName assocName : rOcDef.getNamesOfAssociationsWithOutboundExpressions()) { RefinedAssociationDefinition associationDefinition = rOcDef.findAssociationDefinition(assocName); - + final MappingType outboundMappingType = associationDefinition.getOutboundMappingType(); if (outboundMappingType == null) { continue; } - + // if (associationDefinition.isIgnored(LayerType.MODEL)) { // LOGGER.trace("Skipping processing outbound mapping for attribute {} because it is ignored", assocName); // continue; // } - + Mapping.Builder,PrismContainerDefinition> mappingBuilder = mappingFactory.createMappingBuilder(outboundMappingType, "outbound mapping for " + PrettyPrinter.prettyPrint(associationDefinition.getName()) + " in " + projCtx.getResource()); PrismContainerDefinition outputDefinition = getAssociationContainerDefinition(); Mapping,PrismContainerDefinition> evaluatedMapping = (Mapping) evaluateMapping(mappingBuilder, - assocName, outputDefinition, focusOdo, projectionOdo, operation, rOcDef, + assocName, outputDefinition, focusOdo, projectionOdo, operation, rOcDef, associationDefinition.getAssociationTarget(), context, projCtx, task, result); - + if (evaluatedMapping != null) { outboundConstruction.addAssociationMapping(evaluatedMapping); } } - + projCtx.setOutboundConstruction(outboundConstruction); } - + // TODO: unify with MappingEvaluator.evaluateOutboundMapping(...) private Mapping evaluateMapping(final Mapping.Builder mappingBuilder, QName mappingQName, D targetDefinition, ObjectDeltaObject focusOdo, ObjectDeltaObject projectionOdo, @@ -190,7 +190,7 @@ private Ma LOGGER.trace("Skipping outbound mapping for {} because the channel does not match", mappingQName); return null; } - + // TODO: check access // This is just supposed to be an optimization. The consolidation should deal with the weak mapping @@ -202,7 +202,7 @@ private Ma // LOGGER.trace("Skipping outbound mapping for {} because it is weak", mappingQName); // return null; // } - + mappingBuilder.defaultTargetDefinition(targetDefinition); mappingBuilder.sourceContext(focusOdo); mappingBuilder.mappingQName(mappingQName); @@ -224,7 +224,7 @@ private Ma mappingBuilder.rootNode(focusOdo); mappingBuilder.originType(OriginType.OUTBOUND); mappingBuilder.refinedObjectClassDefinition(rOcDef); - + StringPolicyResolver stringPolicyResolver = new StringPolicyResolver() { private ItemPath outputPath; private ItemDefinition outputDefinition; @@ -232,15 +232,15 @@ private Ma public void setOutputPath(ItemPath outputPath) { this.outputPath = outputPath; } - + @Override public void setOutputDefinition(ItemDefinition outputDefinition) { this.outputDefinition = outputDefinition; } - + @Override public StringPolicyType resolve() { - + if (mappingBuilder.getMappingType().getExpression() != null) { List> evaluators = mappingBuilder.getMappingType().getExpression().getExpressionEvaluator(); for (JAXBElement jaxbEvaluator : evaluators) { @@ -264,7 +264,7 @@ public StringPolicyType resolve() { }; mappingBuilder.stringPolicyResolver(stringPolicyResolver); // TODO: other variables? - + // Set condition masks. There are used as a brakes to avoid evaluating to nonsense values in case user is not present // (e.g. in old values in ADD situations and new values in DELETE situations). if (focusOdo.getOldObject() == null) { @@ -276,10 +276,10 @@ public StringPolicyType resolve() { Mapping mapping = mappingBuilder.build(); mappingEvaluator.evaluateMapping(mapping, context, projCtx, task, result); - + return mapping; } - + private PrismContainerDefinition getAssociationContainerDefinition() { if (associationContainerDefinition == null) { PrismObjectDefinition shadowDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(ShadowType.class); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/PolicyRuleProcessor.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/PolicyRuleProcessor.java index 52146dd9f2b..68cd2064cf6 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/PolicyRuleProcessor.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/PolicyRuleProcessor.java @@ -68,9 +68,9 @@ */ @Component public class PolicyRuleProcessor { - + private static final Trace LOGGER = TraceManager.getTrace(PolicyRuleProcessor.class); - + @Autowired private PrismContext prismContext; @Autowired @Qualifier("cacheRepositoryService") private RepositoryService repositoryService; @Autowired private MappingFactory mappingFactory; @@ -241,7 +241,7 @@ private void checkExclusionsRuleBased(LensContext conte private boolean excludes(ExclusionPolicyConstraintType constraint, EvaluatedAssignmentTargetImpl targetAssignment) throws SchemaException { if (constraint.getTargetRef() == null || targetAssignment.getOid() == null) { return false; // shouldn't occur - + } else if (constraint.getTargetRef() != null) { ObjectReferenceType targetRef = constraint.getTargetRef(); if (targetRef.getOid() != null) { @@ -262,7 +262,7 @@ private boolean excludes(ExclusionPolicyConstraintType constraint, EvaluatedAssi throw new SchemaException("No OID in exclusion reference"); } } - + } else { throw new SchemaException("No target reference in exclusion"); } @@ -330,7 +330,7 @@ private void checkAssigneeConstraints(LensContext conte } } } - + private void checkAssigneeConstraints(LensContext context, EvaluatedAssignment assignment, PlusMinusZero plusMinus, OperationResult result) throws PolicyViolationException, SchemaException { PrismObject target = assignment.getTarget(); if (target == null || !(target.asObjectable() instanceof AbstractRoleType)) { @@ -444,18 +444,18 @@ public boolean processPruning(LensContext context, +", the exclusion prune rule was triggered but there is no conflicting assignment in the trigger"); } LOGGER.debug("Pruning assignment {} because it conflicts with added assignment {}", conflictingAssignment, plusAssignment); - + PrismContainerValue assignmentValueToRemove = conflictingAssignment.getAssignmentType().asPrismContainerValue().clone(); PrismObjectDefinition focusDef = context.getFocusContext().getObjectDefinition(); ContainerDelta assignmentDelta = ContainerDelta.createDelta(FocusType.F_ASSIGNMENT, focusDef); assignmentDelta.addValuesToDelete(assignmentValueToRemove); context.getFocusContext().swallowToSecondaryDelta(assignmentDelta); - + needToReevaluateAssignments = true; } } } - + return needToReevaluateAssignments; } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ProjectionValuesProcessor.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ProjectionValuesProcessor.java index 462195986a6..6f03a50bb31 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ProjectionValuesProcessor.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ProjectionValuesProcessor.java @@ -78,45 +78,45 @@ * Processor that determines values of account attributes. It does so by taking the pre-processed information left * behind by the assignment processor. It also does some checks, such as check of identifier uniqueness. It tries to * do several iterations over the value computations if a conflict is found (and this feature is enabled). - * + * * @author Radovan Semancik */ @Component public class ProjectionValuesProcessor { - + private static final Trace LOGGER = TraceManager.getTrace(ProjectionValuesProcessor.class); - + @Autowired private OutboundProcessor outboundProcessor; - + @Autowired private ConsolidationProcessor consolidationProcessor; - + @Autowired private AssignmentProcessor assignmentProcessor; - + @Autowired @Qualifier("cacheRepositoryService") RepositoryService repositoryService; - + @Autowired private ExpressionFactory expressionFactory; - + @Autowired private PrismContext prismContext; - + @Autowired private CorrelationConfirmationEvaluator correlationConfirmationEvaluator; - + @Autowired private SynchronizationService synchronizationService; @Autowired private ContextLoader contextLoader; - + @Autowired private ProvisioningService provisioningService; - + public void process(LensContext context, LensProjectionContext projectionContext, String activityDescription, Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, ObjectAlreadyExistsException, @@ -133,16 +133,16 @@ public void process(LensContext context, processorResult.recordSuccessIfUnknown(); processProjections((LensContext) context, projectionContext, activityDescription, task, processorResult); - + } - - private void processProjections(LensContext context, + + private void processProjections(LensContext context, LensProjectionContext projContext, String activityDescription, Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException, PolicyViolationException { - + checkSchemaAndPolicies(context, projContext, activityDescription, result); - + SynchronizationPolicyDecision policyDecision = projContext.getSynchronizationPolicyDecision(); if (policyDecision != null && policyDecision == SynchronizationPolicyDecision.UNLINK) { // We will not update accounts that are being unlinked. @@ -152,21 +152,21 @@ private void processProjections(LensContext context, } return; } - + if (consistencyChecks) context.checkConsistence(); - + if (!projContext.hasFullShadow() && hasIterationExpression(projContext)) { contextLoader.loadFullShadow(context, projContext, "iteration expression", task, result); if (projContext.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.BROKEN) { return; } } - + int maxIterations = determineMaxIterations(projContext); int iteration = 0; String iterationToken = null; boolean wasResetIterationCounter = false; - + PrismObject shadowCurrent = projContext.getObjectCurrent(); if (shadowCurrent != null) { Integer shadowIteration = shadowCurrent.asObjectable().getIteration(); @@ -175,65 +175,65 @@ private void processProjections(LensContext context, } iterationToken = shadowCurrent.asObjectable().getIterationToken(); } - + boolean skipUniquenessCheck = false; while (true) { - + projContext.setIteration(iteration); if (iterationToken == null) { iterationToken = formatIterationToken(context, projContext, iteration, task, result); } projContext.setIterationToken(iterationToken); - + String conflictMessage; - + // These are normally null. But there may be leftover from the previous iteration. // While that should not affect the algorithm (it should overwrite it) it may confuse // people during debugging and unecessarily clutter the debug output. projContext.setOutboundConstruction(null); projContext.setSqueezedAttributes(null); projContext.setSqueezedAssociations(null); - + LOGGER.trace("Projection values iteration {}, token '{}' for {}", iteration, iterationToken, projContext.getHumanReadableName()); - + // LensUtil.traceContext(LOGGER, activityDescription, "values (start)", false, context, true); - + if (!evaluateIterationCondition(context, projContext, iteration, iterationToken, true, task, result)) { - + conflictMessage = "pre-iteration condition was false"; LOGGER.debug("Skipping iteration {}, token '{}' for {} because the pre-iteration condition was false", iteration, iterationToken, projContext.getHumanReadableName()); } else { - + if (consistencyChecks) context.checkConsistence(); - + // Re-evaluates the values in the account constructions (including roles) assignmentProcessor.processAssignmentsAccountValues(projContext, result); - + context.recompute(); if (consistencyChecks) context.checkConsistence(); // LensUtil.traceContext(LOGGER, activityDescription, "values (assignment account values)", false, context, true); - + // Evaluates the values in outbound mappings outboundProcessor.processOutbound(context, projContext, task, result); - + context.recompute(); if (consistencyChecks) context.checkConsistence(); - + // LensUtil.traceContext(LOGGER, activityDescription, "values (outbound)", false, context, true); - + // Merges the values together, processing exclusions and strong/weak mappings are needed consolidationProcessor.consolidateValues(context, projContext, task, result); - + if (consistencyChecks) context.checkConsistence(); context.recompute(); if (consistencyChecks) context.checkConsistence(); - + // Aux object classes may have changed during consolidation. Make sure we have up-to-date definitions. context.refreshAuxiliaryObjectClassDefinitions(); - + // Check if we need to reset the iteration counter (and token) e.g. because we have rename // we cannot do that before because the mappings are not yet evaluated and the triples and not // consolidated to deltas. We can do it only now. It means that we will waste the first run @@ -247,25 +247,25 @@ private void processProjections(LensContext context, if (consistencyChecks) context.checkConsistence(); continue; } - + // Too noisy for now // LensUtil.traceContext(LOGGER, activityDescription, "values (consolidation)", false, context, true); - - + + if (policyDecision != null && policyDecision == SynchronizationPolicyDecision.DELETE) { // No need to play the iterative game if the account is deleted break; } - + // Check constraints boolean conflict = true; ShadowConstraintsChecker checker = new ShadowConstraintsChecker(projContext); - + if (skipUniquenessCheck) { skipUniquenessCheck = false; conflict = false; } else { - + checker.setPrismContext(prismContext); checker.setContext(context); checker.setProvisioningService(provisioningService); @@ -284,9 +284,9 @@ private void processProjections(LensContext context, //if object not found exception occurred, its ok..the account was deleted by the discovery, so there esits no more conflicting shadow LOGGER.trace("Conflicting shadow was deleted by discovery. It does not exist anymore. Continue with adding current shadow."); conflict = false; - + } - + result.computeStatus(); // if the result is fatal error, it may mean that the // already exists expection occures before..but in this @@ -296,13 +296,13 @@ private void processProjections(LensContext context, if (result.isError()){ result.muteError(); } - + if (conflict) { PrismObject focus = repositoryService.searchShadowOwner(checker .getConflictingShadow().getOid(), SelectorOptions .createCollection(GetOperationOptions.createAllowNotFound()), result); - - + + //the owner of the shadow exist and it is a current user..so the shadow was successfully created, linked etc..no other recompute is needed.. if (focus != null && focus.getOid().equals(context.getFocusContext().getOid())) { LOGGER.trace("Conflicting projection already linked to the current focus, no recompute needed, continue processing with conflicting projection."); @@ -330,26 +330,26 @@ private void processProjections(LensContext context, skipUniquenessCheck = true; // to avoid endless loop continue; } - + if (focus == null) { LOGGER.trace("There is no owner linked with the conflicting projection."); ResourceType resourceType = projContext.getResource(); - + if (ResourceTypeUtil.isSynchronizationOpportunistic(resourceType)) { LOGGER.trace("Trying to find owner using correlation expression."); - boolean match = synchronizationService.matchUserCorrelationRule(fullConflictingShadow, + boolean match = synchronizationService.matchUserCorrelationRule(fullConflictingShadow, context.getFocusContext().getObjectNew(), resourceType, context.getSystemConfiguration(), task, result); - + if (match){ //check if it is add account (primary delta contains add shadow deltu).. //if it is add account, create new context for conflicting account.. //it ensures, that conflicting account is linked to the user - + if (projContext.getPrimaryDelta() != null && projContext.getPrimaryDelta().isAdd()){ PrismObject shadow = projContext.getPrimaryDelta().getObjectToAdd(); LOGGER.trace("Found primary ADD delta of shadow {}.", shadow); - + LensProjectionContext conflictingAccountContext = context.findProjectionContext(projContext.getResourceShadowDiscriminator(), fullConflictingShadow.getOid()); if (conflictingAccountContext == null){ conflictingAccountContext = LensUtil.createAccountContext(context, projContext.getResourceShadowDiscriminator()); @@ -366,15 +366,15 @@ private void processProjections(LensContext context, conflictingAccountContext.setWave(projContext.getWave()); context.addConflictingProjectionContext(conflictingAccountContext); } - + projContext.setSynchronizationPolicyDecision(SynchronizationPolicyDecision.BROKEN); result.recordFatalError("Could not add account " + projContext.getObjectNew() + ", because the account with the same identifier already exists on the resource. "); LOGGER.error("Could not add account {}, because the account with the same identifier already exists on the resource. ", projContext.getObjectNew()); - + skipUniquenessCheck = true; // to avoid endless loop continue; } - + //found shadow belongs to the current user..need to link it and replace current shadow with the found shadow.. cleanupContext(projContext); projContext.setObjectOld(fullConflictingShadow.clone()); @@ -386,7 +386,7 @@ private void processProjections(LensContext context, secondaryDelta.setOid(projContext.getOid()); } LOGGER.trace("User {} satisfies correlation rules.", context.getFocusContext().getObjectNew()); - + // Re-do this same iteration again (do not increase iteration count). // It will recompute the values and therefore enforce the user deltas and enable reconciliation skipUniquenessCheck = true; // to avoid endless loop @@ -395,15 +395,15 @@ private void processProjections(LensContext context, LOGGER.trace("User {} does not satisfy correlation rules.", context.getFocusContext().getObjectNew()); } } - + } else{ LOGGER.trace("Recomputing shadow identifier, because shadow with the some identifier exists and it belongs to other user."); } } - } + } } } - + if (!conflict) { if (evaluateIterationCondition(context, projContext, iteration, iterationToken, false, task, result)) { // stop the iterations @@ -417,21 +417,21 @@ private void processProjections(LensContext context, conflictMessage = checker.getMessages(); } } - + iteration++; iterationToken = null; LensUtil.checkMaxIterations(iteration, maxIterations, conflictMessage, projContext.getHumanReadableName()); cleanupContext(projContext); if (consistencyChecks) context.checkConsistence(); - + } - + addIterationTokenDeltas(projContext); result.cleanupResult(); if (consistencyChecks) context.checkConsistence(); - - + + } private boolean willResetIterationCounter(LensProjectionContext projectionContext) throws SchemaException { @@ -454,8 +454,8 @@ private boolean willResetIterationCounter(LensProjectionContext projectionContex } return false; } - - + + private boolean hasIterationExpression(LensProjectionContext accountContext) { ResourceObjectTypeDefinitionType accDef = accountContext.getResourceObjectTypeDefinitionType(); @@ -488,8 +488,8 @@ private int determineMaxIterations(LensProjectionContext accountContext) { } } - private String formatIterationToken(LensContext context, - LensProjectionContext accountContext, int iteration, Task task, OperationResult result) + private String formatIterationToken(LensContext context, + LensProjectionContext accountContext, int iteration, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException { ResourceObjectTypeDefinitionType accDef = accountContext.getResourceObjectTypeDefinitionType(); if (accDef == null) { @@ -497,20 +497,20 @@ private String formatIterationToken(LensContext contex } IterationSpecificationType iterationType = accDef.getIteration(); ExpressionVariables variables = createExpressionVariables(context, accountContext); - return LensUtil.formatIterationToken(context, accountContext, iterationType, iteration, + return LensUtil.formatIterationToken(context, accountContext, iterationType, iteration, expressionFactory, variables, task, result); } - - private ExpressionVariables createExpressionVariables(LensContext context, + + private ExpressionVariables createExpressionVariables(LensContext context, LensProjectionContext projectionContext) { return Utils.getDefaultExpressionVariables(context.getFocusContext().getObjectNew(), projectionContext.getObjectNew(), - projectionContext.getResourceShadowDiscriminator(), projectionContext.getResource().asPrismObject(), + projectionContext.getResourceShadowDiscriminator(), projectionContext.getResource().asPrismObject(), context.getSystemConfiguration(), projectionContext); } - private boolean evaluateIterationCondition(LensContext context, - LensProjectionContext accountContext, int iteration, String iterationToken, - boolean beforeIteration, Task task, OperationResult result) + private boolean evaluateIterationCondition(LensContext context, + LensProjectionContext accountContext, int iteration, String iterationToken, + boolean beforeIteration, Task task, OperationResult result) throws ExpressionEvaluationException, SchemaException, ObjectNotFoundException { ResourceObjectTypeDefinitionType accDef = accountContext.getResourceObjectTypeDefinitionType(); if (accDef == null) { @@ -518,27 +518,27 @@ private boolean evaluateIterationCondition(LensContext } IterationSpecificationType iterationType = accDef.getIteration(); ExpressionVariables variables = createExpressionVariables(context, accountContext); - return LensUtil.evaluateIterationCondition(context, accountContext, iterationType, + return LensUtil.evaluateIterationCondition(context, accountContext, iterationType, iteration, iterationToken, beforeIteration, expressionFactory, variables, task, result); } /** * Check that the primary deltas do not violate schema and policies - * TODO: implement schema check + * TODO: implement schema check */ - public void checkSchemaAndPolicies(LensContext context, + public void checkSchemaAndPolicies(LensContext context, LensProjectionContext accountContext, String activityDescription, OperationResult result) throws SchemaException, PolicyViolationException { ObjectDelta primaryDelta = accountContext.getPrimaryDelta(); if (primaryDelta == null || primaryDelta.isDelete()) { return; } - + RefinedObjectClassDefinition rAccountDef = accountContext.getCompositeObjectClassDefinition(); if (rAccountDef == null) { throw new SchemaException("No definition for account type '" +accountContext.getResourceShadowDiscriminator()+"' in "+accountContext.getResource()); } - + if (primaryDelta.isAdd()) { PrismObject accountToAdd = primaryDelta.getObjectToAdd(); ResourceAttributeContainer attributesContainer = ShadowUtil.getAttributesContainer(accountToAdd); @@ -566,7 +566,7 @@ public void checkSchemaAndPolicies(LensContext context throw new IllegalStateException("Whoops!"); } } - + /** * Remove the intermediate results of values processing such as secondary deltas. */ @@ -608,20 +608,20 @@ private void addIterationTokenDeltas(LensProjectionContext accountContext) throw } } PrismObjectDefinition shadowDef = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(ShadowType.class); - + PrismPropertyValue iterationVal = new PrismPropertyValue(accountContext.getIteration()); iterationVal.setOriginType(OriginType.OUTBOUND); - PropertyDelta iterationDelta = PropertyDelta.createReplaceDelta(shadowDef, + PropertyDelta iterationDelta = PropertyDelta.createReplaceDelta(shadowDef, ShadowType.F_ITERATION, iterationVal); accountContext.swallowToSecondaryDelta(iterationDelta); - + PrismPropertyValue iterationTokenVal = new PrismPropertyValue(accountContext.getIterationToken()); iterationTokenVal.setOriginType(OriginType.OUTBOUND); - PropertyDelta iterationTokenDelta = PropertyDelta.createReplaceDelta(shadowDef, + PropertyDelta iterationTokenDelta = PropertyDelta.createReplaceDelta(shadowDef, ShadowType.F_ITERATION_TOKEN, iterationTokenVal); accountContext.swallowToSecondaryDelta(iterationTokenDelta); - + } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/Projector.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/Projector.java index 4ebbb3088bb..17d4e7ecb11 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/Projector.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/Projector.java @@ -55,34 +55,34 @@ import com.evolveum.midpoint.util.logging.TraceManager; /** - * Projector recomputes the context. It takes the context with a few basic data as input. It uses all the policies + * Projector recomputes the context. It takes the context with a few basic data as input. It uses all the policies * and mappings to derive all the other data. E.g. a context with only a user (primary) delta. It applies user template, * outbound mappings and the inbound mappings and then inbound and outbound mappings of other accounts and so on until * all the data are computed. The output is the original context with all the computed delta. - * + * * Primary deltas are in the input, secondary deltas are computed in projector. Projector "projects" primary deltas to * the secondary deltas of user and accounts. - * + * * Projector does NOT execute the deltas. It only recomputes the context. It may read a lot of objects (user, accounts, policies). * But it does not change any of them. - * + * * @author Radovan Semancik * */ @Component public class Projector { - + private static final String OPERATION_PROJECT_PROJECTION = Projector.class.getName() + ".projectProjection"; - + @Autowired private ContextLoader contextLoader; - + @Autowired private FocusProcessor focusProcessor; @Autowired private AssignmentProcessor assignmentProcessor; - + @Autowired private ProjectionValuesProcessor projectionValuesProcessor; @@ -94,13 +94,13 @@ public class Projector { @Autowired private ActivationProcessor activationProcessor; - + @Autowired private DependencyProcessor dependencyProcessor; - + @Autowired private Clock clock; - + private static final Trace LOGGER = TraceManager.getTrace(Projector.class); /** @@ -153,7 +153,7 @@ private void projectInternal(LensContext context, Stri if (context.getDebugListener() != null) { context.getDebugListener().beforeProjection(context); } - + InternalMonitor.recordCount(InternalCounters.PROJECTOR_RUN_COUNT); // Read the time at the beginning so all processors have the same notion of "now" @@ -170,35 +170,35 @@ private void projectInternal(LensContext context, Stri context.normalize(); context.resetProjectionWave(); } - + OperationResult result = parentResult.createSubresult(Projector.class.getName() + ".project"); result.addParam("fromStart", fromStart); result.addContext("projectionWave", context.getProjectionWave()); result.addContext("executionWave", context.getExecutionWave()); - + PartialProcessingOptionsType partialProcessingOptions = context.getPartialProcessingOptions(); - + // Projector is using a set of "processors" to do parts of its work. The processors will be called in sequence // in the following code. - + try { context.reportProgress(new ProgressInformation(PROJECTOR, ENTERING)); if (fromStart) { LensUtil.partialExecute("load", - () -> { + () -> { contextLoader.load(context, activityDescription, task, result); // Set the "fresh" mark now so following consistency check will be stricter context.setFresh(true); if (consistencyChecks) context.checkConsistence(); - }, + }, partialProcessingOptions::getLoad, result); } // For now let's pretend to do just one wave. The maxWaves number will be corrected in the // first wave when dependencies are sorted out for the first time. int maxWaves = context.getExecutionWave() + 1; - + // Start the waves .... LOGGER.trace("WAVE: Starting the waves."); @@ -209,26 +209,26 @@ private void projectInternal(LensContext context, Stri boolean inFirstWave = firstWave; firstWave = false; // in order to not forget to reset it ;) - + context.checkAbortRequested(); LOGGER.trace("WAVE {} (maxWaves={}, executionWave={})", context.getProjectionWave(), maxWaves, context.getExecutionWave()); - + //just make sure everything is loaded and set as needed dependencyProcessor.preprocessDependencies(context); - + // Process the focus-related aspects of the context. That means inbound, focus activation, // object template and assignments. - + LensUtil.partialExecute("focus", - () -> { + () -> { focusProcessor.processFocus(context, activityDescription, now, task, result); context.recomputeFocus(); if (consistencyChecks) context.checkConsistence(); - }, + }, partialProcessingOptions::getFocus, result); - + LensUtil.traceContext(LOGGER, activityDescription, "focus processing", false, context, false); LensUtil.checkContextSanity(context, "focus processing", result); @@ -273,22 +273,22 @@ private void projectInternal(LensContext context, Stri // if there exists some conflicting projection contexts, add them to the context so they will be recomputed in the next wave.. addConflictingContexts(context); } - + if (consistencyChecks) context.checkConsistence(); - + context.incrementProjectionWave(); } - + LOGGER.trace("WAVE: Stopping the waves. There was {} waves", context.getProjectionWave()); - + // We can do this only when computation of all the waves is finished. Before that we do not know // activation of every account and therefore cannot decide what is OK and what is not dependencyProcessor.checkDependenciesFinal(context, result); - + if (consistencyChecks) context.checkConsistence(); - + computeResultStatus(now, result); - + } catch (SchemaException | PolicyViolationException | ExpressionEvaluationException | ObjectAlreadyExistsException | ObjectNotFoundException | CommunicationException | ConfigurationException | SecurityViolationException e) { recordFatalError(e, now, result); @@ -305,78 +305,78 @@ private void projectInternal(LensContext context, Stri } context.reportProgress(new ProgressInformation(PROJECTOR, result)); } - + } private void projectProjection(LensContext context, LensProjectionContext projectionContext, PartialProcessingOptionsType partialProcessingOptions, XMLGregorianCalendar now, String activityDescription, Task task, OperationResult parentResult) throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, PolicyViolationException, ExpressionEvaluationException, ObjectAlreadyExistsException { - + if (projectionContext.getWave() != context.getProjectionWave()) { // Let's skip accounts that do not belong into this wave. return; } - + String projectionDesc = getProjectionDesc(projectionContext); - + OperationResult result = parentResult.createMinorSubresult(OPERATION_PROJECT_PROJECTION); result.addParam(OperationResult.PARAM_PROJECTION, projectionDesc); - + try { - + context.checkAbortRequested(); - - + + if (projectionContext.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.BROKEN || projectionContext.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.IGNORE) { result.recordStatus(OperationResultStatus.NOT_APPLICABLE, "Skipping projection because it is "+projectionContext.getSynchronizationPolicyDecision()); return; } - + if (projectionContext.isThombstone()) { result.recordStatus(OperationResultStatus.NOT_APPLICABLE, "Skipping projection because it is a thombstone"); return; } - + LOGGER.trace("WAVE {} PROJECTION {}", context.getProjectionWave(), projectionDesc); - + // Some projections may not be loaded at this point, e.g. high-order dependency projections contextLoader.makeSureProjectionIsLoaded(context, projectionContext, task, result); - + if (consistencyChecks) context.checkConsistence(); - + if (!dependencyProcessor.checkDependencies(context, projectionContext, result)) { result.recordStatus(OperationResultStatus.NOT_APPLICABLE, "Skipping projection because it has unsatisfied dependencies"); return; } - + // TODO: decide if we need to continue - + LensUtil.partialExecute("projectionValues", () -> { // This is a "composite" processor. it contains several more processor invocations inside projectionValuesProcessor.process(context, projectionContext, activityDescription, task, result); if (consistencyChecks) context.checkConsistence(); - + projectionContext.recompute(); if (consistencyChecks) context.checkConsistence(); }, partialProcessingOptions::getProjectionValues); - - + + LensUtil.partialExecute("projectionCredentials", () -> { projectionCredentialsProcessor.processProjectionCredentials(context, projectionContext, now, task, result); if (consistencyChecks) context.checkConsistence(); - + projectionContext.recompute(); LensUtil.traceContext(LOGGER, activityDescription, "projection values and credentials of "+projectionDesc, false, context, true); if (consistencyChecks) context.checkConsistence(); }, partialProcessingOptions::getProjectionCredentials); - + LensUtil.partialExecute("projectionReconciliation", () -> { reconciliationProcessor.processReconciliation(context, projectionContext, task, result); @@ -385,26 +385,26 @@ private void projectProjection(LensContext context, Le if (consistencyChecks) context.checkConsistence(); }, partialProcessingOptions::getProjectionReconciliation); - - + + LensUtil.partialExecute("projectionLifecycle", () -> { activationProcessor.processLifecycle(context, projectionContext, now, task, result); if (consistencyChecks) context.checkConsistence(); - + projectionContext.recompute(); // LensUtil.traceContext(LOGGER, activityDescription, "projection lifecycle of "+projectionDesc, false, context, false); if (consistencyChecks) context.checkConsistence(); }, partialProcessingOptions::getProjectionLifecycle); - + result.recordSuccess(); - - } catch (ObjectNotFoundException | CommunicationException | SchemaException | ConfigurationException | SecurityViolationException + + } catch (ObjectNotFoundException | CommunicationException | SchemaException | ConfigurationException | SecurityViolationException | PolicyViolationException | ExpressionEvaluationException | ObjectAlreadyExistsException | RuntimeException | Error e) { - + result.recordFatalError(e); - + ResourceType resourceType = projectionContext.getResource(); if (resourceType == null) { throw e; @@ -431,13 +431,13 @@ private void projectProjection(LensContext context, Le } } } - + } private String getProjectionDesc(LensProjectionContext projectionContext) { if (projectionContext.getResource() != null) { - return projectionContext.getResource() + "("+projectionContext.getResourceShadowDiscriminator().getIntent()+")"; + return projectionContext.getResource() + "("+projectionContext.getResourceShadowDiscriminator().getIntent()+")"; } else { ResourceShadowDiscriminator discr = projectionContext.getResourceShadowDiscriminator(); if (discr != null) { @@ -457,7 +457,7 @@ private void addConflictingContexts(LensContext contex } context.clearConflictingProjectionContexts(); } - + } private void recordFatalError(Exception e, XMLGregorianCalendar projectoStartTimestampCal, OperationResult result) { @@ -469,7 +469,7 @@ private void recordFatalError(Exception e, XMLGregorianCalendar projectoStartTim LOGGER.debug("Projector failed: {}. Etime: {} ms", e.getMessage(), (projectorEndTimestamp - projectoStartTimestamp)); } } - + private void computeResultStatus(XMLGregorianCalendar projectoStartTimestampCal, OperationResult result) { boolean hasProjectionErrror = false; OperationResultStatus finalStatus = OperationResultStatus.SUCCESS; diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ReconciliationProcessor.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ReconciliationProcessor.java index f22eb1a3456..57e491c9c86 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ReconciliationProcessor.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ReconciliationProcessor.java @@ -87,7 +87,7 @@ * processor will compare the "projected" state of the account after application * of the deltas to the actual (real) account with the result of the mappings. * The differences will be expressed as additional "reconciliation" deltas. - * + * * @author lazyman * @author Radovan Semancik */ @@ -165,13 +165,13 @@ private void processReconciliationFocus(LensContext co projCtx.recompute(); } - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Starting reconciliation of {}", projCtx.getHumanReadableName()); } reconcileAuxiliaryObjectClasses(projCtx); - + RefinedObjectClassDefinition rOcDef = projCtx.getCompositeObjectClassDefinition(); Map,PrismPropertyDefinition>>> squeezedAttributes = projCtx @@ -206,12 +206,12 @@ private void reconcileAuxiliaryObjectClasses(LensProjectionContext projCtx) thro if (LOGGER.isTraceEnabled()) { LOGGER.trace("Auxiliary object class reconciliation processing {}", projCtx.getHumanReadableName()); } - + PrismObject shadowNew = projCtx.getObjectNew(); PrismPropertyDefinition propDef = shadowNew.getDefinition().findPropertyDefinition(ShadowType.F_AUXILIARY_OBJECT_CLASS); DeltaSetTriple, PrismPropertyDefinition>> pvwoTriple = squeezedAuxiliaryObjectClasses.get(ShadowType.F_AUXILIARY_OBJECT_CLASS); - + Collection,PrismPropertyDefinition>> shouldBePValues = null; if (pvwoTriple == null) { shouldBePValues = new ArrayList<>(); @@ -220,17 +220,17 @@ private void reconcileAuxiliaryObjectClasses(LensProjectionContext projCtx) thro } Collection> arePValues = null; - PrismProperty propertyNew = shadowNew.findProperty(ShadowType.F_AUXILIARY_OBJECT_CLASS); + PrismProperty propertyNew = shadowNew.findProperty(ShadowType.F_AUXILIARY_OBJECT_CLASS); if (propertyNew != null) { arePValues = propertyNew.getValues(); } else { arePValues = new HashSet<>(); } - + ValueMatcher valueMatcher = ValueMatcher.createDefaultMatcher(DOMUtil.XSD_QNAME, matchingRuleRegistry); boolean auxObjectClassChanged = false; - + for (ItemValueWithOrigin, PrismPropertyDefinition> shouldBePvwo : shouldBePValues) { QName shouldBeRealValue = shouldBePvwo.getItemValue().getValue(); if (!isInValues(valueMatcher, shouldBeRealValue, arePValues)) { @@ -239,7 +239,7 @@ private void reconcileAuxiliaryObjectClasses(LensProjectionContext projCtx) thro shouldBePvwo.getSource(), "it is given"); } } - + if (!isTolerantAuxiliaryObjectClasses(projCtx)) { for (PrismPropertyValue isPValue : arePValues) { if (!isInPvwoValues(valueMatcher, isPValue.getValue(), shouldBePValues)) { @@ -249,13 +249,13 @@ private void reconcileAuxiliaryObjectClasses(LensProjectionContext projCtx) thro } } } - + if (auxObjectClassChanged) { projCtx.recompute(); projCtx.refreshAuxiliaryObjectClassDefinitions(); } } - + private boolean isTolerantAuxiliaryObjectClasses(LensProjectionContext projCtx) throws SchemaException { ResourceBidirectionalMappingAndDefinitionType auxiliaryObjectClassMappings = projCtx.getStructuralObjectClassDefinition().getAuxiliaryObjectClassMappings(); if (auxiliaryObjectClassMappings == null) { @@ -311,7 +311,7 @@ private void reconcileMissingAuxiliaryObjectClassAttributes(LensProjectionContex if (deletedAuxObjectClassNames == null || deletedAuxObjectClassNames.isEmpty()) { return; } - + List attributesToDelete = new ArrayList<>(); String projHumanReadableName = projCtx.getHumanReadableName(); RefinedResourceSchema refinedResourceSchema = projCtx.getRefinedResourceSchema(); @@ -349,7 +349,7 @@ private void reconcileMissingAuxiliaryObjectClassAttributes(LensProjectionContex if (attributesToDelete.isEmpty()) { return; } - + for (QName attrNameToDelete: attributesToDelete) { ResourceAttribute attrToDelete = ShadowUtil.getAttribute(objectOld, attrNameToDelete); if (attrToDelete == null || attrToDelete.isEmpty()) { @@ -360,7 +360,7 @@ private void reconcileMissingAuxiliaryObjectClassAttributes(LensProjectionContex projCtx.swallowToSecondaryDelta(attrDelta); } } - + private void reconcileProjectionAttributes( LensProjectionContext projCtx, Map,PrismPropertyDefinition>>> squeezedAttributes, @@ -470,9 +470,9 @@ private void reconcileProjectionAttribute(QName attrName, // sb.append("\n "); // sb.append(isPVal); // } -// LOGGER.trace("{}", sb.toString()); +// LOGGER.trace("{}", sb.toString()); // } - + ValueMatcher valueMatcher = ValueMatcher.createMatcher(attributeDefinition, matchingRuleRegistry); T realValueToReplace = null; @@ -518,9 +518,9 @@ private void reconcileProjectionAttribute(QName attrName, } } } - + decideIfTolerate(projCtx, attributeDefinition, arePValues, shouldBePValues, valueMatcher); - + } private void addPropValuesFromDelta( @@ -779,26 +779,26 @@ private void decideIfTolerate(LensProjectionContext projCtx, Collection> arePValues, Collection,PrismPropertyDefinition>> shouldBePValues, ValueMatcher valueMatcher) throws SchemaException { - + for (PrismPropertyValue isPValue : arePValues){ if (matchPattern(attributeDefinition.getTolerantValuePattern(), isPValue, valueMatcher)){ LOGGER.trace("Reconciliation: KEEPING value {} of the attribute {}: match with tolerant value pattern." , isPValue, attributeDefinition.getName().getLocalPart()); continue; } - + if (matchPattern(attributeDefinition.getIntolerantValuePattern(), isPValue, valueMatcher)){ recordDeleteDelta(isPValue, attributeDefinition, valueMatcher, projCtx, "it has matched with intolerant pattern"); continue; - } - - + } + + if (!attributeDefinition.isTolerant()) { if (!isInPvwoValues(valueMatcher, isPValue.getValue(), shouldBePValues)) { recordDeleteDelta(isPValue, attributeDefinition, valueMatcher, projCtx, "it is not given by any mapping and the attribute is not tolerant"); } } } - + } private void decideIfTolerateAssociation(LensProjectionContext accCtx, @@ -930,13 +930,13 @@ private void recordDelta(ValueMatcher valueMatcher, LensProjectionContext if (!isToBeDeleted(existingDelta, valueMatcher, value)){ attrDelta.addValueToDelete(pValue); } - + } else if (changeType == ModificationType.REPLACE) { attrDelta.setValueToReplace(pValue); } else { throw new IllegalArgumentException("Unknown change type " + changeType); } - + LensUtil.setDeltaOldValue(projCtx, attrDelta); projCtx.swallowToSecondaryDelta(attrDelta); @@ -968,7 +968,7 @@ private void recordAssociationDelta(ValueMatcher valueMatcher, LensProjectionCon PrismContainerValue cValue = value.asPrismContainerValue().clone(); cValue.setOriginType(OriginType.RECONCILIATION); cValue.setOriginObject(originObject); - + if (changeType == ModificationType.ADD) { assocDelta.addValueToAdd(cValue); } else if (changeType == ModificationType.DELETE) { @@ -992,12 +992,12 @@ private boolean isToBeDeleted(ItemDelta existingDelta, ValueMatcher valueMat if (existingDelta == null) { return false; } - + if (existingDelta.getValuesToDelete() == null){ return false; } - - + + for (Object isInDeltaValue : existingDelta.getValuesToDelete()) { if (isInDeltaValue instanceof PrismPropertyValue){ PrismPropertyValue isInRealValue = (PrismPropertyValue) isInDeltaValue; @@ -1013,11 +1013,11 @@ private boolean isToBeDeleted(ItemDelta existingDelta, ValueMatcher valueMat } } //TODO: reference delta??? - + } - + return false; - + } private boolean isInValues(ValueMatcher valueMatcher, T shouldBeValue, @@ -1086,8 +1086,8 @@ private boolean isInCvwoAssociationValues(ValueMatcher valueMatcher, ShadowAssoc } return false; } - - + + private boolean matchValue(T realA, T realB, ValueMatcher valueMatcher) { try { return valueMatcher.match(realA, realB); @@ -1096,7 +1096,7 @@ private boolean matchValue(T realA, T realB, ValueMatcher valueMatcher) { return false; } } - + private boolean matchPattern(List patterns, PrismPropertyValue isPValue, ValueMatcher valueMatcher) { if (patterns == null || patterns.isEmpty()) { diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ShadowConstraintsChecker.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ShadowConstraintsChecker.java index a4d57829219..93f4419c6eb 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ShadowConstraintsChecker.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ShadowConstraintsChecker.java @@ -47,7 +47,7 @@ * */ public class ShadowConstraintsChecker { - + private static final Trace LOGGER = TraceManager.getTrace(ShadowConstraintsChecker.class); private LensProjectionContext projectionContext; @@ -60,7 +60,7 @@ public class ShadowConstraintsChecker { public ShadowConstraintsChecker(LensProjectionContext accountContext) { this.projectionContext = accountContext; } - + public LensProjectionContext getAccountContext() { return projectionContext; } @@ -88,15 +88,15 @@ public void setProvisioningService(ProvisioningService provisioningService) { public LensContext getContext() { return context; } - + public void setContext(LensContext context) { this.context = context; } - + public boolean isSatisfiesConstraints() { return satisfiesConstraints; } - + public String getMessages() { return constraintsCheckingResult.getMessages(); } @@ -106,7 +106,7 @@ public PrismObject getConflictingShadow() { } public void check(Task task, OperationResult result) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { - + RefinedObjectClassDefinition projOcDef = projectionContext.getCompositeObjectClassDefinition(); PrismObject projectionNew = projectionContext.getObjectNew(); if (projectionNew == null) { @@ -115,7 +115,7 @@ public void check(Task task, OperationResult result) throws SchemaException, Obj satisfiesConstraints = true; return; } - + PrismContainer attributesContainer = projectionNew.findContainer(ShadowType.F_ATTRIBUTES); if (attributesContainer == null) { // No attributes no constraint violations @@ -160,7 +160,7 @@ public void check(Task task, OperationResult result) throws SchemaException, Obj satisfiesConstraints = false; } } - + private boolean isInDelta(QName attrName, ObjectDelta delta) { if (delta == null) { diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/SmartAssignmentCollection.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/SmartAssignmentCollection.java index 331e90eff7a..c462e52662a 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/SmartAssignmentCollection.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/SmartAssignmentCollection.java @@ -37,15 +37,15 @@ /** * Smart set of assignment values that keep track whether the assignment is new, old or changed. - * + * * This information is used for various reasons. We specifically distinguish between assignments in objectCurrent and objectOld * to be able to reliably detect phantom adds: a phantom add is an assignment that is both in OLD and CURRENT objects. This is * important in waves greater than 0, where objectCurrent is already updated with existing assignments. (See MID-2422.) - * + * * @author Radovan Semancik */ public class SmartAssignmentCollection implements Iterable, DebugDumpable { - + private Map aMap = null; private Map idMap; @@ -54,19 +54,19 @@ public void collect(PrismObject objectCurrent, PrismObject objectOld, Cont if (objectCurrent != null) { assignmentContainerCurrent = objectCurrent.findContainer(FocusType.F_ASSIGNMENT); } - + if (aMap == null) { int initialCapacity = computeInitialCapacity(assignmentContainerCurrent, assignmentDelta); aMap = new HashMap<>(initialCapacity); idMap = new HashMap<>(initialCapacity); } - + collectAssignments(assignmentContainerCurrent, Mode.CURRENT); - + if (objectOld != null) { collectAssignments(objectOld.findContainer(FocusType.F_ASSIGNMENT), Mode.OLD); } - + collectAssignments(assignmentDelta); } @@ -87,8 +87,8 @@ private void collectAssignments(ContainerDelta assignmentDelta) collectAssignmentsDeltaSet(assignmentDelta.getValuesToAdd()); collectAssignmentsDeltaSet(assignmentDelta.getValuesToDelete()); } - - + + private void collectAssignmentsDeltaSet(Collection> deltaSet) throws SchemaException { if (deltaSet == null) { return; @@ -99,11 +99,11 @@ private void collectAssignmentsDeltaSet(Collection assignmentCVal, Mode mode) throws SchemaException { - + SmartAssignmentElement element = null; - + // Special lookup for empty elements. - // Changed assignments may be "light", i.e. they may contain just the identifier. + // Changed assignments may be "light", i.e. they may contain just the identifier. // Make sure that we always have the full assignment data. if (assignmentCVal.isEmpty()) { if (assignmentCVal.getId() != null) { @@ -117,17 +117,17 @@ private void collectAssignment(PrismContainerValue assignmentCVa throw new SchemaException("Attempt to change empty assignment without ID"); } } - + if (element == null) { element = lookup(assignmentCVal); } - + if (element == null) { element = put(assignmentCVal); } - + switch (mode) { - case CURRENT: + case CURRENT: element.setCurrent(true); break; case OLD: @@ -181,7 +181,7 @@ public Iterator iterator() { return aMap.values().iterator(); } } - + @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); @@ -198,7 +198,7 @@ public String debugDump(int indent) { } return sb.toString(); } - + @Override public String toString() { return "SmartAssignmentCollection(" + aMap.values() + ")"; @@ -207,5 +207,5 @@ public String toString() { private enum Mode { CURRENT, OLD, CHANGED; } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/SmartAssignmentElement.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/SmartAssignmentElement.java index 5de87c1893f..37803de5bf3 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/SmartAssignmentElement.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/SmartAssignmentElement.java @@ -21,7 +21,7 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; /** - * + * * @author semancik */ public class SmartAssignmentElement implements DebugDumpable { @@ -30,11 +30,11 @@ public class SmartAssignmentElement implements DebugDumpable { private boolean isCurrent = false; private boolean isOld = false; private boolean isChanged = false; - + public SmartAssignmentElement(PrismContainerValue assignmentCVal) { this.assignmentCVal = assignmentCVal; } - + public boolean isCurrent() { return isCurrent; } @@ -62,7 +62,7 @@ public void setChanged(boolean isChanged) { public PrismContainerValue getAssignmentCVal() { return assignmentCVal; } - + public SmartAssignmentKey getKey() { return new SmartAssignmentKey(assignmentCVal); } @@ -97,8 +97,8 @@ private void flag(StringBuilder sb, boolean b, String label) { sb.append(label).append(","); } } - + // TODO: equals, hashCode - - + + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/SmartAssignmentKey.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/SmartAssignmentKey.java index af6458f41ce..0c0be0d2461 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/SmartAssignmentKey.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/SmartAssignmentKey.java @@ -27,7 +27,7 @@ public class SmartAssignmentKey { private static final Trace LOGGER = TraceManager.getTrace(SmartAssignmentKey.class); - + private PrismContainerValue assignmentCVal; public SmartAssignmentKey(PrismContainerValue assignmentCVal) { @@ -36,11 +36,11 @@ public SmartAssignmentKey(PrismContainerValue assignmentCVal) { } // This is a key to an assignment hashmap. - // hashCode() and equals() are very important here. + // hashCode() and equals() are very important here. // Especially equals(). We want to make the comparison reliable, but reasonably quick. @Override - public int hashCode() { + public int hashCode() { return assignmentCVal.hashCode(); } @@ -74,5 +74,5 @@ private boolean equalsAssignment(PrismContainerValue other) { public String toString() { return "SmartAssignmentKey(" + assignmentCVal + ")"; } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ValueMatcher.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ValueMatcher.java index 9aafaae75ce..d0b8856a062 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ValueMatcher.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/ValueMatcher.java @@ -32,9 +32,9 @@ * */ public class ValueMatcher { - + private static final Trace LOGGER = TraceManager.getTrace(ValueMatcher.class); - + MatchingRule matchingRule; public ValueMatcher(MatchingRule matchingRule) { @@ -51,20 +51,20 @@ public static ValueMatcher createMatcher(RefinedAttributeDefinition rAttr } return new ValueMatcher(matchingRule); } - + public static ValueMatcher createDefaultMatcher(QName type, MatchingRuleRegistry matchingRuleRegistry) throws SchemaException { MatchingRule matchingRule = matchingRuleRegistry.getMatchingRule(null, type); return new ValueMatcher((MatchingRule) matchingRule); } - + public boolean match(T realA, T realB) throws SchemaException { return matchingRule.match(realA, realB); } - + public boolean matches(T realValue, String regex) throws SchemaException{ return matchingRule.matchRegex(realValue, regex); } - + public boolean hasRealValue(PrismProperty property, PrismPropertyValue pValue) { for (T existingRealValue: property.getRealValues()) { try { @@ -86,7 +86,7 @@ public boolean hasRealValue(PrismProperty property, PrismPropertyValue pVa } return false; } - + public boolean isRealValueToAdd(PropertyDelta delta, PrismPropertyValue pValue) { if (delta.getValuesToAdd() == null){ return false; @@ -116,5 +116,5 @@ public boolean isRealValueToAdd(PropertyDelta delta, PrismPropertyValue pV public String toString() { return "ValueMatcher(" + matchingRule + ")"; } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/credentials/CredentialsProcessor.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/credentials/CredentialsProcessor.java index f28644f2cc1..95b2f29b3e7 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/credentials/CredentialsProcessor.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/credentials/CredentialsProcessor.java @@ -80,22 +80,22 @@ public class CredentialsProcessor { public void processFocusCredentials(LensContext context, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException { - + LensFocusContext focusContext = context.getFocusContext(); if (focusContext == null || !UserType.class.isAssignableFrom(focusContext.getObjectTypeClass())) { LOGGER.trace("Skipping processing credentials because focus is not user"); return; } - + processFocusPassword((LensContext) context, now, task, result); processFocusNonce((LensContext) context, now, task, result); processFocusSecurityQuestions((LensContext) context, now, task, result); } - + private void processFocusPassword(LensContext context, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException { - + PasswordPolicyEvaluator evaluator = new PasswordPolicyEvaluator(); evaluator.setContext(context); evaluator.setMetadataManager(metadataManager); @@ -109,12 +109,12 @@ private void processFocusPassword(LensContext co evaluator.process(); } - + //for now just saving metadata private void processFocusNonce(LensContext context, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException { - + NoncePolicyEvaluator evaluator = new NoncePolicyEvaluator(); evaluator.setContext(context); evaluator.setMetadataManager(metadataManager); @@ -129,11 +129,11 @@ private void processFocusNonce(LensContext context, XMLGregorianCalend evaluator.process(); } - + private void processFocusSecurityQuestions(LensContext context, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException { - + SecurityQuestionsPolicyEvaluator evaluator = new SecurityQuestionsPolicyEvaluator(); evaluator.setContext(context); evaluator.setMetadataManager(metadataManager); @@ -149,7 +149,7 @@ private void processFocusSecurityQuestions(LensContext context, XMLGre } - + /** * Called from ChangeExecutor. Will modify the execution deltas to hash or remove credentials if needed. */ @@ -166,7 +166,7 @@ public ObjectDelta transformFocusExectionDelta(LensCon ObjectDelta transformedDelta = focusDelta.clone(); transformFocusExectionDeltaCredential(context, credsType, credsType.getPassword(), SchemaConstants.PATH_PASSWORD_VALUE, transformedDelta); // TODO: nonce and others - + return transformedDelta; } @@ -177,7 +177,7 @@ private void transformFocusExectionDeltaCredential(LensCo return; } CredentialPolicyType defaltCredPolicyType = credsType.getDefault(); - CredentialsStorageMethodType storageMethod = + CredentialsStorageMethodType storageMethod = SecurityUtil.getCredPolicyItem(defaltCredPolicyType, credPolicyType, pol -> pol.getStorageMethod()); if (storageMethod == null) { return; @@ -211,7 +211,7 @@ private void transformFocusExectionDeltaCredential(LensCo } else { throw new SchemaException("Unkwnon storage type "+storageType); } - + } private void hashValues(Collection> values, @@ -228,7 +228,7 @@ private void hashValues(Collection> valu } /** - * Legacy. Invoked from mappings. TODO: fix + * Legacy. Invoked from mappings. TODO: fix */ public ValuePolicyType determinePasswordPolicy(LensFocusContext focusContext, Task task, OperationResult result) { if (focusContext == null) { diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/credentials/NoncePolicyEvaluator.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/credentials/NoncePolicyEvaluator.java index c1830386fdc..9c231b1b4be 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/credentials/NoncePolicyEvaluator.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/credentials/NoncePolicyEvaluator.java @@ -32,7 +32,7 @@ * */ public class NoncePolicyEvaluator extends CredentialPolicyEvaluator { - + private static final ItemPath NONCE_CONTAINER_PATH = new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_NONCE); @Override @@ -44,7 +44,7 @@ public ItemPath getCredentialsContainerPath() { protected String getCredentialHumanReadableName() { return "nonce"; } - + @Override protected boolean supportsHistory() { return false; @@ -54,5 +54,5 @@ protected boolean supportsHistory() { protected NonceCredentialsPolicyType determineEffectiveCredentialPolicy() throws SchemaException { return SecurityUtil.getEffectiveNonceCredentialsPolicy(getSecurityPolicy()); } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/credentials/PasswordPolicyEvaluator.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/credentials/PasswordPolicyEvaluator.java index 8719c6c891e..70fb33d87e8 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/credentials/PasswordPolicyEvaluator.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/credentials/PasswordPolicyEvaluator.java @@ -27,7 +27,7 @@ * */ public class PasswordPolicyEvaluator extends CredentialPolicyEvaluator { - + private static final ItemPath PASSWORD_CONTAINER_PATH = new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD); @Override @@ -39,7 +39,7 @@ public ItemPath getCredentialsContainerPath() { protected String getCredentialHumanReadableName() { return "password"; } - + @Override protected boolean supportsHistory() { return true; @@ -50,6 +50,6 @@ protected boolean supportsHistory() { protected PasswordCredentialsPolicyType determineEffectiveCredentialPolicy() { return SecurityUtil.getEffectivePasswordCredentialsPolicy(getSecurityPolicy()); } - - + + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/credentials/ProjectionCredentialsProcessor.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/credentials/ProjectionCredentialsProcessor.java index 8bd66971e84..fc56b940af0 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/credentials/ProjectionCredentialsProcessor.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/projector/credentials/ProjectionCredentialsProcessor.java @@ -111,33 +111,33 @@ public void processProjectionCredentials(LensContext c LensProjectionContext projectionContext, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException, CommunicationException, ConfigurationException, SecurityViolationException { - + if (projectionContext.isDelete()) { return; } - + LensFocusContext focusContext = context.getFocusContext(); if (focusContext != null && FocusType.class.isAssignableFrom(focusContext.getObjectTypeClass())) { - + processProjectionCredentialsFocus((LensContext) context, projectionContext, now, task, result); - + } } - + private void processProjectionCredentialsFocus(LensContext context, LensProjectionContext projectionContext, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException, CommunicationException, ConfigurationException, SecurityViolationException { - + ValuePolicyType passwordPolicy = determinePasswordPolicy(context, projectionContext, now, task, result); - + processProjectionPasswordMapping(context, projectionContext, passwordPolicy, now, task, result); - + validateProjectionPassword(context, projectionContext, passwordPolicy, now, task, result); - + applyMetadata(context, projectionContext, now, task, result); } - + private void processProjectionPasswordMapping(LensContext context, final LensProjectionContext projCtx, final ValuePolicyType passwordPolicy, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException { @@ -149,7 +149,7 @@ private void processProjectionPasswordMapping(LensContext< LOGGER.trace("userNew is null, skipping credentials processing"); return; } - + PrismObjectDefinition accountDefinition = prismContext.getSchemaRegistry() .findObjectDefinitionByCompileTimeClass(ShadowType.class); PrismPropertyDefinition projPasswordPropertyDefinition = accountDefinition @@ -168,13 +168,13 @@ private void processProjectionPasswordMapping(LensContext< LOGGER.trace("No outbound password mapping for {}, skipping credentials processing", rsd); return; } - + // HACK if (!projCtx.isDoReconciliation() && !projCtx.isAdd() && !isActivated(outboundMappingTypes, focusContext.getDelta())) { LOGGER.trace("Outbound password mappings not activated for type {}, skipping credentials processing", rsd); return; } - + final ObjectDelta projDelta = projCtx.getDelta(); final PropertyDelta projPasswordDelta; if (projDelta != null && projDelta.getChangeType() == MODIFY) { @@ -205,15 +205,15 @@ public StringPolicyType resolve() { } }; - MappingInitializer,PrismPropertyDefinition> initializer = + MappingInitializer,PrismPropertyDefinition> initializer = (builder) -> { builder.defaultTargetDefinition(projPasswordPropertyDefinition); builder.defaultSource(new Source<>(userPasswordIdi, ExpressionConstants.VAR_INPUT)); builder.stringPolicyResolver(stringPolicyResolver); return builder; }; - - MappingOutputProcessor> processor = + + MappingOutputProcessor> processor = (mappingOutputPath, outputStruct) -> { PrismValueDeltaSetTriple> outputTriple = outputStruct.getOutputTriple(); if (outputTriple == null) { @@ -230,7 +230,7 @@ public StringPolicyType resolve() { } else { newValues = outputTriple.getPlusSet(); } - + if (!canGetCleartext(newValues)) { ObjectDelta projectionPrimaryDelta = projCtx.getPrimaryDelta(); if (projectionPrimaryDelta != null) { @@ -239,7 +239,7 @@ public StringPolicyType resolve() { // We have only hashed value coming from the mapping. There are not very useful // for provisioning. But we have primary projection delta - and that is very likely // to be better. - // Skip all password mappings in this case. Primary delta trumps everything. + // Skip all password mappings in this case. Primary delta trumps everything. // No weak, normal or even strong mapping can change that. // We need to disregard even strong mapping in this case. If we would heed the strong // mapping then account initialization won't be possible. @@ -251,14 +251,14 @@ public StringPolicyType resolve() { return true; }; - - - mappingEvaluator.evaluateOutboundMapping(context, projCtx, outboundMappingTypes, + + + mappingEvaluator.evaluateOutboundMapping(context, projCtx, outboundMappingTypes, SchemaConstants.PATH_PASSWORD_VALUE, SchemaConstants.PATH_PASSWORD_VALUE, initializer, processor, now, true, evaluateWeak, "password mapping", task, result); - + } - + private boolean isActivated(List outboundMappingTypes, ObjectDelta focusDelta) { if (focusDelta == null) { return false; @@ -318,23 +318,23 @@ private boolean getEvaluateWeak(LensProjectionContext projCtx) { private void validateProjectionPassword(LensContext context, final LensProjectionContext projectionContext, final ValuePolicyType passwordPolicy, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException { - + if (passwordPolicy == null) { LOGGER.trace("Skipping processing password policies. Password policy not specified."); return; } - + ObjectDelta accountDelta = projectionContext.getDelta(); - + if (accountDelta == null){ LOGGER.trace("Skipping processing password policies. Shadow delta not specified."); return; } - + if (accountDelta.isDelete()) { return; } - + PrismObject accountShadow = null; PrismProperty password = null; if (accountDelta.isAdd()) { @@ -357,13 +357,13 @@ private void validateProjectionPassword(LensContext con } password = (PrismProperty) passwordValueDelta.getItemNewMatchingPath(null); } - + if (accountShadow == null) { accountShadow = projectionContext.getObjectNew(); } - + String passwordValue = determinePasswordValue(password); - + boolean isValid = valuePolicyProcessor.validateValue(passwordValue, passwordPolicy, accountShadow, "projection password policy", task, result); if (!isValid) { @@ -371,17 +371,17 @@ private void validateProjectionPassword(LensContext con throw new PolicyViolationException("Provided password does not satisfy password policies in " + projectionContext.getHumanReadableName() + ": " + result.getMessage()); } } - + private void applyMetadata(LensContext context, final LensProjectionContext projectionContext, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, PolicyViolationException { - + ObjectDelta accountDelta = projectionContext.getDelta(); - + if (projectionContext.isDelete()) { return; } - + if (accountDelta == null){ LOGGER.trace("Skipping application of password metadata. Shadow delta not specified."); return; @@ -393,7 +393,7 @@ private void applyMetadata(LensContext context, LOGGER.trace("Skipping application of password metadata. No password change."); return; } - + if (projectionContext.isAdd()) { MetadataType metadataType = operationalDataManager.createCreateMetadata(context, now, task); ContainerDelta metadataDelta = ContainerDelta.createDelta(SchemaConstants.PATH_PASSWORD_METADATA, projectionContext.getObjectDefinition()); @@ -412,9 +412,9 @@ private void applyMetadata(LensContext context, } } } - + } - + private ValuePolicyType determinePasswordPolicy(LensContext context, final LensProjectionContext projCtx, XMLGregorianCalendar now, Task task, OperationResult result) { ValuePolicyType passwordPolicy = projCtx.getAccountPasswordPolicy(); @@ -438,7 +438,7 @@ private String determinePasswordValue(PrismProperty passwor return determinePasswordValue(passValue); } - + private String determinePasswordValue(ProtectedStringType passValue) { if (passValue == null) { return null; @@ -457,7 +457,7 @@ private String determinePasswordValue(ProtectedStringType passValue) { return passwordStr; } - + private void checkExistingDeltaSanity(LensProjectionContext projCtx, PropertyDelta passwordDelta) throws SchemaException { if (passwordDelta != null && (passwordDelta.isAdd() || passwordDelta.isDelete())) { diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/migrator/Migrator.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/migrator/Migrator.java index d3426afe882..ae06b91caae 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/migrator/Migrator.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/migrator/Migrator.java @@ -37,7 +37,7 @@ * */ public class Migrator { - + public PrismObject migrate(PrismObject original) { Class origType = original.getCompileTimeClass(); if (ObjectTemplateType.class.isAssignableFrom(origType)) { @@ -58,7 +58,7 @@ public PrismObject migrate(Prism } return (PrismObject) original; } - + private PrismObject migrateObjectTemplate(PrismObject orig) { QName elementName = orig.getElementName(); if (elementName.equals(SchemaConstants.C_OBJECT_TEMPLATE)) { @@ -72,12 +72,12 @@ private PrismObject migrateObjectTemplate(PrismObject migrateResource(PrismObject orig) { return orig; } - + private void migrateObjectSynchronization(ObjectSynchronizationType sync) { if (sync == null || sync.getReaction() == null){ return; } - + List migratedReactions = new ArrayList(); for (SynchronizationReactionType reaction : sync.getReaction()){ if (reaction.getAction() == null){ @@ -92,7 +92,7 @@ private void migrateObjectSynchronization(ObjectSynchronizationType sync) { migratedReaction.getAction().addAll(migratedAction); migratedReactions.add(migratedReaction); } - + sync.getReaction().clear(); sync.getReaction().addAll(migratedReactions); } @@ -101,16 +101,16 @@ private SynchronizationActionType migrateAction(SynchronizationActionType action if (action.getUserTemplateRef() == null){ return action; } - + action.setObjectTemplateRef(action.getUserTemplateRef()); - + return action; } - + private PrismObject migrateFocus(PrismObject orig) { return orig; } - + private PrismObject migrateUser(PrismObject orig) { return orig; } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/rest/MidpointAbstractProvider.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/rest/MidpointAbstractProvider.java index d6fd69edd29..e7de87842e9 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/rest/MidpointAbstractProvider.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/rest/MidpointAbstractProvider.java @@ -48,15 +48,15 @@ public abstract class MidpointAbstractProvider extends AbstractConfigurableProvider implements MessageBodyReader, MessageBodyWriter{ private static transient Trace LOGGER = TraceManager.getTrace(MidpointAbstractProvider.class); - + @Autowired protected PrismContext prismContext; - + // @Override public void init(List cris) { setEnableStreaming(true); } - + @Override public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { @@ -83,10 +83,10 @@ public void writeTo(T object, Class type, Type genericType, // TODO implement in the standard serializer; also change root name QName fakeQName = new QName(PrismConstants.NS_TYPES, "object"); String xml; - + PrismSerializer serializer = getSerializer() .options(SerializationOptions.createSerializeReferenceNames()); - + try { if (object instanceof PrismObject) { xml = serializer.serialize((PrismObject) object); @@ -101,7 +101,7 @@ public void writeTo(T object, Class type, Type genericType, LoggingUtils.logException(LOGGER, "Couldn't marshal element to string: {}", e, object); } } - + protected abstract PrismSerializer getSerializer(); protected abstract PrismParser getParser(InputStream entityStream); @@ -119,13 +119,13 @@ public T readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { - + if (entityStream == null) { return null; } - + PrismParser parser = getParser(entityStream); - + T object; try { LOGGER.info("type of request: {}", type); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/scripting/actions/DiscoverConnectorsExecutor.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/scripting/actions/DiscoverConnectorsExecutor.java index ba4f5dd52eb..7d9b9b52b5f 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/scripting/actions/DiscoverConnectorsExecutor.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/scripting/actions/DiscoverConnectorsExecutor.java @@ -167,7 +167,7 @@ private void determineConnectorMappings(Map rebindMap, ConnectorT connectorType.setConnectorHostRef(ObjectTypeUtil.createObjectRef(connectorType.getConnectorHost().getOid(), ObjectTypes.CONNECTOR_HOST)); connectorType.setConnectorHost(null); } - + } if (connectorType.getConnectorHostRef().equals(foundConnectorType.getConnectorHostRef()) && foundConnectorType.getConnectorVersion() != null && diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/scripting/actions/ScriptExecutor.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/scripting/actions/ScriptExecutor.java index 0264340e488..4cd7434f959 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/scripting/actions/ScriptExecutor.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/scripting/actions/ScriptExecutor.java @@ -171,9 +171,9 @@ private Object executeScript(ScriptExpression scriptExpression, PrismValue prism variables.addVariableDefinition(ExpressionConstants.VAR_INPUT, prismValue); variables.addVariableDefinition(ExpressionConstants.VAR_PRISM_CONTEXT, prismContext); ExpressionUtil.addActorVariable(variables, securityEnforcer); - + List rv = Utils.evaluateScript(scriptExpression, null, variables, true, "in '"+NAME+"' action", context.getTask(), result); - + if (rv == null || rv.size() == 0) { return null; } else if (rv.size() == 1) { diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/AuthenticationEvaluatorImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/AuthenticationEvaluatorImpl.java index 5b33ffe9c84..3cb66b71c9a 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/AuthenticationEvaluatorImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/AuthenticationEvaluatorImpl.java @@ -54,16 +54,16 @@ * */ public abstract class AuthenticationEvaluatorImpl implements AuthenticationEvaluator { - + private static final Trace LOGGER = TraceManager.getTrace(AuthenticationEvaluatorImpl.class); - + @Autowired private Protector protector; @Autowired private Clock clock; @Autowired private SecurityHelper securityHelper; // Has to be package-private so the tests can manipulate it @Autowired UserProfileService userProfileService; - + protected abstract void checkEnteredCredentials(ConnectionEnvironment connEnv, T authCtx); protected abstract boolean suportsAuthzCheck(); protected abstract C getCredential(CredentialsType credentials); @@ -72,65 +72,65 @@ protected abstract boolean passwordMatches(ConnectionEnvironment connEnv, @NotNu T authCtx); protected abstract CredentialPolicyType getEffectiveCredentialPolicy(SecurityPolicyType securityPolicy, T authnCtx) throws SchemaException; protected abstract boolean supportsActivation(); - + @Override - public UsernamePasswordAuthenticationToken authenticate(ConnectionEnvironment connEnv, T authnCtx) - throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException, - CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException { - + public UsernamePasswordAuthenticationToken authenticate(ConnectionEnvironment connEnv, T authnCtx) + throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException, + CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException { + checkEnteredCredentials(connEnv, authnCtx); - + MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), true); - + UserType userType = principal.getUser(); CredentialsType credentials = userType.getCredentials(); CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx); - + if (checkCredentials(principal, authnCtx, connEnv)) { - + recordPasswordAuthenticationSuccess(principal, connEnv, getCredential(credentials), credentialsPolicy); - UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, + UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, authnCtx.getEnteredCredential(), principal.getAuthorities()); return token; - + } else { recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch"); - + throw new BadCredentialsException("web.security.provider.invalid"); } } - + @Override - public UserType checkCredentials(ConnectionEnvironment connEnv, T authnCtx) - throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException, - CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException { - + public UserType checkCredentials(ConnectionEnvironment connEnv, T authnCtx) + throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException, + CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException { + checkEnteredCredentials(connEnv, authnCtx); - + MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), false); - + UserType userType = principal.getUser(); CredentialsType credentials = userType.getCredentials(); CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx); - + if (checkCredentials(principal, authnCtx, connEnv)) { return userType; } else { recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch"); - + throw new BadCredentialsException("web.security.provider.invalid"); } } - + private boolean checkCredentials(MidPointPrincipal principal, T authnCtx, ConnectionEnvironment connEnv) { - + UserType userType = principal.getUser(); CredentialsType credentials = userType.getCredentials(); if (credentials == null || getCredential(credentials) == null) { recordAuthenticationFailure(principal, connEnv, "no credentials in user"); throw new AuthenticationCredentialsNotFoundException("web.security.provider.invalid"); } - + CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx); // Lockout @@ -138,7 +138,7 @@ private boolean checkCredentials(MidPointPrincipal principal, T authnCtx, Connec recordAuthenticationFailure(principal, connEnv, "password locked-out"); throw new LockedException("web.security.provider.locked"); } - + if (suportsAuthzCheck()) { // Authorizations if (!hasAnyAuthorization(principal)) { @@ -146,13 +146,13 @@ private boolean checkCredentials(MidPointPrincipal principal, T authnCtx, Connec throw new DisabledException("web.security.provider.access.denied"); } } - + // Password age checkPasswordValidityAndAge(connEnv, principal, getCredential(credentials), credentialsPolicy); - + return passwordMatches(connEnv, principal, getCredential(credentials), authnCtx); } - + private CredentialPolicyType getCredentialsPolicy(MidPointPrincipal principal, T authnCtx){ SecurityPolicyType securityPolicy = principal.getApplicableSecurityPolicy(); CredentialPolicyType credentialsPolicy = null; @@ -162,23 +162,23 @@ private CredentialPolicyType getCredentialsPolicy(MidPointPrincipal principal, T // TODO how to properly hanlde the error???? throw new AuthenticationServiceException("Bad config"); } - + return credentialsPolicy; } - - + + /** * Special-purpose method used for Web Service authentication based on javax.security callbacks. - * + * * In that case there is no reasonable way how to reuse existing methods. Therefore this method is NOT part of the * AuthenticationEvaluator interface. It is mostly a glue to make the old Java security code work. */ - public String getAndCheckUserPassword(ConnectionEnvironment connEnv, String enteredUsername) - throws AuthenticationCredentialsNotFoundException, DisabledException, LockedException, - CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException { + public String getAndCheckUserPassword(ConnectionEnvironment connEnv, String enteredUsername) + throws AuthenticationCredentialsNotFoundException, DisabledException, LockedException, + CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException { MidPointPrincipal principal = getAndCheckPrincipal(connEnv, enteredUsername, true); - + UserType userType = principal.getUser(); CredentialsType credentials = userType.getCredentials(); if (credentials == null) { @@ -200,40 +200,40 @@ public String getAndCheckUserPassword(ConnectionEnvironment connEnv, String ente recordAuthenticationFailure(principal, connEnv, "no authorizations"); throw new AccessDeniedException("web.security.provider.access.denied"); } - + // Password age checkPasswordValidityAndAge(connEnv, principal, passwordType.getValue(), passwordType.getMetadata(), passwordCredentialsPolicy); - + return getPassword(connEnv, principal, passwordType.getValue()); } - + @Override public PreAuthenticatedAuthenticationToken authenticateUserPreAuthenticated(ConnectionEnvironment connEnv, String enteredUsername) { - + MidPointPrincipal principal = getAndCheckPrincipal(connEnv, enteredUsername, true); - + // Authorizations if (!hasAnyAuthorization(principal)) { recordAuthenticationFailure(principal, connEnv, "no authorizations"); throw new AccessDeniedException("web.security.provider.access.denied"); } - + PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, null, principal.getAuthorities()); - + recordAuthenticationSuccess(principal, connEnv); - + return token; } @NotNull private MidPointPrincipal getAndCheckPrincipal(ConnectionEnvironment connEnv, String enteredUsername, boolean supportsActivationCheck) { - + if (StringUtils.isBlank(enteredUsername)) { recordAuthenticationFailure(enteredUsername, connEnv, "no username"); throw new UsernameNotFoundException("web.security.provider.invalid"); } - + MidPointPrincipal principal; try { principal = userProfileService.getPrincipal(enteredUsername); @@ -244,8 +244,8 @@ private MidPointPrincipal getAndCheckPrincipal(ConnectionEnvironment connEnv, St recordAuthenticationFailure(enteredUsername, connEnv, "schema error"); throw new AccessDeniedException("web.security.provider.invalid"); } - - + + if (principal == null) { recordAuthenticationFailure(enteredUsername, connEnv, "no user"); throw new UsernameNotFoundException("web.security.provider.invalid"); @@ -257,7 +257,7 @@ private MidPointPrincipal getAndCheckPrincipal(ConnectionEnvironment connEnv, St } return principal; } - + private boolean hasAnyAuthorization(MidPointPrincipal principal) { Collection authorizations = principal.getAuthorities(); if (authorizations == null || authorizations.isEmpty()){ @@ -270,20 +270,20 @@ private boolean hasAnyAuthorization(MidPointPrincipal principal) { } return false; } - + private

    void checkPasswordValidityAndAge(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, C credentials, P passwordCredentialsPolicy) { if (credentials == null) { recordAuthenticationFailure(principal, connEnv, "no stored credential value"); throw new AuthenticationCredentialsNotFoundException("web.security.provider.credential.bad"); } - + validateCredentialNotNull(connEnv, principal, credentials); - + if (passwordCredentialsPolicy == null) { return; } - + Duration maxAge = passwordCredentialsPolicy.getMaxAge(); if (maxAge != null) { MetadataType credentialMetedata = credentials.getMetadata(); @@ -298,7 +298,7 @@ private

    void checkPasswordValidityAndAge(Connec } } - private void checkPasswordValidityAndAge(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString, MetadataType passwordMetadata, + private void checkPasswordValidityAndAge(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString, MetadataType passwordMetadata, CredentialPolicyType passwordCredentialsPolicy) { if (protectedString == null) { recordAuthenticationFailure(principal, connEnv, "no stored password value"); @@ -319,13 +319,13 @@ private void checkPasswordValidityAndAge(ConnectionEnvironment connEnv, @NotNull } } } - - + + // protected boolean matchDecryptedValue(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, String decryptedValue, // String enteredPassword){ // return enteredPassword.equals(decryptedValue); // } -// +// protected boolean decryptAndMatch(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString, String enteredPassword) { ProtectedStringType entered = new ProtectedStringType(); @@ -337,7 +337,7 @@ protected boolean decryptAndMatch(ConnectionEnvironment connEnv, @NotNull MidPoi throw new AuthenticationServiceException("web.security.provider.unavailable", e); } } - + protected String getDecryptedValue(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString) { String decryptedPassword; if (protectedString.getEncryptedDataType() != null) { @@ -354,7 +354,7 @@ protected String getDecryptedValue(ConnectionEnvironment connEnv, @NotNull MidPo } return decryptedPassword; } - + private String getPassword(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString) { String decryptedPassword; if (protectedString.getEncryptedDataType() != null) { @@ -375,17 +375,17 @@ private String getPassword(ConnectionEnvironment connEnv, @NotNull MidPointPrinc private boolean isLockedOut(AbstractCredentialType credentialsType, CredentialPolicyType credentialsPolicy) { return isOverFailedLockoutAttempts(credentialsType, credentialsPolicy) && !isLockoutExpired(credentialsType, credentialsPolicy); } - + private boolean isOverFailedLockoutAttempts(AbstractCredentialType credentialsType, CredentialPolicyType credentialsPolicy) { int failedLogins = credentialsType.getFailedLogins() != null ? credentialsType.getFailedLogins() : 0; return isOverFailedLockoutAttempts(failedLogins, credentialsPolicy); } - + private boolean isOverFailedLockoutAttempts(int failedLogins, CredentialPolicyType credentialsPolicy) { return credentialsPolicy != null && credentialsPolicy.getLockoutMaxFailedAttempts() != null && credentialsPolicy.getLockoutMaxFailedAttempts() > 0 && failedLogins >= credentialsPolicy.getLockoutMaxFailedAttempts(); } - + private boolean isLockoutExpired(AbstractCredentialType credentialsType, CredentialPolicyType credentialsPolicy) { Duration lockoutDuration = credentialsPolicy.getLockoutDuration(); if (lockoutDuration == null) { @@ -415,7 +415,7 @@ private void recordPasswordAuthenticationSuccess(MidPointPrincipal principal, Co passwordType.setPreviousSuccessfulLogin(passwordType.getLastSuccessfulLogin()); passwordType.setLastSuccessfulLogin(event); - + ActivationType activation = principal.getUser().getActivation(); if (activation != null) { activation.setLockoutStatus(LockoutStatusType.NORMAL); @@ -423,16 +423,16 @@ private void recordPasswordAuthenticationSuccess(MidPointPrincipal principal, Co } userProfileService.updateUser(principal); - + recordAuthenticationSuccess(principal, connEnv); } - - + + private void recordAuthenticationSuccess(@NotNull MidPointPrincipal principal, @NotNull ConnectionEnvironment connEnv) { securityHelper.auditLoginSuccess(principal.getUser(), connEnv); } - + private void recordPasswordAuthenticationFailure(@NotNull MidPointPrincipal principal, @NotNull ConnectionEnvironment connEnv, @NotNull C passwordType, CredentialPolicyType credentialsPolicy, String reason) { Integer failedLogins = passwordType.getFailedLogins(); @@ -441,7 +441,7 @@ private void recordPasswordAuthenticationFailure(@NotNull MidPointPrincipal prin if (lastFailedLogin != null) { lastFailedLoginTs = lastFailedLogin.getTimestamp(); } - + if (credentialsPolicy != null) { Duration lockoutFailedAttemptsDuration = credentialsPolicy.getLockoutFailedAttemptsDuration(); if (lockoutFailedAttemptsDuration != null) { @@ -458,17 +458,17 @@ private void recordPasswordAuthenticationFailure(@NotNull MidPointPrincipal prin } else { failedLogins++; } - + passwordType.setFailedLogins(failedLogins); - + LoginEventType event = new LoginEventType(); event.setTimestamp(clock.currentTimeXMLGregorianCalendar()); event.setFrom(connEnv.getRemoteHostAddress()); - + passwordType.setLastFailedLogin(event); - + ActivationType activationType = principal.getUser().getActivation(); - + if (failedLogins != null && isOverFailedLockoutAttempts(failedLogins, credentialsPolicy)) { if (activationType == null) { activationType = new ActivationType(); @@ -484,18 +484,18 @@ private void recordPasswordAuthenticationFailure(@NotNull MidPointPrincipal prin } activationType.setLockoutExpirationTimestamp(lockoutExpirationTs); } - + userProfileService.updateUser(principal); - + recordAuthenticationFailure(principal, connEnv, reason); } - + protected void recordAuthenticationFailure(@NotNull MidPointPrincipal principal, ConnectionEnvironment connEnv, String reason) { securityHelper.auditLoginFailure(principal.getUsername(), principal.getUser(), connEnv, reason); } - + protected void recordAuthenticationFailure(String username, ConnectionEnvironment connEnv, String reason) { securityHelper.auditLoginFailure(username, null, connEnv, reason); } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/MidPointLdapAuthenticationProvider.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/MidPointLdapAuthenticationProvider.java index 5c355318a9f..d532be9784d 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/MidPointLdapAuthenticationProvider.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/MidPointLdapAuthenticationProvider.java @@ -17,19 +17,19 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; public class MidPointLdapAuthenticationProvider extends LdapAuthenticationProvider{ - + private static final Trace LOGGER = TraceManager.getTrace(MidPointLdapAuthenticationProvider.class); - + @Autowired private SecurityHelper securityHelper; public MidPointLdapAuthenticationProvider(LdapAuthenticator authenticator) { super(authenticator); } - - + + @Override protected DirContextOperations doAuthentication(UsernamePasswordAuthenticationToken authentication) { - + try { return super.doAuthentication(authentication); } catch (RuntimeException e) { @@ -38,28 +38,28 @@ protected DirContextOperations doAuthentication(UsernamePasswordAuthenticationTo throw e; } } - - + + @Override protected Authentication createSuccessfulAuthentication(UsernamePasswordAuthenticationToken authentication, UserDetails user) { Authentication authNCtx = super.createSuccessfulAuthentication(authentication, user); - + Object principal = authNCtx.getPrincipal(); if (!(principal instanceof MidPointPrincipal)) { throw new BadCredentialsException("LdapAuthentication.incorrect.value"); } MidPointPrincipal midPointPrincipal = (MidPointPrincipal) principal; UserType userType = midPointPrincipal.getUser(); - + if (userType == null) { throw new BadCredentialsException("LdapAuthentication.bad.user"); } - + securityHelper.auditLoginSuccess(userType, ConnectionEnvironment.create(SchemaConstants.CHANNEL_GUI_USER_URI)); return authNCtx; } - - + + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/MidpointRestAuthenticationHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/MidpointRestAuthenticationHandler.java index 2e8246c670f..213edaee46f 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/MidpointRestAuthenticationHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/MidpointRestAuthenticationHandler.java @@ -39,12 +39,12 @@ * @author Radovan Semancik */ public class MidpointRestAuthenticationHandler implements ContainerRequestFilter, ContainerResponseFilter { - + // private static final Trace LOGGER = TraceManager.getTrace(MidpointRestAuthenticationHandler.class); - + @Autowired(required=true) private MidpointRestPasswordAuthenticator passwordAuthenticator; - + @Autowired(required=true) private MidpointRestSecurityQuestionsAuthenticator securityQuestionAuthenticator; @@ -57,20 +57,20 @@ public void filter(ContainerRequestContext request, ContainerResponseContext res @Override public void filter(ContainerRequestContext requestCtx) throws IOException { Message m = JAXRSUtils.getCurrentMessage(); - + AuthorizationPolicy policy = (AuthorizationPolicy) m.get(AuthorizationPolicy.class); if (policy != null) { passwordAuthenticator.handleRequest(policy, m, requestCtx); return; } - + String authorization = requestCtx.getHeaderString("Authorization"); - + if (StringUtils.isBlank(authorization)){ RestServiceUtil.createAbortMessage(requestCtx); return; } - + String[] parts = authorization.split(" "); String authenticationType = parts[0]; @@ -102,13 +102,13 @@ public void filter(ContainerRequestContext requestCtx) throws IOException { } } - + // protected void createAbortMessage(ContainerRequestContext requestCtx){ // requestCtx.abortWith(Response.status(Status.UNAUTHORIZED) // .header("WWW-Authenticate", AuthenticationType.BASIC.getAuthenticationType() + " realm=\"midpoint\", " + AuthenticationType.SECURITY_QUESTIONS.getAuthenticationType()).build()); // } -// +// } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/MidpointRestAuthenticator.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/MidpointRestAuthenticator.java index 0939f7827e3..2c404b8e09c 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/MidpointRestAuthenticator.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/MidpointRestAuthenticator.java @@ -61,52 +61,52 @@ public abstract class MidpointRestAuthenticator { - - + + private static final Trace LOGGER = TraceManager.getTrace(MidpointRestAuthenticator.class); - + @Autowired(required = true) private SecurityEnforcer securityEnforcer; - + @Autowired(required = true) private SecurityHelper securityHelper; - + @Autowired(required=true) private TaskManager taskManager; - + @Autowired(required=true) private ModelService model; - + protected abstract AuthenticationEvaluator getAuthenticationEvaluator(); protected abstract T createAuthenticationContext(AuthorizationPolicy policy, ContainerRequestContext requestCtx); - + public void handleRequest(AuthorizationPolicy policy, Message m, ContainerRequestContext requestCtx) { - + if (policy == null){ RestServiceUtil.createAbortMessage(requestCtx); return; } - - + + T authenticationContext = createAuthenticationContext(policy, requestCtx); - + if (authenticationContext == null) { return; } String enteredUsername = authenticationContext.getUsername(); - + if (enteredUsername == null){ RestServiceUtil.createAbortMessage(requestCtx); return; } - + LOGGER.trace("Authenticating username '{}' to REST service", enteredUsername); - + // We need to create task before attempting authentication. Task ID is also a session ID. Task task = taskManager.createTaskInstance(ModelRestService.OPERATION_REST_SERVICE); task.setChannel(SchemaConstants.CHANNEL_REST_URI); - + ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_REST_URI); connEnv.setSessionIdOverride(task.getTaskIdentifier()); UsernamePasswordAuthenticationToken token; @@ -122,15 +122,15 @@ public void handleRequest(AuthorizationPolicy policy, Message m, ContainerReques requestCtx.abortWith(Response.status(Status.FORBIDDEN).build()); return; } - + UserType user = ((MidPointPrincipal)token.getPrincipal()).getUser(); task.setOwner(user.asPrismObject()); - + // m.put(RestServiceUtil.MESSAGE_PROPERTY_TASK_NAME, task); if (!authorizeUser(user, null, enteredUsername, connEnv, requestCtx)){ return; } - + String oid = requestCtx.getHeaderString("Switch-To-Principal"); OperationResult result = task.getResult(); if (StringUtils.isNotBlank(oid)){ @@ -149,16 +149,16 @@ public void handleRequest(AuthorizationPolicy policy, Message m, ContainerReques requestCtx.abortWith(Response.status(Status.UNAUTHORIZED).header("WWW-Authenticate", "Proxy Authentication failed. Cannot authenticate user.").build()); return; } - - + + } - + m.put(RestServiceUtil.MESSAGE_PROPERTY_TASK_NAME, task); - + LOGGER.trace("Authorized to use REST service ({})", user); - + } - + private boolean authorizeUser(UserType user, PrismObject proxyUser, String enteredUsername, ConnectionEnvironment connEnv, ContainerRequestContext requestCtx) { try { securityEnforcer.setupPreAuthenticatedSecurityContext(user.asPrismObject()); @@ -167,12 +167,12 @@ private boolean authorizeUser(UserType user, PrismObject proxyUser, St requestCtx.abortWith(Response.status(Status.BAD_REQUEST).build()); return false; } - + LOGGER.trace("Authenticated to REST service as {}", user); - + return authorizeUser(AuthorizationConstants.AUTZ_REST_ALL_URL, user, null, enteredUsername, connEnv, requestCtx); } - + private boolean authorizeUser(String authorization, UserType user, PrismObject proxyUser, String enteredUsername, ConnectionEnvironment connEnv, ContainerRequestContext requestCtx){ OperationResult authorizeResult = new OperationResult("Rest authentication/authorization operation."); try { @@ -188,15 +188,15 @@ private boolean authorizeUser(String authorization, UserType user, PrismObject{ - + @Autowired(required = true) private AuthenticationEvaluator passwordAuthenticationEvaluator; - + @Override protected AuthenticationEvaluator getAuthenticationEvaluator() { return passwordAuthenticationEvaluator; diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/MidpointRestSecurityQuestionsAuthenticator.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/MidpointRestSecurityQuestionsAuthenticator.java index 2c3230b6c60..d505777ffd3 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/MidpointRestSecurityQuestionsAuthenticator.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/MidpointRestSecurityQuestionsAuthenticator.java @@ -71,20 +71,20 @@ public class MidpointRestSecurityQuestionsAuthenticator extends MidpointRestAuth protected static final String USER_CHALLENGE = "\"user\" : \"username\""; protected static final String USER_QUESTION_ANSWER_CHALLENGE = ", \"answer\" :"; protected static final String QUESTION = "{\"qid\" : \"$QID\", \"qtxt\" : \"$QTXT\"}"; - + private static final String Q_ID = "$QID"; private static final String Q_TXT = "$QTXT"; - - + + @Autowired private PrismContext prismContext; - + @Autowired private ModelInteractionService modelInteractionService; - + @Autowired(required = true) private AuthenticationEvaluator securityQuestionsAuthenticationEvaluator; - + @Override protected AuthenticationEvaluator getAuthenticationEvaluator() { return securityQuestionsAuthenticationEvaluator; @@ -109,7 +109,7 @@ protected SecurityQuestionsAuthenticationContext createAuthenticationContext(Aut String userName = userNameNode.asText(); policy.setUserName(userName); JsonNode answerNode = node.findPath("answer"); - + if (answerNode instanceof MissingNode) { SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("restapi", "REST", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"))); SearchResultList> users = null; @@ -118,19 +118,19 @@ protected SecurityQuestionsAuthenticationContext createAuthenticationContext(Aut } finally { SecurityContextHolder.getContext().setAuthentication(null); } - + if (users.size() != 1) { requestCtx.abortWith(Response.status(Status.UNAUTHORIZED).header("WWW-Authenticate", "Security question authentication failed. Incorrect username and/or password").build()); return null; } - + PrismObject user = users.get(0); PrismContainer questionAnswerContainer = user.findContainer(SchemaConstants.PATH_SECURITY_QUESTIONS_QUESTION_ANSWER); if (questionAnswerContainer == null || questionAnswerContainer.isEmpty()){ requestCtx.abortWith(Response.status(Status.UNAUTHORIZED).header("WWW-Authenticate", "Security question authentication failed. Incorrect username and/or password").build()); return null; } - + String questionChallenge = ""; List questions = null; try { @@ -150,12 +150,12 @@ protected SecurityQuestionsAuthenticationContext createAuthenticationContext(Aut questionChallenge += ","; } } - + String userChallenge = USER_CHALLENGE.replace("username", userName); String challenge = "{" + userChallenge + ", \"answer\" : [" + questionChallenge + "]}"; RestServiceUtil.createSecurityQuestionAbortMessage(requestCtx, challenge); return null; - + } ArrayNode answers = (ArrayNode) answerNode; Iterator answersList = answers.elements(); @@ -167,16 +167,16 @@ protected SecurityQuestionsAuthenticationContext createAuthenticationContext(Aut questionAnswers.put(questionId, questionAnswer); } return new SecurityQuestionsAuthenticationContext(userName, questionAnswers); - + } - + private SearchResultList> searchUser(String userName) { return getSecurityEnforcer().runPrivileged(new Producer>>() { @Override public SearchResultList> run() { Task task = getTaskManager().createTaskInstance("Search user by name"); OperationResult result = task.getResult(); - + SearchResultList> users; try { users = getModel().searchObjects(UserType.class, ObjectQueryUtil.createNameQuery(userName, prismContext), null, task, result); @@ -187,15 +187,15 @@ public SearchResultList> run() { SecurityContextHolder.getContext().setAuthentication(null); } return users; - + } }); - + } - + private List getQuestions(PrismObject user) { return getSecurityEnforcer().runPrivileged(new Producer>() { - + @Override public List run() { Task task = getTaskManager().createTaskInstance("Search user by name"); @@ -215,7 +215,7 @@ public List run() { return null; } }); - + } } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/NonceAuthenticationEvaluatorImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/NonceAuthenticationEvaluatorImpl.java index 969262f145e..aa58bb4e5e0 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/NonceAuthenticationEvaluatorImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/NonceAuthenticationEvaluatorImpl.java @@ -19,7 +19,7 @@ @Component("nonceAuthenticationEvaluator") public class NonceAuthenticationEvaluatorImpl extends AuthenticationEvaluatorImpl{ - + @Override protected void checkEnteredCredentials(ConnectionEnvironment connEnv, NonceAuthenticationContext authCtx) { @@ -46,7 +46,7 @@ protected void validateCredentialNotNull(ConnectionEnvironment connEnv, MidPoint recordAuthenticationFailure(principal, connEnv, "no stored password value"); throw new AuthenticationCredentialsNotFoundException("web.security.provider.password.bad"); } - + } @Override @@ -65,7 +65,7 @@ protected CredentialPolicyType getEffectiveCredentialPolicy(SecurityPolicyType s return policy; } - + @Override protected boolean supportsActivation() { diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/PasswordAuthenticationEvaluatorImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/PasswordAuthenticationEvaluatorImpl.java index 10509fa4ff8..7376dd38397 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/PasswordAuthenticationEvaluatorImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/PasswordAuthenticationEvaluatorImpl.java @@ -40,14 +40,14 @@ protected PasswordType getCredential(CredentialsType credentials) { @Override protected void validateCredentialNotNull(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, PasswordType credential) { - + ProtectedStringType protectedString = credential.getValue(); - + if (protectedString == null) { recordAuthenticationFailure(principal, connEnv, "no stored password value"); throw new AuthenticationCredentialsNotFoundException("web.security.provider.password.bad"); } - + } @Override @@ -62,11 +62,11 @@ protected CredentialPolicyType getEffectiveCredentialPolicy(SecurityPolicyType s PasswordAuthenticationContext authnCtx) throws SchemaException { return SecurityUtil.getEffectivePasswordCredentialsPolicy(securityPolicy); } - + @Override protected boolean supportsActivation() { return true; } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/PasswordCallback.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/PasswordCallback.java index ce2089735d4..beb601b1f27 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/PasswordCallback.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/PasswordCallback.java @@ -33,7 +33,7 @@ * @author Radovan Semancik */ public class PasswordCallback implements CallbackHandler { - + private static final Trace LOGGER = TraceManager.getTrace(PasswordCallback.class); private PasswordAuthenticationEvaluatorImpl passwordAuthenticationEvaluatorImpl; @@ -49,7 +49,7 @@ public void handle(Callback[] callbacks) throws IOException, UnsupportedCallback String username = pc.getIdentifier(); String wssPasswordType = pc.getType(); LOGGER.trace("Username: '{}', Password type: {}", username, wssPasswordType); - + try { ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_WEB_SERVICE_URI); pc.setPassword(passwordAuthenticationEvaluatorImpl.getAndCheckUserPassword(connEnv, username)); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/PasswordCallbackException.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/PasswordCallbackException.java index 8d7c6c2c5c6..c346edb0474 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/PasswordCallbackException.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/PasswordCallbackException.java @@ -20,10 +20,10 @@ /** * Hack to correctly process exceptions from a password callback; * If this exception is thrown then the event was already audited. - * + * * This is deliberately a subclass of IOException because CXF will * only hanlde IOExceptions correctly. - * + * * @author semancik * */ diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/RestAuthenticationMethod.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/RestAuthenticationMethod.java index e8da6d5ebc9..80bcfb10629 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/RestAuthenticationMethod.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/RestAuthenticationMethod.java @@ -3,12 +3,12 @@ import org.apache.commons.lang.StringUtils; public enum RestAuthenticationMethod { - + BASIC("Basic"), SECURITY_QUESTIONS("SecQ"); - + private String method; - + private RestAuthenticationMethod(String method) { this.method = method; } @@ -16,7 +16,7 @@ private RestAuthenticationMethod(String method) { public String getMethod() { return method; } - + protected boolean equals(String authenticationType) { if (StringUtils.isBlank(authenticationType)) { return false; diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/SecurityHelper.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/SecurityHelper.java index 278c2c6392a..4a13b1ee7a5 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/SecurityHelper.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/SecurityHelper.java @@ -67,7 +67,7 @@ */ @Component public class SecurityHelper { - + private static final Trace LOGGER = TraceManager.getTrace(SecurityHelper.class); public static final String CONTEXTUAL_PROPERTY_AUDITED_NAME = SecurityHelper.class.getName() + ".audited"; @@ -106,7 +106,7 @@ private void auditLogin(@Nullable String username, @Nullable UserType user, @Not auditService.audit(record, task); } - + public void auditLogout(ConnectionEnvironment connEnv, Task task) { AuditEventRecord record = new AuditEventRecord(AuditEventType.TERMINATE_SESSION, AuditEventStage.REQUEST); record.setInitiatorAndLoginParameter(task.getOwner()); @@ -133,12 +133,12 @@ public String getUsernameFromMessage(SOAPMessage saajSoapMessage) throws WSSecur Element securityHeader = WSSecurityUtil.getSecurityHeader(saajSoapMessage.getSOAPPart(), ""); return getUsernameFromSecurityHeader(securityHeader); } - + private String getUsernameFromSecurityHeader(Element securityHeader) { if (securityHeader == null) { return null; } - + String username = ""; NodeList list = securityHeader.getChildNodes(); int len = list.getLength(); @@ -161,21 +161,21 @@ private String getUsernameFromSecurityHeader(Element securityHeader) { } return username; } - + public SOAPMessage getSOAPMessage(SoapMessage msg) { SAAJInInterceptor.INSTANCE.handleMessage(msg); return msg.getContent(SOAPMessage.class); } - + /** * Returns security policy applicable for the specified user. It looks for organization and global policies and takes into account * deprecated properties and password policy references. The resulting security policy has all the (non-deprecated) properties set. * If there is also referenced value policy, it is will be stored as "object" in the value policy reference inside the * returned security policy. */ - public SecurityPolicyType locateSecurityPolicy(PrismObject user, PrismObject systemConfiguration, + public SecurityPolicyType locateSecurityPolicy(PrismObject user, PrismObject systemConfiguration, Task task, OperationResult result) throws SchemaException { - + PrismObject orgSecurityPolicy = objectResolver.searchOrgTreeWidthFirstReference(user, o -> o.asObjectable().getSecurityPolicyRef(), "security policy", task, result); LOGGER.trace("Found organization security policy: {}", orgSecurityPolicy); if (orgSecurityPolicy != null) { @@ -184,15 +184,15 @@ public SecurityPolicyType locateSecurityPolicy(PrismObject traceSecurityPolicy(orgSecurityPolicyType, user); return orgSecurityPolicyType; } - + if (systemConfiguration != null) { SecurityPolicyType globalSecurityPolicy = resolveGlobalSecurityPolicy(user, systemConfiguration.asObjectable(), task, result); if (globalSecurityPolicy != null) { return globalSecurityPolicy; } } - - + + // DEPRECATED, legacy PrismObject orgPasswordPolicy = objectResolver.searchOrgTreeWidthFirstReference(user, o -> o.asObjectable().getPasswordPolicyRef(), "security policy", task, result); LOGGER.trace("Found organization password policy: {}", orgPasswordPolicy); @@ -201,17 +201,17 @@ public SecurityPolicyType locateSecurityPolicy(PrismObject traceSecurityPolicy(policy, user); return policy; } - + if (systemConfiguration != null) { SecurityPolicyType globalPasswordPolicy = resolveGlobalPasswordPolicy(user, systemConfiguration.asObjectable(), task, result); if (globalPasswordPolicy != null) { return globalPasswordPolicy; } } - + return null; } - + public SecurityPolicyType locateGlobalSecurityPolicy(SystemConfigurationType systemConfiguration, Task task, OperationResult result) { if (systemConfiguration != null) { SecurityPolicyType globalSecurityPolicy = resolveGlobalSecurityPolicy(null, systemConfiguration, task, result); @@ -219,10 +219,10 @@ public SecurityPolicyType locateGlobalSecurityPolicy(SystemConfigurationType sys return globalSecurityPolicy; } } - + return null; } - + public SecurityPolicyType locateGlobalPasswordPolicy(SystemConfigurationType systemConfiguration, Task task, OperationResult result) { if (systemConfiguration != null) { SecurityPolicyType globalPasswordPolicy = resolveGlobalPasswordPolicy(null, systemConfiguration, task, result); @@ -230,10 +230,10 @@ public SecurityPolicyType locateGlobalPasswordPolicy(SystemConfigurationType sys return globalPasswordPolicy; } } - + return null; } - + private SecurityPolicyType resolveGlobalSecurityPolicy(PrismObject user, SystemConfigurationType systemConfiguration, Task task, OperationResult result) { ObjectReferenceType globalSecurityPolicyRef = systemConfiguration.getGlobalSecurityPolicyRef(); if (globalSecurityPolicyRef != null) { @@ -249,10 +249,10 @@ private SecurityPolicyType resolveGlobalSecurityPolicy(Pri return null; } } - + return null; } - + private SecurityPolicyType resolveGlobalPasswordPolicy(PrismObject user, SystemConfigurationType systemConfiguration, Task task, OperationResult result) { ObjectReferenceType globalPasswordPolicyRef = systemConfiguration.getGlobalPasswordPolicyRef(); if (globalPasswordPolicyRef != null) { @@ -270,8 +270,8 @@ private SecurityPolicyType resolveGlobalPasswordPolicy(Pri } return null; } - - + + private void traceSecurityPolicy(SecurityPolicyType securityPolicyType, PrismObject user) { if (LOGGER.isTraceEnabled()) { if (user != null) { @@ -288,7 +288,7 @@ private void traceSecurityPolicy(SecurityPolicyType securi } } } - + } private void postProcessSecurityPolicy(SecurityPolicyType securityPolicyType, Task task, OperationResult result) { @@ -307,26 +307,26 @@ private void postProcessSecurityPolicy(SecurityPolicyType securityPolicyType, Ta } } } - + private void postProcessPasswordCredentialPolicy(SecurityPolicyType securityPolicyType, PasswordCredentialsPolicyType passwd, Task task, OperationResult result) { // Deprecated settings Integer passwordHistoryLength = passwd.getPasswordHistoryLength(); if (passwordHistoryLength != null && passwd.getHistoryLength() == null) { passwd.setHistoryLength(passwordHistoryLength); } - + ObjectReferenceType passwordPolicyRef = passwd.getPasswordPolicyRef(); if (passwordPolicyRef != null && passwd.getValuePolicyRef() == null) { passwd.setValuePolicyRef(passwordPolicyRef.clone()); } - + ValuePolicyType valuePolicyType = postProcessCredentialPolicy(securityPolicyType, passwd, "password credential policy", task, result); - + if (valuePolicyType != null) { setDeprecatedPasswordPolicyProperties(valuePolicyType, passwd); } } - + private ValuePolicyType postProcessCredentialPolicy(SecurityPolicyType securityPolicyType, CredentialPolicyType credPolicy, String credShortDesc, Task task, OperationResult result) { ObjectReferenceType valuePolicyRef = credPolicy.getValuePolicyRef(); if (valuePolicyRef == null) { @@ -378,7 +378,7 @@ private void setDeprecatedPasswordPolicyProperties(ValuePolicyType passwordPolic passwd.setMinOccurs(minOccurs); } } - + private Duration daysToDuration(int days) { return XmlTypeConverter.createDuration((long) days * 1000 * 60 * 60 * 24); } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/SecurityQuestionAuthneticationEvaluatorImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/SecurityQuestionAuthneticationEvaluatorImpl.java index ad2ab373651..dc402a397e7 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/SecurityQuestionAuthneticationEvaluatorImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/SecurityQuestionAuthneticationEvaluatorImpl.java @@ -32,7 +32,7 @@ protected void checkEnteredCredentials(ConnectionEnvironment connEnv, recordAuthenticationFailure(authCtx.getUsername(), connEnv, "empty password provided"); throw new BadCredentialsException("web.security.provider.password.encoding"); } - + Map enteredQuestionAnswer = authCtx.getQuestionAnswerMap(); boolean allBlank = false; for (String enteredAnswers : enteredQuestionAnswer.values()) { @@ -40,7 +40,7 @@ protected void checkEnteredCredentials(ConnectionEnvironment connEnv, allBlank = true; } } - + if (allBlank) { recordAuthenticationFailure(authCtx.getUsername(), connEnv, "empty password provided"); throw new BadCredentialsException("web.security.provider.password.encoding"); @@ -61,30 +61,30 @@ protected SecurityQuestionsCredentialsType getCredential(CredentialsType credent protected void validateCredentialNotNull(ConnectionEnvironment connEnv, MidPointPrincipal principal, SecurityQuestionsCredentialsType credential) { List securityQuestionsAnswers = credential.getQuestionAnswer(); - + if (securityQuestionsAnswers == null || securityQuestionsAnswers.isEmpty()) { recordAuthenticationFailure(principal, connEnv, "no stored security questions"); throw new AuthenticationCredentialsNotFoundException("web.security.provider.password.bad"); } - + } @Override protected boolean passwordMatches(ConnectionEnvironment connEnv, MidPointPrincipal principal, SecurityQuestionsCredentialsType passwordType, SecurityQuestionsAuthenticationContext authCtx) { - + SecurityQuestionsCredentialsPolicyType policy = authCtx.getPolicy(); Integer iNumberOfQuestions = policy.getQuestionNumber(); int numberOfQuestions = 0; if (iNumberOfQuestions != null){ numberOfQuestions = iNumberOfQuestions.intValue(); } - + Map enteredQuestionsAnswers = authCtx.getQuestionAnswerMap(); if (numberOfQuestions > enteredQuestionsAnswers.size()){ return false; - } - + } + List quetionsAnswers = passwordType.getQuestionAnswer(); int matched = 0; for (SecurityQuestionAnswerType questionAnswer : quetionsAnswers){ @@ -95,9 +95,9 @@ protected boolean passwordMatches(ConnectionEnvironment connEnv, MidPointPrincip } } } - + return matched > 0 && matched >= numberOfQuestions; - + } @Override @@ -110,7 +110,7 @@ protected CredentialPolicyType getEffectiveCredentialPolicy(SecurityPolicyType s authnCtx.setPolicy(policy); return policy; } - + @Override protected boolean supportsActivation() { return true; diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/SpringAuthenticationInjectorInterceptor.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/SpringAuthenticationInjectorInterceptor.java index b709d513024..1ade5b3639c 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/SpringAuthenticationInjectorInterceptor.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/SpringAuthenticationInjectorInterceptor.java @@ -57,7 +57,7 @@ public class SpringAuthenticationInjectorInterceptor implements PhaseInterceptor { private static final Trace LOGGER = TraceManager.getTrace(SpringAuthenticationInjectorInterceptor.class); - + private String phase; private Set before = new HashSet(); private Set after = new HashSet(); @@ -120,13 +120,13 @@ public void handleMessage(SoapMessage message) throws Fault { try { username = securityHelper.getUsernameFromMessage(saajSoapMessage); LOGGER.trace("Attempt to authenticate user '{}'", username); - + if (StringUtils.isBlank(username)) { message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true); securityHelper.auditLoginFailure(username, null, connEnv, "Empty username"); throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION); } - + MidPointPrincipal principal; try { principal = userDetailsService.getPrincipal(username); @@ -143,13 +143,13 @@ public void handleMessage(SoapMessage message) throws Fault { securityHelper.auditLoginFailure(username, null, connEnv, "No user"); throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION); } - + // Account validity and credentials and all this stuff should be already checked // in the password callback - + Authentication authentication = new UsernamePasswordAuthenticationToken(principal, null); SecurityContextHolder.getContext().setAuthentication(authentication); - + String operationName; try { operationName = DOMUtil.getFirstChildElement(saajSoapMessage.getSOAPBody()).getLocalName(); @@ -160,9 +160,9 @@ public void handleMessage(SoapMessage message) throws Fault { securityHelper.auditLoginFailure(username, principal.getUser(), connEnv, "SOAP error: "+e.getMessage()); throw new Fault(e); } - + // AUTHORIZATION - + boolean isAuthorized; try { isAuthorized = securityEnforcer.isAuthorized(AuthorizationConstants.AUTZ_WS_ALL_URL, AuthorizationPhaseType.REQUEST, null, null, null, null); @@ -193,7 +193,7 @@ public void handleMessage(SoapMessage message) throws Fault { securityHelper.auditLoginFailure(username, principal.getUser(), connEnv, "Not authorized"); throw createFault(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION); } - + } catch (WSSecurityException e) { LOGGER.debug("Access to web service denied for user '{}': security exception: {}", username, e.getMessage(), e); @@ -210,7 +210,7 @@ public void handleMessage(SoapMessage message) throws Fault { // Avoid auditing login attempt again if the operation fails on internal authorization message.put(SecurityHelper.CONTEXTUAL_PROPERTY_AUDITED_NAME, true); - + LOGGER.debug("Access to web service allowed for user '{}'", username); } @@ -222,5 +222,5 @@ private Fault createFault(ErrorCode code) { public void handleFault(SoapMessage message) { // Nothing to do } - + } \ No newline at end of file diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/UserProfileServiceImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/UserProfileServiceImpl.java index 04f5a86d5a6..1f626629b56 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/UserProfileServiceImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/UserProfileServiceImpl.java @@ -125,15 +125,15 @@ public MidPointPrincipal getPrincipal(PrismObject user) throws SchemaE OperationResult result = new OperationResult(OPERATION_GET_PRINCIPAL); return createPrincipal(user, result); } - + private MidPointPrincipal createPrincipal(PrismObject user, OperationResult result) throws SchemaException { if (user == null) { return null; } - + PrismObject systemConfiguration = null; try { - systemConfiguration = repositoryService.getObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), + systemConfiguration = repositoryService.getObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, result); } catch (ObjectNotFoundException | SchemaException e) { LOGGER.warn("No system configuration: {}", e.getMessage(), e); @@ -167,7 +167,7 @@ private PrismObject findByUsername(String username, OperationResult re } return list.get(0); } - + private void initializePrincipalFromAssignments(MidPointPrincipal principal, PrismObject systemConfiguration) throws SchemaException { UserType userType = principal.getUser(); @@ -276,10 +276,10 @@ public PrismObject resolveOwner(P } PrismObject owner = null; OperationResult result = new OperationResult(UserProfileServiceImpl.class+".resolveOwner"); - + if (object.canRepresent(ShadowType.class)) { owner = repositoryService.searchShadowOwner(object.getOid(), null, result); - + } else if (object.canRepresent(UserType.class)) { ObjectQuery query = QueryBuilder.queryFor(UserType.class, prismContext) .item(FocusType.F_PERSONA_REF).ref(object.getOid()).build(); @@ -296,7 +296,7 @@ public PrismObject resolveOwner(P } catch (SchemaException e) { LOGGER.warn("Cannot resolve owner of {}: {}", object, e.getMessage(), e); } - + } else if (object.canRepresent(AbstractRoleType.class)) { ObjectReferenceType ownerRef = ((AbstractRoleType)(object.asObjectable())).getOwnerRef(); if (ownerRef != null && ownerRef.getOid() != null && ownerRef.getType() != null) { @@ -307,7 +307,7 @@ public PrismObject resolveOwner(P LOGGER.warn("Cannot resolve owner of {}: {}", object, e.getMessage(), e); } } - + } else if (object.canRepresent(TaskType.class)) { ObjectReferenceType ownerRef = ((TaskType)(object.asObjectable())).getOwnerRef(); if (ownerRef != null && ownerRef.getOid() != null && ownerRef.getType() != null) { @@ -319,7 +319,7 @@ public PrismObject resolveOwner(P } } } - + if (owner == null) { return null; } @@ -328,7 +328,7 @@ public PrismObject resolveOwner(P } return owner; } - + @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { try { @@ -355,8 +355,8 @@ public UserDetails mapUserFromContext(DirContextOperations ctx, String username, @Override public void mapUserToContext(UserDetails user, DirContextAdapter ctx) { // TODO Auto-generated method stub - + } - - + + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/WsFaultListener.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/WsFaultListener.java index 34d56867916..06939bc3018 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/WsFaultListener.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/security/WsFaultListener.java @@ -29,7 +29,7 @@ public class WsFaultListener implements FaultListener { private static final Trace LOGGER = TraceManager.getTrace(WsFaultListener.class); - + private SecurityHelper securityHelper; public WsFaultListener(SecurityHelper securityHelper) { @@ -73,5 +73,5 @@ public boolean faultOccurred(Exception exception, String description, Message me return true; } - + } \ No newline at end of file diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/ExecuteChangesTaskHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/ExecuteChangesTaskHandler.java index ab348ce74db..47c13df6edf 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/ExecuteChangesTaskHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/ExecuteChangesTaskHandler.java @@ -48,15 +48,15 @@ public class ExecuteChangesTaskHandler extends AbstractSearchIterativeTaskHandle @Autowired private TaskManager taskManager; - + @Autowired private PrismContext prismContext; @Autowired private ModelService model; - + private static final transient Trace LOGGER = TraceManager.getTrace(ExecuteChangesTaskHandler.class); - + public ExecuteChangesTaskHandler() { super("Execute", OperationConstants.EXECUTE); setLogFinishInfo(true); @@ -75,11 +75,11 @@ protected ObjectQuery createQuery(AbstractSearchIterativeResultHandler getType(Task task) { return getTypeFromTask(task, UserType.class); } - + @Override protected AbstractSearchIterativeResultHandler createHandler(TaskRunResult runResult, final Task coordinatorTask, OperationResult opResult) { - + AbstractSearchIterativeResultHandler handler = new AbstractSearchIterativeResultHandler( coordinatorTask, ExecuteChangesTaskHandler.class.getName(), "execute", "execute task", taskManager) { @Override @@ -93,7 +93,7 @@ protected boolean handleObject(PrismObject object, Task workerTask, O } private void executeChange(PrismObject focalObject, Task coordinatorTask, Task task, OperationResult result) throws SchemaException, - ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ObjectAlreadyExistsException, + ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ObjectAlreadyExistsException, ConfigurationException, PolicyViolationException, SecurityViolationException { LOGGER.trace("Recomputing object {}", focalObject); @@ -107,11 +107,11 @@ private void executeChange(PrismObject focalObject, Ta delta.setObjectTypeClass(focalObject.getCompileTimeClass()); } prismContext.adopt(delta); - + model.executeChanges(Collections.singletonList(delta), getExecuteOptionsFromTask(task), task, result); LOGGER.trace("Execute changes {} for object {}: {}", delta, focalObject, result.getStatus()); } - + private ObjectDelta createDeltaFromTask(Task task) throws SchemaException { PrismProperty objectDeltaType = task.getExtensionProperty(SchemaConstants.MODEL_EXTENSION_OBJECT_DELTA); if (objectDeltaType != null && objectDeltaType.getRealValue() != null) { diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/FocusValidityScannerTaskHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/FocusValidityScannerTaskHandler.java index 6f383d3941a..895dc16ecf0 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/FocusValidityScannerTaskHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/FocusValidityScannerTaskHandler.java @@ -77,7 +77,7 @@ import static com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType.F_ASSIGNMENT; /** - * + * * @author Radovan Semancik * */ @@ -88,7 +88,7 @@ public class FocusValidityScannerTaskHandler extends AbstractScannerTaskHandler< // It is a spring bean and it is supposed to handle all search task instances // Therefore it must not have task-specific fields. It can only contain fields specific to // all tasks of a specified type - + public static final String HANDLER_URI = ModelPublicConstants.FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI; @Autowired private ContextFactory contextFactory; @@ -135,21 +135,21 @@ protected Class getType(Task task) { return UserType.class; } return type; - + } @Override protected ObjectQuery createQuery(AbstractScannerResultHandler handler, TaskRunResult runResult, Task coordinatorTask, OperationResult opResult) throws SchemaException { initProcessedOids(coordinatorTask); - + TimeValidityPolicyConstraintType validtyContraintType = getValidityPolicyConstraint(coordinatorTask); - + Duration activateOn = getActivateOn(validtyContraintType); - + ObjectQuery query = new ObjectQuery(); ObjectFilter filter; // PrismObjectDefinition focusObjectDef = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); - + XMLGregorianCalendar lastScanTimestamp = handler.getLastScanTimestamp(); XMLGregorianCalendar thisScanTimestamp = handler.getThisScanTimestamp(); if (activateOn != null) { @@ -163,27 +163,27 @@ protected ObjectQuery createQuery(AbstractScannerResultHandler handler lastScanTimestamp.add(activateOn.negate()); } filter = createFilterFor(getType(coordinatorTask), path, lastScanTimestamp, thisScanTimestamp); - + } else { - + filter = createBasicFilter(lastScanTimestamp, thisScanTimestamp); } - + query.setFilter(filter); - + return query; } - + private Duration getActivateOn(TimeValidityPolicyConstraintType validtyContraintType) { - + Duration activateOn = null; if (validtyContraintType != null) { activateOn = validtyContraintType.getActivateOn(); } - + return activateOn; } - + private ObjectFilter createBasicFilter(XMLGregorianCalendar lastScanTimestamp, XMLGregorianCalendar thisScanTimestamp){ if (lastScanTimestamp == null) { return QueryBuilder.queryFor(FocusType.class, prismContext) @@ -196,7 +196,7 @@ private ObjectFilter createBasicFilter(XMLGregorianCalendar lastScanTimestamp, X .endBlock() .buildFilter(); } - + return QueryBuilder.queryFor(FocusType.class, prismContext) .item(F_ACTIVATION, F_VALID_FROM).gt(lastScanTimestamp) .and().item(F_ACTIVATION, F_VALID_FROM).le(thisScanTimestamp) @@ -210,33 +210,33 @@ private ObjectFilter createBasicFilter(XMLGregorianCalendar lastScanTimestamp, X .and().item(AssignmentType.F_ACTIVATION, F_VALID_TO).le(thisScanTimestamp) .endBlock() .buildFilter(); - + } - + private ObjectFilter createFilterFor(Class type, ItemPath path, XMLGregorianCalendar lastScanTimestamp, XMLGregorianCalendar thisScanTimestamp){ if (lastScanTimestamp == null) { return QueryBuilder.queryFor(type, prismContext) .item(path).le(thisScanTimestamp) .buildFilter(); } - + return QueryBuilder.queryFor(type, prismContext) .item(path).gt(lastScanTimestamp) .and().item(path).le(thisScanTimestamp) .buildFilter(); - + } @Override protected void finish(AbstractScannerResultHandler handler, TaskRunResult runResult, Task coordinatorTask, OperationResult opResult) throws SchemaException { TimeValidityPolicyConstraintType validtyContraintType = getValidityPolicyConstraint(coordinatorTask); - + Duration activateOn = getActivateOn(validtyContraintType); if (activateOn != null) { handler.getThisScanTimestamp().add(activateOn); } - + super.finish(handler, runResult, coordinatorTask, opResult); cleanupProcessedOids(coordinatorTask); } @@ -244,7 +244,7 @@ protected void finish(AbstractScannerResultHandler handler, TaskRunRes @Override protected AbstractScannerResultHandler createHandler(TaskRunResult runResult, final Task coordinatorTask, OperationResult opResult) { - + AbstractScannerResultHandler handler = new AbstractScannerResultHandler( coordinatorTask, FocusValidityScannerTaskHandler.class.getName(), "recompute", "recompute task", taskManager) { @Override @@ -262,10 +262,10 @@ protected boolean handleObject(PrismObject object, Task workerTask, Op } private void reconcileUser(PrismObject user, Task workerTask, OperationResult result) throws SchemaException, - ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ObjectAlreadyExistsException, + ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ObjectAlreadyExistsException, ConfigurationException, PolicyViolationException, SecurityViolationException { LOGGER.trace("Recomputing user {}", user); - // We want reconcile option here. There may be accounts that are in wrong activation state. + // We want reconcile option here. There may be accounts that are in wrong activation state. // We will not notice that unless we go with reconcile. LensContext lensContext = contextFactory.createRecomputeContext(user, ModelExecuteOptions.createReconcile(), workerTask, result); if (isNotifyAction(workerTask)) { @@ -278,47 +278,47 @@ private void reconcileUser(PrismObject user, Task workerTask, Operatio clockwork.run(lensContext, workerTask, result); LOGGER.trace("Recomputing of user {}: {}", user, result.getStatus()); } - + private TimeValidityPolicyConstraintType getValidityPolicyConstraint(Task coordinatorTask) { PolicyRuleType policyRule = coordinatorTask.getPolicyRule(); - + if (policyRule == null) { return null; } - + if (policyRule.getPolicyConstraints() == null) { return null; } - + List timeValidityContstraints = policyRule.getPolicyConstraints().getTimeValidity(); if (CollectionUtils.isEmpty(timeValidityContstraints)){ return null; } - + return timeValidityContstraints.iterator().next(); - + } - + private NotificationPolicyActionType getAction(Task coordinatorTask){ PolicyRuleType policyRule = coordinatorTask.getPolicyRule(); - + if (policyRule == null) { return null; } - + if (policyRule.getPolicyActions() == null) { return null; } - + return policyRule.getPolicyActions().getNotification(); } - + private boolean isNotifyAction(Task coordinatorTask) { return getAction(coordinatorTask) != null; } - + private boolean isTimeValidityConstraint(Task coordinatorTask){ return getValidityPolicyConstraint(coordinatorTask) != null; } - + } 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 d80d9a9c25e..cdc83cd0daf 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 @@ -50,27 +50,27 @@ /** * The task hander 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. - * + * * @author Radovan Semancik * */ @Component public class LiveSyncTaskHandler implements TaskHandler { - + public static final String HANDLER_URI = ModelConstants.NS_SYNCHRONIZATION_TASK_PREFIX + "/live-sync/handler-3"; @Autowired(required=true) private TaskManager taskManager; - + @Autowired(required=true) private ProvisioningService provisioningService; - + @Autowired(required = true) private PrismContext prismContext; - + private static final transient Trace LOGGER = TraceManager.getTrace(LiveSyncTaskHandler.class); @PostConstruct @@ -90,12 +90,12 @@ public TaskRunResult run(Task task) { private TaskRunResult runInternal(Task task) { LOGGER.trace("LiveSyncTaskHandler.run starting"); - + long progress = task.getProgress(); OperationResult opResult = new OperationResult(OperationConstants.LIVE_SYNC); TaskRunResult runResult = new TaskRunResult(); runResult.setOperationResult(opResult); - + String resourceOid = task.getObjectOid(); if (resourceOid == null) { LOGGER.error("Live Sync: No resource OID specified in the task"); @@ -103,7 +103,7 @@ private TaskRunResult runInternal(Task task) { runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR); return runResult; } - + ResourceType resource = null; try { @@ -157,7 +157,7 @@ private TaskRunResult runInternal(Task task) { runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR); return runResult; } - + RefinedResourceSchema refinedSchema; try { refinedSchema = RefinedResourceSchemaImpl.getRefinedSchema(resource, LayerType.MODEL, prismContext); @@ -167,14 +167,14 @@ private TaskRunResult runInternal(Task task) { runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR); return runResult; } - + if (refinedSchema == null){ opResult.recordFatalError("No refined schema defined. Probably some configuration problem."); runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR); LOGGER.error("Live Sync: No refined schema defined. Probably some configuration problem."); return runResult; } - + ObjectClassComplexTypeDefinition objectClass; try { objectClass = Utils.determineObjectClass(refinedSchema, task); @@ -189,11 +189,11 @@ private TaskRunResult runInternal(Task task) { } ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(resourceOid, objectClass==null?null:objectClass.getTypeName()); - + int changesProcessed; - + try { - + // MAIN PART // Calling synchronize(..) in provisioning. // This will detect the changes and notify model about them. @@ -202,7 +202,7 @@ private TaskRunResult runInternal(Task task) { Utils.clearRequestee(task); changesProcessed = provisioningService.synchronize(coords, task, opResult); progress += changesProcessed; - + } catch (ObjectNotFoundException ex) { LOGGER.error("Live Sync: A required object does not exist, OID: {}", ex.getOid()); LOGGER.error("Exception stack trace", ex); @@ -255,7 +255,7 @@ private TaskRunResult runInternal(Task task) { runResult.setProgress(progress); return runResult; } - + opResult.computeStatus("Live sync run has failed"); opResult.createSubresult(OperationConstants.LIVE_SYNC_STATISTICS).recordStatus(OperationResultStatus.SUCCESS, "Changes processed: " + changesProcessed); @@ -274,7 +274,7 @@ public Long heartbeat(Task task) { @Override public void refreshStatus(Task task) { - // Do nothing. Everything is fresh already. + // Do nothing. Everything is fresh already. } @Override diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/RecomputeTaskHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/RecomputeTaskHandler.java index dccc7fbf503..b4f4a4d6698 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/RecomputeTaskHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/RecomputeTaskHandler.java @@ -57,7 +57,7 @@ /** * The task hander for user recompute. - * + * * This handler takes care of executing recompute "runs". The task will iterate over all objects of a given type * and recompute their assignments and expressions. This is needed after the expressions are changed, * e.g in resource outbound expressions or in a role definition. @@ -72,18 +72,18 @@ public class RecomputeTaskHandler extends AbstractSearchIterativeTaskHandler handler, TaskRunResult runResult, Task task, OperationResult opResult) throws SchemaException { return createQueryFromTask(handler, runResult, task, opResult); @@ -107,7 +107,7 @@ protected Class getType(Task task) { @Override protected AbstractSearchIterativeResultHandler createHandler(TaskRunResult runResult, final Task coordinatorTask, OperationResult opResult) { - + AbstractSearchIterativeResultHandler handler = new AbstractSearchIterativeResultHandler( coordinatorTask, RecomputeTaskHandler.class.getName(), "recompute", "recompute task", taskManager) { @Override @@ -131,9 +131,9 @@ private ModelExecuteOptions getOptions(Task coordinatorTask) throws SchemaExcept LOGGER.trace("ModelExecuteOptions: {}", modelExecuteOptions); return modelExecuteOptions; } - + private void recompute(PrismObject focalObject, ModelExecuteOptions options, Task task, OperationResult result) throws SchemaException, - ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ObjectAlreadyExistsException, + ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ObjectAlreadyExistsException, ConfigurationException, PolicyViolationException, SecurityViolationException { LOGGER.trace("Recomputing object {}", focalObject); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/ReconciliationTaskHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/ReconciliationTaskHandler.java index 1284353b86f..45144b1a30e 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/ReconciliationTaskHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/ReconciliationTaskHandler.java @@ -74,14 +74,14 @@ /** * The task hander for reconciliation. - * + * * This handler takes care of executing reconciliation "runs". It means that the * handler "run" method will be as scheduled (every few days). The * responsibility is to iterate over accounts and compare the real state with * the assumed IDM state. - * + * * @author Radovan Semancik - * + * */ @Component public class ReconciliationTaskHandler implements TaskHandler { @@ -94,7 +94,7 @@ public class ReconciliationTaskHandler implements TaskHandler { * setter. */ private ReconciliationTaskResultListener reconciliationTaskResultListener; - + @Autowired(required = true) private TaskManager taskManager; @@ -110,10 +110,10 @@ public class ReconciliationTaskHandler implements TaskHandler { @Autowired(required = true) private ChangeNotificationDispatcher changeNotificationDispatcher; - + @Autowired(required = true) private AuditService auditService; - + @Autowired(required = true) private Clock clock; @@ -173,15 +173,15 @@ public TaskRunResult runInternal(Task coordinatorTask) { recordProgress(coordinatorTask, 0, opResult); // todo consider setting expectedTotal to null here - + PrismObject resource; ObjectClassComplexTypeDefinition objectclassDef; try { resource = provisioningService.getObject(ResourceType.class, resourceOid, null, coordinatorTask, opResult); - + RefinedResourceSchema refinedSchema = RefinedResourceSchemaImpl.getRefinedSchema(resource, LayerType.MODEL, prismContext); objectclassDef = Utils.determineObjectClass(refinedSchema, coordinatorTask); - + } catch (ObjectNotFoundException ex) { // This is bad. The resource does not exist. Permanent problem. processErrorPartial(runResult, "Resource does not exist, OID: " + resourceOid, ex, TaskRunResultStatus.PERMANENT_ERROR, null, coordinatorTask, opResult); @@ -209,12 +209,12 @@ public TaskRunResult runInternal(Task coordinatorTask) { } catch (SecurityViolationException ex) { processErrorPartial(runResult, "Security violation", ex, TaskRunResultStatus.PERMANENT_ERROR, null, coordinatorTask, opResult); return runResult; - + } catch (ExpressionEvaluationException ex) { processErrorPartial(runResult, "Expression error", ex, TaskRunResultStatus.PERMANENT_ERROR, null, coordinatorTask, opResult); return runResult; } - + if (objectclassDef == null) { processErrorPartial(runResult, "Reconciliation without an object class specification is not supported", null, TaskRunResultStatus.PERMANENT_ERROR, null, coordinatorTask, opResult); return runResult; @@ -222,15 +222,15 @@ public TaskRunResult runInternal(Task coordinatorTask) { reconResult.setResource(resource); reconResult.setObjectclassDefinition(objectclassDef); - + LOGGER.info("Start executing reconciliation of resource {}, reconciling object class {}, finish operations only: {}", resource, objectclassDef, finishOperationsOnly); long reconStartTimestamp = clock.currentTimeMillis(); - + AuditEventRecord requestRecord = new AuditEventRecord(AuditEventType.RECONCILIATION, AuditEventStage.REQUEST); requestRecord.setTarget(resource); auditService.audit(requestRecord, coordinatorTask); - + try { if (!scanForUnfinishedOperations(coordinatorTask, resourceOid, reconResult, opResult)) { processInterruption(runResult, resource, coordinatorTask, opResult); // appends also "last N failures" (TODO refactor) @@ -267,7 +267,7 @@ public TaskRunResult runInternal(Task coordinatorTask) { long beforeResourceReconTimestamp = clock.currentTimeMillis(); long afterResourceReconTimestamp; long afterShadowReconTimestamp; - try { + try { if (!finishOperationsOnly && !performResourceReconciliation(resource, objectclassDef, reconResult, coordinatorTask, opResult)) { processInterruption(runResult, resource, coordinatorTask, opResult); return runResult; @@ -309,7 +309,7 @@ public TaskRunResult runInternal(Task coordinatorTask) { processErrorFinal(runResult, "Expression error", ex, TaskRunResultStatus.PERMANENT_ERROR, resource, coordinatorTask, opResult); return runResult; } - + opResult.computeStatus(); // This "run" is finished. But the task goes on ... runResult.setRunResultStatus(TaskRunResultStatus.FINISHED); @@ -318,12 +318,12 @@ public TaskRunResult runInternal(Task coordinatorTask) { LOGGER.trace("Reconciliation.run stopping, result: {}", opResult.getStatus()); // LOGGER.trace("Reconciliation.run stopping, result: {}", opResult.dump()); } - + AuditEventRecord executionRecord = new AuditEventRecord(AuditEventType.RECONCILIATION, AuditEventStage.EXECUTION); executionRecord.setTarget(resource); executionRecord.setOutcome(OperationResultStatus.SUCCESS); auditService.audit(executionRecord , coordinatorTask); - + long reconEndTimestamp = clock.currentTimeMillis(); long etime = reconEndTimestamp - reconStartTimestamp; @@ -331,13 +331,13 @@ public TaskRunResult runInternal(Task coordinatorTask) { long resourceReconTime = afterResourceReconTimestamp - beforeResourceReconTimestamp; long shadowReconTime = afterShadowReconTimestamp - afterResourceReconTimestamp; LOGGER.info("Done executing reconciliation of resource {}, object class {}, Etime: {} ms (un-ops: {}, resource: {}, shadow: {})", - new Object[]{resource, objectclassDef, + new Object[]{resource, objectclassDef, etime, unOpsTime, resourceReconTime, shadowReconTime}); - - reconResult.setRunResult(runResult); + + reconResult.setRunResult(runResult); if (reconciliationTaskResultListener != null) { reconciliationTaskResultListener.process(reconResult); } @@ -429,14 +429,14 @@ private void processErrorFinal(TaskRunResult runResult, String errorDesc, Except TaskHandlerUtil.appendLastFailuresInformation(OperationConstants.RECONCILIATION, task, opResult); // TODO implement more seriously runResult.setRunResultStatus(runResultStatus); runResult.setProgress(task.getProgress()); - + AuditEventRecord executionRecord = new AuditEventRecord(AuditEventType.RECONCILIATION, AuditEventStage.EXECUTION); executionRecord.setTarget(resource); executionRecord.setOutcome(OperationResultStatus.FATAL_ERROR); executionRecord.setMessage(ex.getMessage()); auditService.audit(executionRecord , task); } - + private void processErrorPartial(TaskRunResult runResult, String errorDesc, Exception ex, TaskRunResultStatus runResultStatus, PrismObject resource, Task task, OperationResult opResult) { String message; @@ -470,7 +470,7 @@ private boolean performResourceReconciliation(PrismObject resource coordinatorTask.setExpectedTotal(null); try { - + ObjectQuery query = objectclassDef.createShadowSearchQuery(resource.getOid()); OperationResult searchResult = new OperationResult(OperationConstants.RECONCILIATION+".searchIterative"); @@ -497,10 +497,10 @@ private boolean performResourceReconciliation(PrismObject resource } opResult.recordStatus(resultStatus, message); LOGGER.info("Finished resource part of {} reconciliation: {}", resource, message); - + reconResult.setResourceReconCount(handler.getProgress()); reconResult.setResourceReconErrors(handler.getErrors()); - + } catch (ConfigurationException | SecurityViolationException | SchemaException | CommunicationException | ObjectNotFoundException | ExpressionEvaluationException | RuntimeException | Error e) { opResult.recordFatalError(e); throw e; @@ -514,10 +514,10 @@ private boolean performShadowReconciliation(final PrismObject reso boolean interrupted; // find accounts - + LOGGER.trace("Shadow reconciliation starting for {}, {} -> {}", new Object[]{resource, startTimestamp, endTimestamp}); OperationResult opResult = result.createSubresult(OperationConstants.RECONCILIATION+".shadowReconciliation"); - + ObjectQuery query = QueryBuilder.queryFor(ShadowType.class, prismContext) .block() .item(ShadowType.F_FULL_SYNCHRONIZATION_TIMESTAMP).le(XmlTypeConverter.createXMLGregorianCalendar(startTimestamp)) @@ -531,7 +531,7 @@ private boolean performShadowReconciliation(final PrismObject reso } long started = System.currentTimeMillis(); - + final Holder countHolder = new Holder(0L); ResultHandler handler = new ResultHandler() { @@ -540,7 +540,7 @@ public boolean handle(PrismObject shadow, OperationResult parentResu if ((objectclassDef instanceof RefinedObjectClassDefinition) && !((RefinedObjectClassDefinition)objectclassDef).matches(shadow.asObjectable())) { return true; } - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Shadow reconciliation of {}, fullSynchronizationTimestamp={}", shadow, shadow.asObjectable().getFullSynchronizationTimestamp()); } @@ -554,14 +554,14 @@ public boolean handle(PrismObject shadow, OperationResult parentResu task.recordIterativeOperationEnd(shadow.asObjectable(), started, t); throw t; } - + if (ShadowUtil.isProtected(resourceShadow)) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Skipping recording counter for {} because it is protected", shadow); } return task.canRun(); } - + countHolder.setValue(countHolder.getValue() + 1); incrementAndRecordProgress(task, new OperationResult("dummy")); // reconcileShadow writes to its own dummy OperationResult, so we do the same here return task.canRun(); @@ -570,14 +570,14 @@ public boolean handle(PrismObject shadow, OperationResult parentResu repositoryService.searchObjectsIterative(ShadowType.class, query, handler, null, true, opResult); interrupted = !task.canRun(); - + // for each try the operation again - + opResult.computeStatus(); - - LOGGER.trace("Shadow reconciliation finished, processed {} shadows for {}, result: {}", + + LOGGER.trace("Shadow reconciliation finished, processed {} shadows for {}, result: {}", new Object[]{countHolder.getValue(), resource, opResult.getStatus()}); - + reconResult.setShadowReconCount(countHolder.getValue()); result.createSubresult(OperationConstants.RECONCILIATION+".shadowReconciliation.statistics") @@ -587,7 +587,7 @@ public boolean handle(PrismObject shadow, OperationResult parentResu return !interrupted; } - + private PrismObject reconcileShadow(PrismObject shadow, PrismObject resource, Task task) { OperationResult opResult = new OperationResult(OperationConstants.RECONCILIATION+".shadowReconciliation.object"); try { @@ -605,12 +605,12 @@ private PrismObject reconcileShadow(PrismObject shadow, } catch (CommunicationException | SchemaException | ConfigurationException | SecurityViolationException | ExpressionEvaluationException e) { processShadowReconError(e, shadow, opResult); } - + return null; } - private void reactShadowGone(PrismObject shadow, PrismObject resource, + private void reactShadowGone(PrismObject shadow, PrismObject resource, Task task, OperationResult result) { try { provisioningService.applyDefinition(shadow, task, result); @@ -618,7 +618,7 @@ private void reactShadowGone(PrismObject shadow, PrismObject shadowDelta = ObjectDelta.createDeleteDelta(ShadowType.class, shadow.getOid(), - shadow.getPrismContext()); + shadow.getPrismContext()); change.setObjectDelta(shadowDelta); // Need to also set current shadow. This will get reflected in "old" object in lens context change.setCurrentShadow(shadow); @@ -659,7 +659,7 @@ private boolean scanForUnfinishedOperations(Task task, String resourceOid, Recon long startedAll = System.currentTimeMillis(); int processedSuccess = 0, processedFailure = 0; - + for (PrismObject shadow : shadows) { long started = System.currentTimeMillis(); 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 2b3901a506c..fc6c9314145 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 @@ -24,7 +24,7 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; public class ReconciliationTaskResult implements DebugDumpable { - + private TaskRunResult runResult; PrismObject resource; ObjectClassComplexTypeDefinition objectclassDefinition; @@ -161,5 +161,5 @@ public String debugDump(int indent) { public String debugDump() { return debugDump(0); } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/ReconciliationTaskResultListener.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/ReconciliationTaskResultListener.java index ba5109d38fb..6c7eab2eaa6 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/ReconciliationTaskResultListener.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/ReconciliationTaskResultListener.java @@ -19,7 +19,7 @@ /** * Testability interface. It is used in the tests to check correctness * of reconciliation run. - * + * * @author Radovan Semancik * */ @@ -27,5 +27,5 @@ public interface ReconciliationTaskResultListener { void process(ReconciliationTaskResult reconResult); - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/SynchronizationServiceImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/SynchronizationServiceImpl.java index 370ee5ed35d..a793f87b584 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/SynchronizationServiceImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/SynchronizationServiceImpl.java @@ -102,7 +102,7 @@ * Synchronization service receives change notifications from provisioning. It * decides which synchronization policy to use and evaluates it (correlation, * confirmation, situations, reaction, ...) - * + * * @author lazyman * @author Radovan Semancik * @@ -113,26 +113,26 @@ public class SynchronizationServiceImpl implements SynchronizationService { private static final Trace LOGGER = TraceManager.getTrace(SynchronizationServiceImpl.class); - + @Autowired(required = true) private ActionManager actionManager; - + @Autowired private CorrelationConfirmationEvaluator correlationConfirmationEvaluator; - + @Autowired(required = true) @Qualifier("cacheRepositoryService") private RepositoryService repositoryService; - + @Autowired(required = true) private ContextFactory contextFactory; - + @Autowired(required = true) private Clockwork clockwork; - + @Autowired(required = true) private ExpressionFactory expressionFactory; - + @Autowired(required = true) private SystemObjectCache systemObjectCache; @@ -312,20 +312,20 @@ public void notifyChange(ResourceObjectShadowChangeDescription change, Task task eventInfo.setNewSituation(newSituation); eventInfo.record(task); subResult.computeStatus(); - + } catch (SystemException ex) { // avoid unnecessary re-wrap eventInfo.setException(ex); eventInfo.record(task); subResult.recordFatalError(ex); throw ex; - + } catch (Exception ex) { eventInfo.setException(ex); eventInfo.record(task); subResult.recordFatalError(ex); throw new SystemException(ex); - + } finally { task.markObjectActionExecutedBoundary(); // if (LOGGER.isTraceEnabled()) { @@ -398,7 +398,7 @@ public ObjectSynchronizationType determineSynchronizationPolicy(ResourceType res PrismObject currentShadow, PrismObject configuration, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException { - + SynchronizationType synchronization = resourceType.getSynchronization(); if (synchronization == null) { return null; @@ -420,7 +420,7 @@ private boolean isPolicyApplicable(PrismObject currentShad if (!SynchronizationUtils.isPolicyApplicable(currentShadow, synchronizationPolicy, resource)) { return false; } - + Boolean conditionResult = evaluateSynchronizationPolicyCondition(synchronizationPolicy, currentShadow, resource, configuration, task, result); if (conditionResult != null) { @@ -776,14 +776,14 @@ private SynchronizationSituationType reactToChange(Class saveSyncMetadata(PrismObject shadow, List> deltas = SynchronizationUtils .createSynchronizationSituationAndDescriptionDelta(shadow, situation.getSituation(), change.getSourceChannel(), true); - + if (shadowType.getKind() == null) { ShadowKindType kind = synchronizationPolicy.getKind(); if (kind == null) { @@ -1139,7 +1139,7 @@ private void executeActions(SynchronizationReactionType re /* * (non-Javadoc) - * + * * @see com.evolveum.midpoint.provisioning.api.ResourceObjectChangeListener# * getName () */ diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/SynchronizationSituation.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/SynchronizationSituation.java index 0ee77106bed..5fa1e2fdaad 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/SynchronizationSituation.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/SynchronizationSituation.java @@ -21,9 +21,9 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.SynchronizationSituationType; /** - * + * * @author lazyman - * + * */ public class SynchronizationSituation { diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/SynchronizeAccountResultHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/SynchronizeAccountResultHandler.java index 2dfcabf88be..ae415c8e8ff 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/SynchronizeAccountResultHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/SynchronizeAccountResultHandler.java @@ -40,21 +40,21 @@ /** * Iterative search result handler for account synchronization. Works both for * reconciliation and import from resource. - * + * * This class is called back from the searchObjectsIterative() operation of the * provisioning service. It does most of the work of the "import" and resource * reconciliation operations. - * + * * @see ImportAccountsFromResourceTaskHandler * @see ReconciliationTaskHandler - * + * * @author Radovan Semancik - * + * */ public class SynchronizeAccountResultHandler extends AbstractSearchIterativeResultHandler { private static final Trace LOGGER = TraceManager.getTrace(SynchronizeAccountResultHandler.class); - + private ResourceObjectChangeListener objectChangeListener; private String resourceOid; private ThreadLocal resourceWorkingCopy = new ThreadLocal<>(); // because PrismContainer is not thread safe even for reading, each thread must have its own copy @@ -83,7 +83,7 @@ public boolean isForceAdd() { public void setForceAdd(boolean forceAdd) { this.forceAdd = forceAdd; } - + public QName getSourceChannel() { return sourceChannel; } @@ -91,7 +91,7 @@ public QName getSourceChannel() { public void setSourceChannel(QName sourceChannel) { this.sourceChannel = sourceChannel; } - + public String getResourceOid() { return resourceOid; } @@ -113,7 +113,7 @@ public ObjectClassComplexTypeDefinition getObjectClass() { * This methods will be called for each search result. It means it will be * called for each account on a resource. We will pretend that the account * was created and invoke notification interface. - * + * * @see * com.evolveum.midpoint.provisioning.api.ResultHandler#handle(com.evolveum * .midpoint.xml.ns._public.common.common_1.ObjectType) @@ -142,10 +142,10 @@ protected boolean handleObjectInternal(PrismObject accountShadow, Ta if (LOGGER.isTraceEnabled()) { LOGGER.trace("{} considering object:\n{}", getProcessShortNameCapitalized(), accountShadow.debugDump(1)); } - + ShadowType newShadowType = accountShadow.asObjectable(); if (newShadowType.isProtectedObject() != null && newShadowType.isProtectedObject()) { - LOGGER.trace("{} skipping {} because it is protected", + LOGGER.trace("{} skipping {} because it is protected", getProcessShortNameCapitalized(), accountShadow); result.recordStatus(OperationResultStatus.NOT_APPLICABLE, "Skipped because it is protected"); return true; diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/AddFocusAction.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/AddFocusAction.java index 53784cbb560..00bee2acac5 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/AddFocusAction.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/AddFocusAction.java @@ -41,20 +41,20 @@ public class AddFocusAction implements Action { private static final Trace LOGGER = TraceManager.getTrace(AddFocusAction.class); - + /* (non-Javadoc) * @see com.evolveum.midpoint.model.sync.Action#handle(com.evolveum.midpoint.model.lens.LensContext, com.evolveum.midpoint.model.sync.SynchronizationSituation, java.util.Map, com.evolveum.midpoint.task.api.Task, com.evolveum.midpoint.schema.result.OperationResult) */ @Override public void handle(LensContext context, SynchronizationSituation situation, Map parameters, Task task, OperationResult parentResult) throws SchemaException { - + if (context == null) { throw new UnsupportedOperationException("addFocus action is not supported with synchronize=false"); } - + PrismContext prismContext = context.getPrismContext(); - + LensFocusContext focusContext = context.createFocusContext(); Class focusClass = focusContext.getObjectTypeClass(); LOGGER.trace("addFocus action: add delta for {}", focusClass); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/BaseAction.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/BaseAction.java index 88bbd057c34..ecc2311f0c1 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/BaseAction.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/BaseAction.java @@ -45,7 +45,7 @@ public abstract class BaseAction implements Action { private PrismContext prismContext; private AuditService auditService; private ContextFactory contextFactory; - + public AuditService getAuditService() { return auditService; } @@ -53,7 +53,7 @@ public AuditService getAuditService() { public void setAuditService(AuditService auditService) { this.auditService = auditService; } - + public PrismContext getPrismContext() { return prismContext; } @@ -110,5 +110,5 @@ public ChangeExecutor getExecutor() { public void setExecutor(ChangeExecutor executor) { this.executor = executor; } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/DeleteFocusAction.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/DeleteFocusAction.java index 1f67a37aa7b..11020027ec1 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/DeleteFocusAction.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/DeleteFocusAction.java @@ -36,7 +36,7 @@ * */ public class DeleteFocusAction implements Action { - + private static final Trace LOGGER = TraceManager.getTrace(DeleteFocusAction.class); /* (non-Javadoc) @@ -45,7 +45,7 @@ public class DeleteFocusAction implements Action { @Override public void handle(LensContext context, SynchronizationSituation situation, Map parameters, Task task, OperationResult parentResult) { - + LensFocusContext focusContext = context.getFocusContext(); if (focusContext != null) { PrismObject objectOld = focusContext.getObjectOld(); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/InactivateFocusAction.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/InactivateFocusAction.java index 32caa75d5b5..173daf58607 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/InactivateFocusAction.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/InactivateFocusAction.java @@ -44,7 +44,7 @@ public class InactivateFocusAction extends BaseAction { public void handle(LensContext context, SynchronizationSituation situation, Map parameters, Task task, OperationResult parentResult) { ActivationStatusType desiredStatus = ActivationStatusType.DISABLED; - + LensFocusContext focusContext = context.getFocusContext(); if (focusContext != null) { PrismObject objectCurrent = focusContext.getObjectCurrent(); @@ -58,7 +58,7 @@ public void handle(LensContext context, Synchronization } } ObjectDelta activationDelta = ObjectDelta.createModificationReplaceProperty(focusContext.getObjectTypeClass(), - focusContext.getOid(), SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, getPrismContext(), + focusContext.getOid(), SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, getPrismContext(), desiredStatus); focusContext.setPrimaryDelta(activationDelta); } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/InactivateShadowAction.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/InactivateShadowAction.java index 0b1819e8c4e..d6b4dce3b85 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/InactivateShadowAction.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/InactivateShadowAction.java @@ -45,7 +45,7 @@ public class InactivateShadowAction extends BaseAction { public void handle(LensContext context, SynchronizationSituation situation, Map parameters, Task task, OperationResult parentResult) { ActivationStatusType desiredStatus = ActivationStatusType.DISABLED; - + LensProjectionContext projectionContext = context.getProjectionContextsIterator().next(); PrismObject objectCurrent = projectionContext.getObjectCurrent(); if (objectCurrent != null) { @@ -58,7 +58,7 @@ public void handle(LensContext context, Synchronization } } ObjectDelta activationDelta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, - projectionContext.getOid(), SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, getPrismContext(), + projectionContext.getOid(), SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, getPrismContext(), desiredStatus); projectionContext.setPrimaryDelta(activationDelta); } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/LinkAction.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/LinkAction.java index 26a30a5f5c3..651ea84bf17 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/LinkAction.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/action/LinkAction.java @@ -37,15 +37,15 @@ public class LinkAction implements Action { @Override public void handle(LensContext context, SynchronizationSituation situation, Map parameters, Task task, OperationResult parentResult) { - + // Just add the candidate focus to the context. It will be linked in // synchronization. - + F focusType = situation.getCorrelatedOwner(); LensFocusContext focusContext = context.createFocusContext(); PrismObject focusOld = (PrismObject) focusType.asPrismObject(); focusContext.setLoadedObject(focusOld); - + } } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/trigger/RecomputeTriggerHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/trigger/RecomputeTriggerHandler.java index ab2f6c6549d..ce91d9e1289 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/trigger/RecomputeTriggerHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/trigger/RecomputeTriggerHandler.java @@ -50,38 +50,38 @@ */ @Component public class RecomputeTriggerHandler implements TriggerHandler { - + public static final String HANDLER_URI = ModelConstants.NS_MODEL_TRIGGER_PREFIX + "/recompute/handler-3"; - + private static final transient Trace LOGGER = TraceManager.getTrace(RecomputeTriggerHandler.class); @Autowired(required = true) private TriggerHandlerRegistry triggerHandlerRegistry; - + @Autowired(required = true) private Clockwork clockwork; - + @Autowired(required=true) private PrismContext prismContext; - + @Autowired(required = true) private ProvisioningService provisioningService; - + @Autowired(required = true) private ContextFactory contextFactory; - + @PostConstruct private void initialize() { triggerHandlerRegistry.register(HANDLER_URI, this); } - + /* (non-Javadoc) * @see com.evolveum.midpoint.model.trigger.TriggerHandler#handle(com.evolveum.midpoint.prism.PrismObject) */ @Override public void handle(PrismObject object, TriggerType trigger, Task task, OperationResult result) { try { - + LOGGER.trace("Recomputing {}", object); // Reconcile option used for compatibility. TODO: do we need it? LensContext lensContext = contextFactory.createRecomputeContext(object, ModelExecuteOptions.createReconcile(), task, result); @@ -90,7 +90,7 @@ public void handle(PrismObject object, TriggerType tri } clockwork.run(lensContext, task, result); LOGGER.trace("Recomputing of {}: {}", object, result.getStatus()); - + } catch (SchemaException e) { LOGGER.error(e.getMessage(), e); } catch (ObjectNotFoundException e) { diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/trigger/TriggerHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/trigger/TriggerHandler.java index 363f7c2c9fd..621e4358ab9 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/trigger/TriggerHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/trigger/TriggerHandler.java @@ -26,7 +26,7 @@ * */ public interface TriggerHandler { - + void handle(PrismObject object, TriggerType trigger, Task task, OperationResult result); } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/trigger/TriggerHandlerRegistry.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/trigger/TriggerHandlerRegistry.java index 09d380e4aed..33c41f17337 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/trigger/TriggerHandlerRegistry.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/trigger/TriggerHandlerRegistry.java @@ -26,13 +26,13 @@ */ @Component public class TriggerHandlerRegistry { - + private Map triggerHandlerMap = new HashMap(); - + public void register(String uri, TriggerHandler handler) { triggerHandlerMap.put(uri, handler); } - + public TriggerHandler getHandler(String uri) { return triggerHandlerMap.get(uri); } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/trigger/TriggerScannerTaskHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/trigger/TriggerScannerTaskHandler.java index 100c4ecf711..6d244359744 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/trigger/TriggerScannerTaskHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/trigger/TriggerScannerTaskHandler.java @@ -54,7 +54,7 @@ import static com.evolveum.midpoint.xml.ns._public.common.common_3.TriggerType.F_TIMESTAMP; /** - * + * * @author Radovan Semancik * */ @@ -65,14 +65,14 @@ public class TriggerScannerTaskHandler extends AbstractScannerTaskHandler handl .endBlock() .buildFilter(); } - + query.setFilter(filter); return query; } @@ -155,7 +155,7 @@ protected void finish(AbstractScannerResultHandler handler, TaskRunR @Override protected AbstractScannerResultHandler createHandler(TaskRunResult runResult, final Task coordinatorTask, OperationResult opResult) { - + AbstractScannerResultHandler handler = new AbstractScannerResultHandler( coordinatorTask, TriggerScannerTaskHandler.class.getName(), "trigger", "trigger task", taskManager) { @Override @@ -170,7 +170,7 @@ protected boolean handleObject(PrismObject object, Task workerTask, private void fireTriggers(AbstractScannerResultHandler handler, PrismObject object, Task workerTask, Task coordinatorTask, OperationResult result) throws SchemaException, - ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ObjectAlreadyExistsException, + ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ObjectAlreadyExistsException, ConfigurationException, PolicyViolationException, SecurityViolationException { PrismContainer triggerContainer = object.findContainer(F_TRIGGER); if (triggerContainer == null) { @@ -207,7 +207,7 @@ private List getSortedTriggers(List handler, XMLGregorianCalendar timestamp) { if (handler.getThisScanTimestamp().compare(timestamp) == DatatypeConstants.LESSER) { diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/AbstractScannerResultHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/AbstractScannerResultHandler.java index 2d9acbff509..ab82ae53988 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/AbstractScannerResultHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/AbstractScannerResultHandler.java @@ -8,7 +8,7 @@ public abstract class AbstractScannerResultHandler extends AbstractSearchIterativeResultHandler { - + protected XMLGregorianCalendar lastScanTimestamp; protected XMLGregorianCalendar thisScanTimestamp; @@ -33,6 +33,6 @@ public void setThisScanTimestamp(XMLGregorianCalendar thisScanTimestamp) { this.thisScanTimestamp = thisScanTimestamp; } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/AbstractScannerTaskHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/AbstractScannerTaskHandler.java index 715c0a97f52..f5b96435f64 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/AbstractScannerTaskHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/AbstractScannerTaskHandler.java @@ -42,17 +42,17 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; /** - * + * * @author Radovan Semancik * */ @Component -public abstract class AbstractScannerTaskHandler> +public abstract class AbstractScannerTaskHandler> extends AbstractSearchIterativeTaskHandler { - + @Autowired(required = true) protected Clock clock; - + private static final transient Trace LOGGER = TraceManager.getTrace(AbstractScannerTaskHandler.class); public AbstractScannerTaskHandler(Class type, String taskName, String taskOperationPrefix) { @@ -66,23 +66,23 @@ protected boolean initializeRun(H handler, TaskRunResult runResult, if (!cont) { return cont; } - + XMLGregorianCalendar lastScanTimestamp = null; PrismProperty lastScanTimestampProperty = task.getExtensionProperty(SchemaConstants.MODEL_EXTENSION_LAST_SCAN_TIMESTAMP_PROPERTY_NAME); if (lastScanTimestampProperty != null) { lastScanTimestamp = lastScanTimestampProperty.getValue().getValue(); } handler.setLastScanTimestamp(lastScanTimestamp); - + handler.setThisScanTimestamp(clock.currentTimeXMLGregorianCalendar()); - + return true; } - + @Override protected void finish(H handler, TaskRunResult runResult, Task task, OperationResult opResult) throws SchemaException { super.finish(handler, runResult, task, opResult); - + PrismPropertyDefinition lastScanTimestampDef = new PrismPropertyDefinitionImpl<>( SchemaConstants.MODEL_EXTENSION_LAST_SCAN_TIMESTAMP_PROPERTY_NAME, DOMUtil.XSD_DATETIME, prismContext); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/AbstractSearchIterativeResultHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/AbstractSearchIterativeResultHandler.java index 029e6979fed..ef2de0be915 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/AbstractSearchIterativeResultHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/AbstractSearchIterativeResultHandler.java @@ -94,7 +94,7 @@ public AbstractSearchIterativeResultHandler(Task coordinatorTask, String taskOpe protected String getProcessShortName() { return processShortName; } - + protected String getProcessShortNameCapitalized() { return StringUtils.capitalize(processShortName); } @@ -459,15 +459,15 @@ public long heartbeat() { public long getProgress() { return objectsProcessed.get(); } - + public long getErrors() { return errors.get(); } - + public boolean isStopOnError() { return stopOnError; } - + public void setStopOnError(boolean stopOnError) { this.stopOnError = stopOnError; } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/AbstractSearchIterativeTaskHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/AbstractSearchIterativeTaskHandler.java index 81ee1c331cb..9a39e193489 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/AbstractSearchIterativeTaskHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/AbstractSearchIterativeTaskHandler.java @@ -62,7 +62,7 @@ * */ public abstract class AbstractSearchIterativeTaskHandler> implements TaskHandler { - + // WARNING! This task handler is efficiently singleton! // It is a spring bean and it is supposed to handle all search task instances // Therefore it must not have task-specific fields. It can only contain fields specific to @@ -77,16 +77,16 @@ public abstract class AbstractSearchIterativeTaskHandler handlers = Collections.synchronizedMap(new HashMap()); - + @Autowired protected TaskManager taskManager; - + @Autowired protected ModelObjectResolver modelObjectResolver; @@ -107,7 +107,7 @@ public abstract class AbstractSearchIterativeTaskHandler T resolveObjectRef(Class type, TaskRunResult runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR); return null; } - + return objectType; } - + @Override public void refreshStatus(Task task) { // Local task. No refresh needed. The Task instance has always fresh data. } /** - * Handler parameter may be used to pass task instance state between the calls. + * Handler parameter may be used to pass task instance state between the calls. */ protected abstract ObjectQuery createQuery(H handler, TaskRunResult runResult, Task task, OperationResult opResult) throws SchemaException; @@ -484,10 +484,10 @@ protected boolean useRepositoryDirectly(H resultHandler, TaskRunResult runResult protected abstract H createHandler(TaskRunResult runResult, Task coordinatorTask, OperationResult opResult) throws SchemaException, SecurityViolationException; - + /** * Used to properly initialize the "run", which is kind of task instance. The result handler is already created at this stage. - * Therefore this method may be used to "enrich" the result handler with some instance-specific data. + * Therefore this method may be used to "enrich" the result handler with some instance-specific data. */ protected boolean initializeRun(H handler, TaskRunResult runResult, Task task, OperationResult opResult) { // Nothing to do by default diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/AuditReindexTaskHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/AuditReindexTaskHandler.java index 710f038935f..116c7c0c9cc 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/AuditReindexTaskHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/AuditReindexTaskHandler.java @@ -38,7 +38,7 @@ public class AuditReindexTaskHandler implements TaskHandler { public static final String HANDLER_URI = ModelPublicConstants.AUDIT_REINDEX_TASK_HANDLER_URI; private static final String taskName = "AuditReindex"; - + private int maxResults = 20; private int firstResult = 0; @@ -67,11 +67,11 @@ public TaskRunResult run(Task coordinatorTask) { @Override public boolean handle(AuditEventRecord auditRecord) { - + auditService.reindexEntry(auditRecord); processedObjects.incrementAndGet(); - - return true; + + return true; } @Override @@ -84,7 +84,7 @@ public int getProgress() { return runResult; } - + try { LOGGER.trace("{}: expecting {} objects to be processed", taskName, expectedTotal); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/DebugReconciliationTaskResultListener.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/DebugReconciliationTaskResultListener.java index 5fd4174830a..4175eb77d27 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/DebugReconciliationTaskResultListener.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/DebugReconciliationTaskResultListener.java @@ -26,9 +26,9 @@ /** * Debugging listener for reconciliation tasks. - * - * This is not the best place for this object. But we have to live with it now. - * + * + * This is not the best place for this object. But we have to live with it now. + * * @author semancik * */ @@ -36,27 +36,27 @@ public class DebugReconciliationTaskResultListener implements ReconciliationTaskResultListener { private List results = Collections.synchronizedList(new ArrayList()); - + @Override public void process(ReconciliationTaskResult reconResult) { results.add(reconResult); } - + public void clear() { results.clear(); } - public void assertResult(String resourceOid, long expectedUnOpsCount, long expectedResourceReconCount, long expectedResourceReconErrors, + public void assertResult(String resourceOid, long expectedUnOpsCount, long expectedResourceReconCount, long expectedResourceReconErrors, long expectedShadowReconCount) { ReconciliationTaskResult result = findResult(resourceOid); assert result != null : "No recon result for resource "+resourceOid; - PrismAsserts.assertEquals("Wrong upOpsCount in recon result for resource "+resourceOid, + PrismAsserts.assertEquals("Wrong upOpsCount in recon result for resource "+resourceOid, expectedUnOpsCount, result.getUnOpsCount()); - PrismAsserts.assertEquals("Wrong resourceReconCount in recon result for resource "+resourceOid, + PrismAsserts.assertEquals("Wrong resourceReconCount in recon result for resource "+resourceOid, expectedResourceReconCount, result.getResourceReconCount()); - PrismAsserts.assertEquals("Wrong resourceReconErrors in recon result for resource "+resourceOid, + PrismAsserts.assertEquals("Wrong resourceReconErrors in recon result for resource "+resourceOid, expectedResourceReconErrors, result.getResourceReconErrors()); - PrismAsserts.assertEquals("Wrong shadowReconCount in recon result for resource "+resourceOid, + PrismAsserts.assertEquals("Wrong shadowReconCount in recon result for resource "+resourceOid, expectedShadowReconCount, result.getShadowReconCount()); } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/DeleteTaskHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/DeleteTaskHandler.java index 8fb67ae7be2..020c65c45cd 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/DeleteTaskHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/DeleteTaskHandler.java @@ -71,27 +71,27 @@ */ @Component public class DeleteTaskHandler implements TaskHandler { - + public static final String HANDLER_URI = ModelPublicConstants.DELETE_TASK_HANDLER_URI; public static final long PROGRESS_UPDATE_INTERVAL = 3000L; @Autowired(required=true) protected TaskManager taskManager; - + @Autowired(required=true) protected ModelService modelService; - + @Autowired(required = true) protected PrismContext prismContext; - + private static final transient Trace LOGGER = TraceManager.getTrace(DeleteTaskHandler.class); @PostConstruct private void initialize() { taskManager.registerHandler(HANDLER_URI, this); } - + @Override public TaskRunResult run(Task task) { try { @@ -101,16 +101,16 @@ public TaskRunResult run(Task task) { updateState(task); } } - + public TaskRunResult runInternal(Task task) { LOGGER.trace("Delete task run starting ({})", task); long startTimestamp = System.currentTimeMillis(); - + OperationResult opResult = new OperationResult("DeleteTask.run"); opResult.setStatus(OperationResultStatus.IN_PROGRESS); TaskRunResult runResult = new TaskRunResult(); runResult.setOperationResult(opResult); - + opResult.setSummarizeErrors(true); opResult.setSummarizePartialErrors(true); opResult.setSummarizeSuccesses(true); @@ -126,7 +126,7 @@ public TaskRunResult runInternal(Task task) { runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR); return runResult; } - + Class objectType; QName objectTypeName; PrismProperty objectTypePrismProperty = task.getExtensionProperty(SchemaConstants.MODEL_EXTENSION_OBJECT_TYPE); @@ -139,7 +139,7 @@ public TaskRunResult runInternal(Task task) { runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR); return runResult; } - + ObjectQuery query; try { query = QueryJaxbConvertor.createObjectQuery(objectType, queryType, prismContext); @@ -152,34 +152,34 @@ public TaskRunResult runInternal(Task task) { runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR); return runResult; } - + boolean optionRaw = true; PrismProperty optionRawPrismProperty = task.getExtensionProperty(SchemaConstants.MODEL_EXTENSION_OPTION_RAW); if (optionRawPrismProperty != null && optionRawPrismProperty.getRealValue() != null && !optionRawPrismProperty.getRealValue()) { optionRaw = false; } - + if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Deleting {}, raw={} using query:\n{}", + LOGGER.trace("Deleting {}, raw={} using query:\n{}", new Object[]{objectType.getSimpleName(), optionRaw, query.debugDump()}); } - + boolean countObjectsOnStart = true; // TODO long progress = 0; - + Integer maxSize = 100; ObjectPaging paging = ObjectPaging.createPaging(0, maxSize); query.setPaging(paging); query.setAllowPartialResults(true); - + Collection> searchOptions = null; ModelExecuteOptions execOptions = null; if (optionRaw) { searchOptions = SelectorOptions.createCollection(GetOperationOptions.createRaw()); execOptions = ModelExecuteOptions.createRaw(); } - + try { // counting objects can be within try-catch block, because the handling is similar to handling errors within searchIterative @@ -207,17 +207,17 @@ public TaskRunResult runInternal(Task task) { SearchResultList> objects; while (true) { - + objects = modelService.searchObjects(objectType, query, searchOptions, task, opResult); - + if (objects.isEmpty()) { break; } - + int skipped = 0; for(PrismObject object: objects) { - - if (!optionRaw && ShadowType.class.isAssignableFrom(objectType) + + if (!optionRaw && ShadowType.class.isAssignableFrom(objectType) && Boolean.TRUE == ((ShadowType)(object.asObjectable())).isProtectedObject()) { LOGGER.debug("Skipping delete of protected object {}", object); skipped++; @@ -252,14 +252,14 @@ public TaskRunResult runInternal(Task task) { opResult.summarize(); if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Search returned {} objects, {} skipped, progress: {}, result:\n{}", + LOGGER.trace("Search returned {} objects, {} skipped, progress: {}, result:\n{}", new Object[]{objects.size(), skipped, progress, opResult.debugDump()}); } - + if (objects.size() == skipped) { break; } - + } } catch (ObjectAlreadyExistsException | ObjectNotFoundException | SchemaException @@ -294,18 +294,18 @@ public TaskRunResult runInternal(Task task) { opResult.createSubresult(DeleteTaskHandler.class.getName() + ".statistics").recordStatus(OperationResultStatus.SUCCESS, statistics); LOGGER.info(finishMessage + statistics); - + LOGGER.trace("Run finished (task {}, run result {})", new Object[]{task, runResult}); return runResult; - + } @Override public Long heartbeat(Task task) { return task.getProgress(); } - + @Override public void refreshStatus(Task task) { // Local task. No refresh needed. The Task instance has always fresh data. @@ -325,5 +325,5 @@ private void updateState(Task task) { task.storeOperationStats(); // includes savePendingModifications - this is necessary for the progress to be immediately available in GUI } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/RestServiceUtil.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/RestServiceUtil.java index b03ce4be045..117687b9ab3 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/RestServiceUtil.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/RestServiceUtil.java @@ -65,53 +65,53 @@ public class RestServiceUtil { public static Response handleException(OperationResult result, Exception ex) { return createErrorResponseBuilder(result, ex).build(); } - + public static Response createResponse(Response.Status statusCode, OperationResult result) { - + return createResponse(statusCode, null, result, false); - + } - + public static Response createResponse(Response.Status statusCode, T body, OperationResult result) { - + return createResponse(statusCode, body, result, false); - + } - + public static Response createResponse(Response.Status statusCode, T body, OperationResult result, boolean sendOriginObjectIfNotSuccess) { result.computeStatusIfUnknown(); - + if (result.isPartialError()) { return createBody(Response.status(250), sendOriginObjectIfNotSuccess, body, result).build(); } else if (result.isHandledError()) { return createBody(Response.status(240), sendOriginObjectIfNotSuccess, body, result).build(); - } - + } + return body == null ? Response.status(statusCode).build() : Response.status(statusCode).entity(body).build(); } - + private static ResponseBuilder createBody(ResponseBuilder builder, boolean sendOriginObjectIfNotSuccess, T body, OperationResult result) { if (sendOriginObjectIfNotSuccess) { return builder.entity(body); } return builder.entity(result); - + } - + public static Response createResponse(Response.Status statusCode, URI location, OperationResult result) { result.computeStatusIfUnknown(); - + if (result.isPartialError()) { return createBody(Response.status(250), false, null, result).location(location).build(); } else if (result.isHandledError()) { return createBody(Response.status(240), false, null, result).location(location).build(); - } - - + } + + return location == null ? Response.status(statusCode).build() : Response.status(statusCode).location(location).build(); } - - + + public static Response.ResponseBuilder createErrorResponseBuilder(OperationResult result, Exception ex) { if (ex instanceof ObjectNotFoundException) { @@ -125,13 +125,13 @@ public static Response.ResponseBuilder createErrorResponseBuilder(OperationResul if (ex instanceof SecurityViolationException || ex instanceof AuthorizationException) { return createErrorResponseBuilder(Response.Status.FORBIDDEN, result); } - + if (ex instanceof ConfigurationException) { return createErrorResponseBuilder(Response.Status.BAD_GATEWAY, result); } - - if (ex instanceof SchemaException - || ex instanceof NoFocusNameSchemaException + + if (ex instanceof SchemaException + || ex instanceof NoFocusNameSchemaException || ex instanceof ExpressionEvaluationException) { return createErrorResponseBuilder(Response.Status.BAD_REQUEST, result); } @@ -177,18 +177,18 @@ public static Response.ResponseBuilder createResultHeaders(Response.ResponseBuil // .header(OPERATION_RESULT_STATUS, OperationResultStatus.createStatusType(result.getStatus()).value()) // .header(OPERATION_RESULT_MESSAGE, result.getMessage()); } - + public static void createAbortMessage(ContainerRequestContext requestCtx){ requestCtx.abortWith(Response.status(Status.UNAUTHORIZED) .header("WWW-Authenticate", RestAuthenticationMethod.BASIC.getMethod() + " realm=\"midpoint\", " + RestAuthenticationMethod.SECURITY_QUESTIONS.getMethod()).build()); } - + public static void createSecurityQuestionAbortMessage(ContainerRequestContext requestCtx, String secQChallenge){ String challenge = ""; if (StringUtils.isNotBlank(secQChallenge)) { challenge = " " + Base64Utility.encode(secQChallenge.getBytes()); } - + requestCtx.abortWith(Response.status(Status.UNAUTHORIZED) .header("WWW-Authenticate", RestAuthenticationMethod.SECURITY_QUESTIONS.getMethod() + challenge) diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/Utils.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/Utils.java index 684b57cf87a..95f428566b6 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/Utils.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/util/Utils.java @@ -74,9 +74,9 @@ public final class Utils { private static final Trace LOGGER = TraceManager.getTrace(Utils.class); private static final String OPERATION_RESOLVE_REFERENCE = ObjectImporter.class.getName() + ".resolveReference"; - + @Deprecated // use RepositoryService.objectSearchIterative instead - public static void searchIterative(RepositoryService repositoryService, Class type, ObjectQuery query, + public static void searchIterative(RepositoryService repositoryService, Class type, ObjectQuery query, Handler> handler, int blockSize, OperationResult opResult) throws SchemaException { ObjectQuery myQuery = query.clone(); // TODO: better handle original values in paging @@ -333,7 +333,7 @@ private static void resolveRef(PrismReferenceValue refVal, RepositoryService rep refVal.setOid(oid); result.recordSuccessIfUnknown(); } - + private static boolean containExpression(ObjectFilter filter){ if (filter == null){ return false; @@ -380,7 +380,7 @@ public static ObjectClassComplexTypeDefinition determineObjectClass(RefinedResou private static ObjectClassComplexTypeDefinition determineObjectClassInternal( RefinedResourceSchema refinedSchema, QName objectclass, ShadowKindType kind, String intent, Object source) throws SchemaException { - + if (kind == null && intent == null && objectclass != null) { // Return generic object class definition from resource schema. No kind/intent means that we want // to process all kinds and intents in the object class. @@ -390,7 +390,7 @@ private static ObjectClassComplexTypeDefinition determineObjectClassInternal( } return objectClassDefinition; } - + RefinedObjectClassDefinition refinedObjectClassDefinition; if (kind != null) { @@ -407,7 +407,7 @@ private static ObjectClassComplexTypeDefinition determineObjectClassInternal( } refinedObjectClassDefinition = null; } - + return refinedObjectClassDefinition; } @@ -415,7 +415,7 @@ public static void encrypt(Collection> deltas, OperationResult result) { // Encrypt values even before we log anything. We want to avoid showing unencrypted values in the logfiles if (!ModelExecuteOptions.isNoCrypt(options)) { - for(ObjectDelta delta: deltas) { + for(ObjectDelta delta: deltas) { try { CryptoUtil.encryptValues(protector, delta); } catch (EncryptionException e) { @@ -451,7 +451,7 @@ public static void setRequestee(Task task, PrismObject object) { public static void clearRequestee(Task task) { setRequestee(task, (PrismObject) null); } - + public static boolean isDryRun(Task task) throws SchemaException { Boolean dryRun = isDryRunInternal(task); if (dryRun == null && task.isLightweightAsynchronousTask() && task.getParentForLightweightAsynchronousTask() != null) { @@ -474,7 +474,7 @@ private static Boolean isDryRunInternal(Task task) throws SchemaException{ } return item.getValues().iterator().next().getValue(); } - + public static ModelExecuteOptions getModelExecuteOptions(Task task) throws SchemaException { Validate.notNull(task, "Task must not be null."); if (task.getExtension() == null) { @@ -519,7 +519,7 @@ public static ExpressionVariables getDefaultExpressionVariables(@NotNull LensCon variables.addVariableDefinition(ExpressionConstants.VAR_CONFIGURATION, context.getSystemConfiguration()); return variables; } - + public static ExpressionVariables getDefaultExpressionVariables(ObjectType focusType, ShadowType shadowType, ResourceType resourceType, SystemConfigurationType configurationType) { PrismObject focus = null; @@ -540,17 +540,17 @@ public static ExpressionVariables getDefaultExpressionVariables(ObjectType focus } return getDefaultExpressionVariables(focus, shadow, null, resource, configuration, null); } - + public static ExpressionVariables getDefaultExpressionVariables(PrismObject focus, - PrismObject shadow, ResourceShadowDiscriminator discr, + PrismObject shadow, ResourceShadowDiscriminator discr, PrismObject resource, PrismObject configuration, LensElementContext affectedElementContext) { ExpressionVariables variables = new ExpressionVariables(); addDefaultExpressionVariables(variables, focus, shadow, discr, resource, configuration, affectedElementContext); return variables; } - + public static void addDefaultExpressionVariables(ExpressionVariables variables, PrismObject focus, - PrismObject shadow, ResourceShadowDiscriminator discr, + PrismObject shadow, ResourceShadowDiscriminator discr, PrismObject resource, PrismObject configuration, LensElementContext affectedElementContext) { // Legacy. And convenience/understandability. @@ -564,12 +564,12 @@ public static void addDefaultExpressionVariables(Expressi variables.addVariableDefinition(ExpressionConstants.VAR_PROJECTION, shadow); variables.addVariableDefinition(ExpressionConstants.VAR_RESOURCE, resource); variables.addVariableDefinition(ExpressionConstants.VAR_CONFIGURATION, configuration); - + if (affectedElementContext != null) { variables.addVariableDefinition(ExpressionConstants.VAR_OPERATION, affectedElementContext.getOperation().getValue()); } } - + public static void addAssignmentPathVariables(AssignmentPathVariables assignmentPathVariables, ExpressionVariables expressionVariables) { if (assignmentPathVariables != null) { expressionVariables.addVariableDefinition(ExpressionConstants.VAR_ASSIGNMENT, assignmentPathVariables.getMagicAssignment()); @@ -594,7 +594,7 @@ public static String getPolicyDesc(ObjectSynchronizationType synchronizationPoli } return synchronizationPolicy.toString(); } - + public static PrismReferenceValue determineAuditTargetDeltaOps(Collection> deltaOps) { if (deltaOps == null || deltaOps.isEmpty()) { return null; @@ -613,7 +613,7 @@ public static PrismReferenceValue determineAuditTargetDeltaOps(Collection> deltas) { if (deltas == null || deltas.isEmpty()) { return null; @@ -641,7 +641,7 @@ public static PrismReferenceValue getAditTarget(ObjectDelta List evaluateScript( ScriptExpression scriptExpression, LensContext lensContext, ExpressionVariables variables, boolean useNew, String shortDesc, Task task, OperationResult parentResult) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException { ExpressionEnvironment env = new ExpressionEnvironment<>(); @@ -658,5 +658,5 @@ public static List evaluateScrip // } } } - + } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/validator/ResourceValidatorImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/validator/ResourceValidatorImpl.java index e3847f6f27d..e663fe8180f 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/validator/ResourceValidatorImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/validator/ResourceValidatorImpl.java @@ -82,10 +82,10 @@ public class ResourceValidatorImpl implements ResourceValidator { @Autowired private MatchingRuleRegistry matchingRuleRegistry; - + @Autowired private PrismContext prismContext; - + private class ResourceValidationContext { @NotNull final PrismObject resourceObject; @NotNull final ObjectReferenceType resourceRef; @@ -132,7 +132,7 @@ public ValidationResult validate(@NotNull PrismObject resourceObje } ResourceValidationContext ctx = new ResourceValidationContext(resourceObject, scope, task, vr, resourceSchema, bundle); - + SchemaHandlingType schemaHandling = resource.getSchemaHandling(); if (schemaHandling != null) { checkSchemaHandlingDuplicateObjectTypes(ctx, schemaHandling); 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 99effd2bd48..40cfeacf14d 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 @@ -48,105 +48,105 @@ * */ public class AbstractInternalModelIntegrationTest extends AbstractModelImplementationIntegrationTest { - + 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(); - + public static final File SECURITY_POLICY_FILE = new File(COMMON_DIR, "security-policy.xml"); public static final String SECURITY_POLICY_OID = "28bf845a-b107-11e3-85bc-001e8c717e5b"; - + public static final File USER_ADMINISTRATOR_FILE = new File(COMMON_DIR, "user-administrator.xml"); protected static final String USER_ADMINISTRATOR_NAME = "administrator"; protected static final String USER_ADMINISTRATOR_OID = "00000000-0000-0000-0000-000000000002"; - + 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"; protected static final String USER_JACK_USERNAME = "jack"; protected static final String USER_JACK_PASSWORD = "deadmentellnotales"; - + protected static final File USER_BARBOSSA_FILE = new File(COMMON_DIR, "user-barbossa.xml"); protected static final String USER_BARBOSSA_OID = "c0c010c0-d34d-b33f-f00d-111111111112"; - + protected static final File USER_GUYBRUSH_FILE = new File(COMMON_DIR, "user-guybrush.xml"); protected static final String USER_GUYBRUSH_OID = "c0c010c0-d34d-b33f-f00d-111111111116"; protected static final String USER_GUYBRUSH_USERNAME = "guybrush"; - + static final File USER_ELAINE_FILE = new File(COMMON_DIR, "user-elaine.xml"); protected static final String USER_ELAINE_OID = "c0c010c0-d34d-b33f-f00d-11111111111e"; 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 String USER_LARGO_OID = "c0c010c0-d34d-b33f-f00d-111111111118"; - + public 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 ACCOUNT_HBARBOSSA_DUMMY_FILE = new File(COMMON_DIR, "account-hbarbossa-dummy.xml"); protected static final String ACCOUNT_HBARBOSSA_DUMMY_OID = "c0c010c0-d34d-b33f-f00d-222211111112"; protected static final String ACCOUNT_HBARBOSSA_DUMMY_USERNAME = "hbarbossa"; public static final File ACCOUNT_SHADOW_JACK_DUMMY_FILE = new File(COMMON_DIR, "account-shadow-jack-dummy.xml"); public static final String ACCOUNT_JACK_DUMMY_USERNAME = "jack"; - + public static final File ACCOUNT_HERMAN_DUMMY_FILE = new File(COMMON_DIR, "account-herman-dummy.xml"); public static final String ACCOUNT_HERMAN_DUMMY_OID = "22220000-2200-0000-0000-444400004444"; public static final String ACCOUNT_HERMAN_DUMMY_USERNAME = "ht"; - + public static final File ACCOUNT_SHADOW_GUYBRUSH_DUMMY_FILE = new File(COMMON_DIR, "account-shadow-guybrush-dummy.xml"); public static final String ACCOUNT_SHADOW_GUYBRUSH_OID = "22226666-2200-6666-6666-444400004444"; public static final String ACCOUNT_GUYBRUSH_DUMMY_USERNAME = "guybrush"; public static final String ACCOUNT_GUYBRUSH_DUMMY_FULLNAME = "Guybrush Threepwood"; public static final File ACCOUNT_GUYBRUSH_DUMMY_FILE = new File(COMMON_DIR, "account-guybrush-dummy.xml"); - + public static final File ACCOUNT_SHADOW_ELAINE_DUMMY_FILE = new File(COMMON_DIR, "account-elaine-dummy.xml"); public static final String ACCOUNT_SHADOW_ELAINE_DUMMY_OID = "c0c010c0-d34d-b33f-f00d-22220004000e"; public static final String ACCOUNT_ELAINE_DUMMY_USERNAME = USER_ELAINE_USERNAME; - + public static final File ENTITLEMENT_SHADOW_PIRATE_DUMMY_FILE = new File(COMMON_DIR, "entitlement-shadow-pirate-dummy.xml"); public static final String ENTITLEMENT_PIRATE_DUMMY_NAME = "pirate"; public static final File ACCOUNT_SHADOW_CALYPSO_DUMMY_FILE = new File(COMMON_DIR, "account-shadow-calypso-dummy.xml"); public static final String ACCOUNT_CALYPSO_DUMMY_USERNAME = "calypso"; - + public static final File RESOURCE_DUMMY_FILE = new File(COMMON_DIR, "resource-dummy.xml"); public static final String RESOURCE_DUMMY_OID = "10000000-0000-0000-0000-000000000004"; public static final String RESOURCE_DUMMY_NAMESPACE = MidPointConstants.NS_RI; public static final QName RESOURCE_DUMMY_ACCOUNT_OBJECTCLASS_QNAME = new QName(RESOURCE_DUMMY_NAMESPACE, "AccountObjectClass"); public static final QName RESOURCE_DUMMY_PRIVILEGE_OBJECTCLASS_QNAME = new QName(RESOURCE_DUMMY_NAMESPACE, "CustomprivilegeObjectClass"); - + public static final File USER_TEMPLATE_FILE = new File(COMMON_DIR, "user-template.xml"); public static final String USER_TEMPLATE_OID = "10000000-0000-0000-0000-000000000002"; - + protected static final File PASSWORD_POLICY_GLOBAL_FILE = new File(COMMON_DIR, "password-policy-global.xml"); protected static final String PASSWORD_POLICY_GLOBAL_OID = "12344321-0000-0000-0000-000000000003"; - + 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; protected UserType userTypeBarbossa; protected UserType userTypeGuybrush; protected UserType userTypeElaine; - + protected MockClockworkHook mockClockworkHook; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { LOGGER.trace("initSystem"); super.initSystem(initTask, initResult); - + // We want logging config from logback-test.xml and not from system config object InternalsConfig.setAvoidLoggingChange(true); - + mockClockworkHook = new MockClockworkHook(); hookRegistry.registerChangeHook(MOCK_CLOCKWORK_HOOK_URL, mockClockworkHook); - + modelService.postInit(initResult); - + // System Configuration try { repoAddObjectFromFile(SYSTEM_CONFIGURATION_FILE, initResult); @@ -154,21 +154,21 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti throw new ObjectAlreadyExistsException("System configuration already exists in repository;" + "looks like the previous test haven't cleaned it up", e); } - + repoAddObjectFromFile(SECURITY_POLICY_FILE, initResult); - + // Administrator repoAddObjectFromFile(ROLE_SUPERUSER_FILE, initResult); userAdministrator = repoAddObjectFromFile(USER_ADMINISTRATOR_FILE, initResult); login(userAdministrator); - + // User Templates repoAddObjectFromFile(USER_TEMPLATE_FILE, initResult); // Resources - + initDummyResourcePirate(null, RESOURCE_DUMMY_FILE, RESOURCE_DUMMY_OID, initTask, initResult); - + // We need to create Barbossa's account in exactly the shape that is given by his existing assignments // otherwise any substantial change will trigger reconciliation and the recon changes will interfere with // the tests @@ -181,21 +181,21 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, "rum"); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "Arr!"); getDummyResource().addAccount(account); - + getDummyResourceController().addAccount(ACCOUNT_HERMAN_DUMMY_USERNAME, "Herman Toothrot", "Monkey Island"); getDummyResourceController().addAccount(ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood", "Melee Island"); - + // Accounts repoAddObjectFromFile(ACCOUNT_HBARBOSSA_DUMMY_FILE, initResult); repoAddObjectFromFile(ACCOUNT_SHADOW_GUYBRUSH_DUMMY_FILE, initResult); repoAddObjectFromFile(ACCOUNT_SHADOW_ELAINE_DUMMY_FILE, initResult); - + // Users userTypeJack = repoAddObjectFromFile(USER_JACK_FILE, UserType.class, initResult).asObjectable(); userTypeBarbossa = repoAddObjectFromFile(USER_BARBOSSA_FILE, UserType.class, initResult).asObjectable(); userTypeGuybrush = repoAddObjectFromFile(USER_GUYBRUSH_FILE, UserType.class, initResult).asObjectable(); userTypeElaine = repoAddObjectFromFile(USER_ELAINE_FILE, UserType.class, initResult).asObjectable(); - + } } 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 df12493d24c..33adde8b317 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 @@ -58,52 +58,52 @@ * @author mederly */ public class AbstractModelImplementationIntegrationTest extends AbstractModelIntegrationTest { - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); } - + protected LensContext createLensContext(Class focusType) { return new LensContext(focusType, prismContext, provisioningService); } - + protected LensContext createUserLensContext() { return new LensContext(UserType.class, prismContext, provisioningService); } - - protected LensFocusContext fillContextWithFocus(LensContext context, PrismObject focus) + + protected LensFocusContext fillContextWithFocus(LensContext context, PrismObject focus) throws SchemaException, ObjectNotFoundException { LensFocusContext focusContext = context.getOrCreateFocusContext(); focusContext.setLoadedObject(focus); return focusContext; } - + protected LensFocusContext fillContextWithFocus(LensContext context, Class type, String userOid, OperationResult result) throws SchemaException, ObjectNotFoundException { PrismObject focus = repositoryService.getObject(type, userOid, null, result); return fillContextWithFocus(context, focus); } - + protected LensFocusContext fillContextWithUser(LensContext context, String userOid, OperationResult result) throws SchemaException, ObjectNotFoundException { return fillContextWithFocus(context, UserType.class, userOid, result); } - - + + protected void fillContextWithFocus(LensContext context, File file) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, IOException { PrismObject user = PrismTestUtil.parseObject(file); fillContextWithFocus(context, user); } - + protected void fillContextWithEmtptyAddUserDelta(LensContext context, OperationResult result) throws SchemaException { ObjectDelta userDelta = ObjectDelta.createEmptyAddDelta(UserType.class, null, prismContext); LensFocusContext focusContext = context.getOrCreateFocusContext(); focusContext.setPrimaryDelta(userDelta); } - + protected void fillContextWithAddUserDelta(LensContext context, PrismObject user) throws SchemaException, EncryptionException { CryptoUtil.encryptValues(protector, user); ObjectDelta userDelta = ObjectDelta.createAddDelta(user); @@ -131,7 +131,7 @@ protected LensProjectionContext fillContextWithAccount(LensContext con String resourceOid = accountType.getResourceRef().getOid(); ResourceType resourceType = provisioningService.getObject(ResourceType.class, resourceOid, null, task, result).asObjectable(); applyResourceSchema(accountType, resourceType); - ResourceShadowDiscriminator rat = new ResourceShadowDiscriminator(resourceOid, + ResourceShadowDiscriminator rat = new ResourceShadowDiscriminator(resourceOid, ShadowKindType.ACCOUNT, ShadowUtil.getIntent(accountType)); LensProjectionContext accountSyncContext = context.findOrCreateProjectionContext(rat); accountSyncContext.setOid(account.getOid()); @@ -151,7 +151,7 @@ protected ObjectDelta addFocusModificationToContext( modElement, context.getFocusClass(), prismContext); return addFocusDeltaToContext(context, focusDelta); } - + protected ObjectDelta addFocusDeltaToContext( LensContext context, ObjectDelta focusDelta) throws SchemaException { LensFocusContext focusContext = context.getOrCreateFocusContext(); @@ -174,13 +174,13 @@ protected ObjectDelta addModificationToContextReplaceUserProperty( 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 { @@ -229,18 +229,18 @@ protected ObjectDelta addSyncModificationToContextReplaceAccount accCtx.addAccountSyncDelta(accountDelta); return accountDelta; } - + protected ObjectDelta addModificationToContextAssignRole( LensContext context, String userOid, String roleOid) throws SchemaException { return addModificationToContextAssignRole(context, userOid, roleOid, null); } - + protected ObjectDelta addModificationToContextAssignRole( LensContext context, String userOid, String roleOid, Consumer modificationBlock) throws SchemaException { LensFocusContext focusContext = context.getOrCreateFocusContext(); - ObjectDelta userDelta = createAssignmentUserDelta(userOid, + ObjectDelta userDelta = createAssignmentUserDelta(userOid, roleOid, RoleType.COMPLEX_TYPE, null, modificationBlock, true); focusContext.addPrimaryDelta(userDelta); return userDelta; @@ -250,13 +250,13 @@ protected ObjectDelta addModificationToContextUnassignRole( LensContext context, String userOid, String roleOid) throws SchemaException { LensFocusContext focusContext = context.getOrCreateFocusContext(); - ObjectDelta userDelta = createAssignmentUserDelta(userOid, + ObjectDelta userDelta = createAssignmentUserDelta(userOid, roleOid, RoleType.COMPLEX_TYPE, null, null, null, false); focusContext.addPrimaryDelta(userDelta); return userDelta; } - protected ObjectDelta createAccountDelta(LensProjectionContext accCtx, String accountOid, + protected ObjectDelta createAccountDelta(LensProjectionContext accCtx, String accountOid, String attributeLocalName, T... propertyValues) throws SchemaException { ResourceType resourceType = accCtx.getResource(); QName attrQName = new QName(ResourceTypeUtil.getResourceNamespace(resourceType), attributeLocalName); @@ -273,20 +273,20 @@ protected ObjectDelta createAccountDelta(LensProjectionContext a /** * Breaks user assignment delta in the context by inserting some empty value. This may interfere with comparing the values to - * existing user values. + * existing user values. */ protected void breakAssignmentDelta(LensContext context) throws SchemaException { LensFocusContext focusContext = context.getFocusContext(); ObjectDelta userPrimaryDelta = focusContext.getPrimaryDelta(); - breakAssignmentDelta(userPrimaryDelta); + breakAssignmentDelta(userPrimaryDelta); } - + protected void makeImportSyncDelta(LensProjectionContext accContext) { PrismObject syncAccountToAdd = accContext.getObjectOld().clone(); ObjectDelta syncDelta = ObjectDelta.createAddDelta(syncAccountToAdd); accContext.setSyncDelta(syncDelta); } - + protected void assertNoUserPrimaryDelta(LensContext context) { LensFocusContext focusContext = context.getFocusContext(); ObjectDelta userPrimaryDelta = focusContext.getPrimaryDelta(); @@ -302,7 +302,7 @@ protected void assertUserPrimaryDelta(LensContext context) { 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(); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/ModelWebServiceTest.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/ModelWebServiceTest.java index 471ba9f3227..da713002739 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/ModelWebServiceTest.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/ModelWebServiceTest.java @@ -86,7 +86,7 @@ public class ModelWebServiceTest extends AbstractTestNGSpringContextTests { @Autowired(required = true) @Qualifier("cacheRepositoryService") RepositoryService repositoryService; - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); @@ -124,7 +124,7 @@ public void before() { // } // Assert.fail("add must fail."); // } - + @Test(expectedExceptions = FaultMessage.class) public void testGetNullOid() throws FaultMessage { try { @@ -244,7 +244,7 @@ public void getNonexistingObject() throws FaultMessage, ObjectNotFoundException, // @Test(expectedExceptions = FaultMessage.class) public void nullQueryType() throws FaultMessage, SchemaException, IOException, JAXBException { - + try { final UserType expectedUser = (UserType) PrismTestUtil.parseObject(new File( TEST_FOLDER_CONTROLLER, "./addObject/add-user-without-name.xml")).asObjectable(); @@ -258,7 +258,7 @@ public void nullQueryType() throws FaultMessage, SchemaException, IOException, J } finally { SecurityContextHolder.getContext().setAuthentication(null); } - + } // @Test(expectedExceptions = FaultMessage.class) @@ -276,7 +276,7 @@ public void nullQueryTypeAndPaging() throws FaultMessage, SchemaException, IOExc } finally { SecurityContextHolder.getContext().setAuthentication(null); } - + } @Test(expectedExceptions = FaultMessage.class) @@ -367,7 +367,7 @@ public void emptyAccountOidListAccountShadowOwner() throws FaultMessage { } Assert.fail("Illegal argument exception must be thrown"); } - + private void setSecurityContext(UserType user) { SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken( new MidPointPrincipal(user), null)); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/SpringApplicationContextTest.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/SpringApplicationContextTest.java index be5ea4eab38..8f6163603da 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/SpringApplicationContextTest.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/SpringApplicationContextTest.java @@ -25,11 +25,11 @@ import com.evolveum.midpoint.repo.api.RepositoryService; /** - * + * * Test of spring application context initialization - * + * * @author Igor Farinic - * + * */ @ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) public class SpringApplicationContextTest extends AbstractTestNGSpringContextTests { 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 c46aae06dae..a30d189c0df 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 @@ -49,25 +49,25 @@ @ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestRefinedSchema extends AbstractInternalModelIntegrationTest { - + protected static final File TEST_DIR = new File("src/test/resources/refinedschema"); - - public static final File TASK_RECONCILE_DUMMY_OBJECTCLASS_FILE = new File(TEST_DIR, + + public static final File TASK_RECONCILE_DUMMY_OBJECTCLASS_FILE = new File(TEST_DIR, "task-reconcile-dummy-objectclass.xml"); public static final String TASK_RECONCILE_DUMMY_OBJECTCLASS_OID = "bed15976-e604-11e5-a181-af0dade5e5a0"; - public static final File TASK_RECONCILE_DUMMY_KIND_INTENT_FILE = new File(TEST_DIR, + public static final File TASK_RECONCILE_DUMMY_KIND_INTENT_FILE = new File(TEST_DIR, "task-reconcile-dummy-kind-intent.xml"); public static final String TASK_RECONCILE_DUMMY_KIND_INTENT_OID = "d4cd18f2-e60c-11e5-a806-3faae6c13aff"; - public static final File TASK_RECONCILE_DUMMY_KIND_INTENT_OBJECTCLASS_FILE = new File(TEST_DIR, + public static final File TASK_RECONCILE_DUMMY_KIND_INTENT_OBJECTCLASS_FILE = new File(TEST_DIR, "task-reconcile-dummy-kind-intent-objectclass.xml"); public static final String TASK_RECONCILE_DUMMY_KIND_INTENT_OBJECTCLASS_OID = "3f2a1140-e60e-11e5-adb7-776abfbb2227"; - + private RefinedResourceSchema refinedSchema; private RefinedResourceSchema refinedSchemaModel; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -82,13 +82,13 @@ public void test000Sanity() throws Exception { // WHEN refinedSchema = RefinedResourceSchemaImpl.getRefinedSchema(getDummyResourceType(), prismContext); - + display("Dummy refined schema", refinedSchema); - + // THEN getDummyResourceController().assertRefinedSchemaSanity(refinedSchema); } - + @Test public void test010SanityModel() throws Exception { final String TEST_NAME = "test010SanityModel"; @@ -96,12 +96,12 @@ public void test010SanityModel() throws Exception { // WHEN refinedSchemaModel = RefinedResourceSchemaImpl.getRefinedSchema(getDummyResourceType(), LayerType.MODEL, prismContext); - + display("Dummy refined schema (MODEL)", refinedSchemaModel); - + // THEN getDummyResourceController().assertRefinedSchemaSanity(refinedSchemaModel); - + assertTrue("Not layer refined schema, it is "+refinedSchemaModel.getClass(), refinedSchemaModel instanceof LayerRefinedResourceSchema); assertEquals("Wrong layer", LayerType.MODEL, ((LayerRefinedResourceSchema)refinedSchemaModel).getLayer()); } @@ -113,18 +113,18 @@ public void test100EntitlementRefinedObjectClasses() throws Exception { // WHEN Collection entitlementROcDefs = refinedSchema.getRefinedDefinitions(ShadowKindType.ENTITLEMENT); - + display("entitlement rOcDefs", entitlementROcDefs); - + // THEN - + for (RefinedObjectClassDefinition entitlementROcDef: entitlementROcDefs) { assertEquals("Wrong kind in "+entitlementROcDef, ShadowKindType.ENTITLEMENT, entitlementROcDef.getKind()); } - + assertEquals("Wrong number of entitlement rOcDefs", 6, entitlementROcDefs.size()); } - + @Test public void test101EntitlementRefinedObjectClassesModel() throws Exception { final String TEST_NAME = "test101EntitlementRefinedObjectClassesModel"; @@ -132,15 +132,15 @@ public void test101EntitlementRefinedObjectClassesModel() throws Exception { // WHEN Collection entitlementROcDefs = refinedSchemaModel.getRefinedDefinitions(ShadowKindType.ENTITLEMENT); - + display("entitlement rOcDefs", entitlementROcDefs); - + // THEN - + for (RefinedObjectClassDefinition entitlementROcDef: entitlementROcDefs) { assertEquals("Wrong kind in "+entitlementROcDef, ShadowKindType.ENTITLEMENT, entitlementROcDef.getKind()); } - + assertEquals("Wrong number of entitlement rOcDefs", 6, entitlementROcDefs.size()); } @@ -150,20 +150,20 @@ public void test110DetermineObjectClassObjectClass() throws Exception { TestUtil.displayTestTitle(this, TEST_NAME); OperationResult result = new OperationResult(TestRefinedSchema.class.getName() + "." + TEST_NAME); - + importObjectFromFile(TASK_RECONCILE_DUMMY_OBJECTCLASS_FILE); - + Task task = taskManager.getTask(TASK_RECONCILE_DUMMY_OBJECTCLASS_OID, result); display("Task", task); - + // WHEN ObjectClassComplexTypeDefinition objectClass = Utils.determineObjectClass(refinedSchema, task); - + // THEN display("Object class", objectClass); - + deleteObject(TaskType.class, TASK_RECONCILE_DUMMY_OBJECTCLASS_OID); - + assertObjectClass(objectClass, RESOURCE_DUMMY_ACCOUNT_OBJECTCLASS_QNAME); } @@ -173,20 +173,20 @@ public void test112DetermineObjectClassKindIntent() throws Exception { TestUtil.displayTestTitle(this, TEST_NAME); OperationResult result = new OperationResult(TestRefinedSchema.class.getName() + "." + TEST_NAME); - + importObjectFromFile(TASK_RECONCILE_DUMMY_KIND_INTENT_FILE); - + Task task = taskManager.getTask(TASK_RECONCILE_DUMMY_KIND_INTENT_OID, result); display("Task", task); - + // WHEN ObjectClassComplexTypeDefinition objectClass = Utils.determineObjectClass(refinedSchema, task); - + // THEN display("Object class", objectClass); - + deleteObject(TaskType.class, TASK_RECONCILE_DUMMY_KIND_INTENT_OID); - + assertRefinedObjectClass(objectClass, RESOURCE_DUMMY_PRIVILEGE_OBJECTCLASS_QNAME, ShadowKindType.ENTITLEMENT, "privilege"); } @@ -196,20 +196,20 @@ public void test114DetermineObjectClassKindIntentObjectClass() throws Exception TestUtil.displayTestTitle(this, TEST_NAME); OperationResult result = new OperationResult(TestRefinedSchema.class.getName() + "." + TEST_NAME); - + importObjectFromFile(TASK_RECONCILE_DUMMY_KIND_INTENT_OBJECTCLASS_FILE); - + Task task = taskManager.getTask(TASK_RECONCILE_DUMMY_KIND_INTENT_OBJECTCLASS_OID, result); display("Task", task); - + // WHEN ObjectClassComplexTypeDefinition objectClass = Utils.determineObjectClass(refinedSchema, task); - + // THEN display("Object class", objectClass); - + deleteObject(TaskType.class, TASK_RECONCILE_DUMMY_KIND_INTENT_OBJECTCLASS_OID); - + assertRefinedObjectClass(objectClass, RESOURCE_DUMMY_PRIVILEGE_OBJECTCLASS_QNAME, ShadowKindType.ENTITLEMENT, "privilege"); } @@ -219,21 +219,21 @@ public void test120DetermineObjectClassObjectClassModel() throws Exception { TestUtil.displayTestTitle(this, TEST_NAME); OperationResult result = new OperationResult(TestRefinedSchema.class.getName() + "." + TEST_NAME); - + importObjectFromFile(TASK_RECONCILE_DUMMY_OBJECTCLASS_FILE); - + Task task = taskManager.getTask(TASK_RECONCILE_DUMMY_OBJECTCLASS_OID, result); display("Task", task); - + // WHEN ObjectClassComplexTypeDefinition objectClass = Utils.determineObjectClass(refinedSchemaModel, task); - + // THEN display("Object class", objectClass); display("Object class (toString)", objectClass.toString()); - + deleteObject(TaskType.class, TASK_RECONCILE_DUMMY_OBJECTCLASS_OID); - + assertObjectClass(objectClass, RESOURCE_DUMMY_ACCOUNT_OBJECTCLASS_QNAME); } @@ -243,22 +243,22 @@ public void test122DetermineObjectClassKindIntentModel() throws Exception { TestUtil.displayTestTitle(this, TEST_NAME); OperationResult result = new OperationResult(TestRefinedSchema.class.getName() + "." + TEST_NAME); - + importObjectFromFile(TASK_RECONCILE_DUMMY_KIND_INTENT_FILE); - + Task task = taskManager.getTask(TASK_RECONCILE_DUMMY_KIND_INTENT_OID, result); display("Task", task); - + // WHEN ObjectClassComplexTypeDefinition objectClass = Utils.determineObjectClass(refinedSchemaModel, task); - + // THEN display("Object class", objectClass); display("Object class (toString)", objectClass.toString()); - + deleteObject(TaskType.class, TASK_RECONCILE_DUMMY_KIND_INTENT_OID); - - assertLayerRefinedObjectClass(objectClass, RESOURCE_DUMMY_PRIVILEGE_OBJECTCLASS_QNAME, + + assertLayerRefinedObjectClass(objectClass, RESOURCE_DUMMY_PRIVILEGE_OBJECTCLASS_QNAME, ShadowKindType.ENTITLEMENT, "privilege", LayerType.MODEL); } @@ -268,22 +268,22 @@ public void test124DetermineObjectClassKindIntentObjectClassModel() throws Excep TestUtil.displayTestTitle(this, TEST_NAME); OperationResult result = new OperationResult(TestRefinedSchema.class.getName() + "." + TEST_NAME); - + importObjectFromFile(TASK_RECONCILE_DUMMY_KIND_INTENT_OBJECTCLASS_FILE); - + Task task = taskManager.getTask(TASK_RECONCILE_DUMMY_KIND_INTENT_OBJECTCLASS_OID, result); display("Task", task); - + // WHEN ObjectClassComplexTypeDefinition objectClass = Utils.determineObjectClass(refinedSchemaModel, task); - + // THEN display("Object class", objectClass); display("Object class (toString)", objectClass.toString()); - + deleteObject(TaskType.class, TASK_RECONCILE_DUMMY_KIND_INTENT_OBJECTCLASS_OID); - - assertLayerRefinedObjectClass(objectClass, RESOURCE_DUMMY_PRIVILEGE_OBJECTCLASS_QNAME, + + assertLayerRefinedObjectClass(objectClass, RESOURCE_DUMMY_PRIVILEGE_OBJECTCLASS_QNAME, ShadowKindType.ENTITLEMENT, "privilege", LayerType.MODEL); } @@ -304,7 +304,7 @@ private void assertRefinedObjectClass(ObjectClassComplexTypeDefinition objectCla assertEquals("Wrong kind in rOcDef "+rOcDef, kind, rOcDef.getKind()); assertEquals("Wrong kind in rOcDef "+rOcDef, intent, rOcDef.getIntent()); } - + private void assertLayerRefinedObjectClass(ObjectClassComplexTypeDefinition objectClass, QName objectClassQName, ShadowKindType kind, String intent, LayerType layer) { assertRefinedObjectClass(objectClass, objectClassQName, kind, intent); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerAddObjectTest.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerAddObjectTest.java index 8d718cf30ca..7cf87f7ad88 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerAddObjectTest.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerAddObjectTest.java @@ -76,9 +76,9 @@ import com.evolveum.midpoint.xml.ns._public.common.fault_3.FaultMessage; /** - * + * * @author lazyman - * + * */ @ContextConfiguration(locations = { "classpath:ctx-model-test-no-repo.xml"}) public class ControllerAddObjectTest extends AbstractTestNGSpringContextTests { @@ -101,7 +101,7 @@ public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - + @BeforeMethod public void before() { Mockito.reset(provisioning, repository); @@ -141,10 +141,10 @@ public void addUserWithoutName() throws Exception { @SuppressWarnings("unchecked") public void addUserCorrect() throws Exception { TestUtil.displayTestTitle("addUserCorrect"); - + // GIVEN Task task = taskManager.createTaskInstance(); - + ModelTUtil.mockGetSystemConfiguration(repository, new File(TEST_FOLDER_COMMON, "system-configuration.xml")); final PrismObject expectedUser = PrismTestUtil.parseObject(new File(TEST_FOLDER, @@ -167,10 +167,10 @@ public String answer(InvocationOnMock invocation) throws Throwable { }); OperationResult result = new OperationResult("Test Operation"); - + // WHEN String userOid = controller.addObject(expectedUser, null, task, result); - + // THEN display("addObject result",result.debugDump()); @@ -185,10 +185,10 @@ public void addResourceCorrect() throws JAXBException, FaultMessage, ObjectAlrea SchemaException, CommunicationException, ObjectNotFoundException, ExpressionEvaluationException, IOException, ConfigurationException, PolicyViolationException, SecurityViolationException { TestUtil.displayTestTitle("addResourceCorrect"); - - + + Task task = taskManager.createTaskInstance(); - + final PrismObject expectedResource = PrismTestUtil.parseObject(new File( TEST_FOLDER, "add-resource-correct.xml")); final ResourceType expectedResourceType = expectedResource.asObjectable(); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerGetObjectTest.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerGetObjectTest.java index 69dcde82d8c..157b27fb057 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerGetObjectTest.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerGetObjectTest.java @@ -42,9 +42,9 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; /** - * + * * @author lazyman - * + * */ @ContextConfiguration(locations = { "classpath:ctx-model-test-no-repo.xml" }) public class ControllerGetObjectTest extends AbstractTestNGSpringContextTests { diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerLaunchImportTest.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerLaunchImportTest.java index a0b0ef1f07c..5f35908e118 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerLaunchImportTest.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerLaunchImportTest.java @@ -30,9 +30,9 @@ import com.evolveum.midpoint.util.logging.TraceManager; /** - * + * * @author lazyman - * + * */ @ContextConfiguration(locations = { "classpath:ctx-model-test-no-repo.xml" }) public class ControllerLaunchImportTest extends AbstractTestNGSpringContextTests { diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerListResourceObjectsTest.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerListResourceObjectsTest.java index 940fa0395b3..234b7223d3a 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerListResourceObjectsTest.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerListResourceObjectsTest.java @@ -35,9 +35,9 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; /** - * + * * @author lazyman - * + * */ @ContextConfiguration(locations = { "classpath:ctx-model-test-no-repo.xml" }) public class ControllerListResourceObjectsTest extends AbstractTestNGSpringContextTests { diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerModifyObjectTest.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerModifyObjectTest.java index 70f7d37e380..9458c9f24d0 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerModifyObjectTest.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerModifyObjectTest.java @@ -32,9 +32,9 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; /** - * + * * @author lazyman - * + * */ @ContextConfiguration(locations = { "classpath:ctx-model-test-no-repo.xml" }) public class ControllerModifyObjectTest extends AbstractTestNGSpringContextTests { diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerSearchObjectsTest.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerSearchObjectsTest.java index 706b526ce79..b44a3635fb0 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerSearchObjectsTest.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerSearchObjectsTest.java @@ -32,9 +32,9 @@ import org.testng.annotations.Test; /** - * + * * @author lazyman - * + * */ @ContextConfiguration(locations = { "classpath:ctx-model-test-no-repo.xml" }) public class ControllerSearchObjectsTest extends AbstractTestNGSpringContextTests { diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerTestResourceTest.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerTestResourceTest.java index c0bedaed351..07a14064bd1 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerTestResourceTest.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ControllerTestResourceTest.java @@ -29,9 +29,9 @@ import com.evolveum.midpoint.util.logging.TraceManager; /** - * + * * @author lazyman - * + * */ @ContextConfiguration(locations = { "classpath:ctx-model-test-no-repo.xml" }) public class ControllerTestResourceTest extends AbstractTestNGSpringContextTests { diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/FilterManagerImplTest.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/FilterManagerImplTest.java index 2de0474cc75..ff857c18118 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/FilterManagerImplTest.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/FilterManagerImplTest.java @@ -26,9 +26,9 @@ import com.evolveum.midpoint.common.filter.FilterManager; /** - * + * * @author lazyman - * + * */ @ContextConfiguration(locations = { "classpath:ctx-model-test-no-repo.xml" }) public class FilterManagerImplTest extends AbstractTestNGSpringContextTests { diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ModelUtilsTest.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ModelUtilsTest.java index a80b5e7cc48..5a06e629c35 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ModelUtilsTest.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/controller/ModelUtilsTest.java @@ -37,9 +37,9 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; /** - * + * * @author lazyman - * + * */ @ContextConfiguration(locations = { "classpath:ctx-model-test-no-repo.xml" }) public class ModelUtilsTest extends AbstractTestNGSpringContextTests { @@ -47,7 +47,7 @@ public class ModelUtilsTest extends AbstractTestNGSpringContextTests { private static final File TEST_FOLDER = new File("./src/test/resources/controller"); @Autowired(required = true) private Protector protector; - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/expr/ExpressionHandlerImplTest.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/expr/ExpressionHandlerImplTest.java index f4697403b0a..72ab2b11588 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/expr/ExpressionHandlerImplTest.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/expr/ExpressionHandlerImplTest.java @@ -61,9 +61,9 @@ import javax.xml.namespace.QName; /** - * + * * @author lazyman - * + * */ @ContextConfiguration(locations = { "classpath:ctx-model-test-no-repo.xml" }) public class ExpressionHandlerImplTest extends AbstractTestNGSpringContextTests { @@ -92,7 +92,7 @@ public void setup() throws SchemaException, SAXException, IOException { public void testConfirmUser() throws Exception { PrismObject account = PrismTestUtil.parseObject(new File( TEST_FOLDER, "account-xpath-evaluation.xml")); - + PrismObject user = PrismTestUtil.parseObject(new File(TEST_FOLDER, "user-new.xml")); //TODO: "$c:user/c:givenName/t:orig replaced with "$c:user/c:givenName diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/expr/TestFilterExpression.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/expr/TestFilterExpression.java index f7b52bbff42..8a1f451de71 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/expr/TestFilterExpression.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/expr/TestFilterExpression.java @@ -92,29 +92,29 @@ public void setup() throws SchemaException, SAXException, IOException { public void test100EvaluateExpressionEmployeeTypeUndefinedFilter() throws Exception { final String TEST_NAME = "testEvaluateExpressionEmployeeTypeUndefinedFilter"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); - - ObjectFilter filter = evaluateExpressionAssertFilter("expression-employeeType-undefined-filter.xml", + + ObjectFilter filter = evaluateExpressionAssertFilter("expression-employeeType-undefined-filter.xml", null, UndefinedFilter.class, task, result); - + executeFilter(filter, 5, task, result); } - + @Test public void test110EvaluateExpressionEmployeeTypeNoneFilter() throws Exception { final String TEST_NAME = "testEvaluateExpressionEmployeeTypeNoneFilter"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); - - ObjectFilter filter = evaluateExpressionAssertFilter("expression-employeeType-none-filter.xml", + + ObjectFilter filter = evaluateExpressionAssertFilter("expression-employeeType-none-filter.xml", null, NoneFilter.class, task, result); - + executeFilter(filter, 0, task, result); } @@ -122,14 +122,14 @@ public void test110EvaluateExpressionEmployeeTypeNoneFilter() throws Exception { public void test120EvaluateExpressionEmployeeTypeAllFilter() throws Exception { final String TEST_NAME = "testEvaluateExpressionEmployeeTypeAllFilter"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); - - ObjectFilter filter = evaluateExpressionAssertFilter("expression-employeeType-all-filter.xml", + + ObjectFilter filter = evaluateExpressionAssertFilter("expression-employeeType-all-filter.xml", null, AllFilter.class, task, result); - + executeFilter(filter, 5, task, result); } @@ -137,13 +137,13 @@ public void test120EvaluateExpressionEmployeeTypeAllFilter() throws Exception { public void test130EvaluateExpressionEmployeeTypeError() throws Exception { final String TEST_NAME = "testEvaluateExpressionEmployeeTypeError"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); - + try { - evaluateExpressionAssertFilter("expression-employeeType-error.xml", + evaluateExpressionAssertFilter("expression-employeeType-error.xml", null, NoneFilter.class, task, result); AssertJUnit.fail("Unexpected success"); } catch (ExpressionEvaluationException e) { @@ -152,22 +152,22 @@ public void test130EvaluateExpressionEmployeeTypeError() throws Exception { } } - + @Test public void test140EvaluateExpressionEmployeeTypeEmptyFilter() throws Exception { final String TEST_NAME = "testEvaluateExpressionEmployeeTypeEmptyFilter"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); - - ObjectFilter filter = evaluateExpressionAssertFilter("expression-employeeType-empty-filter.xml", + + ObjectFilter filter = evaluateExpressionAssertFilter("expression-employeeType-empty-filter.xml", null, EqualFilter.class, task, result); - + EqualFilter equalFilter = (EqualFilter) filter; AssertJUnit.assertNull("Expected NO values in filter, but found " + equalFilter.getValues(), equalFilter.getValues()); - + executeFilter(filter, 4, task, result); } @@ -175,114 +175,114 @@ public void test140EvaluateExpressionEmployeeTypeEmptyFilter() throws Exception public void test150EvaluateExpressionEmployeeTypeDefaultsNull() throws Exception { final String TEST_NAME = "test150EvaluateExpressionEmployeeTypeDefaultsNull"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); - - - ObjectFilter filter = evaluateExpressionAssertFilter("expression-employeeType-filter-defaults.xml", + + + ObjectFilter filter = evaluateExpressionAssertFilter("expression-employeeType-filter-defaults.xml", null, EqualFilter.class, task, result); EqualFilter equalFilter = (EqualFilter) filter; AssertJUnit.assertNull("Expected NO values in filter, but found " + equalFilter.getValues(), equalFilter.getValues()); - + executeFilter(filter, 4, task, result); } - + @Test public void test152EvaluateExpressionEmployeeTypeDefaultsCaptain() throws Exception { final String TEST_NAME = "test152EvaluateExpressionEmployeeTypeDefaultsCaptain"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); - - ObjectFilter filter = evaluateExpressionAssertFilter("expression-employeeType-filter-defaults.xml", + + ObjectFilter filter = evaluateExpressionAssertFilter("expression-employeeType-filter-defaults.xml", "CAPTAIN", EqualFilter.class, task, result); EqualFilter equalFilter = (EqualFilter) filter; PrismAsserts.assertValues("Wrong values in filter", equalFilter.getValues(), "CAPTAIN"); - + executeFilter(filter, 1, task, result); } - - + + @Test public void test200EvaluateExpressionLinkRefDefaultsNull() throws Exception { final String TEST_NAME = "test200EvaluateExpressionLinkRefDefaultsNull"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); - - ObjectFilter filter = evaluateExpressionAssertFilter("expression-linkref-filter-defaults.xml", + + ObjectFilter filter = evaluateExpressionAssertFilter("expression-linkref-filter-defaults.xml", null, RefFilter.class, task, result); RefFilter refFilter = (RefFilter) filter; AssertJUnit.assertNull("Expected NO values in filter, but found " + refFilter.getValues(), refFilter.getValues()); - + executeFilter(filter, 2, task, result); } - + @Test public void test202EvaluateExpressionLinkRefObjectReferenceTypeDefaultsNull() throws Exception { final String TEST_NAME = "test202EvaluateExpressionLinkRefObjectReferenceTypeDefaultsNull"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); - - ObjectFilter filter = evaluateExpressionAssertFilter("expression-linkref-object-reference-type-filter-defaults.xml", + + ObjectFilter filter = evaluateExpressionAssertFilter("expression-linkref-object-reference-type-filter-defaults.xml", null, RefFilter.class, task, result); RefFilter refFilter = (RefFilter) filter; AssertJUnit.assertNull("Expected NO values in filter, but found " + refFilter.getValues(), refFilter.getValues()); - + executeFilter(filter, 2, task, result); } - + @Test public void test210EvaluateExpressionLinkRefDefaultsVal() throws Exception { final String TEST_NAME = "test210EvaluateExpressionLinkRefDefaultsVal"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); - - ObjectFilter filter = evaluateExpressionAssertFilter("expression-linkref-filter-defaults.xml", + + ObjectFilter filter = evaluateExpressionAssertFilter("expression-linkref-filter-defaults.xml", ACCOUNT_SHADOW_GUYBRUSH_OID, RefFilter.class, task, result); RefFilter refFilter = (RefFilter) filter; assertEquals("Wrong number of values in filter: " + refFilter.getValues(), 1, refFilter.getValues().size()); - + executeFilter(filter, 1, task, result); } - + @Test public void test212EvaluateExpressionLinkRefObjectReferenceTypeDefaultsVal() throws Exception { final String TEST_NAME = "test212EvaluateExpressionLinkRefObjectReferenceTypeDefaultsVal"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); - - ObjectFilter filter = evaluateExpressionAssertFilter("expression-linkref-object-reference-type-filter-defaults.xml", + + ObjectFilter filter = evaluateExpressionAssertFilter("expression-linkref-object-reference-type-filter-defaults.xml", ACCOUNT_SHADOW_GUYBRUSH_OID, RefFilter.class, task, result); RefFilter refFilter = (RefFilter) filter; assertEquals("Wrong number of values in filter: " + refFilter.getValues(), 1, refFilter.getValues().size()); - + executeFilter(filter, 1, task, result); } - - private ObjectFilter evaluateExpressionAssertFilter(String filename, + + private ObjectFilter evaluateExpressionAssertFilter(String filename, String input, Class expectedType, Task task, OperationResult result) throws SchemaException, IOException, ObjectNotFoundException, ExpressionEvaluationException { PrismContext prismContext = PrismTestUtil.getPrismContext(); @@ -308,10 +308,10 @@ private ObjectFilter evaluateExpressionAssertFilter(String filename, // THEN display("Evaluated filter", evaluatedFilter); AssertJUnit.assertTrue("Expression should be evaluated to "+expectedType+", but was "+evaluatedFilter, expectedType.isAssignableFrom(evaluatedFilter.getClass())); - + return evaluatedFilter; } - + private void executeFilter(ObjectFilter filter, int expectedNumberOfResults, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { ObjectQuery query = ObjectQuery.createObjectQuery(filter); SearchResultList> objects = modelService.searchObjects(UserType.class, query, null, task, result); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/expr/TestModelExpressions.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/expr/TestModelExpressions.java index 4e0ca16eeca..8b7b2ff30c5 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/expr/TestModelExpressions.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/expr/TestModelExpressions.java @@ -65,11 +65,11 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; /** - * + * * @author lazyman * @author mederly * @author semancik - * + * */ @ContextConfiguration(locations = { "classpath:ctx-model-test-main.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @@ -78,7 +78,7 @@ public class TestModelExpressions extends AbstractInternalModelIntegrationTest { private static final File TEST_DIR = new File("src/test/resources/expr"); private static final QName PROPERTY_NAME = new QName(SchemaConstants.NS_C, "foo"); - + private static final Trace LOGGER = TraceManager.getTrace(TestModelExpressions.class); private static final String CHEF_OID = "00000003-0000-0000-0000-000000000000"; @@ -105,7 +105,7 @@ public void setup() throws SchemaException, SAXException, IOException { @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + importObjectFromFile(TEST_EXPRESSIONS_OBJECTS_FILE); } @@ -113,7 +113,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti public void testHello() throws Exception { final String TEST_NAME = "testHello"; TestUtil.displayTestTitle(this, TEST_NAME); - + assertExecuteScriptExpressionString(TEST_NAME, null, "Hello swashbuckler"); } @@ -131,7 +131,7 @@ public void testGetUserByOid() throws Exception { // GIVEN OperationResult result = new OperationResult(TestModelExpressions.class.getName() + "." + TEST_NAME); PrismObject chef = repositoryService.getObject(UserType.class, CHEF_OID, null, result); - + ExpressionVariables variables = ExpressionVariables.create(ExpressionConstants.VAR_USER, chef); // WHEN, THEN @@ -167,7 +167,7 @@ public void testGetManagersOids() throws Exception { Set expectedOids = new HashSet(Arrays.asList(new String[] { CHEESE_OID, CHEESE_JR_OID, LECHUCK_OID })); assertEquals("Unexpected script output", expectedOids, oids); } - + /** * MID-2887 */ @@ -204,18 +204,18 @@ public void testGetOrgByName() throws Exception { TestUtil.displayTestTitle(this, TEST_NAME); assertExecuteScriptExpressionString(TEST_NAME, null, F0006_OID); } - + @Test public void testGetLinkedShadowName() throws Exception { final String TEST_NAME = "testGetLinkedShadowName"; TestUtil.displayTestTitle(this, TEST_NAME); - + rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + ExpressionVariables variables = ExpressionVariables.create(ExpressionConstants.VAR_USER, getUser(USER_GUYBRUSH_OID)); - + assertExecuteScriptExpressionString(TEST_NAME, variables, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); } @@ -223,41 +223,41 @@ public void testGetLinkedShadowName() throws Exception { public void testGetLinkedShadowKindIntentUsername() throws Exception { final String TEST_NAME = "testGetLinkedShadowKindIntentUsername"; TestUtil.displayTestTitle(this, TEST_NAME); - + rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + ExpressionVariables variables = ExpressionVariables.create(ExpressionConstants.VAR_USER, getUser(USER_GUYBRUSH_OID)); - + assertExecuteScriptExpressionString(TEST_NAME, variables, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); } - + @Test public void testGetLinkedShadowKindIntentFullname() throws Exception { final String TEST_NAME = "testGetLinkedShadowKindIntentFullname"; TestUtil.displayTestTitle(this, TEST_NAME); - + rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + ExpressionVariables variables = ExpressionVariables.create(ExpressionConstants.VAR_USER, getUser(USER_GUYBRUSH_OID)); - + assertExecuteScriptExpressionString(TEST_NAME, variables, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME); - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); } - + @Test public void testGetLinkedShadowNameRepo() throws Exception { final String TEST_NAME = "testGetLinkedShadowNameRepo"; TestUtil.displayTestTitle(this, TEST_NAME); - + rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + ExpressionVariables variables = ExpressionVariables.create(ExpressionConstants.VAR_USER, getUser(USER_GUYBRUSH_OID)); - + assertExecuteScriptExpressionString(TEST_NAME, variables, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); } @@ -265,40 +265,40 @@ public void testGetLinkedShadowNameRepo() throws Exception { public void testGetLinkedShadowKindIntentUsernameRepo() throws Exception { final String TEST_NAME = "testGetLinkedShadowKindIntentUsernameRepo"; TestUtil.displayTestTitle(this, TEST_NAME); - + rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + ExpressionVariables variables = ExpressionVariables.create(ExpressionConstants.VAR_USER, getUser(USER_GUYBRUSH_OID)); - + assertExecuteScriptExpressionString(TEST_NAME, variables, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); } - + @Test public void testGetLinkedShadowKindIntentFullnameRepo() throws Exception { final String TEST_NAME = "testGetLinkedShadowKindIntentFullnameRepo"; TestUtil.displayTestTitle(this, TEST_NAME); - + rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + ExpressionVariables variables = ExpressionVariables.create(ExpressionConstants.VAR_USER, getUser(USER_GUYBRUSH_OID)); - + assertExecuteScriptExpressionString(TEST_NAME, variables, null); - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); } - + private void assertExecuteScriptExpressionString(final String TEST_NAME, ExpressionVariables variables, String expectedOutput) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, IOException, JAXBException { String output = executeScriptExpressionString(TEST_NAME, variables); assertEquals("Unexpected script output", expectedOutput, output); } - + private String executeScriptExpressionString(final String TEST_NAME, ExpressionVariables variables) throws SchemaException, IOException, JAXBException, ExpressionEvaluationException, ObjectNotFoundException { // GIVEN OperationResult result = new OperationResult(TestModelExpressions.class.getName() + "." + TEST_NAME); - + ScriptExpressionEvaluatorType scriptType = parseScriptType("expression-" + TEST_NAME + ".xml"); ItemDefinition outputDefinition = new PrismPropertyDefinitionImpl(PROPERTY_NAME, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext()); ScriptExpression scriptExpression = scriptExpressionFactory.createScriptExpression(scriptType, outputDefinition, TEST_NAME); @@ -315,14 +315,14 @@ private String executeScriptExpressionString(final String TEST_NAME, ExpressionV display("Script output", scriptOutputs); result.computeStatus(); TestUtil.assertSuccess(result); - + if (scriptOutputs.size() == 0) { return null; } - + assertEquals("Unexpected number of script outputs", 1, scriptOutputs.size()); return scriptOutputs.get(0).getValue(); - + } private List> evaluate(ScriptExpression scriptExpression, ExpressionVariables variables, boolean useNew, 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 fd208280a99..6e359a832a3 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 @@ -43,9 +43,9 @@ @ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public abstract class AbstractLensTest extends AbstractInternalModelIntegrationTest { - + protected static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "lens"); - + protected static final File ASSIGNMENT_DIRECT_FILE = new File(TEST_DIR, "assignment-direct.xml"); protected static final File ASSIGNMENT_DIRECT_EXPRESSION_FILE = new File(TEST_DIR, "assignment-direct-expression.xml"); protected static final File ASSIGNMENT_ROLE_ENGINEER_FILE = new File(TEST_DIR, "assignment-role-engineer.xml"); @@ -57,8 +57,8 @@ public abstract class AbstractLensTest extends AbstractInternalModelIntegrationT // protected static final String REQ_USER_JACK_MODIFY_ADD_ASSIGNMENT_ACCOUNT_OPENDJ = TEST_RESOURCE_DIR_NAME + // "/user-jack-modify-add-assignment-account-opendj.xml"; - - protected static final File REQ_USER_JACK_MODIFY_ADD_ASSIGNMENT_ACCOUNT_DUMMY = new File(TEST_DIR, + + protected static final File REQ_USER_JACK_MODIFY_ADD_ASSIGNMENT_ACCOUNT_DUMMY = new File(TEST_DIR, "user-jack-modify-add-assignment-account-dummy.xml"); protected static final File REQ_USER_JACK_MODIFY_ADD_ASSIGNMENT_ACCOUNT_DUMMY_ATTR = new File(TEST_DIR, @@ -72,27 +72,27 @@ public abstract class AbstractLensTest extends AbstractInternalModelIntegrationT protected static final File REQ_USER_JACK_MODIFY_DELETE_ASSIGNMENT_ACCOUNT_DUMMY = new File(TEST_DIR, "user-jack-modify-delete-assignment-account-dummy.xml"); - + protected static final File REQ_USER_BARBOSSA_MODIFY_ADD_ASSIGNMENT_ACCOUNT_DUMMY_ATTR = new File(TEST_DIR, "user-barbossa-modify-add-assignment-account-dummy-attr.xml"); - + protected static final File REQ_USER_BARBOSSA_MODIFY_DELETE_ASSIGNMENT_ACCOUNT_DUMMY_ATTR = new File(TEST_DIR, "user-barbossa-modify-delete-assignment-account-dummy-attr.xml"); - + protected static final File ROLE_PIRATE_FILE = new File(TEST_DIR, "role-pirate.xml"); protected static final File ROLE_PIRATE_SITUATION_ONLY_FILE = new File(TEST_DIR, "role-pirate-situation-only.xml"); protected static final String ROLE_PIRATE_OID = "12345678-d34d-b33f-f00d-555555556666"; - + protected static final File ROLE_MUTINIER_FILE = new File(TEST_DIR, "role-mutinier.xml"); protected static final String ROLE_MUTINIER_OID = "12345678-d34d-b33f-f00d-555555556668"; protected static final File ROLE_JUDGE_FILE = new File(TEST_DIR, "role-judge.xml"); protected static final File ROLE_JUDGE_SITUATION_ONLY_FILE = new File(TEST_DIR, "role-judge-situation-only.xml"); protected static final String ROLE_JUDGE_OID = "12345111-1111-2222-1111-121212111111"; - + protected static final File ROLE_CONSTABLE_FILE = new File(TEST_DIR, "role-constable.xml"); protected static final String ROLE_CONSTABLE_OID = "16ac2572-de66-11e6-bc86-23e62333976a"; - + protected static final File ROLE_THIEF_FILE = new File(TEST_DIR, "role-thief.xml"); protected static final String ROLE_THIEF_OID = "5ad00bd6-c550-466f-b15e-4d5fb195b369"; @@ -138,17 +138,17 @@ public abstract class AbstractLensTest extends AbstractInternalModelIntegrationT ROLE_CORP_ENGINEER_FILE, ROLE_CORP_MANAGER_FILE }; - + protected static final File ROLE_PERSONA_ADMIN_FILE = new File(TEST_DIR, "role-persona-admin.xml"); protected static final String ROLE_PERSONA_ADMIN_OID = "16813ae6-2c0a-11e7-91fc-8333c244329e"; protected static final File ORG_BRETHREN_FILE = new File(TEST_DIR, "org-brethren.xml"); protected static final String ORG_BRETHREN_OID = "9c6bfc9a-ca01-11e3-a5aa-001e8c717e5b"; protected static final String ORG_BRETHREN_INDUCED_ORGANIZATION = "Pirate Brethren"; - + @Autowired(required = true) protected Projector projector; - + @Autowired(required = true) protected TaskManager taskManager; 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 bc5e3b4d2ac..3acd562f892 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 @@ -84,28 +84,28 @@ public abstract class TestAbstractAssignmentEvaluator extends AbstractLensTest { @Autowired private RepositoryService repositoryService; - + @Autowired private ObjectResolver objectResolver; - + @Autowired private SystemObjectCache systemObjectCache; - + @Autowired private Clock clock; - + @Autowired private ActivationComputer activationComputer; @Autowired private MappingFactory mappingFactory; - + @Autowired private MappingEvaluator mappingEvaluator; - + public abstract File[] getRoleCorpFiles(); - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -115,7 +115,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti public void test100Direct() throws Exception { final String TEST_NAME = "test100Direct"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(TestAssignmentEvaluator.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); @@ -123,41 +123,41 @@ public void test100Direct() throws Exception { PrismAsserts.assertParentConsistency(userTypeJack.asPrismObject()); AssignmentType assignmentType = getAssignmentType(ASSIGNMENT_DIRECT_FILE); - + ObjectDeltaObject userOdo = new ObjectDeltaObject<>(userTypeJack.asPrismObject(), null, null); userOdo.recompute(); - + ItemDeltaItem,PrismContainerDefinition> assignmentIdi = new ItemDeltaItem<>(); assignmentIdi.setItemOld(LensUtil.createAssignmentSingleValueContainerClone(assignmentType)); assignmentIdi.recompute(); - + // WHEN TestUtil.displayWhen(TEST_NAME); EvaluatedAssignmentImpl evaluatedAssignment = assignmentEvaluator.evaluate(assignmentIdi, PlusMinusZero.ZERO, false, userTypeJack, "testDirect", task, result); evaluatedAssignment.evaluateConstructions(userOdo, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertNotNull(evaluatedAssignment); display("Evaluated assignment", evaluatedAssignment.debugDump()); assertEquals(1, evaluatedAssignment.getConstructionTriple().size()); PrismAsserts.assertParentConsistency(userTypeJack.asPrismObject()); - + Construction construction = evaluatedAssignment.getConstructionTriple().getZeroSet().iterator().next(); display("Evaluated construction", construction); assertNotNull("No object class definition in construction", construction.getRefinedObjectClassDefinition()); - + assertEquals("Wrong number of admin GUI configs", 0, evaluatedAssignment.getAdminGuiConfigurations().size()); } - + @Test public void test110DirectExpression() throws Exception { final String TEST_NAME = "test110DirectExpression"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(TestAssignmentEvaluator.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); @@ -168,41 +168,41 @@ public void test110DirectExpression() throws Exception { ObjectDeltaObject userOdo = new ObjectDeltaObject<>(userTypeJack.asPrismObject(), null, null); userOdo.recompute(); AssignmentEvaluator assignmentEvaluator = createAssignmentEvaluator(userOdo); - + ItemDeltaItem,PrismContainerDefinition> assignmentIdi = new ItemDeltaItem<>(); assignmentIdi.setItemOld(LensUtil.createAssignmentSingleValueContainerClone(assignmentType)); assignmentIdi.recompute(); - + // WHEN TestUtil.displayWhen(TEST_NAME); EvaluatedAssignmentImpl evaluatedAssignment = assignmentEvaluator.evaluate(assignmentIdi, PlusMinusZero.ZERO, false, userTypeJack, "testDirect", task, result); evaluatedAssignment.evaluateConstructions(userOdo, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertNotNull(evaluatedAssignment); display("Evaluated assignment", evaluatedAssignment); assertEquals(1, evaluatedAssignment.getConstructionTriple().size()); PrismAsserts.assertParentConsistency(userTypeJack.asPrismObject()); - + Construction construction = evaluatedAssignment.getConstructionTriple().getZeroSet().iterator().next(); assertNotNull("No object class definition in construction", construction.getRefinedObjectClassDefinition()); - + assertEquals("Wrong number of admin GUI configs", 0, evaluatedAssignment.getAdminGuiConfigurations().size()); } - + @Test public void test120DirectExpressionReplaceDescription() throws Exception { final String TEST_NAME = "test120DirectExpressionReplaceDescription"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(TestAssignmentEvaluator.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject user = userTypeJack.asPrismObject().clone(); AssignmentType assignmentType = unmarshallValueFromFile(ASSIGNMENT_DIRECT_EXPRESSION_FILE, AssignmentType.class); user.asObjectable().getAssignment().add(assignmentType.clone()); @@ -211,32 +211,32 @@ public void test120DirectExpressionReplaceDescription() throws Exception { new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(123L), new NameItemPathSegment(AssignmentType.F_DESCRIPTION)); - ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_JACK_OID, + ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_JACK_OID, path, prismContext, "captain"); ObjectDeltaObject userOdo = new ObjectDeltaObject<>(user, userDelta, null); userOdo.recompute(); AssignmentEvaluator assignmentEvaluator = createAssignmentEvaluator(userOdo); - + ItemDeltaItem,PrismContainerDefinition> assignmentIdi = new ItemDeltaItem<>(); assignmentIdi.setItemOld(LensUtil.createAssignmentSingleValueContainerClone(assignmentType)); assignmentIdi.setSubItemDeltas(userDelta.getModifications()); assignmentIdi.recompute(); - + // WHEN TestUtil.displayWhen(TEST_NAME); EvaluatedAssignmentImpl evaluatedAssignment = assignmentEvaluator.evaluate(assignmentIdi, PlusMinusZero.ZERO, false, userTypeJack, "testDirect", task, result); evaluatedAssignment.evaluateConstructions(userOdo, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertNotNull(evaluatedAssignment); 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()); @@ -253,59 +253,59 @@ public void test120DirectExpressionReplaceDescription() throws Exception { assertConstruction(evaluatedAssignment, ZERO, "title", MINUS, "The best pirate the world has ever seen"); assertNoConstruction(evaluatedAssignment, PLUS, "title"); assertNoConstruction(evaluatedAssignment, MINUS, "title"); - + assertEquals("Wrong number of admin GUI configs", 0, evaluatedAssignment.getAdminGuiConfigurations().size()); } - + @Test public void test130DirectExpressionReplaceDescriptionFromNull() throws Exception { final String TEST_NAME = "test130DirectExpressionReplaceDescriptionFromNull"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(TestAssignmentEvaluator.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject user = userTypeJack.asPrismObject().clone(); AssignmentType assignmentType = unmarshallValueFromFile(ASSIGNMENT_DIRECT_EXPRESSION_FILE, AssignmentType.class); assignmentType.setDescription(null); user.asObjectable().getAssignment().add(assignmentType.clone()); - + // // We need to make sure that the assignment has a parent // PrismContainerDefinition assignmentContainerDefinition = user.getDefinition().findContainerDefinition(UserType.F_ASSIGNMENT); // PrismContainer assignmentContainer = assignmentContainerDefinition.instantiate(); // assignmentContainer.add(assignmentType.asPrismContainerValue().clone()); - + ItemPath path = new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(123L), new NameItemPathSegment(AssignmentType.F_DESCRIPTION)); - ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_JACK_OID, + ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_JACK_OID, path, prismContext, "sailor"); ObjectDeltaObject userOdo = new ObjectDeltaObject<>(user, userDelta, null); userOdo.recompute(); AssignmentEvaluator assignmentEvaluator = createAssignmentEvaluator(userOdo); - + ItemDeltaItem,PrismContainerDefinition> assignmentIdi = new ItemDeltaItem<>(); assignmentIdi.setItemOld(LensUtil.createAssignmentSingleValueContainerClone(assignmentType)); assignmentIdi.setSubItemDeltas(userDelta.getModifications()); assignmentIdi.recompute(); - + // WHEN TestUtil.displayWhen(TEST_NAME); EvaluatedAssignmentImpl evaluatedAssignment = assignmentEvaluator.evaluate(assignmentIdi, PlusMinusZero.ZERO, false, userTypeJack, "testDirect", task, result); evaluatedAssignment.evaluateConstructions(userOdo, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertNotNull(evaluatedAssignment); 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()); @@ -322,7 +322,7 @@ public void test130DirectExpressionReplaceDescriptionFromNull() throws Exception assertConstruction(evaluatedAssignment, ZERO, "title", MINUS, "The best man the world has ever seen"); assertNoConstruction(evaluatedAssignment, PLUS, "title"); assertNoConstruction(evaluatedAssignment, MINUS, "title"); - + assertEquals("Wrong number of admin GUI configs", 0, evaluatedAssignment.getAdminGuiConfigurations().size()); } @@ -394,7 +394,7 @@ public void test140RoleVisitor() throws Exception { assertConstruction(evaluatedAssignment, ZERO, "location", MINUS); assertNoConstruction(evaluatedAssignment, PLUS, "location"); assertNoConstruction(evaluatedAssignment, MINUS, "location"); - + assertEquals("Wrong number of admin GUI configs", 0, evaluatedAssignment.getAdminGuiConfigurations().size()); } @@ -494,7 +494,7 @@ public void test150RoleEngineer() throws Exception { assertConstruction(evaluatedAssignment, ZERO, "location", MINUS); assertNoConstruction(evaluatedAssignment, PLUS, "location"); assertNoConstruction(evaluatedAssignment, MINUS, "location"); - + assertEquals("Wrong number of admin GUI configs", 1, evaluatedAssignment.getAdminGuiConfigurations().size()); } @@ -561,7 +561,7 @@ public void test160AddRoleEngineer() throws Exception { assertConstruction(evaluatedAssignment, ZERO, "location", MINUS); assertNoConstruction(evaluatedAssignment, PLUS, "location"); assertNoConstruction(evaluatedAssignment, MINUS, "location"); - + assertEquals("Wrong number of admin GUI configs", 1, evaluatedAssignment.getAdminGuiConfigurations().size()); } @@ -907,7 +907,7 @@ protected void assertNoConstruction(EvaluatedAssignmentImpl evaluatedA } } - + protected void assertConstruction(EvaluatedAssignmentImpl evaluatedAssignment, PlusMinusZero constructionSet, String attributeName, PlusMinusZero attributeSet, String... expectedValues) { Collection> constructions = evaluatedAssignment.getConstructionSet(constructionSet); Set realValues = new HashSet<>(); @@ -933,7 +933,7 @@ protected AssignmentEvaluator createAssignmentEvaluator() throws Objec focusOdo.recompute(); return createAssignmentEvaluator(focusOdo); } - + protected AssignmentEvaluator createAssignmentEvaluator(ObjectDeltaObject focusOdo) throws ObjectNotFoundException, SchemaException { LensContext lensContext = createLensContext(UserType.class); LensFocusContext focusContext = lensContext.getOrCreateFocusContext(); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignmentEvaluator.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignmentEvaluator.java index 2300e6891ad..b5d720949d9 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignmentEvaluator.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignmentEvaluator.java @@ -31,7 +31,7 @@ @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestAssignmentEvaluator extends TestAbstractAssignmentEvaluator { - + protected static final File[] ROLE_CORP_FILES = { ROLE_METAROLE_SOD_NOTIFICATION_FILE, ROLE_CORP_AUTH_FILE, @@ -44,14 +44,14 @@ public class TestAssignmentEvaluator extends TestAbstractAssignmentEvaluator { ROLE_CORP_ENGINEER_FILE, ROLE_CORP_MANAGER_FILE }; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); addObjects(getRoleCorpFiles()); } - + @Override public File[] getRoleCorpFiles() { return ROLE_CORP_FILES; diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignmentEvaluatorDynamic.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignmentEvaluatorDynamic.java index 09337a7e14d..f911e087775 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignmentEvaluatorDynamic.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignmentEvaluatorDynamic.java @@ -18,11 +18,11 @@ public class TestAssignmentEvaluatorDynamic extends TestAbstractAssignmentEvalua protected static final File ROLE_CORP_GENERIC_METAROLE_DYNAMIC_FILE = new File(TEST_DIR, "role-corp-generic-metarole-dynamic.xml"); protected static final File ROLE_CORP_JOB_METAROLE_DYNAMIC_FILE = new File(TEST_DIR, "role-corp-job-metarole-dynamic.xml"); - + protected static final File ROLE_CORP_MANAGER_DYNAMIC_FILE = new File(TEST_DIR, "role-corp-manager-dynamic.xml"); - + protected static final String NS_PIRACY = "http://midpoint.evolveum.com/xml/ns/samples/piracy"; - + protected static final File[] ROLE_CORP_FILES = { ROLE_METAROLE_SOD_NOTIFICATION_FILE, ROLE_CORP_AUTH_FILE, // TODO prepare a dynamic version of this file @@ -35,33 +35,33 @@ public class TestAssignmentEvaluatorDynamic extends TestAbstractAssignmentEvalua ROLE_CORP_ENGINEER_FILE, ROLE_CORP_MANAGER_FILE }; - + @Override public File[] getRoleCorpFiles() { return ROLE_CORP_FILES; } - - + + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); addObjects(getRoleCorpFiles()); - + // PrismObject userJack = getObject(UserType.class, USER_JACK_OID); // ItemPath resourceNamePath = new ItemPath(FocusType.F_EXTENSION, new QName(NS_PIRACY, "resourceName")); // ItemPath resourceRefPath = new ItemPath(FocusType.F_EXTENSION, new QName(NS_PIRACY, "resourceRef")); -// +// // Collection modifications = new ArrayList<>(); // modifications.add(PropertyDelta.createModificationAddProperty(resourceNamePath, userJack.getDefinition().findPropertyDefinition(resourceNamePath), "Dummy Resource")); // modifications.add(ReferenceDelta.createModificationAdd(resourceRefPath, userJack.getDefinition(), ObjectTypeUtil.createObjectRef("10000000-0000-0000-0000-000000000004", ObjectTypes.RESOURCE).asReferenceValue())); -// +// // Collection deltas = new ArrayList<>(); // deltas.add(ObjectDelta.createModifyDelta(USER_JACK_OID, modifications, UserType.class, prismContext)); // modelService.executeChanges(deltas, null, initTask, initResult); -// +// // userTypeJack = getObject(UserType.class, USER_JACK_OID).asObjectable(); - + } - + } 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 92825171d95..876c2c68fbb 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 @@ -60,7 +60,7 @@ public class TestAssignmentProcessor extends AbstractLensTest { @Autowired private AssignmentProcessor assignmentProcessor; - + @Autowired private Clock clock; @@ -142,31 +142,31 @@ public void test002ModifyUser() throws Exception { ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertNull("Account secondary delta sneaked in", accountSecondaryDelta); - + assertNoDecision(accContext); assertLegal(accContext); - + assignmentProcessor.processAssignmentsAccountValues(accContext, result); - + PrismValueDeltaSetTriple> accountConstructionDeltaSetTriple = accContext.getConstructionDeltaSetTriple(); display("accountConstructionDeltaSetTriple", accountConstructionDeltaSetTriple); - + PrismAsserts.assertTripleNoMinus(accountConstructionDeltaSetTriple); PrismAsserts.assertTripleNoPlus(accountConstructionDeltaSetTriple); assertSetSize("zero", accountConstructionDeltaSetTriple.getZeroSet(), 2); - + Construction zeroAccountConstruction = getZeroAccountConstruction(accountConstructionDeltaSetTriple, "Brethren account construction"); - - assertNoZeroAttributeValues(zeroAccountConstruction, + + assertNoZeroAttributeValues(zeroAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME)); - assertPlusAttributeValues(zeroAccountConstruction, + assertPlusAttributeValues(zeroAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME), "Tortuga"); - assertMinusAttributeValues(zeroAccountConstruction, + assertMinusAttributeValues(zeroAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME), "Caribbean"); - + } - + @Test public void test011AddAssignmentAddAccountDirect() throws Exception { final String TEST_NAME = "test011AddAssignmentAddAccountDirect"; @@ -204,7 +204,7 @@ public void test011AddAssignmentAddAccountDirect() throws Exception { ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertNull("Account secondary delta sneaked in", accountSecondaryDelta); - + assertNoDecision(accContext); assertLegal(accContext); } @@ -248,36 +248,36 @@ public void test012AddAssignmentAddAccountDirectAssignmentWithAttrs() throws Exc ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertNull("Account secondary delta sneaked in", accountSecondaryDelta); - + assertNoDecision(accContext); assertLegal(accContext); - + assignmentProcessor.processAssignmentsAccountValues(accContext, result); - + PrismValueDeltaSetTriple> accountConstructionDeltaSetTriple = accContext.getConstructionDeltaSetTriple(); - + PrismAsserts.assertTripleNoMinus(accountConstructionDeltaSetTriple); PrismAsserts.assertTripleNoZero(accountConstructionDeltaSetTriple); assertSetSize("plus", accountConstructionDeltaSetTriple.getPlusSet(), 1); - + Construction plusAccountConstruction = getPlusAccountConstruction(accountConstructionDeltaSetTriple); - - assertZeroAttributeValues(plusAccountConstruction, + + assertZeroAttributeValues(plusAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME), "Pirate Brethren, Inc."); - assertNoPlusAttributeValues(plusAccountConstruction, + assertNoPlusAttributeValues(plusAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME)); - assertNoMinusAttributeValues(plusAccountConstruction, + assertNoMinusAttributeValues(plusAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME)); - - assertZeroAttributeValues(plusAccountConstruction, + + assertZeroAttributeValues(plusAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME), "Caribbean"); - assertNoPlusAttributeValues(plusAccountConstruction, + assertNoPlusAttributeValues(plusAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME)); - assertNoMinusAttributeValues(plusAccountConstruction, + assertNoMinusAttributeValues(plusAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME)); - + } @Test @@ -317,21 +317,21 @@ public void test021AddAssignmentModifyAccountAssignment() throws Exception { ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertNull("Account secondary delta sneaked in", accountSecondaryDelta); - + assertNoDecision(accContext); assertLegal(accContext); - + assignmentProcessor.processAssignmentsAccountValues(accContext, result); - + PrismValueDeltaSetTriple> accountConstructionDeltaSetTriple = accContext.getConstructionDeltaSetTriple(); - + PrismAsserts.assertTripleNoMinus(accountConstructionDeltaSetTriple); - + assertSetSize("zero", accountConstructionDeltaSetTriple.getZeroSet(), 2); Construction zeroAccountConstruction = getZeroAccountConstruction(accountConstructionDeltaSetTriple, "Brethren account construction"); - + assertZeroAttributeValues(zeroAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME), "Pirate Brethren, Inc."); @@ -339,37 +339,37 @@ public void test021AddAssignmentModifyAccountAssignment() throws Exception { getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME)); assertNoMinusAttributeValues(zeroAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME)); - + assertZeroAttributeValues(zeroAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME), "Caribbean"); assertNoPlusAttributeValues(zeroAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME)); assertNoMinusAttributeValues(zeroAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME)); - + assertZeroAttributeValues(zeroAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME), "Sword"); assertNoPlusAttributeValues(zeroAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME)); assertNoMinusAttributeValues(zeroAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME)); - + assertSetSize("plus", accountConstructionDeltaSetTriple.getPlusSet(), 1); Construction plusAccountConstruction = getPlusAccountConstruction(accountConstructionDeltaSetTriple, "Monkey account construction"); - + assertZeroAttributeValues(plusAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME), "Rum"); assertNoPlusAttributeValues(plusAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME)); assertNoMinusAttributeValues(plusAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME)); - - assertZeroAttributeValues(plusAccountConstruction, + + assertZeroAttributeValues(plusAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME), "Dagger", "Pistol"); - assertNoPlusAttributeValues(plusAccountConstruction, + assertNoPlusAttributeValues(plusAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME)); - assertNoMinusAttributeValues(plusAccountConstruction, + assertNoMinusAttributeValues(plusAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME)); } @@ -390,7 +390,7 @@ public void test031DeleteAssignmentModifyAccount() throws Exception { context.recomputeFocus(); display("Input context", context); - + PrismObject userNew = context.getFocusContext().getObjectNew(); assertEquals("Unexpected number of assignemnts in userNew after recompute", 1, userNew.asObjectable().getAssignment().size()); @@ -420,46 +420,46 @@ public void test031DeleteAssignmentModifyAccount() throws Exception { assertNoDecision(accContext); assertLegal(accContext); - + assignmentProcessor.processAssignmentsAccountValues(accContext, result); - - + + PrismValueDeltaSetTriple> accountConstructionDeltaSetTriple = accContext.getConstructionDeltaSetTriple(); - + PrismAsserts.assertTripleNoPlus(accountConstructionDeltaSetTriple); - + assertSetSize("zero", accountConstructionDeltaSetTriple.getZeroSet(), 1); Construction zeroAccountConstruction = getZeroAccountConstruction(accountConstructionDeltaSetTriple); - - assertZeroAttributeValues(zeroAccountConstruction, + + assertZeroAttributeValues(zeroAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME), "Caribbean"); - assertNoPlusAttributeValues(zeroAccountConstruction, + assertNoPlusAttributeValues(zeroAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME)); assertNoMinusAttributeValues(zeroAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME)); - - assertZeroAttributeValues(zeroAccountConstruction, + + assertZeroAttributeValues(zeroAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME), "Pirate Brethren, Inc."); - assertNoPlusAttributeValues(zeroAccountConstruction, + assertNoPlusAttributeValues(zeroAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME)); assertNoMinusAttributeValues(zeroAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME)); - + assertSetSize("minus", accountConstructionDeltaSetTriple.getMinusSet(), 1); Construction minusAccountConstruction = getMinusAccountConstruction(accountConstructionDeltaSetTriple); - - assertZeroAttributeValues(minusAccountConstruction, + + assertZeroAttributeValues(minusAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME), "Undead Monkey"); - assertNoPlusAttributeValues(minusAccountConstruction, + assertNoPlusAttributeValues(minusAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME)); - assertNoMinusAttributeValues(minusAccountConstruction, + assertNoMinusAttributeValues(minusAccountConstruction, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME)); } - + @Test public void test032ModifyUserLegalizeAccount() throws Exception { final String TEST_NAME = "test032ModifyUserLegalizeAccount"; @@ -470,17 +470,17 @@ public void test032ModifyUserLegalizeAccount() throws Exception { OperationResult result = task.getResult(); 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(); - + ProjectionPolicyType accountSynchronizationSettings = new ProjectionPolicyType(); accountSynchronizationSettings.setLegalize(Boolean.TRUE); accountSynchronizationSettings.setAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType.POSITIVE); context.setAccountSynchronizationSettings(accountSynchronizationSettings); - + assumeResourceAssigmentPolicy(RESOURCE_DUMMY_OID, AssignmentPolicyEnforcementType.POSITIVE, true); display("Input context", context); @@ -489,7 +489,7 @@ public void test032ModifyUserLegalizeAccount() throws Exception { // WHEN assignmentProcessor.processAssignmentsProjections(context, getNow(), task, result); - + context.recompute(); // THEN display("Output context", context); @@ -499,9 +499,9 @@ public void test032ModifyUserLegalizeAccount() throws Exception { assertEquals("Unexpected number of secundary changes. ", 1, context.getFocusContext().getSecondaryDelta().getModifications().size()); assertNotNull("Expected assigment delta in secondary changes, but it does not exist.", ContainerDelta.findContainerDelta(context.getFocusContext().getSecondaryDelta().getModifications(), UserType.F_ASSIGNMENT)); assertFalse("No account changes", context.getProjectionContexts().isEmpty()); - + LensProjectionContext accContext = context.getProjectionContexts().iterator().next(); - + assertNoDecision(accContext); assertLegal(accContext); @@ -787,7 +787,7 @@ private void assertPlusAttributeValues(Construction accountConstruction, QNa Collection actual = getMultiValueFromDeltaSetTriple(triple, 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); @@ -795,7 +795,7 @@ private void assertZeroAttributeValues(Construction accountConstruction, QNa Collection actual = getMultiValueFromDeltaSetTriple(triple, 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); @@ -803,7 +803,7 @@ private void assertMinusAttributeValues(Construction accountConstruction, QN Collection actual = getMultiValueFromDeltaSetTriple(triple, triple.getMinusSet()); TestUtil.assertSetEquals("Attribute "+attrName+" value in minus set", actual, expectedValue); } - + private void assertNoPlusAttributeValues(Construction accountConstruction, QName attrName) { PrismValueDeltaSetTripleProducer, ? extends PrismPropertyDefinition> vc = accountConstruction.getAttributeMapping(attrName); PrismValueDeltaSetTriple> triple = vc.getOutputTriple(); @@ -822,14 +822,14 @@ private void assertNoMinusAttributeValues(Construction accountConstruction, QNam PrismAsserts.assertTripleNoMinus(triple); } - private Object getSingleValueFromDeltaSetTriple(PrismValueDeltaSetTriple> triple, + private Object getSingleValueFromDeltaSetTriple(PrismValueDeltaSetTriple> triple, Collection> set) { Collection values = getMultiValueFromDeltaSetTriple(triple,set); assertEquals(1,values.size()); return values.iterator().next(); } - - private Collection getMultiValueFromDeltaSetTriple(PrismValueDeltaSetTriple> triple, + + private Collection getMultiValueFromDeltaSetTriple(PrismValueDeltaSetTriple> triple, Collection> set) { Collection vals = new ArrayList(set.size()); for (PrismPropertyValue pval: set) { @@ -837,7 +837,7 @@ private Collection getMultiValueFromDeltaSetTriple(PrismValueDeltaSetTrip } return vals; } - + private void assertSetSize(String setName, Collection> set, int expectedSize) { assertEquals("Unexpected number of value in "+setName+" set", expectedSize, set.size()); @@ -847,14 +847,14 @@ private Construction getZeroAccountConstruction( PrismValueDeltaSetTriple> accountConstructionDeltaSetTriple) { return getZeroAccountConstruction(accountConstructionDeltaSetTriple, null); } - + private Construction getZeroAccountConstruction( PrismValueDeltaSetTriple> accountConstructionDeltaSetTriple, String description) { Collection> set = accountConstructionDeltaSetTriple.getZeroSet(); return getAccountConstruction(accountConstructionDeltaSetTriple, description, set, "zero"); } - + private Construction getPlusAccountConstruction( PrismValueDeltaSetTriple> accountConstructionDeltaSetTriple) { return getPlusAccountConstruction(accountConstructionDeltaSetTriple, null); @@ -878,7 +878,7 @@ private Construction getMinusAccountConstruction( Collection> set = accountConstructionDeltaSetTriple.getMinusSet(); return getAccountConstruction(accountConstructionDeltaSetTriple, description, set, "minus"); } - + private Construction getAccountConstruction(PrismValueDeltaSetTriple> accountConstructionDeltaSetTriple, String description, Collection> set, String setName) { for (PrismPropertyValue constructionPVal: set) { @@ -902,9 +902,9 @@ private void assertIllegal(LensProjectionContext accContext) { private void assertNoDecision(LensProjectionContext accContext) { assertNull("Projection "+accContext+" has decision "+accContext.getSynchronizationPolicyDecision()+" while not expecting any", accContext.getSynchronizationPolicyDecision()); } - + private XMLGregorianCalendar getNow() { return clock.currentTimeXMLGregorianCalendar(); } - + } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignmentProcessor2.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignmentProcessor2.java index 90e397ecf33..5bc1a96df7b 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignmentProcessor2.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignmentProcessor2.java @@ -155,15 +155,15 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti createObjectsInFirstPart(false, initTask, initResult, null); } } - + @Test(enabled = FIRST_PART) public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; displayTestTitle(TEST_NAME); - + assertEquals("Wrong default relation", SchemaConstants.ORG_DEFAULT, prismContext.getDefaultRelation()); } - + @Test(enabled = FIRST_PART) public void test010AssignR1ToJack() throws Exception { final String TEST_NAME = "test010AssignR1ToJack"; diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestClockwork.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestClockwork.java index 6b8f185fb1c..8fec5f5df04 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestClockwork.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestClockwork.java @@ -82,17 +82,17 @@ @ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestClockwork extends AbstractLensTest { - + @Autowired(required = true) private Clockwork clockwork; - + @Autowired(required = true) private TaskManager taskManager; - + public TestClockwork() throws JAXBException { super(); } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { @@ -146,37 +146,37 @@ public void test020AssignAccountToJackSync() throws Exception { TestUtil.displayTestTitle(this, TEST_NAME); try { - + // GIVEN Task task = taskManager.createTaskInstance(TestClockwork.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + LensContext context = createJackAssignAccountContext(result); - + display("Input context", context); - + assertFocusModificationSanity(context); mockClockworkHook.reset(); mockClockworkHook.setRecord(true); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN displayWhen(TEST_NAME); clockwork.run(context, task, result); - + // THEN displayThen(TEST_NAME); mockClockworkHook.setRecord(false); display("Output context", context); display("Hook contexts", mockClockworkHook); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + assertJackAssignAccountContext(context); assertJackAccountShadow(context); - + List> hookContexts = mockClockworkHook.getContexts(); assertFalse("No contexts recorded by the hook", hookContexts.isEmpty()); - + } finally { displayCleanup(TEST_NAME); mockClockworkHook.reset(); @@ -189,9 +189,9 @@ public void test020AssignAccountToJackSync() throws Exception { public void test030AssignAccountToJackAsyncNoserialize() throws Exception { final String TEST_NAME = "test030AssignAccountToJackAsyncNoserialize"; try { - + assignAccountToJackAsync(TEST_NAME, false); - + } finally { displayCleanup(TEST_NAME); mockClockworkHook.reset(); @@ -204,9 +204,9 @@ public void test030AssignAccountToJackAsyncNoserialize() throws Exception { public void test031AssignAccountToJackAsyncSerialize() throws Exception { final String TEST_NAME = "test031AssignAccountToJackAsyncSerialize"; try { - + assignAccountToJackAsync(TEST_NAME, true); - + } finally { displayCleanup(TEST_NAME); mockClockworkHook.reset(); @@ -214,7 +214,7 @@ public void test031AssignAccountToJackAsyncSerialize() throws Exception { assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } } - + /** * 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. @@ -243,11 +243,11 @@ public void test053ModifyUserBarbossaDisable() throws Exception { // WHEN displayWhen(TEST_NAME); clockwork.run(context, task, result); - + // THEN displayThen(TEST_NAME); display("Output context", context); - + assertTrue(context.getFocusContext().getPrimaryDelta().getChangeType() == ChangeType.MODIFY); assertSideEffectiveDeltasOnly(context.getFocusContext().getSecondaryDelta(), "user secondary delta", ActivationStatusType.DISABLED); @@ -263,12 +263,12 @@ public void test053ModifyUserBarbossaDisable() throws Exception { assertEquals(ChangeType.MODIFY, accountSecondaryDelta.getChangeType()); // originally here was 6 (TODO why now four?) assertEquals("Unexpected number of account secondary changes", 4, accountSecondaryDelta.getModifications().size()); - PrismAsserts.assertPropertyReplace(accountSecondaryDelta, + PrismAsserts.assertPropertyReplace(accountSecondaryDelta, new ItemPath(ShadowType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), ActivationStatusType.DISABLED); PrismAsserts.assertPropertyReplace(accountSecondaryDelta, SchemaConstants.PATH_ACTIVATION_DISABLE_REASON, SchemaConstants.MODEL_DISABLE_REASON_MAPPED); - + ContainerDelta triggerDelta = accountSecondaryDelta.findContainerDelta(ObjectType.F_TRIGGER); assertNotNull("No trigger delta in account secondary delta", triggerDelta); assertEquals("Wrong trigger delta size", 1, triggerDelta.getValuesToAdd().size()); @@ -279,18 +279,18 @@ public void test053ModifyUserBarbossaDisable() throws Exception { XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); end.add(XmlTypeConverter.createDuration(true, 0, 0, 35, 0, 0, 0)); TestUtil.assertBetween("Wrong trigger timestamp", start, end, triggerType.getTimestamp()); - + } - + private void assignAccountToJackAsync(String testName, boolean serialize) throws Exception { displayTestTitle(testName); - + // GIVEN Task task = createTask(testName); OperationResult result = task.getResult(); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); - + LensContext context = createJackAssignAccountContext(result); // display("Input context", context); @@ -300,19 +300,19 @@ private void assignAccountToJackAsync(String testName, boolean serialize) throws mockClockworkHook.setRecord(true); mockClockworkHook.setAsynchronous(true); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN displayWhen(testName); while(context.getState() != ModelState.FINAL) { - + display("CLICK START: "+context.getState()); HookOperationMode mode = clockwork.click(context, task, result); 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); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + if (serialize) { display("Context before serialization", context); @@ -330,18 +330,18 @@ private void assignAccountToJackAsync(String testName, boolean serialize) throws context.checkConsistence(); } } - + // THEN displayThen(testName); mockClockworkHook.setRecord(false); // display("Output context", context); // display("Hook contexts", mockClockworkHook); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + assertJackAssignAccountContext(context); assertJackAccountShadow(context); } - + private void assertJackAssignAccountContext(LensContext context) { assertTrue(context.getFocusContext().getPrimaryDelta().getChangeType() == ChangeType.MODIFY); if (context.getFocusContext().getSecondaryDelta() != null) { @@ -356,15 +356,15 @@ private void assertJackAssignAccountContext(LensContext context) { assertNull("Account primary delta sneaked in", accContext.getPrimaryDelta()); assertEquals(SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); - + ObjectDelta executedDelta = getExecutedDelta(accContext); assertNotNull("No executed delta in "+accContext, executedDelta); assertEquals(ChangeType.ADD, executedDelta.getChangeType()); PrismAsserts.assertPropertyAdd(executedDelta, getIcfsNameAttributePath(), "jack"); PrismAsserts.assertPropertyAdd(executedDelta, getDummyResourceController().getAttributeFullnamePath(), "Jack Sparrow"); - + } - + private ObjectDelta getExecutedDelta(LensProjectionContext ctx) { List> executedDeltas = ctx.getExecutedDeltas(); if (executedDeltas.isEmpty()) { @@ -382,7 +382,7 @@ private void assertJackAccountShadow(LensContext context) throws Objec LensProjectionContext accContext = accountContexts.iterator().next(); String accountOid = accContext.getOid(); assertNotNull("No OID in account context "+accContext); - + PrismObject newAccount = getShadowModel(accountOid); assertEquals(DEFAULT_INTENT, newAccount.findProperty(ShadowType.F_INTENT).getRealValue()); assertEquals(new QName(ResourceTypeUtil.getResourceNamespace(getDummyResourceType()), "AccountObjectClass"), 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 7ace0e93568..e996ee0e600 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 @@ -68,41 +68,41 @@ @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) private DependencyProcessor dependencyProcessor; - + @Autowired(required = true) private TaskManager taskManager; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + initDummy("a", initTask, initResult); initDummy("b", initTask, initResult); // depends on A initDummy("c", initTask, initResult); // depends on B initDummy("d", initTask, initResult); // depends on B - + initDummy("p", initTask, initResult); // depends on R (order 5) initDummy("r", initTask, initResult); // depends on P (order 0) - + initDummy("x", initTask, initResult); // depends on Y (circular) initDummy("y", initTask, initResult); // depends on Z (circular) initDummy("z", initTask, initResult); // depends on X (circular) } - + private void initDummy(String name, Task initTask, OperationResult initResult) throws FileNotFoundException, ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ConnectException, SchemaViolationException, ConflictException, ExpressionEvaluationException { String resourceOid = getDummyOid(name); DummyResourceContoller resourceCtl = DummyResourceContoller.create(name.toUpperCase()); resourceCtl.extendSchemaPirate(); - PrismObject resource = importAndGetObjectFromFile(ResourceType.class, + PrismObject resource = importAndGetObjectFromFile(ResourceType.class, getDummFile(name), resourceOid, initTask, initResult); resourceCtl.setResource(resource); } @@ -114,7 +114,7 @@ private File getDummFile(String name) { private String getDummyOid(String name) { return "14440000-0000-0000-000"+name+"-000000000000"; } - + private String getDummuAccountOid(String dummyName, String accountName) { return "14440000-0000-0000-000"+dummyName+"-10000000000"+accountName; } @@ -128,22 +128,22 @@ public void test100SortToWavesIdependent() throws Exception { Task task = taskManager.createTaskInstance(TestDependencies.class.getName() + "." + TEST_NAME); 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); fillContextWithDummyElaineAccount(context, "a", task, result); - + context.recompute(); - display("Context before", context); + display("Context before", context); context.checkConsistence(); - + // WHEN dependencyProcessor.sortProjectionsToWaves(context); - + // THEN display("Context after", context); - + assertWave(context, RESOURCE_DUMMY_OID, 0, 0); assertWave(context, getDummyOid("a"), 0, 0); } @@ -157,28 +157,28 @@ public void test101SortToWavesAB() throws Exception { Task task = taskManager.createTaskInstance(TestDependencies.class.getName() + "." + TEST_NAME); 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); fillContextWithDummyElaineAccount(context, "a", task, result); fillContextWithDummyElaineAccount(context, "b", task, result); - + context.recompute(); - display("Context before", context); + display("Context before", context); context.checkConsistence(); - + // WHEN dependencyProcessor.sortProjectionsToWaves(context); - + // THEN display("Context after", context); - + assertWave(context, RESOURCE_DUMMY_OID, 0, 0); assertWave(context, getDummyOid("a"), 0, 0); assertWave(context, getDummyOid("b"), 0, 1); } - + @Test public void test102SortToWavesABCD() throws Exception { final String TEST_NAME = "test102SortToWavesABCD"; @@ -188,7 +188,7 @@ public void test102SortToWavesABCD() throws Exception { Task task = taskManager.createTaskInstance(TestDependencies.class.getName() + "." + TEST_NAME); 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); @@ -196,24 +196,24 @@ public void test102SortToWavesABCD() throws Exception { fillContextWithDummyElaineAccount(context, "b", task, result); fillContextWithDummyElaineAccount(context, "c", task, result); fillContextWithDummyElaineAccount(context, "d", task, result); - + context.recompute(); - display("Context before", context); + display("Context before", context); context.checkConsistence(); - + // WHEN dependencyProcessor.sortProjectionsToWaves(context); - + // THEN display("Context after", context); - + assertWave(context, RESOURCE_DUMMY_OID, 0, 0); assertWave(context, getDummyOid("a"), 0, 0); assertWave(context, getDummyOid("b"), 0, 1); assertWave(context, getDummyOid("c"), 0, 2); assertWave(context, getDummyOid("d"), 0, 2); } - + @Test public void test120SortToWavesBCUnsatisfied() throws Exception { final String TEST_NAME = "test120SortToWavesBCUnsatisfied"; @@ -223,16 +223,16 @@ public void test120SortToWavesBCUnsatisfied() throws Exception { Task task = taskManager.createTaskInstance(TestDependencies.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + LensContext context = createUserLensContext(); LensFocusContext focusContext = fillContextWithUser(context, USER_ELAINE_OID, result); fillContextWithDummyElaineAccount(context, "b", task, result); fillContextWithDummyElaineAccount(context, "c", task, result); - + context.recompute(); - display("Context before", context); + display("Context before", context); context.checkConsistence(); - + try { // WHEN dependencyProcessor.sortProjectionsToWaves(context); @@ -241,10 +241,10 @@ public void test120SortToWavesBCUnsatisfied() throws Exception { AssertJUnit.fail("Unexpected success"); } catch (PolicyViolationException e) { // this is expected - } + } } - + @Test public void test151SortToWavesPR() throws Exception { final String TEST_NAME = "test151SortToWavesPR"; @@ -254,22 +254,22 @@ public void test151SortToWavesPR() throws Exception { Task task = taskManager.createTaskInstance(TestDependencies.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + LensContext context = createUserLensContext(); fillContextWithUser(context, USER_ELAINE_OID, result); fillContextWithDummyElaineAccount(context, "p", task, result); fillContextWithDummyElaineAccount(context, "r", task, result); - + context.recompute(); - display("Context before", context); + display("Context before", context); context.checkConsistence(); - + // WHEN dependencyProcessor.sortProjectionsToWaves(context); - + // THEN display("Context after", context); - + assertWave(context, getDummyOid("p"), 0, 0); assertWave(context, getDummyOid("r"), 0, 1); assertWave(context, getDummyOid("p"), 5, 2); @@ -288,27 +288,27 @@ public void test152SortToWavesRP() throws Exception { Task task = taskManager.createTaskInstance(TestDependencies.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + LensContext context = createUserLensContext(); fillContextWithUser(context, USER_ELAINE_OID, result); fillContextWithDummyElaineAccount(context, "r", task, result); fillContextWithDummyElaineAccount(context, "p", task, result); - + context.recompute(); - display("Context before", context); + display("Context before", context); context.checkConsistence(); - + // WHEN dependencyProcessor.sortProjectionsToWaves(context); - + // THEN display("Context after", context); - + assertWave(context, getDummyOid("p"), 0, 0); assertWave(context, getDummyOid("r"), 0, 1); assertWave(context, getDummyOid("p"), 5, 2); } - + @Test public void test200SortToWavesIdependentDeprovision() throws Exception { final String TEST_NAME = "test200SortToWavesIdependentDeprovision"; @@ -318,27 +318,27 @@ public void test200SortToWavesIdependentDeprovision() throws Exception { Task task = taskManager.createTaskInstance(TestDependencies.class.getName() + "." + TEST_NAME); 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); setDelete(accountContext); setDelete(fillContextWithDummyElaineAccount(context, "a", task, result)); - + context.recompute(); - display("Context before", context); + display("Context before", context); context.checkConsistence(); - + // WHEN dependencyProcessor.sortProjectionsToWaves(context); - + // THEN display("Context after", context); - + assertWave(context, RESOURCE_DUMMY_OID, 0, 0); assertWave(context, getDummyOid("a"), 0, 0); } - + @Test public void test201SortToWavesABDeprovision() throws Exception { final String TEST_NAME = "test201SortToWavesABDeprovision"; @@ -348,29 +348,29 @@ public void test201SortToWavesABDeprovision() throws Exception { Task task = taskManager.createTaskInstance(TestDependencies.class.getName() + "." + TEST_NAME); 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); setDelete(accountContext); setDelete(fillContextWithDummyElaineAccount(context, "a", task, result)); setDelete(fillContextWithDummyElaineAccount(context, "b", task, result)); - + context.recompute(); - display("Context before", context); + display("Context before", context); context.checkConsistence(); - + // WHEN dependencyProcessor.sortProjectionsToWaves(context); - + // THEN display("Context after", context); - + assertWave(context, RESOURCE_DUMMY_OID, 0, 0); assertWave(context, getDummyOid("a"), 0, 1); assertWave(context, getDummyOid("b"), 0, 0); } - + @Test public void test202SortToWavesABCDDeprovision() throws Exception { final String TEST_NAME = "test202SortToWavesABCDDeprovision"; @@ -380,7 +380,7 @@ public void test202SortToWavesABCDDeprovision() throws Exception { Task task = taskManager.createTaskInstance(TestDependencies.class.getName() + "." + TEST_NAME); 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); @@ -389,24 +389,24 @@ public void test202SortToWavesABCDDeprovision() throws Exception { setDelete(fillContextWithDummyElaineAccount(context, "b", task, result)); setDelete(fillContextWithDummyElaineAccount(context, "c", task, result)); setDelete(fillContextWithDummyElaineAccount(context, "d", task, result)); - + context.recompute(); - display("Context before", context); + display("Context before", context); context.checkConsistence(); - + // WHEN dependencyProcessor.sortProjectionsToWaves(context); - + // THEN display("Context after", context); - + assertWave(context, RESOURCE_DUMMY_OID, 0, 0); assertWave(context, getDummyOid("a"), 0, 2); assertWave(context, getDummyOid("b"), 0, 1); assertWave(context, getDummyOid("c"), 0, 0); assertWave(context, getDummyOid("d"), 0, 0); } - + private void setDelete(LensProjectionContext accountContext) { accountContext.setPrimaryDelta(ObjectDelta.createDeleteDelta(ShadowType.class, accountContext.getOid(), prismContext)); } @@ -420,29 +420,29 @@ public void test300SortToWavesXYZCircular() throws Exception { Task task = taskManager.createTaskInstance(TestDependencies.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + LensContext context = createUserLensContext(); fillContextWithUser(context, USER_ELAINE_OID, result); fillContextWithDummyElaineAccount(context, "x", task, result); fillContextWithDummyElaineAccount(context, "y", task, result); fillContextWithDummyElaineAccount(context, "z", task, result); - + context.recompute(); - display("Context before", context); + display("Context before", context); context.checkConsistence(); - + try { // WHEN dependencyProcessor.sortProjectionsToWaves(context); - + AssertJUnit.fail("Unexpected success"); } catch (PolicyViolationException e) { // This is expected display("Expected exception", e); } - + } - + private LensProjectionContext fillContextWithDummyElaineAccount( LensContext context, String dummyName, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, IOException, ExpressionEvaluationException { String resourceOid = getDummyOid(dummyName); @@ -454,7 +454,7 @@ private LensProjectionContext fillContextWithDummyElaineAccount( provisioningService.applyDefinition(account, task, result); return fillContextWithAccount(context, account, task, result); } - + private void assertWave(LensContext context, String resourceOid, int order, int expectedWave) { LensProjectionContext ctxAccDummy = findAccountContext(context, resourceOid, order); @@ -472,5 +472,5 @@ 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/TestPasswordPolicyProcessor.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestPasswordPolicyProcessor.java index 7d5704c54d8..1ba06970a13 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestPasswordPolicyProcessor.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestPasswordPolicyProcessor.java @@ -65,7 +65,7 @@ public class TestPasswordPolicyProcessor extends AbstractLensTest { private static final String PASSWORD_NO_HISTORY_POLICY_NAME = "password-policy-no-history.xml"; private static final File PASSWORD_NO_HISTORY_POLICY_FILE = new File(BASE_PATH, PASSWORD_NO_HISTORY_POLICY_NAME); - + private static final String PASSWORD1 = "ch4nGedPa33word1"; private static final String PASSWORD2 = "ch4nGedPa33word2"; private static final String PASSWORD3 = "ch4nGedPa33word3"; @@ -106,7 +106,7 @@ public void test100CreateUserWithPassword() throws Exception { public void test101ModifyUserPassword() throws Exception { final String TEST_NAME = "test101ModifyUserPassword"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); @@ -135,13 +135,13 @@ public void test101ModifyUserPassword() throws Exception { public void test102ModifyUserPassword() throws Exception { final String TEST_NAME = "test102ModifyUserPassword"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = taskManager.createTaskInstance(TEST_NAME); OperationResult result = task.getResult(); // WHEN modifyUserChangePassword(USER_JACK_OID, PASSWORD2, task, result); - + // THEN PrismObject jack = getObject(UserType.class, USER_JACK_OID); assertNotNull("User Jack was not found.", jack); @@ -164,7 +164,7 @@ public void test102ModifyUserPassword() throws Exception { public void test103ModifyUserPasswordAgain() throws Exception { final String TEST_NAME = "test103ModifyUserPasswordAgain"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); @@ -183,13 +183,13 @@ public void test103ModifyUserPasswordAgain() throws Exception { assertNotNull("No password set for user Jack", passwordTypeAfterSecondChnage); ProtectedStringType passwordAfterSecondChange = passwordTypeAfterSecondChnage.getValue(); assertNotNull("Password musn't be null", passwordAfterSecondChange); - + assertPasswords(PASSWORD3, passwordAfterSecondChange); assertPasswordHistoryEntries(passwordTypeAfterSecondChnage, PASSWORD1, PASSWORD2); } - + @Test public void test111ModifyUserPasswordOldPassword1() throws Exception { doTestModifyUserPasswordExpectFailure("test111ModifyUserPasswordOldPassword1", PASSWORD1); @@ -204,7 +204,7 @@ public void test112ModifyUserPasswordOldPassword2() throws Exception { public void test113ModifyUserPasswordSamePassword3() throws Exception { doTestModifyUserPasswordExpectFailure("test113ModifyUserPasswordSamePassword3", PASSWORD3); } - + public void doTestModifyUserPasswordExpectFailure(final String TEST_NAME, String password) throws Exception { Task task = taskManager.createTaskInstance(TEST_NAME); TestUtil.displayTestTitle(TEST_NAME); @@ -213,7 +213,7 @@ public void doTestModifyUserPasswordExpectFailure(final String TEST_NAME, String try { // WHEN modifyUserChangePassword(USER_JACK_OID, password, task, result); - + fail("Expected PolicyViolationException but didn't get one."); } catch (PolicyViolationException ex) { // this is expected @@ -275,16 +275,16 @@ public void test202createUserJackNoPasswordHistory() throws Exception { public void test203modifyUserJackPasswordNoPasswordHistory() throws Exception { final String TEST_NAME = "test203modifyUserJackPasswordNoPasswordHistory"; modifyUserJackPasswordNoHistory(TEST_NAME); - + } - + @Test public void test204modifyUserJackSamePasswordNoPasswordHistory() throws Exception { final String TEST_NAME = "test204modifyUserJackSamePasswordNoPasswordHistory"; modifyUserJackPasswordNoHistory(TEST_NAME); - + } - + private void modifyUserJackPasswordNoHistory(String TEST_NAME) throws Exception{ TestUtil.displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); @@ -314,12 +314,12 @@ private void modifyUserJackPasswordNoHistory(String TEST_NAME) throws Exception{ historyEntries.size()); } - - + + private void assertPasswords(String password, ProtectedStringType passwordAfterChange) throws SchemaException, EncryptionException { ProtectedStringType protectedStringType = new ProtectedStringType(); protectedStringType.setClearValue(password); - AssertJUnit.assertTrue("Password doesn't match", + AssertJUnit.assertTrue("Password doesn't match", protector.compare(protectedStringType, passwordAfterChange)); } @@ -329,7 +329,7 @@ private void initPasswordPolicy(String title, int historyLength, String password OperationResult result = task.getResult(); // ObjectReferenceType passwordPolicyRef = ObjectTypeUtil.createObjectRef(passwordPolicyOid, -// ObjectTypes.PASSWORD_POLICY); +// ObjectTypes.PASSWORD_POLICY); modifyObjectReplaceProperty(SecurityPolicyType.class, SECURITY_POLICY_OID, new ItemPath(SecurityPolicyType.F_CREDENTIALS, CredentialsPolicyType.F_PASSWORD, PasswordCredentialsPolicyType.F_HISTORY_LENGTH), task, result, historyLength); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestPolicyMetadata.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestPolicyMetadata.java index 0952ae12fd9..93d73767b0a 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestPolicyMetadata.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestPolicyMetadata.java @@ -44,14 +44,14 @@ @ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestPolicyMetadata extends AbstractLensTest { - + private static final String ROLE_JUDGE_POLICY_RULE_EXCLUSION_NAME = "criminal exclusion"; @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); setDefaultUserTemplate(USER_TEMPLATE_OID); - + addObject(ROLE_PIRATE_SITUATION_ONLY_FILE); addObject(ROLE_MUTINIER_FILE); addObject(ROLE_JUDGE_SITUATION_ONLY_FILE); @@ -61,7 +61,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti addObjects(ROLE_CORP_FILES); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + InternalMonitor.reset(); DebugUtil.setPrettyPrintBeansAs(PrismContext.LANG_YAML); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestPolicyRules.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestPolicyRules.java index 2e5a44c7768..6387c78d750 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestPolicyRules.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestPolicyRules.java @@ -54,14 +54,14 @@ @ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestPolicyRules extends AbstractLensTest { - + private static final String ROLE_JUDGE_POLICY_RULE_EXCLUSION_NAME = "criminal exclusion"; @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); setDefaultUserTemplate(USER_TEMPLATE_OID); - + addObject(ROLE_PIRATE_FILE); addObject(ROLE_MUTINIER_FILE); addObject(ROLE_JUDGE_FILE); @@ -71,7 +71,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti addObjects(ROLE_CORP_FILES); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + InternalMonitor.reset(); // InternalMonitor.setTraceShadowFetchOperation(true); @@ -158,16 +158,16 @@ public void test010JackAssignRoleJudge() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestPolicyRules.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_JUDGE_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", userAfter); assertAssignedRole(userAfter, ROLE_JUDGE_OID); @@ -221,7 +221,7 @@ public void test100AssignRoleMutinierToJack() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestPolicyRules.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + LensContext context = createUserLensContext(); fillContextWithUser(context, USER_JACK_OID, result); addModificationToContextAssignRole(context, USER_JACK_OID, ROLE_MUTINIER_OID); @@ -230,28 +230,28 @@ public void test100AssignRoleMutinierToJack() throws Exception { assertFocusModificationSanity(context); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); projector.project(context, "test", task, result); - - // THEN + + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); assertAssignAccountToJack(context); - - DeltaSetTriple> evaluatedAssignmentTriple = + + DeltaSetTriple> evaluatedAssignmentTriple = (DeltaSetTriple)context.getEvaluatedAssignmentTriple(); // display("Output evaluatedAssignmentTriple", evaluatedAssignmentTriple); - + dumpPolicyRules(context); - + assertEvaluatedRules(context, 4); assertTriggeredRules(context, 0, null); } - + @Test public void test110AssignRolePirateToJack() throws Exception { final String TEST_NAME = "test110AssignRolePirateToJack"; @@ -260,7 +260,7 @@ public void test110AssignRolePirateToJack() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestPolicyRules.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + LensContext context = createUserLensContext(); fillContextWithUser(context, USER_JACK_OID, result); addModificationToContextAssignRole(context, USER_JACK_OID, ROLE_PIRATE_OID); @@ -269,30 +269,30 @@ public void test110AssignRolePirateToJack() throws Exception { assertFocusModificationSanity(context); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); projector.project(context, "test", task, result); - - // THEN + + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertAssignAccountToJack(context); - - DeltaSetTriple> evaluatedAssignmentTriple = + + DeltaSetTriple> evaluatedAssignmentTriple = (DeltaSetTriple)context.getEvaluatedAssignmentTriple(); // display("Output evaluatedAssignmentTriple", evaluatedAssignmentTriple); - + dumpPolicyRules(context); - + assertEvaluatedRules(context, 4); EvaluatedExclusionTrigger trigger = (EvaluatedExclusionTrigger) assertTriggeredRule(context, null, PolicyConstraintKindType.EXCLUSION, 1, true); assertNotNull("No conflicting assignment in trigger", trigger.getConflictingAssignment()); assertEquals("Wrong conflicting assignment in trigger", ROLE_PIRATE_OID, trigger.getConflictingAssignment().getTarget().getOid()); } - + /** * Assignment with an exception from the exclusion rule. */ @@ -304,7 +304,7 @@ public void test112AssignRolePirateWithExceptionToJack() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestPolicyRules.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + LensContext context = createUserLensContext(); fillContextWithUser(context, USER_JACK_OID, result); addModificationToContextAssignRole(context, USER_JACK_OID, ROLE_PIRATE_OID, @@ -318,24 +318,24 @@ public void test112AssignRolePirateWithExceptionToJack() throws Exception { assertFocusModificationSanity(context); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); projector.project(context, "test", task, result); - - // THEN + + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertAssignAccountToJack(context); - - DeltaSetTriple> evaluatedAssignmentTriple = + + DeltaSetTriple> evaluatedAssignmentTriple = (DeltaSetTriple)context.getEvaluatedAssignmentTriple(); // display("Output evaluatedAssignmentTriple", evaluatedAssignmentTriple); dumpPolicyRules(context); - + List evaluatedRules = assertEvaluatedRules(context, 4); assertTriggeredRules(context, 0, null); @@ -343,9 +343,9 @@ public void test112AssignRolePirateWithExceptionToJack() throws Exception { Collection exceptions = evaluatedPolicyRule.getPolicyExceptions(); assertEquals("Wrong number of exceptions", 1, exceptions.size()); PolicyExceptionType policyException = exceptions.iterator().next(); - assertEquals("Wrong rule name in poliy excpetion", ROLE_JUDGE_POLICY_RULE_EXCLUSION_NAME, policyException.getRuleName()); + assertEquals("Wrong rule name in poliy excpetion", ROLE_JUDGE_POLICY_RULE_EXCLUSION_NAME, policyException.getRuleName()); } - + @Test public void test120AssignRoleConstableToJack() throws Exception { final String TEST_NAME = "test120AssignRoleConstableToJack"; @@ -354,7 +354,7 @@ public void test120AssignRoleConstableToJack() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestPolicyRules.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + LensContext context = createUserLensContext(); fillContextWithUser(context, USER_JACK_OID, result); addModificationToContextAssignRole(context, USER_JACK_OID, ROLE_CONSTABLE_OID); @@ -363,30 +363,30 @@ public void test120AssignRoleConstableToJack() throws Exception { assertFocusModificationSanity(context); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); projector.project(context, "test", task, result); - - // THEN + + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + display("Output context", context); - - DeltaSetTriple> evaluatedAssignmentTriple = + + DeltaSetTriple> evaluatedAssignmentTriple = (DeltaSetTriple)context.getEvaluatedAssignmentTriple(); // display("Output evaluatedAssignmentTriple", evaluatedAssignmentTriple); dumpPolicyRules(context); - + assertEvaluatedRules(context, 5); // conflicting assignment was pruned, so the exclusion is no longer present here // EvaluatedExclusionTrigger trigger = (EvaluatedExclusionTrigger) assertTriggeredRule(context, null, PolicyConstraintKindType.EXCLUSION, 1, true); // assertNotNull("No conflicting assignment in trigger", trigger.getConflictingAssignment()); // assertEquals("Wrong conflicting assignment in trigger", ROLE_JUDGE_OID, trigger.getConflictingAssignment().getTarget().getOid()); - + ObjectDelta focusSecondaryDelta = context.getFocusContext().getSecondaryDelta(); PrismAsserts.assertIsModify(focusSecondaryDelta); PrismAsserts.assertModifications(focusSecondaryDelta, 2); @@ -394,12 +394,12 @@ public void test120AssignRoleConstableToJack() throws Exception { assertEquals("Unexpected assignment secondary delta", 1, assignmentDelta.getValuesToDelete().size()); PrismContainerValue deletedAssignment = assignmentDelta.getValuesToDelete().iterator().next(); assertEquals("Wrong OID in deleted assignment", ROLE_JUDGE_OID, deletedAssignment.asContainerable().getTargetRef().getOid()); - + ObjectDelta accountSecondaryDelta = assertAssignAccountToJack(context); - PrismAsserts.assertPropertyAdd(accountSecondaryDelta, + PrismAsserts.assertPropertyAdd(accountSecondaryDelta, getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME), "Constable"); - PrismAsserts.assertPropertyDelete(accountSecondaryDelta, + PrismAsserts.assertPropertyDelete(accountSecondaryDelta, getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME), "Honorable Justice"); } @@ -607,7 +607,7 @@ private List assertEvaluatedRules(LensContext con assertEquals("Unexpected number of evaluated policy rules in the context", expected, rules.size()); return rules; } - + private void assertTriggeredRules(LensContext context, int expected, PolicyConstraintKindType expectedConstraintKind) { List triggers = new ArrayList<>(); forTriggeredRule(context, null, trigger -> { @@ -649,7 +649,7 @@ private EvaluatedPolicyRule getTriggeredRule(LensContext context, Stri } return rules.get(0); } - + private void forTriggeredRule(LensContext context, String targetOid, Consumer handler) { forEvaluatedRule(context, targetOid, rule -> { Collection> triggers = rule.getTriggers(); @@ -658,9 +658,9 @@ private void forTriggeredRule(LensContext context, String targetOid, C } }); } - + private void forEvaluatedRule(LensContext context, String targetOid, Consumer handler) { - DeltaSetTriple> evaluatedAssignmentTriple = + DeltaSetTriple> evaluatedAssignmentTriple = (DeltaSetTriple)context.getEvaluatedAssignmentTriple(); evaluatedAssignmentTriple.simpleAccept(assignment -> { if (targetOid == null || assignment.getTarget() != null && targetOid.equals(assignment.getTarget().getOid())) { @@ -675,7 +675,7 @@ private void dumpPolicyRules(LensContext context) { private ObjectDelta assertAssignAccountToJack(LensContext context) { display("Output context", context); - + assertTrue(context.getFocusContext().getPrimaryDelta().getChangeType() == ChangeType.MODIFY); assertFalse("No account changes", context.getProjectionContexts().isEmpty()); Collection accountContexts = context.getProjectionContexts(); @@ -684,11 +684,11 @@ private ObjectDelta assertAssignAccountToJack(LensContext assertNull("Account primary delta sneaked in", accContext.getPrimaryDelta()); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); - + assertEquals("Wrong decision", SynchronizationPolicyDecision.KEEP,accContext.getSynchronizationPolicyDecision()); - + assertEquals(ChangeType.MODIFY, accountSecondaryDelta.getChangeType()); - + return accountSecondaryDelta; } 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 1c20323521d..f491348b6c9 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 @@ -92,10 +92,10 @@ @ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestProjector extends AbstractLensTest { - - public static final File USER_BARBOSSA_MODIFY_ASSIGNMENT_REPLACE_AC_FILE = new File(TEST_DIR, + + public static final File USER_BARBOSSA_MODIFY_ASSIGNMENT_REPLACE_AC_FILE = new File(TEST_DIR, "user-barbossa-modify-assignment-replace-ac.xml"); - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -110,10 +110,10 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; TestUtil.displayTestTitle(this, TEST_NAME); - + assertNoJackShadow(); } - + @Test public void test010BasicContextOperations() throws Exception { final String TEST_NAME = "test010BasicContextOperations"; @@ -123,21 +123,21 @@ public void test010BasicContextOperations() throws Exception { Task task = taskManager.createTaskInstance(TestProjector.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + LensContext context = createUserLensContext(); LensFocusContext focusContext = fillContextWithUser(context, USER_ELAINE_OID, result); LensProjectionContext accountContext = fillContextWithAccount(context, ACCOUNT_SHADOW_ELAINE_DUMMY_OID, task, result); - + // User deltas - ObjectDelta userDeltaPrimary = createModifyUserReplaceDelta(USER_ELAINE_OID, UserType.F_FULL_NAME, + ObjectDelta userDeltaPrimary = createModifyUserReplaceDelta(USER_ELAINE_OID, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Elaine Threepwood")); ObjectDelta userDeltaPrimaryClone = userDeltaPrimary.clone(); - ObjectDelta userDeltaSecondary = createModifyUserReplaceDelta(USER_ELAINE_OID, UserType.F_FULL_NAME, + ObjectDelta userDeltaSecondary = createModifyUserReplaceDelta(USER_ELAINE_OID, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Elaine LeChuck")); ObjectDelta userDeltaSecondaryClone = userDeltaSecondary.clone(); focusContext.setPrimaryDelta(userDeltaPrimary); focusContext.setSecondaryDelta(userDeltaSecondary, 0); - + // Account Deltas ObjectDelta accountDeltaPrimary = createModifyAccountShadowReplaceAttributeDelta( ACCOUNT_SHADOW_ELAINE_DUMMY_OID, getDummyResourceObject(), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Elie Marley"); @@ -149,23 +149,23 @@ public void test010BasicContextOperations() throws Exception { ObjectDelta accountDeltaSecondaryClone = accountDeltaSecondary.clone(); accountContext.setPrimaryDelta(accountDeltaPrimary); accountContext.setSecondaryDelta(accountDeltaSecondary); - + display("Context before", context); - + // WHEN: checkConsistence context.checkConsistence(); - + display("Context after checkConsistence", context); - + assert focusContext == context.getFocusContext() : "focus context delta replaced"; assert focusContext.getPrimaryDelta() == userDeltaPrimary : "focus primary delta replaced"; assert userDeltaPrimaryClone.equals(userDeltaPrimary) : "focus primary delta changed"; - + ObjectDelta focusSecondaryDelta = focusContext.getSecondaryDelta(); display("Focus secondary delta", focusSecondaryDelta); display("Orig user secondary delta", userDeltaSecondaryClone); assert focusSecondaryDelta.equals(userDeltaSecondaryClone) : "focus secondary delta not equal"; - + assert accountContext == context.findProjectionContext( new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, null)) : "wrong account context"; @@ -173,20 +173,20 @@ public void test010BasicContextOperations() throws Exception { assert accountDeltaPrimaryClone.equals(accountDeltaPrimary) : "account primary delta changed"; assert accountContext.getSecondaryDelta() == accountDeltaSecondary : "account secondary delta replaced"; assert accountDeltaSecondaryClone.equals(accountDeltaSecondary) : "account secondary delta changed"; - + // WHEN: recompute context.recompute(); - + display("Context after recompute", context); - + assert focusContext == context.getFocusContext() : "focus context delta replaced"; assert focusContext.getPrimaryDelta() == userDeltaPrimary : "focus primary delta replaced"; - + focusSecondaryDelta = focusContext.getSecondaryDelta(); display("Focus secondary delta", focusSecondaryDelta); display("Orig user secondary delta", userDeltaSecondaryClone); assert focusSecondaryDelta.equals(userDeltaSecondaryClone) : "focus secondary delta not equal"; - + assert accountContext == context.findProjectionContext( new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, null)) : "wrong account context"; @@ -196,10 +196,10 @@ public void test010BasicContextOperations() throws Exception { assert accountDeltaPrimaryClone.equals(accountDeltaPrimary) : "account primary delta changed"; assert accountContext.getSecondaryDelta() == accountDeltaSecondary : "account secondary delta replaced"; assert accountDeltaSecondaryClone.equals(accountDeltaSecondary) : "account secondary delta changed"; - + } - + @Test public void test100AddAccountToJackDirect() throws Exception { final String TEST_NAME = "test100AddAccountToJackDirect"; @@ -209,28 +209,28 @@ public void test100AddAccountToJackDirect() throws Exception { Task task = taskManager.createTaskInstance(TestProjector.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + LensContext context = createUserLensContext(); fillContextWithUser(context, USER_JACK_OID, result); - // We want "shadow" so the fullname will be computed by outbound expression + // We want "shadow" so the fullname will be computed by outbound expression addModificationToContextAddAccountFromFile(context, ACCOUNT_SHADOW_JACK_DUMMY_FILE); display("Input context", context); assertFocusModificationSanity(context); - + rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); projector.project(context, "test", task, result); - + // THEN TestUtil.displayThen(TEST_NAME); display("Output context", context); // 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()); assertSideEffectiveDeltasOnly(context.getFocusContext().getSecondaryDelta(), "user secondary delta", ActivationStatusType.ENABLED); assertFalse("No account changes", context.getProjectionContexts().isEmpty()); @@ -238,7 +238,7 @@ public void test100AddAccountToJackDirect() throws Exception { Collection accountContexts = context.getProjectionContexts(); assertEquals(1, accountContexts.size()); LensProjectionContext accContext = accountContexts.iterator().next(); - + assertEquals("Wrong policy decision", SynchronizationPolicyDecision.ADD, accContext.getSynchronizationPolicyDecision()); ObjectDelta accountPrimaryDelta = accContext.getPrimaryDelta(); assertEquals(ChangeType.ADD, accountPrimaryDelta.getChangeType()); @@ -262,12 +262,12 @@ public void test100AddAccountToJackDirect() throws Exception { PrismObject accountNew = accContext.getObjectNew(); IntegrationTestTools.assertIcfsNameAttribute(accountNew, "jack"); - IntegrationTestTools.assertAttribute(accountNew, + IntegrationTestTools.assertAttribute(accountNew, getDummyResourceController().getAttributeFullnameQName(), "Jack Sparrow"); - IntegrationTestTools.assertAttribute(accountNew, + IntegrationTestTools.assertAttribute(accountNew, getDummyResourceController().getAttributeWeaponQName(), "mouth", "pistol"); } - + @Test public void test110AssignAccountToJack() throws Exception { final String TEST_NAME = "test110AssignAccountToJack"; @@ -277,7 +277,7 @@ public void test110AssignAccountToJack() throws Exception { Task task = taskManager.createTaskInstance(TestProjector.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + LensContext context = createUserLensContext(); fillContextWithUser(context, USER_JACK_OID, result); addFocusModificationToContext(context, REQ_USER_JACK_MODIFY_ADD_ASSIGNMENT_ACCOUNT_DUMMY); @@ -286,14 +286,14 @@ public void test110AssignAccountToJack() throws Exception { assertFocusModificationSanity(context); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN projector.project(context, "test", task, result); - + // THEN assertAssignAccountToJack(context); } - + /** * Same sa previous test but the deltas are slightly broken. */ @@ -306,7 +306,7 @@ public void test111AssignAccountToJackBroken() throws Exception { Task task = taskManager.createTaskInstance(TestProjector.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + LensContext context = createUserLensContext(); fillContextWithUser(context, USER_JACK_OID, result); addFocusModificationToContext(context, REQ_USER_JACK_MODIFY_ADD_ASSIGNMENT_ACCOUNT_DUMMY); @@ -314,14 +314,14 @@ public void test111AssignAccountToJackBroken() throws Exception { display("Input context", context); assertFocusModificationSanity(context); - + // Let's break it a bit... breakAssignmentDelta(context); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN projector.project(context, "test", task, result); - + // THEN assertAssignAccountToJack(context); } @@ -330,7 +330,7 @@ private void assertAssignAccountToJack(LensContext context) { display("Output context", context); // Not loading anything. The account is already loaded in the context assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + assertTrue(context.getFocusContext().getPrimaryDelta().getChangeType() == ChangeType.MODIFY); assertSideEffectiveDeltasOnly(context.getFocusContext().getSecondaryDelta(), "user secondary delta", ActivationStatusType.ENABLED); assertFalse("No account changes", context.getProjectionContexts().isEmpty()); @@ -341,17 +341,17 @@ private void assertAssignAccountToJack(LensContext context) { assertNull("Account primary delta sneaked in", accContext.getPrimaryDelta()); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); - + assertEquals("Wrong decision", SynchronizationPolicyDecision.ADD,accContext.getSynchronizationPolicyDecision()); - + assertEquals(ChangeType.MODIFY, accountSecondaryDelta.getChangeType()); - + PrismAsserts.assertPropertyReplace(accountSecondaryDelta, getIcfsNameAttributePath() , "jack"); - PrismAsserts.assertPropertyReplace(accountSecondaryDelta, + PrismAsserts.assertPropertyReplace(accountSecondaryDelta, getDummyResourceController().getAttributeFullnamePath() , "Jack Sparrow"); - PrismAsserts.assertPropertyAdd(accountSecondaryDelta, + PrismAsserts.assertPropertyAdd(accountSecondaryDelta, getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME) , "mouth", "pistol"); - + PrismAsserts.assertOrigin(accountSecondaryDelta, OriginType.OUTBOUND); } @@ -383,10 +383,10 @@ public void test250ModifyUserBarbossaLocality() throws Exception { // WHEN projector.project(context, "test", task, result); - + // THEN display("Output context", context); - + assertTrue(context.getFocusContext().getPrimaryDelta().getChangeType() == ChangeType.MODIFY); assertSideEffectiveDeltasOnly("user secondary delta", context.getFocusContext().getSecondaryDelta()); assertFalse("No account changes", context.getProjectionContexts().isEmpty()); @@ -400,11 +400,11 @@ public void test250ModifyUserBarbossaLocality() throws Exception { ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertEquals(ChangeType.MODIFY, accountSecondaryDelta.getChangeType()); assertEquals("Unexpected number of account secondary changes", 3, accountSecondaryDelta.getModifications().size()); - PrismAsserts.assertPropertyReplace(accountSecondaryDelta, + PrismAsserts.assertPropertyReplace(accountSecondaryDelta, getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME) , "Tortuga"); - + PrismAsserts.assertOrigin(accountSecondaryDelta, OriginType.ASSIGNMENTS, OriginType.OUTBOUND); - + } /** @@ -435,10 +435,10 @@ public void test251ModifyUserBarbossaFullname() throws Exception { // WHEN projector.project(context, "test", task, result); - + // THEN display("Output context", context); - + assertTrue(context.getFocusContext().getPrimaryDelta().getChangeType() == ChangeType.MODIFY); assertSideEffectiveDeltasOnly("user secondary delta", context.getFocusContext().getSecondaryDelta()); assertFalse("No account changes", context.getProjectionContexts().isEmpty()); @@ -452,14 +452,14 @@ public void test251ModifyUserBarbossaFullname() throws Exception { 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) , + PrismAsserts.assertPropertyReplace(accountSecondaryDelta, + getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME) , "Captain Hector Barbossa"); - + PrismAsserts.assertOrigin(accountSecondaryDelta, OriginType.OUTBOUND); - + } - + /** * 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. @@ -489,10 +489,10 @@ public void test254ModifyUserBarbossaDisable() throws Exception { // WHEN projector.project(context, "test", task, result); - + // THEN display("Output context", context); - + assertTrue(context.getFocusContext().getPrimaryDelta().getChangeType() == ChangeType.MODIFY); assertSideEffectiveDeltasOnly(context.getFocusContext().getSecondaryDelta(), "user secondary delta", ActivationStatusType.DISABLED); assertFalse("No account changes", context.getProjectionContexts().isEmpty()); @@ -507,13 +507,13 @@ public void test254ModifyUserBarbossaDisable() throws Exception { assertNotNull("No account secondary delta", accountSecondaryDelta); assertEquals(ChangeType.MODIFY, accountSecondaryDelta.getChangeType()); assertEquals("Unexpected number of account secondary changes", 6, accountSecondaryDelta.getModifications().size()); - PropertyDelta enabledDelta = accountSecondaryDelta.findPropertyDelta(new ItemPath(ShadowType.F_ACTIVATION, + PropertyDelta enabledDelta = accountSecondaryDelta.findPropertyDelta(new ItemPath(ShadowType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS)); PrismAsserts.assertReplace(enabledDelta, ActivationStatusType.DISABLED); PrismAsserts.assertOrigin(enabledDelta, OriginType.OUTBOUND); PrismAsserts.assertPropertyReplace(accountSecondaryDelta, SchemaConstants.PATH_ACTIVATION_DISABLE_REASON, SchemaConstants.MODEL_DISABLE_REASON_MAPPED); - + ContainerDelta triggerDelta = accountSecondaryDelta.findContainerDelta(ObjectType.F_TRIGGER); assertNotNull("No trigger delta in account secondary delta", triggerDelta); assertEquals("Wrong trigger delta size", 1, triggerDelta.getValuesToAdd().size()); @@ -525,7 +525,7 @@ public void test254ModifyUserBarbossaDisable() throws Exception { end.add(XmlTypeConverter.createDuration(true, 0, 0, 35, 0, 0, 0)); TestUtil.assertBetween("Wrong trigger timestamp", start, end, triggerType.getTimestamp()); } - + /** * User barbossa has a direct account assignment. Let's modify that assignment and see if the * changes will be reflected. @@ -553,10 +553,10 @@ public void test255ModifyUserBarbossaAssignment() throws Exception { // WHEN projector.project(context, "test", task, result); - + // THEN display("Output context", context); - + assertTrue(context.getFocusContext().getPrimaryDelta().getChangeType() == ChangeType.MODIFY); ObjectDelta userSecondaryDelta = context.getFocusContext().getSecondaryDelta(); display("User Secondary Delta", userSecondaryDelta); @@ -573,13 +573,13 @@ public void test255ModifyUserBarbossaAssignment() throws Exception { assertEquals(ChangeType.MODIFY, accountSecondaryDelta.getChangeType()); // There is a lot of changes caused by the reconciliation. But we are only interested in the new one assertEquals("Unexpected number of account secondary changes", 3, accountSecondaryDelta.getModifications().size()); - PrismAsserts.assertPropertyAdd(accountSecondaryDelta, + PrismAsserts.assertPropertyAdd(accountSecondaryDelta, getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME), "Pirate of Caribbean"); PrismAsserts.assertOrigin(accountSecondaryDelta, OriginType.RECONCILIATION, OriginType.OUTBOUND); - + } - + /** * The drink attribute is NOT tolerant. Therefore an attempt to manually change it using * account primary delta should fail. @@ -598,7 +598,7 @@ public void test260ModifyAccountBarbossaDrinkReplace() throws Exception { LensContext context = createUserLensContext(); fillContextWithUser(context, USER_BARBOSSA_OID, result); fillContextWithAccount(context, ACCOUNT_HBARBOSSA_DUMMY_OID, task, result); - addModificationToContextReplaceAccountAttribute(context, ACCOUNT_HBARBOSSA_DUMMY_OID, + addModificationToContextReplaceAccountAttribute(context, ACCOUNT_HBARBOSSA_DUMMY_OID, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, "Water"); context.recompute(); @@ -609,15 +609,15 @@ public void test260ModifyAccountBarbossaDrinkReplace() throws Exception { try { // WHEN projector.project(context, "test", task, result); - + AssertJUnit.fail("Unexpected success of projector"); } catch (PolicyViolationException e) { // This is expected - + } - + } - + /** * The quote attribute has a strong mapping and is tolerant. Therefore an attempt to manually change it using * account primary delta should succeed. The modification is by purpose a replace modification. Therefore the @@ -638,7 +638,7 @@ public void test261ModifyAccountBarbossaQuoteReplace() throws Exception { LensContext context = createUserLensContext(); fillContextWithUser(context, USER_BARBOSSA_OID, result); fillContextWithAccount(context, ACCOUNT_HBARBOSSA_DUMMY_OID, task, result); - addModificationToContextReplaceAccountAttribute(context, ACCOUNT_HBARBOSSA_DUMMY_OID, + addModificationToContextReplaceAccountAttribute(context, ACCOUNT_HBARBOSSA_DUMMY_OID, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "I'm disinclined to acquiesce to your request."); context.recompute(); @@ -648,10 +648,10 @@ public void test261ModifyAccountBarbossaQuoteReplace() throws Exception { // WHEN projector.project(context, "test", task, result); - + // THEN display("Output context", context); - + assertNull("Unexpected user primary changes", context.getFocusContext().getPrimaryDelta()); assertSideEffectiveDeltasOnly("user secondary delta", context.getFocusContext().getSecondaryDelta()); assertFalse("No account changes", context.getProjectionContexts().isEmpty()); @@ -663,25 +663,25 @@ public void test261ModifyAccountBarbossaQuoteReplace() throws Exception { ObjectDelta accountPrimaryDelta = accContext.getPrimaryDelta(); 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) , + PrismAsserts.assertPropertyReplace(accountPrimaryDelta, + getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME) , "I'm disinclined to acquiesce to your request."); - + 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) , + PrismAsserts.assertPropertyAdd(accountSecondaryDelta, + 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. @@ -706,8 +706,8 @@ public void test269DeleteBarbossaDummyAccount() throws Exception { display("Input context", context); try { - - // WHEN + + // WHEN projector.project(context, "test", task, result); // THEN: fail @@ -720,9 +720,9 @@ public void test269DeleteBarbossaDummyAccount() throws Exception { // this is expected display("Expected exception",e); } - + } - + @Test public void test270AddUserBarbossaAssignmentBrethren() throws Exception { final String TEST_NAME = "test270AddUserBarbossaAssignmentBrethren"; @@ -737,7 +737,7 @@ public void test270AddUserBarbossaAssignmentBrethren() throws Exception { LensContext context = createUserLensContext(); fillContextWithUser(context, USER_BARBOSSA_OID, result); fillContextWithAccount(context, ACCOUNT_HBARBOSSA_DUMMY_OID, task, result); - addFocusDeltaToContext(context, createAssignmentUserDelta(USER_BARBOSSA_OID, ORG_BRETHREN_OID, + addFocusDeltaToContext(context, createAssignmentUserDelta(USER_BARBOSSA_OID, ORG_BRETHREN_OID, OrgType.COMPLEX_TYPE, null, null, true)); context.recompute(); @@ -747,10 +747,10 @@ public void test270AddUserBarbossaAssignmentBrethren() throws Exception { // WHEN projector.project(context, "test", task, result); - + // THEN display("Output context", context); - + assertTrue(context.getFocusContext().getPrimaryDelta().getChangeType() == ChangeType.MODIFY); ObjectDelta userSecondaryDelta = context.getFocusContext().getSecondaryDelta(); display("User Secondary Delta", userSecondaryDelta); @@ -767,9 +767,9 @@ public void test270AddUserBarbossaAssignmentBrethren() throws Exception { assertEquals(ChangeType.MODIFY, accountSecondaryDelta.getChangeType()); // iteration & iterationToken assertEquals("Unexpected number of account secondary changes", 2, accountSecondaryDelta.getModifications().size()); - + } - + @Test public void test275DeleteUserBarbossaAssignmentBrethren() throws Exception { final String TEST_NAME = "test275DeleteUserBarbossaAssignmentBrethren"; @@ -784,16 +784,16 @@ public void test275DeleteUserBarbossaAssignmentBrethren() throws Exception { modifyUserReplace(USER_BARBOSSA_OID, UserType.F_ORGANIZATION, task, result, PrismTestUtil.createPolyString(ORG_BRETHREN_INDUCED_ORGANIZATION)); LensContext context = createUserLensContext(); PrismObject focus = repositoryService.getObject(UserType.class, USER_BARBOSSA_OID, null, result); - ObjectDelta addAssignmentDelta = createAssignmentUserDelta(USER_BARBOSSA_OID, ORG_BRETHREN_OID, + ObjectDelta addAssignmentDelta = createAssignmentUserDelta(USER_BARBOSSA_OID, ORG_BRETHREN_OID, OrgType.COMPLEX_TYPE, null, null, true); addAssignmentDelta.applyTo(focus); fillContextWithFocus(context, focus); - + fillContextWithAccount(context, ACCOUNT_HBARBOSSA_DUMMY_OID, task, result); - - addFocusDeltaToContext(context, createAssignmentUserDelta(USER_BARBOSSA_OID, ORG_BRETHREN_OID, + + addFocusDeltaToContext(context, createAssignmentUserDelta(USER_BARBOSSA_OID, ORG_BRETHREN_OID, OrgType.COMPLEX_TYPE, null, null, false)); - + context.recompute(); display("Input context", context); @@ -802,10 +802,10 @@ public void test275DeleteUserBarbossaAssignmentBrethren() throws Exception { // WHEN projector.project(context, "test", task, result); - + // THEN display("Output context", context); - + assertTrue(context.getFocusContext().getPrimaryDelta().getChangeType() == ChangeType.MODIFY); ObjectDelta userSecondaryDelta = context.getFocusContext().getSecondaryDelta(); display("User Secondary Delta", userSecondaryDelta); @@ -816,9 +816,9 @@ public void test275DeleteUserBarbossaAssignmentBrethren() throws Exception { LensProjectionContext accContext = accountContexts.iterator().next(); assertNull(accContext.getPrimaryDelta()); assertEquals(SynchronizationPolicyDecision.KEEP,accContext.getSynchronizationPolicyDecision()); - + } - + @Test public void test280AddUserBarbossaAssignmentMutinier() throws Exception { final String TEST_NAME = "test280AddUserBarbossaAssignmentMutinier"; @@ -833,7 +833,7 @@ public void test280AddUserBarbossaAssignmentMutinier() throws Exception { LensContext context = createUserLensContext(); fillContextWithUser(context, USER_BARBOSSA_OID, result); fillContextWithAccount(context, ACCOUNT_HBARBOSSA_DUMMY_OID, task, result); - addFocusDeltaToContext(context, createAssignmentUserDelta(USER_BARBOSSA_OID, ROLE_MUTINIER_OID, + addFocusDeltaToContext(context, createAssignmentUserDelta(USER_BARBOSSA_OID, ROLE_MUTINIER_OID, RoleType.COMPLEX_TYPE, null, null, true)); context.recompute(); @@ -843,10 +843,10 @@ public void test280AddUserBarbossaAssignmentMutinier() throws Exception { // WHEN projector.project(context, "test", task, result); - + // THEN display("Output context", context); - + assertTrue(context.getFocusContext().getPrimaryDelta().getChangeType() == ChangeType.MODIFY); ObjectDelta userSecondaryDelta = context.getFocusContext().getSecondaryDelta(); assertSideEffectiveDeltasOnly("user secondary delta", userSecondaryDelta); @@ -861,12 +861,12 @@ public void test280AddUserBarbossaAssignmentMutinier() throws Exception { assertNotNull("No account secondary delta", accountSecondaryDelta); assertEquals(ChangeType.MODIFY, accountSecondaryDelta.getChangeType()); assertEquals("Unexpected number of account secondary changes", 1, accountSecondaryDelta.getModifications().size()); - PrismAsserts.assertPropertyAdd(accountSecondaryDelta, + PrismAsserts.assertPropertyAdd(accountSecondaryDelta, getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME), "Damned mutinier"); PrismAsserts.assertOrigin(accountSecondaryDelta, OriginType.ASSIGNMENTS); } - + @Test public void test301AssignConflictingAccountToJack() throws Exception { final String TEST_NAME = "test301AssignConflictingAccountToJack"; @@ -877,10 +877,10 @@ public void test301AssignConflictingAccountToJack() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + // Make sure there is a shadow with conflicting account repoAddObjectFromFile(ACCOUNT_SHADOW_JACK_DUMMY_FILE, result); - + LensContext context = createUserLensContext(); fillContextWithUser(context, USER_JACK_OID, result); addFocusModificationToContext(context, REQ_USER_JACK_MODIFY_ADD_ASSIGNMENT_ACCOUNT_DUMMY); @@ -888,13 +888,13 @@ public void test301AssignConflictingAccountToJack() throws Exception { display("Input context", context); assertFocusModificationSanity(context); - + // WHEN projector.project(context, "test", task, result); - + // THEN display("Output context", context); - + assertTrue(context.getFocusContext().getPrimaryDelta().getChangeType() == ChangeType.MODIFY); assertSideEffectiveDeltasOnly(context.getFocusContext().getSecondaryDelta(), "user secondary delta", ActivationStatusType.ENABLED); assertFalse("No account changes", context.getProjectionContexts().isEmpty()); @@ -905,9 +905,9 @@ public void test301AssignConflictingAccountToJack() throws Exception { assertNull(accContext.getPrimaryDelta()); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); - + assertEquals("Wrong decision", SynchronizationPolicyDecision.ADD,accContext.getSynchronizationPolicyDecision()); - + assertEquals(ChangeType.MODIFY, accountSecondaryDelta.getChangeType()); PrismAsserts.assertPropertyReplace(accountSecondaryDelta, getIcfsNameAttributePath() , "jack"); @@ -915,7 +915,7 @@ public void test301AssignConflictingAccountToJack() throws Exception { PrismAsserts.assertOrigin(accountSecondaryDelta, OriginType.OUTBOUND); } - + @Test public void test400ImportHermanDummy() throws Exception { final String TEST_NAME = "test400ImportHermanDummy"; @@ -940,24 +940,24 @@ public void test400ImportHermanDummy() throws Exception { // WHEN projector.project(context, "test", task, result); - + // THEN display("Output context", context); - + // TODO - + assertTrue(context.getFocusContext().getPrimaryDelta().getChangeType() == ChangeType.ADD); ObjectDelta userSecondaryDelta = context.getFocusContext().getSecondaryDelta(); assertNotNull("No user secondary delta", userSecondaryDelta); PrismAsserts.assertPropertyAdd(userSecondaryDelta, UserType.F_DESCRIPTION, "Came from Monkey Island"); - + assertFalse("No account changes", context.getProjectionContexts().isEmpty()); Collection accountContexts = context.getProjectionContexts(); assertEquals(1, accountContexts.size()); LensProjectionContext accContext = accountContexts.iterator().next(); assertNull(accContext.getPrimaryDelta()); - + ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); PrismAsserts.assertNoItemDelta(accountSecondaryDelta, SchemaTestConstants.ICFS_NAME_PATH); @@ -998,16 +998,16 @@ public void test401ImportHermanDummy() throws Exception { // WHEN projector.project(context, "test", task, result); - + // THEN display("Output context", context); - + // TODO - + assertTrue(context.getFocusContext().getPrimaryDelta().getChangeType() == ChangeType.ADD); ObjectDelta userSecondaryDelta = context.getFocusContext().getSecondaryDelta(); assertNotNull("No user secondary delta", userSecondaryDelta); - + assertFalse("No account changes", context.getProjectionContexts().isEmpty()); Collection accountContexts = context.getProjectionContexts(); @@ -1020,7 +1020,7 @@ public void test401ImportHermanDummy() throws Exception { assertOriginWithSideEffectChanges(userSecondaryDelta, OriginType.INBOUND); } - + @Test public void test450GuybrushInboundFromDelta() throws Exception { final String TEST_NAME = "test450GuybrushInboundFromDelta"; @@ -1043,15 +1043,15 @@ public void test450GuybrushInboundFromDelta() throws Exception { // WHEN projector.project(context, "test", task, result); - + // THEN display("Output context", context); - + assertNoUserPrimaryDelta(context); 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); } @@ -1065,7 +1065,7 @@ public void test451GuybrushInboundFromAbsolute() throws Exception { Task task = taskManager.createTaskInstance(TestProjector.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - + PrismObject passPolicy = PrismTestUtil.parseObject(PASSWORD_POLICY_GLOBAL_FILE); ObjectDelta delta = ObjectDelta.createAddDelta(passPolicy); Collection> deltas = new ArrayList>(); @@ -1076,7 +1076,7 @@ public void test451GuybrushInboundFromAbsolute() throws Exception { ObjectDelta refDelta = ObjectDelta.createModificationAddReference(SystemConfigurationType.class, SYSTEM_CONFIGURATION_OID, SystemConfigurationType.F_GLOBAL_PASSWORD_POLICY_REF, prismContext, passPolicy); // We need to execute this using repo. Otherwise logging config will be ruined repositoryService.modifyObject(SystemConfigurationType.class, SYSTEM_CONFIGURATION_OID, refDelta.getModifications(), result); - + PrismObject passPol = modelService.getObject(ValuePolicyType.class, PASSWORD_POLICY_GLOBAL_OID, null, task, result); assertNotNull(passPol); PrismObject sysConfig = modelService.getObject(SystemConfigurationType.class, SYSTEM_CONFIGURATION_OID, null, task, result); @@ -1098,20 +1098,20 @@ public void test451GuybrushInboundFromAbsolute() throws Exception { // WHEN projector.project(context, "test", task, result); - + // THEN display("Output context", context); - + assertNoUserPrimaryDelta(context); 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"; @@ -1122,17 +1122,17 @@ public void test500ReconcileGuybrushDummy() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - + // Change the guybrush account on dummy resource directly. This creates inconsistency. DummyAccount dummyAccount = getDummyResource().getAccountByUsername(ACCOUNT_GUYBRUSH_DUMMY_USERNAME); dummyAccount.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Fuycrush Greepdood"); dummyAccount.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Phatt Island"); - + LensContext context = createUserLensContext(); context.setChannel(SchemaConstants.CHANGE_CHANNEL_RECON); fillContextWithUser(context, USER_GUYBRUSH_OID, result); context.setDoReconciliationForAllProjections(true); - + display("Guybrush account before: ", dummyAccount); display("Input context", context); @@ -1141,12 +1141,12 @@ public void test500ReconcileGuybrushDummy() throws Exception { // WHEN projector.project(context, "test", task, result); - + // THEN display("Output context", context); - + assertNull("User primary delta sneaked in", context.getFocusContext().getPrimaryDelta()); - + // There is an inbound mapping for password that generates it if not present. it is triggered in this case. ObjectDelta userSecondaryDelta = context.getFocusContext().getSecondaryDelta(); assertTrue(userSecondaryDelta.getChangeType() == ChangeType.MODIFY); @@ -1161,7 +1161,7 @@ public void test500ReconcileGuybrushDummy() throws Exception { assertEquals(1, accountContexts.size()); LensProjectionContext accContext = accountContexts.iterator().next(); assertNull(accContext.getPrimaryDelta()); - + ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); PrismAsserts.assertNoItemDelta(accountSecondaryDelta, SchemaTestConstants.ICFS_NAME_PATH); // Full name is not changed, it has normal mapping strength @@ -1171,9 +1171,9 @@ public void test500ReconcileGuybrushDummy() throws Exception { assertNotNull("No location delta in projection secondary delta", locationDelta); PrismAsserts.assertReplace(locationDelta, "Melee Island"); PrismAsserts.assertOrigin(locationDelta, OriginType.RECONCILIATION); - + } - + /** * Let's add user without a fullname. The expression in user template should compute it. */ @@ -1198,22 +1198,22 @@ public void test600AddLargo() throws Exception { // WHEN projector.project(context, "test", task, result); - + // THEN display("Output context", context); - + // TODO - + assertTrue(context.getFocusContext().getPrimaryDelta().getChangeType() == ChangeType.ADD); ObjectDelta userSecondaryDelta = context.getFocusContext().getSecondaryDelta(); assertNotNull("No user secondary delta", userSecondaryDelta); assertFalse("Empty user secondary delta", userSecondaryDelta.isEmpty()); - PrismAsserts.assertPropertyReplace(userSecondaryDelta, UserType.F_FULL_NAME, + PrismAsserts.assertPropertyReplace(userSecondaryDelta, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Largo LaGrande")); PrismAsserts.assertPropertyReplace(userSecondaryDelta, UserType.F_NICK_NAME, PrismTestUtil.createPolyString("Largo LaGrande")); // MID-2149 } - + private void assertNoJackShadow() throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject jackAccount = findAccountByUsername(ACCOUNT_JACK_DUMMY_USERNAME, getDummyResourceObject()); assertNull("Found jack's shadow!", jackAccount); @@ -1238,5 +1238,5 @@ private void assertOriginWithSideEffectChanges(ObjectDelta delta, Orig 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 0548e8d467a..64048347586 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 @@ -94,7 +94,7 @@ @ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestProjectorPersona extends AbstractLensTest { - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -113,10 +113,10 @@ public void test100AssignRolePersonaAdminToJack() throws Exception { Task task = taskManager.createTaskInstance(TestProjectorPersona.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + LensContext context = createUserLensContext(); fillContextWithUser(context, USER_JACK_OID, result); - ObjectDelta focusDelta = createAssignmentFocusDelta(UserType.class, USER_JACK_OID, + ObjectDelta focusDelta = createAssignmentFocusDelta(UserType.class, USER_JACK_OID, ROLE_PERSONA_ADMIN_OID, RoleType.COMPLEX_TYPE, null, null, null, true); addFocusDeltaToContext(context, focusDelta); @@ -124,21 +124,21 @@ public void test100AssignRolePersonaAdminToJack() throws Exception { assertFocusModificationSanity(context); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN projector.project(context, "test", task, result); - + // THEN display("Output context", context); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + assertTrue(context.getFocusContext().getPrimaryDelta().getChangeType() == ChangeType.MODIFY); assertSideEffectiveDeltasOnly(context.getFocusContext().getSecondaryDelta(), "user secondary delta", ActivationStatusType.ENABLED); assertTrue("Unexpected projection changes", context.getProjectionContexts().isEmpty()); - + DeltaSetTriple> evaluatedAssignmentTriple = context.getEvaluatedAssignmentTriple(); assertNotNull("No evaluatedAssignmentTriple", evaluatedAssignmentTriple); - + assertTrue("Unexpected evaluatedAssignmentTriple zero set", evaluatedAssignmentTriple.getZeroSet().isEmpty()); assertTrue("Unexpected evaluatedAssignmentTriple minus set", evaluatedAssignmentTriple.getMinusSet().isEmpty()); assertNotNull("No evaluatedAssignmentTriple plus set", evaluatedAssignmentTriple.getPlusSet()); @@ -160,9 +160,9 @@ public void test100AssignRolePersonaAdminToJack() throws Exception { assertNotNull("No personaConstructionType", personaConstructionType); 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 beac72e7171..35e0a55b88a 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 @@ -65,22 +65,22 @@ @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, + + 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) private Projector projector; - + @Autowired(required = true) private TaskManager taskManager; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + addObject(ROLE_PIRATE_FILE); - + // Set user template. This DOES NOT EXIST in the repository. // Setting this nonsense is used to check that projector does not even try to use the template. setDefaultUserTemplate(USER_TEMPLATE_OID); @@ -99,22 +99,22 @@ public void test100AddEntitlementToPirateDirect() throws Exception { Task task = taskManager.createTaskInstance(TestProjectorRoleEntitlement.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + LensContext context = createLensContext(RoleType.class); fillContextWithFocus(context, RoleType.class, ROLE_PIRATE_OID, result); - // We want "shadow" so the fullname will be computed by outbound expression + // We want "shadow" so the fullname will be computed by outbound expression addModificationToContextAddProjection(context, RoleType.class, ENTITLEMENT_SHADOW_PIRATE_DUMMY_FILE); display("Input context", context); assertFocusModificationSanity(context); - + // WHEN projector.project(context, "test", task, result); - + // THEN display("Output context", context); - + 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()); @@ -122,7 +122,7 @@ public void test100AddEntitlementToPirateDirect() throws Exception { Collection accountContexts = context.getProjectionContexts(); assertEquals(1, accountContexts.size()); LensProjectionContext projContext = accountContexts.iterator().next(); - + assertEquals("Wrong policy decision", SynchronizationPolicyDecision.ADD, projContext.getSynchronizationPolicyDecision()); ObjectDelta accountPrimaryDelta = projContext.getPrimaryDelta(); assertEquals(ChangeType.ADD, accountPrimaryDelta.getChangeType()); @@ -139,7 +139,7 @@ public void test100AddEntitlementToPirateDirect() throws Exception { ObjectDelta projSecondaryDelta = projContext.getSecondaryDelta(); assertEquals(ChangeType.MODIFY, projSecondaryDelta.getChangeType()); - + PropertyDelta groupDescriptionDelta = projSecondaryDelta.findPropertyDelta( getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_GROUP_ATTRIBUTE_DESCRIPTION)); assertNotNull("No group description delta", groupDescriptionDelta); @@ -148,11 +148,11 @@ public void test100AddEntitlementToPirateDirect() throws Exception { PrismObject projectionNew = projContext.getObjectNew(); IntegrationTestTools.assertIcfsNameAttribute(projectionNew, "pirate"); - IntegrationTestTools.assertAttribute(projectionNew, + IntegrationTestTools.assertAttribute(projectionNew, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_GROUP_ATTRIBUTE_DESCRIPTION), "Bloody pirates"); } - + @Test public void test110AssignEntitlementToPirate() throws Exception { final String TEST_NAME = "test110AssignEntitlementToPirate"; @@ -162,24 +162,24 @@ public void test110AssignEntitlementToPirate() throws Exception { Task task = taskManager.createTaskInstance(TestProjectorRoleEntitlement.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + LensContext context = createLensContext(RoleType.class); fillContextWithFocus(context, RoleType.class, ROLE_PIRATE_OID, result); - ObjectDelta roleAssignmentDelta = createAssignmentDelta(RoleType.class, + ObjectDelta roleAssignmentDelta = createAssignmentDelta(RoleType.class, ROLE_PIRATE_OID, RESOURCE_DUMMY_OID, ShadowKindType.ENTITLEMENT, "group", true); addFocusDeltaToContext(context, roleAssignmentDelta); display("Input context", context); assertFocusModificationSanity(context); - + // WHEN projector.project(context, "test", task, result); - + // THEN assertAssignEntitlementToPirate(context); } - + /** * Same sa previous test but the deltas are slightly broken. */ @@ -192,30 +192,30 @@ public void test111AssignEntitlementToPirateBroken() throws Exception { Task task = taskManager.createTaskInstance(TestProjectorRoleEntitlement.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + LensContext context = createLensContext(RoleType.class); fillContextWithFocus(context, RoleType.class, ROLE_PIRATE_OID, result); - ObjectDelta roleAssignmentDelta = createAssignmentDelta(RoleType.class, + ObjectDelta roleAssignmentDelta = createAssignmentDelta(RoleType.class, ROLE_PIRATE_OID, RESOURCE_DUMMY_OID, ShadowKindType.ENTITLEMENT, "group", true); addFocusDeltaToContext(context, roleAssignmentDelta); display("Input context", context); assertFocusModificationSanity(context); - + // Let's break it a bit... breakAssignmentDelta(context); - + // WHEN projector.project(context, "test", task, result); - + // THEN assertAssignEntitlementToPirate(context); } - + 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); assertFalse("No projection changes", context.getProjectionContexts().isEmpty()); @@ -226,18 +226,18 @@ private void assertAssignEntitlementToPirate(LensContext context) { assertNull("Projection primary delta sneaked in", projContext.getPrimaryDelta()); ObjectDelta projSecondaryDelta = projContext.getSecondaryDelta(); - + assertEquals("Wrong decision", SynchronizationPolicyDecision.ADD,projContext.getSynchronizationPolicyDecision()); - + assertEquals(ChangeType.MODIFY, projSecondaryDelta.getChangeType()); - + PrismAsserts.assertPropertyReplace(projSecondaryDelta, getIcfsNameAttributePath() , "Pirate"); - PrismAsserts.assertPropertyReplace(projSecondaryDelta, + PrismAsserts.assertPropertyReplace(projSecondaryDelta, getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_GROUP_ATTRIBUTE_DESCRIPTION), - "Bloody pirates"); + "Bloody pirates"); PrismAsserts.assertOrigin(projSecondaryDelta, OriginType.OUTBOUND); } - + } 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 cd383bad3ac..69ea187d31c 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 @@ -50,10 +50,10 @@ @ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestReconScript extends AbstractInternalModelIntegrationTest { - + private static final String TASK_RECON_DUMMY_FILENAME = "src/test/resources/common/task-reconcile-dummy.xml"; private static final String TASK_RECON_DUMMY_OID = "10000000-0000-0000-5656-565600000004"; - + private static final String ACCOUNT_BEFORE_SCRIPT_FILENAME = "src/test/resources/lens/account-before-script.xml"; private static final String ACCOUNT_BEFORE_SCRIPT_OID = "acc00000-0000-0000-0000-000000001234"; @@ -64,18 +64,18 @@ public void text001testReconcileScriptsWhenProvisioning() throws Exception{ Task task = taskManager.createTaskInstance(TEST_NAME); OperationResult parentResult = new OperationResult(TEST_NAME); - + ObjectDelta delta = createModifyUserAddAccount(USER_JACK_OID, getDummyResourceObject()); Collection> deltas = new ArrayList>(); deltas.add(delta); - + task.setChannel(QNameUtil.qNameToUri(SchemaConstants.CHANGE_CHANNEL_RECON)); modelService.executeChanges(deltas, ModelExecuteOptions.createReconcile(), task, parentResult); - + delta = createModifyUserReplaceDelta(USER_JACK_OID, new ItemPath(UserType.F_FULL_NAME), new PolyString("tralala")); deltas = new ArrayList>(); deltas.add(delta); - + modelService.executeChanges(deltas, ModelExecuteOptions.createReconcile(), task, parentResult); delta = createModifyUserReplaceDelta(USER_BARBOSSA_OID, new ItemPath(UserType.F_FULL_NAME), new PolyString("tralala")); @@ -83,8 +83,8 @@ public void text001testReconcileScriptsWhenProvisioning() throws Exception{ deltas.add(delta); modelService.executeChanges(deltas, ModelExecuteOptions.createReconcile(), task, parentResult); - - + + for (ScriptHistoryEntry script : getDummyResource().getScriptHistory()){ String userName = (String) script.getParams().get("midpoint_usercn"); String idPath = (String) script.getParams().get("midpoint_idpath"); @@ -93,30 +93,30 @@ public void text001testReconcileScriptsWhenProvisioning() throws Exception{ 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 +"]"); } } } - + @Test public void test002testReconcileScriptsWhenReconciling() throws Exception{ final String TEST_NAME = "test002testReconcileScriptsWhenReconciling"; TestUtil.displayTestTitle(this, TEST_NAME); getDummyResource().getScriptHistory().clear(); - + importObjectFromFile(new File(TASK_RECON_DUMMY_FILENAME)); - + waitForTaskStart(TASK_RECON_DUMMY_OID, false, DEFAULT_TASK_WAIT_TIMEOUT); - + waitForTaskNextRunAssertSuccess(TASK_RECON_DUMMY_OID, false, DEFAULT_TASK_WAIT_TIMEOUT); - + waitForTaskFinish(TASK_RECON_DUMMY_OID, false); - + 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"); @@ -124,14 +124,14 @@ public void test002testReconcileScriptsWhenReconciling() throws Exception{ 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 +"]"); } } - + } - + @Test public void test003testReconcileScriptsAddUserAction() throws Exception{ final String TEST_NAME = "test003testReconcileScriptsAddUserAction"; @@ -141,35 +141,35 @@ public void test003testReconcileScriptsAddUserAction() throws Exception{ OperationResult parentResult = new OperationResult(TEST_NAME); ShadowType shadow = parseObjectType(new File(ACCOUNT_BEFORE_SCRIPT_FILENAME), ShadowType.class); - + provisioningService.addObject(shadow.asPrismObject(), null, null, task, parentResult); - + getDummyResource().getScriptHistory().clear(); - + waitForTaskStart(TASK_RECON_DUMMY_OID, false, DEFAULT_TASK_WAIT_TIMEOUT); waitForTaskNextRunAssertSuccess(TASK_RECON_DUMMY_OID, false, DEFAULT_TASK_WAIT_TIMEOUT); - + waitForTaskFinish(TASK_RECON_DUMMY_OID, true); - + PrismObject afterRecon = repositoryService.getObject(ShadowType.class, ACCOUNT_BEFORE_SCRIPT_OID, null, parentResult); AssertJUnit.assertNotNull(afterRecon); - + ShadowType afterReconShadow = afterRecon.asObjectable(); - + if (afterReconShadow.getResult() != null) { OperationResult beforeScriptResult = OperationResult .createOperationResult(afterReconShadow.getResult()); display("result in shadow: " + beforeScriptResult); AssertJUnit.fail("Operation in shadow not null, recocniliation failed. "); } - + 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()){ - + String userName = (String) script.getParams().get("midpoint_usercn"); String idPath = (String) script.getParams().get("midpoint_idpath"); String tempPath = (String) script.getParams().get("midpoint_temppath"); @@ -177,88 +177,88 @@ public void test003testReconcileScriptsAddUserAction() throws Exception{ 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 +"]"); } } - + } - + @Test public void test005TestDryRunDelete() throws Exception{ final String TEST_NAME = "test005TestDryRunDelete"; TestUtil.displayTestTitle(this, TEST_NAME); - + PrismObject task = getTask(TASK_RECON_DUMMY_OID); OperationResult parentResult = new OperationResult(TEST_NAME); - + PropertyDelta dryRunDelta = PropertyDelta.createModificationReplaceProperty(new ItemPath(TaskType.F_EXTENSION, SchemaConstants.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); - + waitForTaskFinish(TASK_RECON_DUMMY_OID, false); - + PrismObject shadow = repositoryService.getObject(ShadowType.class, ACCOUNT_BEFORE_SCRIPT_OID, null, parentResult); AssertJUnit.assertNotNull(shadow); - + 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"; TestUtil.displayTestTitle(this, TEST_NAME); - + PrismObject task = getTask(TASK_RECON_DUMMY_OID); OperationResult parentResult = new OperationResult(TEST_NAME); - + PropertyDelta dryRunDelta = PropertyDelta.createModificationReplaceProperty(new ItemPath(TaskType.F_EXTENSION, SchemaConstants.MODEL_EXTENSION_DRY_RUN), task.getDefinition(), false); Collection modifications = new ArrayList<>(); modifications.add(dryRunDelta); - + repositoryService.modifyObject(TaskType.class, TASK_RECON_DUMMY_OID, modifications, parentResult); - + // dummyResource.deleteAccount("beforeScript"); // WHEN TestUtil.displayWhen(TEST_NAME); waitForTaskStart(TASK_RECON_DUMMY_OID, false); - + waitForTaskNextRunAssertSuccess(TASK_RECON_DUMMY_OID, false); - + waitForTaskFinish(TASK_RECON_DUMMY_OID, false); - + // THEN TestUtil.displayThen(TEST_NAME); - + try{ PrismObject shadow = repositoryService.getObject(ShadowType.class, ACCOUNT_BEFORE_SCRIPT_OID, null, parentResult); - + display("Unexpected shadow", shadow); AssertJUnit.fail("Expected object not found, but haven't got one"); } catch (ObjectNotFoundException ex){ //this is ok } - + PrismObject user = repositoryService.searchShadowOwner(ACCOUNT_BEFORE_SCRIPT_OID, null, parentResult); display("Unexpected owner", user); AssertJUnit.assertNull("Owner for account " + ACCOUNT_BEFORE_SCRIPT_OID + " was found, but it should be not.", user); - - + + } } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/migrator/TestMigrator.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/migrator/TestMigrator.java index d424549ad10..e860e923c29 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/migrator/TestMigrator.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/migrator/TestMigrator.java @@ -53,18 +53,18 @@ * */ public class TestMigrator { - + public static final File TEST_DIR = new File("src/test/resources/migrator"); private static final File TEST_DIR_BEFORE = new File(TEST_DIR, "before"); private static final File TEST_DIR_AFTER = new File(TEST_DIR, "after"); - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - - + + @Test public void testMigrateUserTemplate() throws Exception { TestUtil.displayTestTitle("testMigrateUserTemplate"); @@ -75,56 +75,56 @@ public void testMigrateUserTemplate() throws Exception { continue; } File afterFile = new File(TEST_DIR_AFTER, beforeName); - + assertSimpleMigration(beforeFile, afterFile); } } - + @Test public void testUserCredentials() throws Exception{ Migrator migrator = createMigrator(); - + PrismContext prismContext = PrismTestUtil.getPrismContext(); PrismObject oldUser = prismContext.parseObject(new File(TEST_DIR + "/user-migrate-credentials.xml")); - + PrismObject newUser = migrator.migrate(oldUser); - + UserType newUserType = newUser.asObjectable(); - + assertNull("Credentials in migrated object must be null.", newUserType.getCredentials()); assertNotNull("Migrated user must contain assignment.", newUserType.getAssignment()); assertEquals("Migrated user must contain 1 assignment.", newUserType.getAssignment().size(), 1); - + AssignmentType superUserRole = newUserType.getAssignment().get(0); - + assertNotNull("Target ref in the user's assignment must not be null.", superUserRole.getTargetRef()); assertEquals(superUserRole.getTargetRef().getOid(), SystemObjectsType.ROLE_SUPERUSER.value()); } - + private void assertSimpleMigration(File fileOld, File fileNew) throws SchemaException, IOException { // GIVEN Migrator migrator = createMigrator(); - + PrismContext prismContext = PrismTestUtil.getPrismContext(); PrismObject objectOld = prismContext.parseObject(fileOld); - + // WHEN PrismObject objectNew = migrator.migrate(objectOld); - + // THEN - + IntegrationTestTools.display("Migrated object "+fileOld.getName(), objectNew); assertNotNull("No migrated object "+fileOld.getName(), objectNew); IntegrationTestTools.display("Migrated object "+fileOld.getName(), objectNew); String migratedXml = PrismTestUtil.serializeObjectToString(objectNew, PrismContext.LANG_XML); IntegrationTestTools.display("Migrated object XML "+fileOld.getName(), migratedXml); - + PrismObject expectedObject = prismContext.parseObject(fileNew); IntegrationTestTools.display("Expected object "+fileOld.getName(), expectedObject); String expectedXml = PrismTestUtil.serializeObjectToString(expectedObject, PrismContext.LANG_XML); IntegrationTestTools.display("Expected object XML "+fileOld.getName(), expectedXml); - + List expectedXmlLines = MiscUtil.splitLines(expectedXml); Patch patch = DiffUtils.diff(expectedXmlLines, MiscUtil.splitLines(migratedXml)); List diffLines = DiffUtils.generateUnifiedDiff(fileOld.getPath(), fileNew.getPath(), expectedXmlLines, patch, 3); @@ -133,7 +133,7 @@ private void assertSimpleMigration(File fileOld, File fil PrismAsserts.assertEquivalent("Unexpected migration result for "+fileOld.getName(), expectedObject, objectNew); assertEquals("Unexpected element name for "+fileOld.getName(), expectedObject.getElementName(), objectNew.getElementName()); } - + private Migrator createMigrator() { return new Migrator(); } 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 c0ad91ec978..ed8836ca554 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 @@ -80,61 +80,61 @@ @DirtiesContext @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public abstract class TestAbstractAuthenticationEvaluator> extends AbstractInternalModelIntegrationTest { - + protected static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "security"); - + private static final Trace LOGGER = TraceManager.getTrace(TestAbstractAuthenticationEvaluator.class); protected static final String USER_GUYBRUSH_PASSWORD = "XmarksTHEspot"; - - + + @Autowired(required=true) private UserProfileService userProfileService; - + @Autowired(required = true) private Clock clock; /* (non-Javadoc) * @see com.evolveum.midpoint.test.AbstractIntegrationTest#initSystem(com.evolveum.midpoint.task.api.Task, com.evolveum.midpoint.schema.result.OperationResult) */ - + public abstract T getAuthenticationEvaluator(); public abstract AC getAuthenticationContext(String username, V value); - + public abstract V getGoodPasswordJack(); public abstract V getBadPasswordJack(); public abstract V getGoodPasswordGuybrush(); public abstract V getBadPasswordGuybrush(); public abstract V get103EmptyPasswordJack(); - + public abstract AbstractCredentialType getCredentialUsedForAuthentication(UserType user); public abstract QName getCredentialType(); - + public abstract void modifyUserCredential(Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + ((AuthenticationEvaluatorImpl)getAuthenticationEvaluator()).userProfileService = new UserProfileService() { - + @Override public PrismObject resolveOwner(PrismObject object) { return userProfileService.resolveOwner(object); } - + @Override public void updateUser(MidPointPrincipal principal) { userProfileService.updateUser(principal); } - + @Override public MidPointPrincipal getPrincipal(PrismObject user) throws SchemaException { MidPointPrincipal principal = userProfileService.getPrincipal(user); addFakeAuthorization(principal); return principal; } - + @Override public MidPointPrincipal getPrincipal(String username) throws ObjectNotFoundException, SchemaException { MidPointPrincipal principal = userProfileService.getPrincipal(username); @@ -143,102 +143,102 @@ public MidPointPrincipal getPrincipal(String username) throws ObjectNotFoundExce } }; } - + @Test public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; TestUtil.displayTestTitle(TEST_NAME); - + assertNotNull(getAuthenticationEvaluator()); MidPointPrincipal principal = userProfileService.getPrincipal(USER_JACK_USERNAME); assertPrincipalJack(principal); } - + @Test public void test100PasswordLoginGoodPasswordJack() throws Exception { final String TEST_NAME = "test100PasswordLoginGoodPasswordJack"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN ConnectionEnvironment connEnv = createConnectionEnvironment(); XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); Authentication authentication = getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, getGoodPasswordJack())); - + // THEN TestUtil.displayThen(TEST_NAME); XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); assertGoodPasswordAuthentication(authentication, USER_JACK_USERNAME); - + PrismObject userAfter = getUser(USER_JACK_OID); display("user after", userAfter); assertFailedLogins(userAfter, 0); assertLastSuccessfulLogin(userAfter, startTs, endTs); } - + @Test public void test101PasswordLoginBadPasswordJack() throws Exception { final String TEST_NAME = "test101PasswordLoginBadPasswordJack"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN ConnectionEnvironment connEnv = createConnectionEnvironment(); XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - + try { - + // WHEN TestUtil.displayWhen(TEST_NAME); - + getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, getBadPasswordJack())); - + AssertJUnit.fail("Unexpected success"); - + } catch (BadCredentialsException e) { // This is expected - + // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); assertBadPasswordException(e, USER_JACK_USERNAME); } XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userAfter = getUser(USER_JACK_OID); display("user after", userAfter); assertFailedLogins(userAfter, 1); assertUserLockout(userAfter, LockoutStatusType.NORMAL); assertLastFailedLogin(userAfter, startTs, endTs); } - + @Test public void test102PasswordLoginNullPasswordJack() throws Exception { final String TEST_NAME = "test102PasswordLoginNullPasswordJack"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN ConnectionEnvironment connEnv = createConnectionEnvironment(); - + try { - + // WHEN TestUtil.displayWhen(TEST_NAME); - + getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, null)); - + AssertJUnit.fail("Unexpected success"); - + } catch (BadCredentialsException e) { // This is expected - + // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); assertPasswordEncodingException(e, USER_JACK_USERNAME); } - + PrismObject userAfter = getUser(USER_JACK_OID); display("user after", userAfter); assertFailedLogins(userAfter, 1); @@ -250,116 +250,116 @@ public void test102PasswordLoginNullPasswordJack() throws Exception { public void test103PasswordLoginEmptyPasswordJack() throws Exception { final String TEST_NAME = "test103PasswordLoginEmptyPasswordJack"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN ConnectionEnvironment connEnv = createConnectionEnvironment(); - + try { - + // WHEN TestUtil.displayWhen(TEST_NAME); - + getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, get103EmptyPasswordJack())); - + AssertJUnit.fail("Unexpected success"); - + } catch (BadCredentialsException e) { // This is expected - + // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); assertPasswordEncodingException(e, USER_JACK_USERNAME); } - + PrismObject userAfter = getUser(USER_JACK_OID); display("user after", userAfter); assertFailedLogins(userAfter, 1); assertUserLockout(userAfter, LockoutStatusType.NORMAL); } - + @Test public void test105PasswordLoginNullUsernameNullPassword() throws Exception { final String TEST_NAME = "test105PasswordLoginNullUsernameNullPassword"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN ConnectionEnvironment connEnv = createConnectionEnvironment(); - + try { - + // WHEN TestUtil.displayWhen(TEST_NAME); - + getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(null, null)); - + AssertJUnit.fail("Unexpected success"); - + } catch (BadCredentialsException e) { // This is expected - + // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); assertPasswordEncodingException(e, null); } - + } - + @Test public void test106PasswordLoginEmptyUsernameBadPassword() throws Exception { final String TEST_NAME = "test106PasswordLoginEmptyUsernameBadPassword"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN ConnectionEnvironment connEnv = createConnectionEnvironment(); - + try { - + // WHEN TestUtil.displayWhen(TEST_NAME); - + getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext("", getBadPasswordJack())); - + AssertJUnit.fail("Unexpected success"); - + } catch (UsernameNotFoundException e) { // This is expected - + // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); assertNoUserException(e, null); } - + } @Test public void test107PasswordLoginBadUsernameBadPassword() throws Exception { final String TEST_NAME = "test107PasswordLoginBadUsernameBadPassword"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN ConnectionEnvironment connEnv = createConnectionEnvironment(); - + try { - + // WHEN TestUtil.displayWhen(TEST_NAME); - + getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext("NoSuchUser", getBadPasswordJack())); - + AssertJUnit.fail("Unexpected success"); - + } catch (UsernameNotFoundException e) { // This is expected - + // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); assertNoUserException(e, null); } - + } /** @@ -370,32 +370,32 @@ public void test107PasswordLoginBadUsernameBadPassword() throws Exception { public void test125PasswordLoginBadPasswordJackAfterLockoutFailedAttemptsDuration() throws Exception { final String TEST_NAME = "test125PasswordLoginBadPasswordJackAfterLockoutFailedAttemptsDuration"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN clock.overrideDuration("PT5M"); - + ConnectionEnvironment connEnv = createConnectionEnvironment(); XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - + try { - + // WHEN TestUtil.displayWhen(TEST_NAME); - + getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, getBadPasswordJack())); - + AssertJUnit.fail("Unexpected success"); - + } catch (BadCredentialsException e) { // This is expected - + // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); assertBadPasswordException(e, USER_JACK_USERNAME); } XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userAfter = getUser(USER_JACK_OID); display("user after", userAfter); assertFailedLogins(userAfter, 1); @@ -408,7 +408,7 @@ public void test125PasswordLoginBadPasswordJackAfterLockoutFailedAttemptsDuratio public void test130PasswordLoginLockout() throws Exception { final String TEST_NAME = "test130PasswordLoginLockout"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN ConnectionEnvironment connEnv = createConnectionEnvironment(); XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); @@ -416,71 +416,71 @@ public void test130PasswordLoginLockout() throws Exception { // WHEN TestUtil.displayWhen(TEST_NAME); try { - + getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, getBadPasswordJack())); - + AssertJUnit.fail("Unexpected success"); } catch (BadCredentialsException e) { // This is expected - + display("expected exception", e); assertBadPasswordException(e, USER_JACK_USERNAME); } - + PrismObject userBetween = getUser(USER_JACK_OID); display("user after", userBetween); assertFailedLogins(userBetween, 2); assertUserLockout(userBetween, LockoutStatusType.NORMAL); - + try { - + getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, getBadPasswordJack())); - + AssertJUnit.fail("Unexpected success"); } catch (BadCredentialsException e) { // This is expected - + display("expected exception", e); assertBadPasswordException(e, USER_JACK_USERNAME); } - - + + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - + // THEN TestUtil.displayThen(TEST_NAME); - + PrismObject userAfter = getUser(USER_JACK_OID); display("user after", userAfter); assertFailedLogins(userAfter, 3); assertLastFailedLogin(userAfter, startTs, endTs); assertUserLockout(userAfter, LockoutStatusType.LOCKED); } - + @Test public void test132PasswordLoginLockedoutGoodPassword() throws Exception { final String TEST_NAME = "test132PasswordLoginLockedoutGoodPassword"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN ConnectionEnvironment connEnv = createConnectionEnvironment(); // WHEN TestUtil.displayWhen(TEST_NAME); try { - + getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, getGoodPasswordJack())); - + AssertJUnit.fail("Unexpected success"); } catch (LockedException e) { // This is expected - + // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); assertLockedException(e, USER_JACK_USERNAME); } - + PrismObject userAfter = getUser(USER_JACK_OID); display("user after", userAfter); assertFailedLogins(userAfter, 3); @@ -491,29 +491,29 @@ public void test132PasswordLoginLockedoutGoodPassword() throws Exception { public void test133PasswordLoginLockedoutBadPassword() throws Exception { final String TEST_NAME = "test133PasswordLoginLockedoutBadPassword"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN ConnectionEnvironment connEnv = createConnectionEnvironment(); // WHEN TestUtil.displayWhen(TEST_NAME); try { - + getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, getBadPasswordJack())); - + AssertJUnit.fail("Unexpected success"); } catch (LockedException e) { // This is expected - + // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); - + // this is important. The exception should give no indication whether the password is // good or bad assertLockedException(e, USER_JACK_USERNAME); } - + PrismObject userAfter = getUser(USER_JACK_OID); display("user after", userAfter); assertFailedLogins(userAfter, 3); @@ -524,34 +524,34 @@ public void test133PasswordLoginLockedoutBadPassword() throws Exception { public void test135PasswordLoginLockedoutLockExpires() throws Exception { final String TEST_NAME = "test135PasswordLoginLockedoutLockExpires"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN clock.overrideDuration("PT30M"); - + ConnectionEnvironment connEnv = createConnectionEnvironment(); XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); Authentication authentication = getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, getGoodPasswordJack())); - + // THEN TestUtil.displayThen(TEST_NAME); XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); assertGoodPasswordAuthentication(authentication, USER_JACK_USERNAME); - + PrismObject userAfter = getUser(USER_JACK_OID); display("user after", userAfter); assertFailedLogins(userAfter, 0); assertLastSuccessfulLogin(userAfter, startTs, endTs); assertUserLockout(userAfter, LockoutStatusType.NORMAL); } - + @Test public void test136PasswordLoginLockoutAgain() throws Exception { final String TEST_NAME = "test136PasswordLoginLockoutAgain"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN ConnectionEnvironment connEnv = createConnectionEnvironment(); XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); @@ -559,32 +559,32 @@ public void test136PasswordLoginLockoutAgain() throws Exception { // WHEN TestUtil.displayWhen(TEST_NAME); try { - + getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, getBadPasswordJack())); - + AssertJUnit.fail("Unexpected success"); } catch (BadCredentialsException e) { // This is expected - + // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); assertBadPasswordException(e, USER_JACK_USERNAME); } - + PrismObject userBetween = getUser(USER_JACK_OID); display("user after", userBetween); assertFailedLogins(userBetween, 1); assertUserLockout(userBetween, LockoutStatusType.NORMAL); - + try { - + getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, getBadPasswordJack())); - + AssertJUnit.fail("Unexpected success"); } catch (BadCredentialsException e) { // This is expected - + // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); @@ -595,79 +595,79 @@ public void test136PasswordLoginLockoutAgain() throws Exception { display("user after", userBetween); assertFailedLogins(userBetween, 2); assertUserLockout(userBetween, LockoutStatusType.NORMAL); - + try { - + getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, getBadPasswordJack())); - + AssertJUnit.fail("Unexpected success"); } catch (BadCredentialsException e) { // This is expected - + // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); assertBadPasswordException(e, USER_JACK_USERNAME); } - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userAfter = getUser(USER_JACK_OID); display("user after", userAfter); assertFailedLogins(userAfter, 3); assertLastFailedLogin(userAfter, startTs, endTs); assertUserLockout(userAfter, LockoutStatusType.LOCKED); } - + @Test public void test137PasswordLoginLockedoutGoodPasswordAgain() throws Exception { final String TEST_NAME = "test137PasswordLoginLockedoutGoodPasswordAgain"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN ConnectionEnvironment connEnv = createConnectionEnvironment(); // WHEN TestUtil.displayWhen(TEST_NAME); try { - + getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, getGoodPasswordJack())); - + AssertJUnit.fail("Unexpected success"); } catch (LockedException e) { // This is expected - + // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); assertLockedException(e, USER_JACK_USERNAME); } - + PrismObject userAfter = getUser(USER_JACK_OID); display("user after", userAfter); assertFailedLogins(userAfter, 3); assertUserLockout(userAfter, LockoutStatusType.LOCKED); } - + @Test public void test138UnlockUserGoodPassword() throws Exception { final String TEST_NAME = "test138UnlockUserGoodPassword"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TestAbstractAuthenticationEvaluator.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ConnectionEnvironment connEnv = createConnectionEnvironment(); // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, task, result, LockoutStatusType.NORMAL); - + // THEN TestUtil.displayThen(TEST_NAME); - + PrismObject userBetween = getUser(USER_JACK_OID); display("user after", userBetween); assertFailedLogins(userBetween, 0); @@ -675,23 +675,23 @@ public void test138UnlockUserGoodPassword() throws Exception { // GIVEN XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); Authentication authentication = getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, getGoodPasswordJack())); - + // THEN TestUtil.displayThen(TEST_NAME); XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); assertGoodPasswordAuthentication(authentication, USER_JACK_USERNAME); - + PrismObject userAfter = getUser(USER_JACK_OID); display("user after", userAfter); assertFailedLogins(userAfter, 0); assertLastSuccessfulLogin(userAfter, startTs, endTs); assertUserLockout(userAfter, LockoutStatusType.NORMAL); } - + /** * MID-2862 */ @@ -699,219 +699,219 @@ public void test138UnlockUserGoodPassword() throws Exception { public void test139TryToLockByModelService() throws Exception { final String TEST_NAME = "test139TryToLockByModelService"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TestAbstractAuthenticationEvaluator.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); try { - + modifyUserReplace(USER_JACK_OID, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, task, result, LockoutStatusType.LOCKED); - + AssertJUnit.fail("Unexpected success"); } catch (SchemaException e) { // This is expected - + // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); - + } - + PrismObject userAfter = getUser(USER_JACK_OID); display("user after", userAfter); assertFailedLogins(userAfter, 0); assertUserLockout(userAfter, LockoutStatusType.NORMAL); } - + @Test public void test150PasswordLoginDisabledGoodPassword() throws Exception { final String TEST_NAME = "test150PasswordLoginDisabledGoodPassword"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TestAbstractAuthenticationEvaluator.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); modifyUserReplace(USER_JACK_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.DISABLED); - + loginJackGoodPasswordExpectDenied(TEST_NAME, task, result); } - + @Test public void test152PasswordLoginEnabledGoodPassword() throws Exception { final String TEST_NAME = "test152PasswordLoginEnabledGoodPassword"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TestAbstractAuthenticationEvaluator.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); modifyUserReplace(USER_JACK_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.ENABLED); - + loginJackGoodPasswordExpectSuccess(TEST_NAME, task, result); } - + @Test public void test154PasswordLoginNotValidYetGoodPassword() throws Exception { final String TEST_NAME = "test154PasswordLoginNotValidYetGoodPassword"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TestAbstractAuthenticationEvaluator.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + XMLGregorianCalendar validFrom = XmlTypeConverter.addDuration(clock.currentTimeXMLGregorianCalendar(), "PT1H"); XMLGregorianCalendar validTo = XmlTypeConverter.addDuration(clock.currentTimeXMLGregorianCalendar(), "P2D"); - + modifyUserReplace(USER_JACK_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result); modifyUserReplace(USER_JACK_OID, ACTIVATION_VALID_FROM_PATH, task, result, validFrom); modifyUserReplace(USER_JACK_OID, ACTIVATION_VALID_TO_PATH, task, result, validTo); - + loginJackGoodPasswordExpectDenied(TEST_NAME, task, result); } - + @Test public void test155PasswordLoginValidGoodPassword() throws Exception { final String TEST_NAME = "test155PasswordLoginValidGoodPassword"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN clock.overrideDuration("PT2H"); - + Task task = createTask(TestAbstractAuthenticationEvaluator.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + loginJackGoodPasswordExpectSuccess(TEST_NAME, task, result); } - + @Test public void test156PasswordLoginNotValidAnyLongerGoodPassword() throws Exception { final String TEST_NAME = "test156PasswordLoginNotValidAnyLongerGoodPassword"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN clock.overrideDuration("P2D"); - + Task task = createTask(TestAbstractAuthenticationEvaluator.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + loginJackGoodPasswordExpectDenied(TEST_NAME, task, result); } - + @Test public void test159PasswordLoginNoLongerValidEnabledGoodPassword() throws Exception { final String TEST_NAME = "test159PasswordLoginNoLongerValidEnabledGoodPassword"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TestAbstractAuthenticationEvaluator.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); modifyUserReplace(USER_JACK_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.ENABLED); - + loginJackGoodPasswordExpectSuccess(TEST_NAME, task, result); } - + @Test public void test160PasswordLoginLifecycleActiveGoodPassword() throws Exception { final String TEST_NAME = "test160PasswordLoginLifecycleActiveGoodPassword"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TestAbstractAuthenticationEvaluator.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - - modifyUserReplace(USER_JACK_OID, UserType.F_LIFECYCLE_STATE, task, result, + + modifyUserReplace(USER_JACK_OID, UserType.F_LIFECYCLE_STATE, task, result, SchemaConstants.LIFECYCLE_ACTIVE); - + loginJackGoodPasswordExpectSuccess(TEST_NAME, task, result); } - + @Test public void test162PasswordLoginLifecycleDraftGoodPassword() throws Exception { final String TEST_NAME = "test162PasswordLoginLifecycleDraftGoodPassword"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TestAbstractAuthenticationEvaluator.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - - modifyUserReplace(USER_JACK_OID, UserType.F_LIFECYCLE_STATE, task, result, + + modifyUserReplace(USER_JACK_OID, UserType.F_LIFECYCLE_STATE, task, result, SchemaConstants.LIFECYCLE_DRAFT); - + loginJackGoodPasswordExpectDenied(TEST_NAME, task, result); } - + @Test public void test164PasswordLoginLifecycleDeprecatedGoodPassword() throws Exception { final String TEST_NAME = "test164PasswordLoginLifecycleDeprecatedGoodPassword"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TestAbstractAuthenticationEvaluator.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - - modifyUserReplace(USER_JACK_OID, UserType.F_LIFECYCLE_STATE, task, result, + + modifyUserReplace(USER_JACK_OID, UserType.F_LIFECYCLE_STATE, task, result, SchemaConstants.LIFECYCLE_DEPRECATED); - + loginJackGoodPasswordExpectSuccess(TEST_NAME, task, result); } - + @Test public void test166PasswordLoginLifecycleProposedGoodPassword() throws Exception { final String TEST_NAME = "test166PasswordLoginLifecycleProposedGoodPassword"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TestAbstractAuthenticationEvaluator.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - - modifyUserReplace(USER_JACK_OID, UserType.F_LIFECYCLE_STATE, task, result, + + modifyUserReplace(USER_JACK_OID, UserType.F_LIFECYCLE_STATE, task, result, SchemaConstants.LIFECYCLE_PROPOSED); - + loginJackGoodPasswordExpectDenied(TEST_NAME, task, result); } - + @Test public void test168PasswordLoginLifecycleArchivedGoodPassword() throws Exception { final String TEST_NAME = "test168PasswordLoginLifecycleArchivedGoodPassword"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TestAbstractAuthenticationEvaluator.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - - modifyUserReplace(USER_JACK_OID, UserType.F_LIFECYCLE_STATE, task, result, + + modifyUserReplace(USER_JACK_OID, UserType.F_LIFECYCLE_STATE, task, result, SchemaConstants.LIFECYCLE_ARCHIVED); - + loginJackGoodPasswordExpectDenied(TEST_NAME, task, result); } - + @Test public void test200UserGuybrushSetCredentials() throws Exception { final String TEST_NAME = "test200UserGuybrushSetPassword"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TestAbstractAuthenticationEvaluator.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserCredential(task, result); - + // THEN TestUtil.displayThen(TEST_NAME); XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("user after", userAfter); - + // assertEncryptedUserPassword(userAfter, USER_GUYBRUSH_PASSWORD); assertPasswordMetadata(userAfter, getCredentialType(), false, startTs, endTs, null, SchemaConstants.CHANNEL_GUI_USER_URI); - + assertFailedLogins(userAfter, 0); } @@ -919,121 +919,121 @@ public void test200UserGuybrushSetCredentials() throws Exception { public void test201UserGuybrushPasswordLoginGoodPassword() throws Exception { final String TEST_NAME = "test201UserGuybrushPasswordLoginGoodPassword"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN ConnectionEnvironment connEnv = createConnectionEnvironment(); XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); Authentication authentication = getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_GUYBRUSH_USERNAME, getGoodPasswordGuybrush())); - + // THEN TestUtil.displayThen(TEST_NAME); XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); assertGoodPasswordAuthentication(authentication, USER_GUYBRUSH_USERNAME); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("user after", userAfter); assertFailedLogins(userAfter, 0); assertLastSuccessfulLogin(userAfter, startTs, endTs); } - + @Test public void test202UserGuybrushPasswordLoginBadPassword() throws Exception { final String TEST_NAME = "test202UserGuybrushPasswordLoginBadPassword"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN ConnectionEnvironment connEnv = createConnectionEnvironment(); XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - + try { - + // WHEN TestUtil.displayWhen(TEST_NAME); - + getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_GUYBRUSH_USERNAME, getBadPasswordGuybrush())); - + AssertJUnit.fail("Unexpected success"); - + } catch (BadCredentialsException e) { // This is expected - + // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); assertBadPasswordException(e, USER_GUYBRUSH_USERNAME); } XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("user after", userAfter); assertFailedLogins(userAfter, 1); assertLastFailedLogin(userAfter, startTs, endTs); } - + @Test public void test209UserGuybrushPasswordLoginGoodPasswordBeforeExpiration() throws Exception { final String TEST_NAME = "test209UserGuybrushPasswordLoginGoodPasswordBeforeExpiration"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN clock.overrideDuration("P29D"); - + ConnectionEnvironment connEnv = createConnectionEnvironment(); XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); Authentication authentication = getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_GUYBRUSH_USERNAME, getGoodPasswordGuybrush())); - + // THEN TestUtil.displayThen(TEST_NAME); XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); assertGoodPasswordAuthentication(authentication, USER_GUYBRUSH_USERNAME); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("user after", userAfter); assertFailedLogins(userAfter, 0); assertLastSuccessfulLogin(userAfter, startTs, endTs); } - + @Test public void test210UserGuybrushPasswordLoginGoodPasswordExpired() throws Exception { final String TEST_NAME = "test210UserGuybrushPasswordLoginGoodPasswordExpired"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN clock.overrideDuration("P2D"); - + ConnectionEnvironment connEnv = createConnectionEnvironment(); XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - + try { - + // WHEN TestUtil.displayWhen(TEST_NAME); - + getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_GUYBRUSH_USERNAME, getGoodPasswordGuybrush())); - + AssertJUnit.fail("Unexpected success"); - + } catch (CredentialsExpiredException e) { // This is expected - + // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); assertExpiredException(e, USER_GUYBRUSH_USERNAME); } XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("user after", userAfter); assertFailedLogins(userAfter, 0); } - + private void assertGoodPasswordAuthentication(Authentication authentication, String expectedUsername) { assertNotNull("No authentication", authentication); assertTrue("authentication: not authenticated", authentication.isAuthenticated()); @@ -1044,37 +1044,37 @@ private void assertGoodPasswordAuthentication(Authentication authentication, Str private void assertBadPasswordException(BadCredentialsException e, String username) { assertEquals("Wrong exception meessage (key)", "web.security.provider.invalid", e.getMessage()); } - + private void assertPasswordEncodingException(BadCredentialsException e, String principal) { assertEquals("Wrong exception meessage (key)", "web.security.provider.password.encoding", e.getMessage()); } - + private void assertDeniedException(AccessDeniedException e, String principal) { assertEquals("Wrong exception meessage (key)", "web.security.provider.access.denied", e.getMessage()); } - + private void assertLockedException(LockedException e, String principal) { assertEquals("Wrong exception meessage (key)", "web.security.provider.locked", e.getMessage()); } - + private void assertDisabledException(DisabledException e, String principal) { assertEquals("Wrong exception meessage (key)", "web.security.provider.disabled", e.getMessage()); } - + private void assertExpiredException(CredentialsExpiredException e, String principal) { assertEquals("Wrong exception meessage (key)", "web.security.provider.password.bad", e.getMessage()); } - + private void assertNoUserException(UsernameNotFoundException e, String principal) { assertEquals("Wrong exception meessage (key)", "web.security.provider.invalid", e.getMessage()); } - + private ConnectionEnvironment createConnectionEnvironment() { HttpConnectionInformation connInfo = new HttpConnectionInformation(); connInfo.setRemoteHostAddress("remote.example.com"); return new ConnectionEnvironment(null, connInfo); } - + private void assertFailedLogins(PrismObject user, int expected) { if (expected == 0 && getCredentialUsedForAuthentication(user.asObjectable()).getFailedLogins() == null) { return; @@ -1089,7 +1089,7 @@ private void assertLastSuccessfulLogin(PrismObject user, XMLGregorianC XMLGregorianCalendar successfulLoginTs = lastSuccessfulLogin.getTimestamp(); TestUtil.assertBetween("wrong last successful login timestamp", startTs, endTs, successfulLoginTs); } - + private void assertLastFailedLogin(PrismObject user, XMLGregorianCalendar startTs, XMLGregorianCalendar endTs) { LoginEventType lastFailedLogin = getCredentialUsedForAuthentication(user.asObjectable()).getLastFailedLogin(); @@ -1117,7 +1117,7 @@ private void assertPrincipalJack(MidPointPrincipal principal) { assertNotNull("No user in principal",user); assertEquals("Bad name in user in principal", USER_JACK_USERNAME, user.getName().getOrig()); } - + private void loginJackGoodPasswordExpectSuccess(final String TEST_NAME, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { display("now", clock.currentTimeXMLGregorianCalendar()); ConnectionEnvironment connEnv = createConnectionEnvironment(); @@ -1126,18 +1126,18 @@ private void loginJackGoodPasswordExpectSuccess(final String TEST_NAME, Task tas // WHEN TestUtil.displayWhen(TEST_NAME); Authentication authentication = getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, getGoodPasswordJack())); - + // THEN TestUtil.displayThen(TEST_NAME); XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); assertGoodPasswordAuthentication(authentication, USER_JACK_USERNAME); - + PrismObject userAfter = getUser(USER_JACK_OID); display("user after", userAfter); assertFailedLogins(userAfter, 0); assertLastSuccessfulLogin(userAfter, startTs, endTs); } - + private void loginJackGoodPasswordExpectDenied(final String TEST_NAME, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { display("now", clock.currentTimeXMLGregorianCalendar()); ConnectionEnvironment connEnv = createConnectionEnvironment(); @@ -1146,22 +1146,22 @@ private void loginJackGoodPasswordExpectDenied(final String TEST_NAME, Task task // WHEN TestUtil.displayWhen(TEST_NAME); try { - + getAuthenticationEvaluator().authenticate(connEnv, getAuthenticationContext(USER_JACK_USERNAME, getGoodPasswordJack())); - + AssertJUnit.fail("Unexpected success"); } catch (DisabledException e) { // This is expected - + // THEN TestUtil.displayThen(TEST_NAME); display("expected exception", e); - + // this is important. The exception should give no indication whether the password is // good or bad assertDisabledException(e, USER_JACK_USERNAME); } - + PrismObject userAfter = getUser(USER_JACK_OID); display("user after", userAfter); assertFailedLogins(userAfter, 0); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/security/TestNonceAuthenticationEvaluator.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/security/TestNonceAuthenticationEvaluator.java index 5d04a1ab71b..3dbad4fb790 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/security/TestNonceAuthenticationEvaluator.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/security/TestNonceAuthenticationEvaluator.java @@ -30,10 +30,10 @@ public class TestNonceAuthenticationEvaluator extends TestAbstractAuthentication private static final String USER_JACK_NONCE = "asdfghjkl123456"; private static final String USER_GUYBRUSH_NONCE = "asdfghjkl654321"; - + @Autowired(required=true) private AuthenticationEvaluator nonceAuthenticationEvaluator; - + @Override public AuthenticationEvaluator getAuthenticationEvaluator() { return nonceAuthenticationEvaluator; @@ -85,12 +85,12 @@ public void modifyUserCredential(Task task, OperationResult result) throws Objec SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyUserReplace(USER_GUYBRUSH_OID, SchemaConstants.PATH_NONCE_VALUE, task, result, getGuybrushNonce()); - + } - + @Override public QName getCredentialType() { return CredentialsType.F_NONCE; } - + } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/security/TestPasswordAuthenticationEvaluator.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/security/TestPasswordAuthenticationEvaluator.java index f2e50a33c10..ea10483f14a 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/security/TestPasswordAuthenticationEvaluator.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/security/TestPasswordAuthenticationEvaluator.java @@ -28,7 +28,7 @@ public class TestPasswordAuthenticationEvaluator extends TestAbstractAuthenticat @Autowired(required=true) private AuthenticationEvaluator passwordAuthenticationEvaluator; - + @Override public AuthenticationEvaluator getAuthenticationEvaluator() { return passwordAuthenticationEvaluator; @@ -68,7 +68,7 @@ public String get103EmptyPasswordJack() { public AbstractCredentialType getCredentialUsedForAuthentication(UserType user) { return user.getCredentials().getPassword(); } - + private ProtectedStringType getGuybrushPassword() { ProtectedStringType protectedString = new ProtectedStringType(); protectedString.setClearValue(USER_GUYBRUSH_PASSWORD); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/security/TestSecurityQuestionsAuthenticationEvaluator.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/security/TestSecurityQuestionsAuthenticationEvaluator.java index a9f3bd34af1..f8bad6e3bb0 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/security/TestSecurityQuestionsAuthenticationEvaluator.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/security/TestSecurityQuestionsAuthenticationEvaluator.java @@ -33,10 +33,10 @@ public class TestSecurityQuestionsAuthenticationEvaluator extends TestAbstractAu private static final String SECURITY_QUESTION_GOOD_ANSWER_JACK = "Some generic answer"; private static final String SECURITY_QUESTION_BAD_ANSWER ="This isn't correct answer!"; private static final String SECURITY_QUESTION_GOOD_ANSWER_GUYBRUSH = "Some some generic answer"; - + @Autowired(required=true) private AuthenticationEvaluator securityQuestionsAuthenticationEvaluator; - + @Override public AuthenticationEvaluator getAuthenticationEvaluator() { return securityQuestionsAuthenticationEvaluator; @@ -82,7 +82,7 @@ public AbstractCredentialType getCredentialUsedForAuthentication(UserType user) public QName getCredentialType() { return CredentialsType.F_SECURITY_QUESTIONS; } - + private SecurityQuestionAnswerType getSecurityQuestionAnswer(){ SecurityQuestionAnswerType questionAnswer = new SecurityQuestionAnswerType(); questionAnswer.setQuestionIdentifier(SECURITY_QUESTION_ID); @@ -97,14 +97,14 @@ public void modifyUserCredential(Task task, OperationResult result) throws Objec SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyObjectReplaceContainer(UserType.class, USER_GUYBRUSH_OID, SchemaConstants.PATH_SECURITY_QUESTIONS_QUESTION_ANSWER, task, result, getSecurityQuestionAnswer()); - + } - + private Map createMap(String id, String value) { Map questionAnswers = new HashMap<>(); questionAnswers.put(id, value); return questionAnswers; } - - + + } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/ActionManagerImplTest.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/ActionManagerImplTest.java index 82f1cbad42a..01cc1700423 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/ActionManagerImplTest.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/ActionManagerImplTest.java @@ -27,9 +27,9 @@ import com.evolveum.midpoint.model.impl.sync.ActionManager; /** - * + * * @author lazyman - * + * */ @ContextConfiguration(locations = { "classpath:ctx-model-test-no-repo.xml" }) public class ActionManagerImplTest extends AbstractTestNGSpringContextTests { diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/SynchronizationSituationTest.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/SynchronizationSituationTest.java index a9cacf68371..ed703338687 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/SynchronizationSituationTest.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/SynchronizationSituationTest.java @@ -23,9 +23,9 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; /** - * + * * @author lazyman - * + * */ public class SynchronizationSituationTest { diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestCorrelationConfiramtionEvaluator.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestCorrelationConfiramtionEvaluator.java index fe2da821e34..1535c1049e4 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestCorrelationConfiramtionEvaluator.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestCorrelationConfiramtionEvaluator.java @@ -52,7 +52,7 @@ @ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestCorrelationConfiramtionEvaluator extends AbstractInternalModelIntegrationTest{ - + private static final String TEST_DIR = "src/test/resources/sync"; private static final String CORRELATION_OR_FILTER = TEST_DIR + "/correlation-or-filter.xml"; private static final String CORRELATION_CASE_INSENSITIVE = TEST_DIR + "/correlation-case-insensitive.xml"; @@ -61,14 +61,14 @@ public class TestCorrelationConfiramtionEvaluator extends AbstractInternalModelI private static final String CORRELATION_SECOND_FILTER = TEST_DIR + "/correlation-second-filter.xml"; private static final String CORRELATION_WITH_CONDITION = TEST_DIR + "/correlation-with-condition.xml"; private static final String CORRELATION_WITH_CONDITION_EMPL_NUMBER = TEST_DIR + "/correlation-with-condition-emplNumber.xml"; - + @Autowired(required=true) private RepositoryService repositoryService; - + @Autowired(required = true) private CorrelationConfirmationEvaluator evaluator; - - + + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { @@ -78,133 +78,133 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti repoAddObjectFromFile(ROLE_SUPERUSER_FILE, initResult); login(userAdministrator); } - + @Test public void test001CorrelationOrFilter() throws Exception{ String TEST_NAME = "test001CorrelationOrFilter"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TEST_NAME); OperationResult result = task.getResult(); - + importObjectFromFile(USER_JACK_FILE); - + PrismObject userType = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); //assert jack assertNotNull(userType); - + ShadowType shadow = parseObjectType(ACCOUNT_SHADOW_JACK_DUMMY_FILE, ShadowType.class); - + ConditionalSearchFilterType filter = PrismTestUtil.parseAtomicValue(new File(CORRELATION_OR_FILTER), ConditionalSearchFilterType.COMPLEX_TYPE); List filters = new ArrayList<>(); filters.add(filter); - + ResourceType resourceType = parseObjectType(RESOURCE_DUMMY_FILE, ResourceType.class); IntegrationTestTools.display("Queries", filters); - + // WHEN List> matchedUsers = evaluator.findFocusesByCorrelationRule(UserType.class, shadow, filters, resourceType, getSystemConfiguration(), task, result); - + // THEN assertNotNull("Correlation evaluator returned null collection of matched users.", matchedUsers); assertEquals("Found more than one user.", 1, matchedUsers.size()); - + 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"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TEST_NAME); OperationResult result = task.getResult(); - + // importObjectFromFile(USER_JACK_FILENAME); - + PrismObject userType = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); //assert jack assertNotNull(userType); - + ShadowType shadow = parseObjectType(ACCOUNT_SHADOW_JACK_DUMMY_FILE, ShadowType.class); - + List filters = new ArrayList<>(); ConditionalSearchFilterType filter = PrismTestUtil.parseAtomicValue(new File(CORRELATION_FIRST_FILTER), ConditionalSearchFilterType.COMPLEX_TYPE); filters.add(filter); - + filter = PrismTestUtil.parseAtomicValue(new File(CORRELATION_SECOND_FILTER), ConditionalSearchFilterType.COMPLEX_TYPE); filters.add(filter); - + ResourceType resourceType = parseObjectType(RESOURCE_DUMMY_FILE, ResourceType.class); List> matchedUsers = evaluator.findFocusesByCorrelationRule(UserType.class, shadow, filters, resourceType, getSystemConfiguration(), task, result); - + assertNotNull("Correlation evaluator returned null collection of matched users.", matchedUsers); assertEquals("Found more than one user.", 1, matchedUsers.size()); - + 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"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TEST_NAME); OperationResult result = task.getResult(); - + // importObjectFromFile(USER_JACK_FILENAME); - + PrismObject userType = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); //assert jack assertNotNull(userType); - + ShadowType shadow = parseObjectType(ACCOUNT_SHADOW_JACK_DUMMY_FILE, ShadowType.class); - + List queries = new ArrayList<>(); ConditionalSearchFilterType query = PrismTestUtil.parseAtomicValue(new File(CORRELATION_WITH_CONDITION), ConditionalSearchFilterType.COMPLEX_TYPE); queries.add(query); - + query = PrismTestUtil.parseAtomicValue(new File(CORRELATION_WITH_CONDITION_EMPL_NUMBER), ConditionalSearchFilterType.COMPLEX_TYPE); queries.add(query); - + ResourceType resourceType = parseObjectType(RESOURCE_DUMMY_FILE, ResourceType.class); List> matchedUsers = evaluator.findFocusesByCorrelationRule(UserType.class, shadow, queries, resourceType, getSystemConfiguration(), task, result); - + assertNotNull("Correlation evaluator returned null collection of matched users.", matchedUsers); assertEquals("Found more than one user.", 1, matchedUsers.size()); - + 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"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TEST_NAME); OperationResult result = task.getResult(); - + // importObjectFromFile(USER_JACK_FILENAME); - + PrismObject userType = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); //assert jack assertNotNull(userType); - + ShadowType shadow = parseObjectType(ACCOUNT_SHADOW_JACK_DUMMY_FILE, ShadowType.class); ConditionalSearchFilterType query = PrismTestUtil.parseAtomicValue(new File(CORRELATION_CASE_INSENSITIVE), ConditionalSearchFilterType.COMPLEX_TYPE); // List queries = new ArrayList(); // queries.add(query); -// +// ResourceType resourceType = parseObjectType(RESOURCE_DUMMY_FILE, ResourceType.class); resourceType.getSynchronization().getObjectSynchronization().get(0).getCorrelation().clear(); resourceType.getSynchronization().getObjectSynchronization().get(0).getCorrelation().add(query); @@ -213,9 +213,9 @@ public void test004CorrelationMatchCaseInsensitive() throws Exception{ try{ boolean matchedUsers = evaluator.matchUserCorrelationRule(UserType.class, shadow.asPrismObject(), userType, objectSynchronizationType, resourceType, getSystemConfiguration(), task, result); - + System.out.println("matched users " + matchedUsers); - + AssertJUnit.assertTrue(matchedUsers); } catch (Exception ex){ LOGGER.error("exception occured: {}", ex.getMessage(), ex); @@ -223,46 +223,46 @@ public void test004CorrelationMatchCaseInsensitive() throws Exception{ } // assertNotNull("Correlation evaluator returned null collection of matched users.", matchedUsers); // assertEquals("Found more than one user.", 1, matchedUsers.size()); -// +// // PrismObject jack = matchedUsers.get(0); // assertUser(jack, "c0c010c0-d34d-b33f-f00d-111111111111", "jack", "Jack Sparrow", "Jack", "Sparrow"); - + } - + @Test public void test005CorrelationMatchCaseInsensitive() throws Exception{ String TEST_NAME = "test005CorrelationMatchCaseInsensitive"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TEST_NAME); OperationResult result = task.getResult(); - + // importObjectFromFile(USER_JACK_FILENAME); - + PrismObject userType = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); //assert jack assertNotNull(userType); - + ShadowType shadow = parseObjectType(ACCOUNT_SHADOW_JACK_DUMMY_FILE, ShadowType.class); ConditionalSearchFilterType query = PrismTestUtil.parseAtomicValue(new File(CORRELATION_CASE_INSENSITIVE_EMPL_NUMBER), ConditionalSearchFilterType.COMPLEX_TYPE); // ObjectQuery query = ObjectQuery.createObjectQuery(EqualsFilter.createEqual(null, userType.getDefinition().findItemDefinition(UserType.F_EMPLOYEE_NUMBER), "stringIgnoreCase", "ps1234")); // List queries = new ArrayList(); // queries.add(query); -// +// ResourceType resourceType = parseObjectType(RESOURCE_DUMMY_FILE, ResourceType.class); resourceType.getSynchronization().getObjectSynchronization().get(0).getCorrelation().clear(); resourceType.getSynchronization().getObjectSynchronization().get(0).getCorrelation().add(query); - + userType.asObjectable().setEmployeeNumber("JaCk"); ObjectSynchronizationType objectSynchronizationType = resourceType.getSynchronization().getObjectSynchronization().get(0); try{ boolean matchedUsers = evaluator.matchUserCorrelationRule(UserType.class, shadow.asPrismObject(), userType, objectSynchronizationType, resourceType, getSystemConfiguration(), task, result); - + System.out.println("matched users " + matchedUsers); - + AssertJUnit.assertTrue(matchedUsers); } catch (Exception ex){ LOGGER.error("exception occured: {}", ex.getMessage(), ex); @@ -270,49 +270,49 @@ public void test005CorrelationMatchCaseInsensitive() throws Exception{ } // assertNotNull("Correlation evaluator returned null collection of matched users.", matchedUsers); // assertEquals("Found more than one user.", 1, matchedUsers.size()); -// +// // PrismObject jack = matchedUsers.get(0); // assertUser(jack, "c0c010c0-d34d-b33f-f00d-111111111111", "jack", "Jack Sparrow", "Jack", "Sparrow"); - + } - - + + @Test public void test006CorrelationFindCaseInsensitive() throws Exception{ String TEST_NAME = "test006CorrelationFindCaseInsensitive"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TEST_NAME); OperationResult result = task.getResult(); - + // importObjectFromFile(USER_JACK_FILENAME); - + PrismObject userType = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); //assert jack assertNotNull(userType); - + ShadowType shadow = parseObjectType(ACCOUNT_SHADOW_JACK_DUMMY_FILE, ShadowType.class); ConditionalSearchFilterType query = PrismTestUtil.parseAtomicValue(new File(CORRELATION_CASE_INSENSITIVE), ConditionalSearchFilterType.COMPLEX_TYPE); List queries = new ArrayList<>(); queries.add(query); -// +// ResourceType resourceType = parseObjectType(RESOURCE_DUMMY_FILE, ResourceType.class); // resourceType.getSynchronization().getObjectSynchronization().get(0).getCorrelation().add(query); userType.asObjectable().setName(new PolyStringType("JACK")); Collection modifications = PropertyDelta.createModificationReplacePropertyCollection(UserType.F_NAME, userType.getDefinition(), new PolyString("JACK", "jack")); repositoryService.modifyObject(UserType.class, USER_JACK_OID, modifications, result); - + List> matchedUsers = evaluator.findFocusesByCorrelationRule(UserType.class, shadow, queries, resourceType, getSystemConfiguration(), task, result); - + System.out.println("matched users " + matchedUsers); - + assertNotNull("Correlation evaluator returned null collection of matched users.", matchedUsers); assertEquals("Found more than one user.", 1, matchedUsers.size()); - + 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 b30c64c292b..a437f346717 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 @@ -61,23 +61,23 @@ @ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestSynchronizationService extends AbstractInternalModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/sync"); - + public static final File SHADOW_PIRATES_DUMMY_FILE = new File(TEST_DIR, "shadow-pirates-dummy.xml"); public static final String GROUP_PIRATES_DUMMY_NAME = "pirates"; private static final String INTENT_GROUP = "group"; - + @Autowired SynchronizationService synchronizationService; - + @Autowired Clockwork clockwork; - + private String accountShadowJackDummyOid = null; private String accountShadowCalypsoDummyOid = null; - + @Test public void test010AddedAccountJack() throws Exception { final String TEST_NAME = "test010AddedAccountJack"; @@ -86,10 +86,10 @@ public void test010AddedAccountJack() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestSynchronizationService.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + MockLensDebugListener mockListener = new MockLensDebugListener(); clockwork.setDebugListener(mockListener); - + PrismObject accountShadowJack = repoAddObjectFromFile(ACCOUNT_SHADOW_JACK_DUMMY_FILE, result); accountShadowJackDummyOid = accountShadowJack.getOid(); provisioningService.applyDefinition(accountShadowJack, task, result); @@ -100,45 +100,45 @@ public void test010AddedAccountJack() throws Exception { dummyAccount.setEnabled(true); dummyAccount.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Jack Sparrow"); getDummyResource().addAccount(dummyAccount); - + ResourceObjectShadowChangeDescription change = new ResourceObjectShadowChangeDescription(); change.setCurrentShadow(accountShadowJack); change.setResource(getDummyResourceObject()); - + // WHEN synchronizationService.notifyChange(change, task, result); - + // THEN LensContext context = mockListener.getLastSyncContext(); display("Resulting context (as seen by debug listener)", context); assertNotNull("No resulting context (as seen by debug listener)", context); - + assertNull("Unexpected user primary delta", context.getFocusContext().getPrimaryDelta()); assertSideEffectiveDeltasOnly(context.getFocusContext().getSecondaryDelta(), "user secondary delta", ActivationStatusType.ENABLED); - + ResourceShadowDiscriminator rat = new ResourceShadowDiscriminator(getDummyResourceObject().getOid(), ShadowKindType.ACCOUNT, null); LensProjectionContext accCtx = context.findProjectionContext(rat); assertNotNull("No account sync context for "+rat, accCtx); assertEquals("Wrong detected situation in context", SynchronizationSituationType.UNLINKED, accCtx.getSynchronizationSituationDetected()); assertEquals("Wrong resolved situation in context", SynchronizationSituationType.LINKED, accCtx.getSynchronizationSituationResolved()); - + PrismAsserts.assertNoDelta("Unexpected account primary delta", accCtx.getPrimaryDelta()); //it this really expected?? delta was already executed, should we expect it in the secondary delta? // assertNotNull("Missing account secondary delta", accCtx.getSecondaryDelta()); // assertIterationDelta(accCtx.getSecondaryDelta(), 0, ""); - + assertLinked(context.getFocusContext().getObjectOld().getOid(), accountShadowJack.getOid()); - + PrismObject shadow = getShadowModelNoFetch(accountShadowJackDummyOid); assertIteration(shadow, 0, ""); assertSituation(shadow, SynchronizationSituationType.LINKED); - + result.computeStatus(); TestUtil.assertSuccess(result); } - + @Test public void test020ModifyLootAbsolute() throws Exception { final String TEST_NAME = "test020ModifyLootAbsolute"; @@ -147,59 +147,59 @@ public void test020ModifyLootAbsolute() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestSynchronizationService.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + MockLensDebugListener mockListener = new MockLensDebugListener(); clockwork.setDebugListener(mockListener); - + DummyAccount dummyAccount = getDummyResource().getAccountByUsername(ACCOUNT_JACK_DUMMY_USERNAME); dummyAccount.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOOT_NAME, "999"); - + ResourceObjectShadowChangeDescription change = new ResourceObjectShadowChangeDescription(); PrismObject accountShadowJack = provisioningService.getObject(ShadowType.class, accountShadowJackDummyOid, null, task, result); change.setCurrentShadow(accountShadowJack); change.setResource(getDummyResourceObject()); change.setSourceChannel(SchemaConstants.CHANGE_CHANNEL_LIVE_SYNC_URI); - + // WHEN TestUtil.displayWhen(TEST_NAME); synchronizationService.notifyChange(change, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); LensContext context = mockListener.getLastSyncContext(); display("Resulting context (as seen by debug listener)", context); assertNotNull("No resulting context (as seen by debug listener)", context); - + assertNull("Unexpected user primary delta", context.getFocusContext().getPrimaryDelta()); assertEquals("Unexpected number of executed deltas", 1, context.getFocusContext().getExecutedDeltas().size()); ObjectDelta userSecondaryDelta = context.getFocusContext().getExecutedDeltas().iterator().next().getObjectDelta(); assertNotNull("No user secondary delta", userSecondaryDelta); assertEquals("Unexpected number of modifications in user secondary delta", 3, userSecondaryDelta.getModifications().size()); PrismAsserts.assertPropertyAdd(userSecondaryDelta, UserType.F_COST_CENTER, "999"); - + ResourceShadowDiscriminator rat = new ResourceShadowDiscriminator(getDummyResourceObject().getOid(), ShadowKindType.ACCOUNT, null); LensProjectionContext accCtx = context.findProjectionContext(rat); assertNotNull("No account sync context for "+rat, accCtx); - + PrismAsserts.assertNoDelta("account primary delta", accCtx.getPrimaryDelta()); PrismAsserts.assertNoDelta("account secondary delta", accCtx.getSecondaryDelta()); - + assertEquals("Wrong detected situation in context", SynchronizationSituationType.LINKED, accCtx.getSynchronizationSituationDetected()); - + assertLinked(context.getFocusContext().getObjectOld().getOid(), accountShadowJack.getOid()); - + PrismObject user = getUser(USER_JACK_OID); assertEquals("Unexpected used constCenter", "999", user.asObjectable().getCostCenter()); - + PrismObject shadow = getShadowModelNoFetch(accountShadowJackDummyOid); assertIteration(shadow, 0, ""); assertSituation(shadow, SynchronizationSituationType.LINKED); - + result.computeStatus(); TestUtil.assertSuccess(result); } - + @Test public void test021ModifyLootAbsoluteEmpty() throws Exception { final String TEST_NAME = "test021ModifyLootAbsoluteEmpty"; @@ -208,30 +208,30 @@ public void test021ModifyLootAbsoluteEmpty() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestSynchronizationService.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + MockLensDebugListener mockListener = new MockLensDebugListener(); clockwork.setDebugListener(mockListener); - + DummyAccount dummyAccount = getDummyResource().getAccountByUsername(ACCOUNT_JACK_DUMMY_USERNAME); dummyAccount.replaceAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOOT_NAME); - + ResourceObjectShadowChangeDescription change = new ResourceObjectShadowChangeDescription(); PrismObject accountShadowJack = provisioningService.getObject(ShadowType.class, accountShadowJackDummyOid, null, task, result); change.setCurrentShadow(accountShadowJack); change.setResource(getDummyResourceObject()); change.setSourceChannel(SchemaConstants.CHANGE_CHANNEL_LIVE_SYNC_URI); - + display("SENDING CHANGE NOTIFICATION", change); - + // WHEN synchronizationService.notifyChange(change, task, result); - + // THEN LensContext context = mockListener.getLastSyncContext(); display("Resulting context (as seen by debug listener)", context); assertNotNull("No resulting context (as seen by debug listener)", context); - + assertNull("Unexpected user primary delta", context.getFocusContext().getPrimaryDelta()); assertEquals("Unexpected number of executed deltas", 1, context.getFocusContext().getExecutedDeltas().size()); ObjectDelta userSecondaryDelta = context.getFocusContext().getExecutedDeltas().iterator().next().getObjectDelta(); @@ -239,25 +239,25 @@ public void test021ModifyLootAbsoluteEmpty() throws Exception { assertNotNull("No user secondary delta", userSecondaryDelta); assertEquals("Unexpected number of modifications in user secondary delta", 3, userSecondaryDelta.getModifications().size()); PrismAsserts.assertPropertyReplace(userSecondaryDelta, UserType.F_COST_CENTER); - + ResourceShadowDiscriminator rat = new ResourceShadowDiscriminator(getDummyResourceObject().getOid(), ShadowKindType.ACCOUNT, null); LensProjectionContext accCtx = context.findProjectionContext(rat); assertNotNull("No account sync context for "+rat, accCtx); - + PrismAsserts.assertNoDelta("Unexpected account primary delta", accCtx.getPrimaryDelta()); PrismAsserts.assertNoDelta("Unexpected account secondary delta", accCtx.getSecondaryDelta()); - + assertEquals("Wrong detected situation in context", SynchronizationSituationType.LINKED, accCtx.getSynchronizationSituationDetected()); - + assertLinked(context.getFocusContext().getObjectOld().getOid(), accountShadowJack.getOid()); - + PrismObject user = getUser(USER_JACK_OID); assertEquals("Unexpected used constCenter", null, user.asObjectable().getCostCenter()); - + PrismObject shadow = getShadowModelNoFetch(accountShadowJackDummyOid); assertIteration(shadow, 0, ""); assertSituation(shadow, SynchronizationSituationType.LINKED); - + result.computeStatus(); TestUtil.assertSuccess(result); } @@ -273,44 +273,44 @@ public void test030Reconcile() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestSynchronizationService.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + MockLensDebugListener mockListener = new MockLensDebugListener(); clockwork.setDebugListener(mockListener); - + ResourceObjectShadowChangeDescription change = new ResourceObjectShadowChangeDescription(); PrismObject accountShadowJack = provisioningService.getObject(ShadowType.class, accountShadowJackDummyOid, null, task, result); change.setCurrentShadow(accountShadowJack); change.setResource(getDummyResourceObject()); change.setSourceChannel(SchemaConstants.CHANGE_CHANNEL_DISCOVERY_URI); - + // WHEN synchronizationService.notifyChange(change, task, result); - + // THEN LensContext context = mockListener.getLastSyncContext(); display("Resulting context (as seen by debug listener)", context); assertNotNull("No resulting context (as seen by debug listener)", context); - + assertNull("Unexpected user primary delta", context.getFocusContext().getPrimaryDelta()); assertSideEffectiveDeltasOnly("user secondary delta", context.getFocusContext().getSecondaryDelta()); - - ResourceShadowDiscriminator rat = new ResourceShadowDiscriminator(getDummyResourceObject().getOid(), + + ResourceShadowDiscriminator rat = new ResourceShadowDiscriminator(getDummyResourceObject().getOid(), ShadowKindType.ACCOUNT, null); LensProjectionContext accCtx = context.findProjectionContext(rat); assertNotNull("No account sync context for "+rat, accCtx); - + PrismAsserts.assertNoDelta("account primary delta", accCtx.getPrimaryDelta()); PrismAsserts.assertNoDelta("account secondary delta", accCtx.getSecondaryDelta()); - + assertEquals("Wrong detected situation in context", SynchronizationSituationType.LINKED, accCtx.getSynchronizationSituationDetected()); - + assertLinked(context.getFocusContext().getObjectOld().getOid(), accountShadowJack.getOid()); - + PrismObject shadow = getShadowModelNoFetch(accountShadowJackDummyOid); assertIteration(shadow, 0, ""); assertSituation(shadow, SynchronizationSituationType.LINKED); - + result.computeStatus(); TestUtil.assertSuccess(result); } @@ -327,58 +327,58 @@ public void test039DeletedAccountJack() throws Exception { PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountShadowJackDummyOid, null, result); assertIteration(shadowRepo, 0, ""); assertSituation(shadowRepo, SynchronizationSituationType.LINKED); - + MockLensDebugListener mockListener = new MockLensDebugListener(); clockwork.setDebugListener(mockListener); getDummyResource().deleteAccountByName(ACCOUNT_JACK_DUMMY_USERNAME); - + PrismObject shadow = getShadowModelNoFetch(accountShadowJackDummyOid); - + shadowRepo = repositoryService.getObject(ShadowType.class, accountShadowJackDummyOid, null, result); assertIteration(shadowRepo, 0, ""); assertSituation(shadowRepo, SynchronizationSituationType.LINKED); - + ResourceObjectShadowChangeDescription change = new ResourceObjectShadowChangeDescription(); change.setCurrentShadow(shadow); change.setResource(getDummyResourceObject()); ObjectDelta syncDelta = ObjectDelta.createDeleteDelta(ShadowType.class, accountShadowJackDummyOid, prismContext); change.setObjectDelta(syncDelta); - + // WHEN TestUtil.displayWhen(TEST_NAME); synchronizationService.notifyChange(change, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); LensContext context = mockListener.getLastSyncContext(); display("Resulting context (as seen by debug listener)", context); assertNotNull("No resulting context (as seen by debug listener)", context); - + assertNull("Unexpected user primary delta", context.getFocusContext().getPrimaryDelta()); assertSideEffectiveDeltasOnly("user secondary delta", context.getFocusContext().getSecondaryDelta()); - - ResourceShadowDiscriminator rat = new ResourceShadowDiscriminator(getDummyResourceObject().getOid(), + + ResourceShadowDiscriminator rat = new ResourceShadowDiscriminator(getDummyResourceObject().getOid(), ShadowKindType.ACCOUNT, null, true); LensProjectionContext accCtx = context.findProjectionContext(rat); assertNotNull("No account sync context for "+rat, accCtx); assertEquals("Wrong detected situation in context", SynchronizationSituationType.DELETED, accCtx.getSynchronizationSituationDetected()); - + PrismAsserts.assertNoDelta("Unexpected account primary delta", accCtx.getPrimaryDelta()); - + assertNotLinked(context.getFocusContext().getObjectOld().getOid(), accountShadowJackDummyOid); - + shadowRepo = repositoryService.getObject(ShadowType.class, accountShadowJackDummyOid, null, result); assertIteration(shadowRepo, 0, ""); assertSituation(shadowRepo, SynchronizationSituationType.DELETED); - + result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); assertLinks(userAfter, 0); - + repositoryService.deleteObject(ShadowType.class, accountShadowJackDummyOid, result); } @@ -393,43 +393,43 @@ public void test050AddedAccountCalypso() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestSynchronizationService.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + MockLensDebugListener mockListener = new MockLensDebugListener(); clockwork.setDebugListener(mockListener); - + PrismObject accountShadowCalypso = repoAddObjectFromFile(ACCOUNT_SHADOW_CALYPSO_DUMMY_FILE, result); accountShadowCalypsoDummyOid = accountShadowCalypso.getOid(); provisioningService.applyDefinition(accountShadowCalypso, task, result); assertNotNull("No oid in shadow", accountShadowCalypso.getOid()); // Make sure that it is properly marked as protected. This is what provisioning would normally do accountShadowCalypso.asObjectable().setProtectedObject(true); - + DummyAccount dummyAccount = new DummyAccount(); dummyAccount.setName(ACCOUNT_CALYPSO_DUMMY_USERNAME); dummyAccount.setPassword("h1ghS3AS"); dummyAccount.setEnabled(true); dummyAccount.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Calypso"); getDummyResource().addAccount(dummyAccount); - + ResourceObjectShadowChangeDescription change = new ResourceObjectShadowChangeDescription(); change.setCurrentShadow(accountShadowCalypso); change.setResource(getDummyResourceObject()); - + // WHEN synchronizationService.notifyChange(change, task, result); - + // THEN LensContext context = mockListener.getLastSyncContext(); display("Resulting context (as seen by debug listener)", context); assertNull("Unexpected lens context", context); - + PrismObject userCalypso = findUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); assertNull("Unexpected user "+userCalypso, userCalypso); - + PrismObject shadow = getShadowModelNoFetch(accountShadowCalypsoDummyOid); assertSituation(shadow, null); - + result.computeStatus(); TestUtil.assertSuccess(result); } @@ -445,46 +445,46 @@ public void test051CalypsoRecon() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestSynchronizationService.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + MockLensDebugListener mockListener = new MockLensDebugListener(); clockwork.setDebugListener(mockListener); - + // Lets make this a bit more interesting by setting up a fake situation in the shadow - ObjectDelta objectDelta = createModifyAccountShadowReplaceDelta(accountShadowCalypsoDummyOid, + ObjectDelta objectDelta = createModifyAccountShadowReplaceDelta(accountShadowCalypsoDummyOid, getDummyResourceObject(), new ItemPath(ShadowType.F_SYNCHRONIZATION_SITUATION), SynchronizationSituationType.DISPUTED); repositoryService.modifyObject(ShadowType.class, accountShadowCalypsoDummyOid, objectDelta.getModifications(), result); - + PrismObject accountShadowCalypso = getShadowModelNoFetch(accountShadowCalypsoDummyOid); // Make sure that it is properly marked as protected. This is what provisioning would normally do accountShadowCalypso.asObjectable().setProtectedObject(true); - + ResourceObjectShadowChangeDescription change = new ResourceObjectShadowChangeDescription(); change.setCurrentShadow(accountShadowCalypso); change.setResource(getDummyResourceObject()); - + display("Change notification", change); - + // WHEN TestUtil.displayWhen(TEST_NAME); synchronizationService.notifyChange(change, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); LensContext context = mockListener.getLastSyncContext(); display("Resulting context (as seen by debug listener)", context); assertNull("Unexpected lens context", context); - + PrismObject userCalypso = findUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); assertNull("Unexpected user "+userCalypso, userCalypso); - + PrismObject shadow = getShadowModelNoFetch(accountShadowCalypsoDummyOid); assertSituation(shadow, SynchronizationSituationType.DISPUTED); - + result.computeStatus(); TestUtil.assertSuccess(result); } - + @Test public void test100AddedAccountJack() throws Exception { final String TEST_NAME = "test100AddedAccountJack"; @@ -493,13 +493,13 @@ public void test100AddedAccountJack() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestSynchronizationService.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); assertLinks(userBefore, 0); - + MockLensDebugListener mockListener = new MockLensDebugListener(); clockwork.setDebugListener(mockListener); - + PrismObject accountShadowJack = repoAddObjectFromFile(ACCOUNT_SHADOW_JACK_DUMMY_FILE, result); accountShadowJackDummyOid = accountShadowJack.getOid(); provisioningService.applyDefinition(accountShadowJack, task, result); @@ -510,51 +510,51 @@ public void test100AddedAccountJack() throws Exception { dummyAccount.setEnabled(true); dummyAccount.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Jack Sparrow"); getDummyResource().addAccount(dummyAccount); - + display("Dummy resource before", getDummyResource()); - + ResourceObjectShadowChangeDescription change = new ResourceObjectShadowChangeDescription(); change.setCurrentShadow(accountShadowJack); change.setResource(getDummyResourceObject()); - + // WHEN synchronizationService.notifyChange(change, task, result); - + // THEN LensContext context = mockListener.getLastSyncContext(); display("Resulting context (as seen by debug listener)", context); assertNotNull("No resulting context (as seen by debug listener)", context); - + assertNull("Unexpected user primary delta", context.getFocusContext().getPrimaryDelta()); assertSideEffectiveDeltasOnly(context.getFocusContext().getSecondaryDelta(), "user secondary delta", ActivationStatusType.ENABLED); - + ResourceShadowDiscriminator rat = new ResourceShadowDiscriminator(getDummyResourceObject().getOid(), ShadowKindType.ACCOUNT, null); LensProjectionContext accCtx = context.findProjectionContext(rat); assertNotNull("No account sync context for "+rat, accCtx); assertEquals("Wrong detected situation in context", SynchronizationSituationType.UNLINKED, accCtx.getSynchronizationSituationDetected()); assertEquals("Wrong resolved situation in context", SynchronizationSituationType.LINKED, accCtx.getSynchronizationSituationResolved()); - + PrismAsserts.assertNoDelta("Unexpected account primary delta", accCtx.getPrimaryDelta()); //it this really expected?? delta was already executed, should we expect it in the secondary delta? // assertNotNull("Missing account secondary delta", accCtx.getSecondaryDelta()); // assertIterationDelta(accCtx.getSecondaryDelta(), 0, ""); - + assertLinked(context.getFocusContext().getObjectOld().getOid(), accountShadowJack.getOid()); - + PrismObject shadow = getShadowModelNoFetch(accountShadowJackDummyOid); assertIteration(shadow, 0, ""); assertSituation(shadow, SynchronizationSituationType.LINKED); - + result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); assertLinks(userAfter, 1); assertLinked(userAfter, shadow); } - + /** * Delete the account but also the shadow in the repo. The system should work well. */ @@ -566,54 +566,54 @@ public void test199DeletedAccountJackTotal() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestSynchronizationService.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + MockLensDebugListener mockListener = new MockLensDebugListener(); clockwork.setDebugListener(mockListener); getDummyResource().deleteAccountByName(ACCOUNT_JACK_DUMMY_USERNAME); PrismObject shadow = getShadowModelNoFetch(accountShadowJackDummyOid); - + ResourceObjectShadowChangeDescription change = new ResourceObjectShadowChangeDescription(); change.setCurrentShadow(shadow); change.setResource(getDummyResourceObject()); ObjectDelta syncDelta = ObjectDelta.createDeleteDelta(ShadowType.class, accountShadowJackDummyOid, prismContext); change.setObjectDelta(syncDelta); - + repositoryService.deleteObject(ShadowType.class, accountShadowJackDummyOid, result); - + // WHEN synchronizationService.notifyChange(change, task, result); - + // THEN LensContext context = mockListener.getLastSyncContext(); display("Resulting context (as seen by debug listener)", context); assertNotNull("No resulting context (as seen by debug listener)", context); - + assertNotNull("No focus context", context.getFocusContext()); assertNull("Unexpected user primary delta", context.getFocusContext().getPrimaryDelta()); assertSideEffectiveDeltasOnly("user secondary delta", context.getFocusContext().getSecondaryDelta()); - - ResourceShadowDiscriminator rat = new ResourceShadowDiscriminator(getDummyResourceObject().getOid(), + + ResourceShadowDiscriminator rat = new ResourceShadowDiscriminator(getDummyResourceObject().getOid(), ShadowKindType.ACCOUNT, null, true); LensProjectionContext accCtx = context.findProjectionContext(rat); assertNotNull("No account sync context for "+rat, accCtx); assertEquals("Wrong detected situation in context", SynchronizationSituationType.DELETED, accCtx.getSynchronizationSituationDetected()); - + PrismAsserts.assertNoDelta("Unexpected account primary delta", accCtx.getPrimaryDelta()); - + assertNotLinked(context.getFocusContext().getObjectOld().getOid(), accountShadowJackDummyOid); - + PrismObject userAfter = getUser(USER_JACK_OID); assertLinks(userAfter, 0); - + result.computeStatus(); display("Final result", result); TestUtil.assertSuccess(result,1); - + assertNoObject(ShadowType.class, accountShadowJackDummyOid, task, result); } - + @Test public void test210AddedGroupPirates() throws Exception { final String TEST_NAME = "test210AddedGroupPirates"; @@ -622,10 +622,10 @@ public void test210AddedGroupPirates() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestSynchronizationService.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + MockLensDebugListener mockListener = new MockLensDebugListener(); clockwork.setDebugListener(mockListener); - + PrismObject shadowPirates = repoAddObjectFromFile(SHADOW_PIRATES_DUMMY_FILE, result); provisioningService.applyDefinition(shadowPirates, task, result); assertNotNull("No oid in shadow", shadowPirates.getOid()); @@ -634,47 +634,47 @@ public void test210AddedGroupPirates() throws Exception { dummyGroup.setEnabled(true); dummyGroup.addAttributeValues(DummyResourceContoller.DUMMY_GROUP_ATTRIBUTE_DESCRIPTION, "Scurvy Pirates"); getDummyResource().addGroup(dummyGroup); - + ResourceObjectShadowChangeDescription change = new ResourceObjectShadowChangeDescription(); change.setCurrentShadow(shadowPirates); change.setResource(getDummyResourceObject()); - + // WHEN TestUtil.displayWhen(TEST_NAME); synchronizationService.notifyChange(change, task, result); - + // THEN TestUtil.displayWhen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + LensContext context = mockListener.getLastSyncContext(); display("Resulting context (as seen by debug listener)", context); assertNotNull("No resulting context (as seen by debug listener)", context); - + assertNotNull("No focus primary delta", context.getFocusContext().getPrimaryDelta()); // assertNotNull("No focus secondary delta", context.getFocusContext().getSecondaryDelta()); assertFalse("No executed focus deltas", context.getFocusContext().getExecutedDeltas().isEmpty()); ObjectDelta userSecondaryDelta = (ObjectDelta) context.getFocusContext().getExecutedDeltas().iterator().next().getObjectDelta(); - - ResourceShadowDiscriminator rat = new ResourceShadowDiscriminator(getDummyResourceObject().getOid(), + + ResourceShadowDiscriminator rat = new ResourceShadowDiscriminator(getDummyResourceObject().getOid(), ShadowKindType.ENTITLEMENT, INTENT_GROUP); LensProjectionContext projCtx = context.findProjectionContext(rat); assertNotNull("No projection sync context for "+rat, projCtx); assertEquals("Wrong detected situation in context", SynchronizationSituationType.UNMATCHED, projCtx.getSynchronizationSituationDetected()); assertEquals("Wrong resolved situation in context", SynchronizationSituationType.LINKED, projCtx.getSynchronizationSituationResolved()); - + PrismAsserts.assertNoDelta("Unexpected projection primary delta", projCtx.getPrimaryDelta()); //it this really expected?? delta was already executed, should we expect it in the secondary delta? // assertNotNull("Missing account secondary delta", accCtx.getSecondaryDelta()); // assertIterationDelta(accCtx.getSecondaryDelta(), 0, ""); - + assertLinked(RoleType.class, context.getFocusContext().getOid(), shadowPirates.getOid()); - + PrismObject shadow = getShadowModelNoFetch(shadowPirates.getOid()); assertIteration(shadow, 0, ""); assertSituation(shadow, SynchronizationSituationType.LINKED); - + } } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/ModelTUtil.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/ModelTUtil.java index 372e0687e3c..d1a2a82bd9a 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/ModelTUtil.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/ModelTUtil.java @@ -47,9 +47,9 @@ import com.evolveum.midpoint.xml.ns._public.common.fault_3.ObjectNotFoundFaultType; /** - * + * * @author lazyman - * + * */ public class ModelTUtil { @@ -117,7 +117,7 @@ public static ObjectType addObjectToRepo(RepositoryService repositoryService, St } /** - * + * * @param repository * @param file * - user to be found diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/ObjectTypeNameMatcher.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/ObjectTypeNameMatcher.java index 59ad997bdd0..a58ed876d20 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/ObjectTypeNameMatcher.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/ObjectTypeNameMatcher.java @@ -24,7 +24,7 @@ import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; /** - * + * * @author lazyman */ public class ObjectTypeNameMatcher extends BaseMatcher> { @@ -34,7 +34,7 @@ public class ObjectTypeNameMatcher extends BaseMatcher> public ObjectTypeNameMatcher(PolyStringType name) { this.name = name.getOrig(); } - + public ObjectTypeNameMatcher(String name) { this.name = name; } 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 24491c813e0..c9e8b0a642c 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 @@ -36,7 +36,7 @@ * */ public class MockClockworkHook implements ChangeHook, DebugDumpable { - + private List> contexts = new ArrayList>(); private LensContext lastAsyncContext = null; private boolean record = false; @@ -49,7 +49,7 @@ public boolean isRecord() { public void setRecord(boolean record) { this.record = record; } - + public boolean isAsynchronous() { return asynchronous; } @@ -61,7 +61,7 @@ public void setAsynchronous(boolean asynchronous) { public List> getContexts() { return contexts; } - + public void reset() { System.out.println("RESETING"); record = false; @@ -113,7 +113,7 @@ public void invokeOnException(@NotNull ModelContext context, @NotNull Throwable // // TODO Auto-generated method stub // // } - + /* (non-Javadoc) * @see com.evolveum.midpoint.util.DebugDumpable#debugDump() */ diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/mock/MockFactory.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/mock/MockFactory.java index 6edfc720e9d..c02c2888bcf 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/mock/MockFactory.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/mock/MockFactory.java @@ -24,7 +24,7 @@ import static org.mockito.Mockito.withSettings; /** - * + * * @author lazyman */ public class MockFactory { @@ -36,9 +36,9 @@ public static ProvisioningService createProvisioningPortType() { public static RepositoryService createRepositoryPortType() { return Mockito.mock(RepositoryService.class, withSettings().defaultAnswer(new MidpointDefaultAnswer())); } - + public static ChangeNotificationDispatcher createChangeNotificationDispatcher() { return Mockito.mock(ChangeNotificationDispatcher.class); } - + } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/mock/MockLensDebugListener.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/mock/MockLensDebugListener.java index 7b454754b99..4f10c02a682 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/mock/MockLensDebugListener.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/mock/MockLensDebugListener.java @@ -27,13 +27,13 @@ * */ public class MockLensDebugListener implements LensDebugListener { - + private static final Trace LOGGER = TraceManager.getTrace(MockLensDebugListener.class); private static final String SEPARATOR = "############################################################################"; private LensContext lastSyncContext; - + public LensContext getLastSyncContext() { return lastSyncContext; } @@ -41,7 +41,7 @@ public LensContext getLastSyncContext() { public void setLastSyncContext(LensContext lastSyncContext) { this.lastSyncContext = lastSyncContext; } - + /* (non-Javadoc) * @see com.evolveum.midpoint.model.lens.LensDebugListener#beforeSync(com.evolveum.midpoint.model.lens.LensContext) */ @@ -62,20 +62,20 @@ public void afterSync(LensContext context) { @Override public void beforeProjection( LensContext context) { - + } @Override public void afterProjection( LensContext context) { - + } @Override public void afterMappingEvaluation( LensContext context, Mapping evaluatedMapping) { - + } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/visualizer/TestVisualizer.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/visualizer/TestVisualizer.java index 59816081429..d68a41a774f 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/visualizer/TestVisualizer.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/visualizer/TestVisualizer.java @@ -73,7 +73,7 @@ public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - + @Test public void test100UserBasic() throws Exception { final String TEST_NAME = "test100UserBasic"; 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 a94ff490290..150450d867d 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 @@ -76,43 +76,43 @@ * */ public class AbstractConfiguredModelIntegrationTest 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 int NUMBER_OF_GLOBAL_POLICY_RULES = 3; - + public 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 String USER_TEMPLATE_FILENAME = COMMON_DIR + "/user-template.xml"; protected static final String USER_TEMPLATE_OID = "10000000-0000-0000-0000-000000000002"; - + protected static final File USER_TEMPLATE_COMPLEX_FILE = new File(COMMON_DIR, "user-template-complex.xml"); protected static final String USER_TEMPLATE_COMPLEX_OID = "10000000-0000-0000-0000-000000000222"; - + protected static final String USER_TEMPLATE_INBOUNDS_FILENAME = COMMON_DIR + "/user-template-inbounds.xml"; protected static final String USER_TEMPLATE_INBOUNDS_OID = "10000000-0000-0000-0000-000000000555"; - + protected static final String USER_TEMPLATE_COMPLEX_INCLUDE_FILENAME = COMMON_DIR + "/user-template-complex-include.xml"; protected static final String USER_TEMPLATE_COMPLEX_INCLUDE_OID = "10000000-0000-0000-0000-000000000223"; - + protected static final String USER_TEMPLATE_SYNC_FILENAME = COMMON_DIR + "/user-template-sync.xml"; protected static final String USER_TEMPLATE_SYNC_OID = "10000000-0000-0000-0000-000000000333"; protected static final String USER_TEMPLATE_ORG_ASSIGNMENT_FILENAME = COMMON_DIR + "/user-template-org-assignment.xml"; protected static final String USER_TEMPLATE_ORG_ASSIGNMENT_OID = "10000000-0000-0000-0000-000000000444"; - + protected static final File OBJECT_TEMPLATE_PERSONA_ADMIN_FILE = new File(COMMON_DIR, "object-template-persona-admin.xml"); protected static final String OBJECT_TEMPLATE_PERSONA_ADMIN_OID = "894ea1a8-2c0a-11e7-a950-ff2047b0c053"; - + protected static final String CONNECTOR_LDAP_FILENAME = COMMON_DIR + "/connector-ldap.xml"; - + protected static final String CONNECTOR_DBTABLE_FILENAME = COMMON_DIR + "/connector-dbtable.xml"; - + protected static final String CONNECTOR_DUMMY_FILENAME = COMMON_DIR + "/connector-dummy.xml"; - + protected static final File RESOURCE_DUMMY_FILE = new File(COMMON_DIR, "resource-dummy.xml"); protected static final File RESOURCE_DUMMY_DEPRECATED_FILE = new File(COMMON_DIR, "resource-dummy-deprecated.xml"); protected static final File RESOURCE_DUMMY_CACHING_FILE = new File(COMMON_DIR, "resource-dummy-caching.xml"); @@ -121,14 +121,14 @@ public class AbstractConfiguredModelIntegrationTest extends AbstractModelIntegra protected static final String RESOURCE_DUMMY_DRINK = "rum"; protected static final String RESOURCE_DUMMY_QUOTE = "Arr!"; protected static final String RESOURCE_DUMMY_USELESS_STRING = "USEless"; - + // RED resource has STRONG mappings protected static final File RESOURCE_DUMMY_RED_FILE = new File(COMMON_DIR, "resource-dummy-red.xml"); protected static final String RESOURCE_DUMMY_RED_OID = "10000000-0000-0000-0000-000000000104"; protected static final String RESOURCE_DUMMY_RED_NAME = "red"; protected static final String RESOURCE_DUMMY_RED_NAMESPACE = MidPointConstants.NS_RI; protected static final String RESOURCE_DUMMY_RED_USELESS_STRING = IntegrationTestTools.CONST_USELESS; - + // BLUE resource has WEAK mappings, outbound/inbound protected static final File RESOURCE_DUMMY_BLUE_FILE = new File(COMMON_DIR, "resource-dummy-blue.xml"); protected static final File RESOURCE_DUMMY_BLUE_DEPRECATED_FILE = new File(COMMON_DIR, "resource-dummy-blue-deprecated.xml"); @@ -136,13 +136,13 @@ public class AbstractConfiguredModelIntegrationTest extends AbstractModelIntegra protected static final String RESOURCE_DUMMY_BLUE_OID = "10000000-0000-0000-0000-000000000204"; protected static final String RESOURCE_DUMMY_BLUE_NAME = "blue"; protected static final String RESOURCE_DUMMY_BLUE_NAMESPACE = MidPointConstants.NS_RI; - + // CYAN has WEAK mappings, outbound only protected static final File RESOURCE_DUMMY_CYAN_FILE = new File(COMMON_DIR, "resource-dummy-cyan.xml"); protected static final String RESOURCE_DUMMY_CYAN_OID = "10000000-0000-0000-0000-00000000c204"; protected static final String RESOURCE_DUMMY_CYAN_NAME = "cyan"; protected static final String RESOURCE_DUMMY_CYAN_NAMESPACE = MidPointConstants.NS_RI; - + // WHITE dummy resource has almost no configuration: no schema, no schemahandling, no synchronization, ... protected static final String RESOURCE_DUMMY_WHITE_FILENAME = COMMON_DIR + "/resource-dummy-white.xml"; protected static final String RESOURCE_DUMMY_WHITE_OID = "10000000-0000-0000-0000-000000000304"; @@ -163,7 +163,7 @@ public class AbstractConfiguredModelIntegrationTest extends AbstractModelIntegra protected static final String RESOURCE_DUMMY_GREEN_OID = "10000000-0000-0000-0000-000000000404"; protected static final String RESOURCE_DUMMY_GREEN_NAME = "green"; protected static final String RESOURCE_DUMMY_GREEN_NAMESPACE = MidPointConstants.NS_RI; - + // This is authoritative resource similar to green resource but it has a bit wilder inbound mappings. protected static final File RESOURCE_DUMMY_EMERALD_FILE = new File(COMMON_DIR, "resource-dummy-emerald.xml"); protected static final File RESOURCE_DUMMY_EMERALD_DEPRECATED_FILE = new File(COMMON_DIR, "resource-dummy-emerald-deprecated.xml"); @@ -176,7 +176,7 @@ public class AbstractConfiguredModelIntegrationTest extends AbstractModelIntegra protected static final String RESOURCE_DUMMY_BLACK_OID = "10000000-0000-0000-0000-000000000305"; protected static final String RESOURCE_DUMMY_BLACK_NAME = "black"; protected static final String RESOURCE_DUMMY_BLACK_NAMESPACE = MidPointConstants.NS_RI; - + // Black dummy resource for testing tolerant attributes protected static final File RESOURCE_DUMMY_RELATIVE_FILE = new File(COMMON_DIR, "resource-dummy-relative.xml"); protected static final String RESOURCE_DUMMY_RELATIVE_OID = "adcd4654-0f15-11e7-8337-0bdf60ad7bcd"; @@ -215,27 +215,27 @@ public class AbstractConfiguredModelIntegrationTest extends AbstractModelIntegra protected static final String ROLE_PIRATE_DESCRIPTION = "Scurvy Pirates"; protected static final String ROLE_PIRATE_TITLE = "Bloody Pirate"; protected static final String ROLE_PIRATE_WEAPON = "cutlass"; - + protected static final File ROLE_CARIBBEAN_PIRATE_FILE = new File(COMMON_DIR, "role-caribbean-pirate.xml"); protected static final String ROLE_CARIBBEAN_PIRATE_OID = "0719ec66-edd9-11e6-bd70-03a74157ff9e"; - + protected static final File ROLE_PIRATE_GREEN_FILE = new File(COMMON_DIR, "role-pirate-green.xml"); protected static final String ROLE_PIRATE_GREEN_OID = "12345678-d34d-b33f-f00d-555555557777"; protected static final String ROLE_PIRATE_GREEN_NAME = "Pirate Green"; protected static final String ROLE_PIRATE_GREEN_DESCRIPTION = "Scurvy Pirates"; - + protected static final File ROLE_PIRATE_RELATIVE_FILE = new File(COMMON_DIR, "role-pirate-relative.xml"); protected static final String ROLE_PIRATE_RELATIVE_OID = "4a579cd0-0f17-11e7-967c-130ecd6fb7dc"; protected static final String ROLE_PIRAT_RELATIVEE_NAME = "Relative Pirate"; - + protected static final File ROLE_BUCCANEER_GREEN_FILE = new File(COMMON_DIR, "role-buccaneer-green.xml"); protected static final String ROLE_BUCCANEER_GREEN_OID = "12345678-d34d-b33f-f00d-555555558888"; protected static final String ROLE_BUCCANEER_GREEN_NAME = "Bucaneers Green"; protected static final String ROLE_BUCCANEER_GREEN_DESCRIPTION = "Scurvy Bucaneers"; - + protected static final String ROLE_NICE_PIRATE_FILENAME = COMMON_DIR + "/role-nice-pirate.xml"; protected static final String ROLE_NICE_PIRATE_OID = "12345678-d34d-b33f-f00d-555555556677"; - + protected static final String ROLE_CAPTAIN_FILENAME = COMMON_DIR + "/role-captain.xml"; protected static final String ROLE_CAPTAIN_OID = "12345678-d34d-b33f-f00d-55555555cccc"; @@ -249,29 +249,29 @@ public class AbstractConfiguredModelIntegrationTest extends AbstractModelIntegra protected static final File ROLE_JUDGE_DEPRECATED_FILE = new File(COMMON_DIR, "role-judge-deprecated.xml"); protected static final String ROLE_JUDGE_DEPRECATED_OID = "12345111-1111-2222-1111-d21212111111"; - + protected static final File ROLE_THIEF_FILE = new File(COMMON_DIR, "role-thief.xml"); protected static final String ROLE_THIEF_OID = "b189fcb8-1ff9-11e5-8912-001e8c717e5b"; - + protected static final File ROLE_EMPTY_FILE = new File(COMMON_DIR, "role-empty.xml"); protected static final String ROLE_EMPTY_OID = "12345111-1111-2222-1111-121212111112"; - + protected static final File ROLE_SAILOR_FILE = new File(COMMON_DIR, "role-sailor.xml"); protected static final String ROLE_SAILOR_OID = "12345111-1111-2222-1111-121212111113"; protected static final String ROLE_SAILOR_DRINK = "grog"; - + protected static final File ROLE_RED_SAILOR_FILE = new File(COMMON_DIR, "role-red-sailor.xml"); protected static final String ROLE_RED_SAILOR_OID = "12345111-1111-2222-1111-121212111223"; protected static final File ROLE_CYAN_SAILOR_FILE = new File(COMMON_DIR, "role-cyan-sailor.xml"); protected static final String ROLE_CYAN_SAILOR_OID = "d3abd794-9c30-11e6-bb5a-af14bf2cc29b"; - + protected static final File ROLE_STRONG_SAILOR_FILE = new File(COMMON_DIR, "role-strong-sailor.xml"); protected static final String ROLE_STRONG_SAILOR_OID = "0bf7532e-7d15-11e7-8594-7bff6e0adc6e"; - + protected static final File ROLE_DRINKER_FILE = new File(COMMON_DIR, "role-drinker.xml"); protected static final String ROLE_DRINKER_OID = "0abbde4c-ab3f-11e6-910d-d7dabf5f09f0"; - + protected static final File ROLE_PERSONA_ADMIN_FILE = new File(COMMON_DIR, "role-persona-admin.xml"); protected static final String ROLE_PERSONA_ADMIN_OID = "16813ae6-2c0a-11e7-91fc-8333c244329e"; @@ -299,12 +299,12 @@ public class AbstractConfiguredModelIntegrationTest extends AbstractModelIntegra protected static final String USER_GUYBRUSH_GIVEN_NAME = "Guybrush"; protected static final String USER_GUYBRUSH_FAMILY_NAME = "Threepwood"; protected static final String USER_GUYBRUSH_LOCALITY = "Melee Island"; - + // 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 String USER_LARGO_OID = "c0c010c0-d34d-b33f-f00d-111111111118"; protected static final String USER_LARGO_USERNAME = "largo"; - + // Rapp does not have a full name set, employeeType=COOK protected static final File USER_RAPP_FILE = new File(COMMON_DIR, "user-rapp.xml"); protected static final String USER_RAPP_OID = "c0c010c0-d34d-b33f-f00d-11111111c008"; @@ -325,36 +325,36 @@ public class AbstractConfiguredModelIntegrationTest extends AbstractModelIntegra // Has null name, doesn not have given name, no employeeType protected static final String USER_THREE_HEADED_MONKEY_FILENAME = COMMON_DIR + "/user-three-headed-monkey.xml"; protected static final String USER_THREE_HEADED_MONKEY_OID = "c0c010c0-d34d-b33f-f00d-110011001133"; - + // Elaine has account on the dummy resources (default, red, blue) // The accounts are also assigned static final File USER_ELAINE_FILE = new File (COMMON_DIR, "user-elaine.xml"); protected static final String USER_ELAINE_OID = "c0c010c0-d34d-b33f-f00d-11111111111e"; protected static final String USER_ELAINE_USERNAME = "elaine"; - - // Captain Kate Capsize does not exist in the repo. This user is designed to be added. + + // Captain Kate Capsize does not exist in the repo. This user is designed to be added. // She has account on dummy resources (default, red, blue) // The accounts are also assigned static final File USER_CAPSIZE_FILE = new File(COMMON_DIR, "user-capsize.xml"); protected static final String USER_CAPSIZE_OID = "c0c010c0-d34d-b33f-f00d-11c1c1c1c11c"; protected static final String USER_CAPSIZE_USERNAME = "capsize"; - + protected static final File USER_DRAKE_FILE = new File(COMMON_DIR, "user-drake.xml"); protected static final String USER_DRAKE_OID = "c0c010c0-d34d-b33f-f00d-11d1d1d1d1d1"; protected static final String USER_DRAKE_USERNAME = "drake"; - + public static final File ACCOUNT_JACK_DUMMY_FILE = new File(COMMON_DIR, "account-jack-dummy.xml"); public static final File ACCOUNT_JACK_DUMMY_RED_FILE = new File(COMMON_DIR, "account-jack-dummy-red.xml"); public static final String ACCOUNT_JACK_DUMMY_USERNAME = "jack"; public static final String ACCOUNT_JACK_DUMMY_FULLNAME = "Jack Sparrow"; - + public static final File ACCOUNT_HERMAN_DUMMY_FILE = new File(COMMON_DIR, "account-herman-dummy.xml"); public static final String ACCOUNT_HERMAN_DUMMY_OID = "22220000-2200-0000-0000-444400004444"; public static final String ACCOUNT_HERMAN_DUMMY_USERNAME = "ht"; - + public static final String ACCOUNT_HERMAN_OPENDJ_FILENAME = COMMON_DIR + "/account-herman-opendj.xml"; public static final String ACCOUNT_HERMAN_OPENDJ_OID = "22220000-2200-0000-0000-333300003333"; - + public static final File ACCOUNT_SHADOW_GUYBRUSH_DUMMY_FILE = new File(COMMON_DIR, "account-shadow-guybrush-dummy.xml"); public static final String ACCOUNT_SHADOW_GUYBRUSH_OID = "22226666-2200-6666-6666-444400004444"; public static final String ACCOUNT_GUYBRUSH_DUMMY_USERNAME = "guybrush"; @@ -362,17 +362,17 @@ public class AbstractConfiguredModelIntegrationTest extends AbstractModelIntegra public static final String ACCOUNT_GUYBRUSH_DUMMY_LOCATION = "Melee Island"; public static final File ACCOUNT_GUYBRUSH_DUMMY_FILE = new File (COMMON_DIR, "account-guybrush-dummy.xml"); public static final File ACCOUNT_GUYBRUSH_DUMMY_RED_FILE = new File(COMMON_DIR, "account-guybrush-dummy-red.xml"); - + public static final String ACCOUNT_SHADOW_JACK_DUMMY_FILENAME = COMMON_DIR + "/account-shadow-jack-dummy.xml"; - + public static final String ACCOUNT_DAVIEJONES_DUMMY_USERNAME = "daviejones"; public static final String ACCOUNT_CALYPSO_DUMMY_USERNAME = "calypso"; - + public static final File ACCOUNT_SHADOW_ELAINE_DUMMY_FILE = new File(COMMON_DIR, "account-elaine-dummy.xml"); public static final String ACCOUNT_SHADOW_ELAINE_DUMMY_OID = "c0c010c0-d34d-b33f-f00d-22220004000e"; public static final String ACCOUNT_ELAINE_DUMMY_USERNAME = USER_ELAINE_USERNAME; public static final String ACCOUNT_ELAINE_DUMMY_FULLNAME = "Elaine Marley"; - + public static final File ACCOUNT_SHADOW_ELAINE_DUMMY_RED_FILE = new File(COMMON_DIR, "account-elaine-dummy-red.xml"); public static final String ACCOUNT_SHADOW_ELAINE_DUMMY_RED_OID = "c0c010c0-d34d-b33f-f00d-22220104000e"; public static final String ACCOUNT_ELAINE_DUMMY_RED_USERNAME = USER_ELAINE_USERNAME; @@ -380,29 +380,29 @@ public class AbstractConfiguredModelIntegrationTest extends AbstractModelIntegra public static final File ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_FILE = new File(COMMON_DIR, "account-elaine-dummy-blue.xml"); public static final String ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_OID = "c0c010c0-d34d-b33f-f00d-22220204000e"; public static final String ACCOUNT_ELAINE_DUMMY_BLUE_USERNAME = USER_ELAINE_USERNAME; - + public static final File GROUP_PIRATE_DUMMY_FILE = new File(COMMON_DIR, "group-pirate-dummy.xml"); public static final String GROUP_PIRATE_DUMMY_NAME = "pirate"; public static final String GROUP_PIRATE_DUMMY_DESCRIPTION = "Scurvy pirates"; - + public static final File SHADOW_GROUP_DUMMY_TESTERS_FILE = new File(COMMON_DIR, "group-testers-dummy.xml"); public static final String SHADOW_GROUP_DUMMY_TESTERS_OID = "20000000-0000-0000-3333-000000000002"; public static final String GROUP_DUMMY_TESTERS_NAME = "testers"; public static final String GROUP_DUMMY_TESTERS_DESCRIPTION = "To boldly go where no pirate has gone before"; - + public static final File GROUP_SHADOW_JOKER_DUMMY_UPCASE_FILE = new File(COMMON_DIR, "group-shadow-dummy-upcase-joker.xml"); public static final String GROUP_SHADOW_JOKER_DUMMY_UPCASE_OID = "bc2a1d98-9ca4-11e4-a600-001e8c717e5b"; public static final String GROUP_SHADOW_JOKER_DUMMY_UPCASE_NAME = "joker"; public static final String GROUP_JOKER_DUMMY_UPCASE_NAME = "JOKER"; - + public static final String DUMMY_ORG_TOP_NAME = DummyResourceContoller.ORG_TOP_NAME; - + protected static final File PASSWORD_POLICY_GLOBAL_FILE = new File(COMMON_DIR, "password-policy-global.xml"); protected static final String PASSWORD_POLICY_GLOBAL_OID = "12344321-0000-0000-0000-000000000003"; - + protected static final File PASSWORD_POLICY_BENEVOLENT_FILE = new File(COMMON_DIR, "password-policy-benevolent.xml"); protected static final String PASSWORD_POLICY_BENEVOLENT_OID = "ed8026dc-569a-11e7-abdf-4fce56706755"; - + protected static final File ORG_MONKEY_ISLAND_FILE = new File(COMMON_DIR, "org-monkey-island.xml"); protected static final String ORG_GOVERNOR_OFFICE_OID = "00000000-8888-6666-0000-100000000001"; protected static final String ORG_SCUMM_BAR_OID = "00000000-8888-6666-0000-100000000006"; @@ -416,47 +416,47 @@ public class AbstractConfiguredModelIntegrationTest extends AbstractModelIntegra protected static final String ORG_PROJECT_ROOT_OID = "00000000-8888-6666-0000-200000000000"; protected static final String ORG_SAVE_ELAINE_OID = "00000000-8888-6666-0000-200000000001"; protected static final String ORG_KIDNAP_AND_MARRY_ELAINE_OID = "00000000-8888-6666-0000-200000000002"; - - protected static final String ORG_TYPE_FUNCTIONAL = "functional"; + + protected static final String ORG_TYPE_FUNCTIONAL = "functional"; protected static final String ORG_TYPE_PROJECT = "project"; - + protected static final File SERVICE_SHIP_SEA_MONKEY_FILE = new File(COMMON_DIR, "service-ship-sea-monkey.xml"); protected static final String SERVICE_SHIP_SEA_MONKEY_OID = "914b94be-1901-11e6-9269-972ee32cd8db"; - + protected static final String TASK_RECONCILE_DUMMY_FILENAME = COMMON_DIR + "/task-reconcile-dummy.xml"; protected static final String TASK_RECONCILE_DUMMY_OID = "10000000-0000-0000-5656-565600000004"; - + protected static final String TASK_RECONCILE_DUMMY_BLUE_FILENAME = COMMON_DIR + "/task-reconcile-dummy-blue.xml"; protected static final String TASK_RECONCILE_DUMMY_BLUE_OID = "10000000-0000-0000-5656-565600000204"; - + protected static final String TASK_RECONCILE_DUMMY_GREEN_FILENAME = COMMON_DIR + "/task-reconcile-dummy-green.xml"; protected static final String TASK_RECONCILE_DUMMY_GREEN_OID = "10000000-0000-0000-5656-565600000404"; - + protected static final String TASK_LIVE_SYNC_DUMMY_FILENAME = COMMON_DIR + "/task-dumy-livesync.xml"; protected static final String TASK_LIVE_SYNC_DUMMY_OID = "10000000-0000-0000-5555-555500000004"; - + protected static final String TASK_LIVE_SYNC_DUMMY_BLUE_FILENAME = COMMON_DIR + "/task-dumy-blue-livesync.xml"; protected static final String TASK_LIVE_SYNC_DUMMY_BLUE_OID = "10000000-0000-0000-5555-555500000204"; - + protected static final String TASK_LIVE_SYNC_DUMMY_GREEN_FILENAME = COMMON_DIR + "/task-dumy-green-livesync.xml"; protected static final String TASK_LIVE_SYNC_DUMMY_GREEN_OID = "10000000-0000-0000-5555-555500000404"; - + protected static final String TASK_VALIDITY_SCANNER_FILENAME = COMMON_DIR + "/task-validity-scanner.xml"; protected static final String TASK_VALIDITY_SCANNER_OID = "10000000-0000-0000-5555-555505060400"; - + 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"; - + protected static final File TASK_MOCK_JACK_FILE = new File(COMMON_DIR, "task-mock-jack.xml"); protected static final String TASK_MOCK_JACK_OID = "10000000-0000-0000-5656-565674633311"; - + public static final File LOOKUP_LANGUAGES_FILE = new File(COMMON_DIR, "lookup-languages.xml"); public static final String LOOKUP_LANGUAGES_OID = "70000000-0000-0000-1111-000000000001"; public static final String LOOKUP_LANGUAGES_NAME = "Languages"; - + protected static final File SECURITY_POLICY_FILE = new File(COMMON_DIR, "security-policy.xml"); protected static final String SECURITY_POLICY_OID = "28bf845a-b107-11e3-85bc-001e8c717e5b"; - + protected static final String NS_PIRACY = "http://midpoint.evolveum.com/xml/ns/samples/piracy"; protected static final QName PIRACY_SHIP = new QName(NS_PIRACY, "ship"); protected static final QName PIRACY_SHIP_BROKEN = new QName(NS_PIRACY, "ship-broken"); @@ -475,13 +475,13 @@ public class AbstractConfiguredModelIntegrationTest extends AbstractModelIntegra protected static final String DUMMY_ACCOUNT_ATTRIBUTE_SEA_NAME = "sea"; protected static final String DUMMY_ACCOUNT_ATTRIBUTE_MATE_NAME = "mate"; - + protected static final String INTENT_TEST = "test"; protected static final String INTENT_DUMMY_GROUP = "group"; protected static final String INTENT_DUMMY_PRIVILEGE = "privilege"; - + // Authorizations - + protected static final String NS_TEST_AUTZ = "http://midpoint.evolveum.com/xml/ns/test/authorization"; protected static final QName AUTZ_LOOT_QNAME = new QName(NS_TEST_AUTZ, "loot"); protected static final String AUTZ_LOOT_URL = QNameUtil.qNameToUri(AUTZ_LOOT_QNAME); @@ -497,14 +497,14 @@ public class AbstractConfiguredModelIntegrationTest extends AbstractModelIntegra protected static final String AUTZ_NONSENSE_URL = QNameUtil.qNameToUri(AUTZ_NONSENSE_QNAME); protected static final QName AUTZ_SAIL_QNAME = new QName(NS_TEST_AUTZ, "sail"); protected static final String AUTZ_SAIL_URL = QNameUtil.qNameToUri(AUTZ_SAIL_QNAME); - + protected static final String NOTIFIER_ACCOUNT_PASSWORD_NAME = "accountPasswordNotifier"; protected static final String NOTIFIER_ACCOUNT_ACTIVATION_NAME = "accountActivationNotifier"; - + private static final Trace LOGGER = TraceManager.getTrace(AbstractConfiguredModelIntegrationTest.class); - + protected PrismObject userAdministrator; - + public AbstractConfiguredModelIntegrationTest() { super(); } @@ -515,10 +515,10 @@ public void initSystem(Task initTask, OperationResult initResult) throws Except // We want logging config from logback-test.xml and not from system config object InternalsConfig.setAvoidLoggingChange(true); super.initSystem(initTask, initResult); - + modelService.postInit(initResult); ManualConnectorInstance.setRandomDelayRange(0); - + // System Configuration try { repoAddObjectFromFile(getSystemConfigurationFile(), initResult); @@ -526,17 +526,17 @@ public void initSystem(Task initTask, OperationResult initResult) throws Except throw new ObjectAlreadyExistsException("System configuration already exists in repository;" + "looks like the previous test haven't cleaned it up", e); } - + // Users userAdministrator = repoAddObjectFromFile(USER_ADMINISTRATOR_FILE, UserType.class, initResult); repoAddObjectFromFile(ROLE_SUPERUSER_FILE, initResult); login(userAdministrator); } - + protected int getNumberOfRoles() { return 1; // Superuser role } - + protected File getSystemConfigurationFile() { return SYSTEM_CONFIGURATION_FILE; } @@ -544,7 +544,7 @@ protected File getSystemConfigurationFile() { protected PrismObject getDefaultActor() { return userAdministrator; } - + @Override public void run(IHookCallBack callBack, ITestResult testResult) { long time = System.currentTimeMillis(); @@ -637,11 +637,11 @@ protected void springTestContextPrepareTestInstance() throws Exception { super.springTestContextPrepareTestInstance(); LOGGER.info("###>>> springTestContextPrepareTestInstance end ({}ms)", new Object[]{(System.currentTimeMillis() - time)}); } - + protected PrismSchema getPiracySchema() { return prismContext.getSchemaRegistry().findSchemaByNamespace(NS_PIRACY); } - + protected void assertLastRecomputeTimestamp(String taskOid, XMLGregorianCalendar startCal, XMLGregorianCalendar endCal) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject task = getTask(taskOid); display("Task", task); @@ -653,11 +653,11 @@ protected void assertLastRecomputeTimestamp(String taskOid, XMLGregorianCalendar assertNotNull("null lastRecomputeTimestamp", lastRecomputeTimestamp); TestUtil.assertBetween("lastRecomputeTimestamp", startCal, endCal, lastRecomputeTimestamp); } - + protected void assertPasswordMetadata(PrismObject user, boolean create, XMLGregorianCalendar start, XMLGregorianCalendar end) { assertPasswordMetadata(user, create, start, end, USER_ADMINISTRATOR_OID, SchemaConstants.CHANNEL_GUI_USER_URI); } - + @SuppressWarnings({ "rawtypes", "unchecked" }) protected void clearUserOrgAndRoleRefs(String userOid) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { OperationResult result = new OperationResult("clearUserOrgAndRoleRefs"); @@ -674,7 +674,7 @@ protected void clearUserOrgAndRoleRefs(String userOid) throws ObjectNotFoundExce PrismObject userBefore = getUser(userOid); display("User before", userBefore); } - + protected void assertEvaluatedRole(Collection evaluatedRoles, String expectedRoleOid) { for (EvaluatedAssignmentTarget evalRole: evaluatedRoles) { @@ -684,28 +684,28 @@ protected void assertEvaluatedRole(Collection resourceDummyGreen; - + protected static DummyResource dummyResourceEmerald; protected static DummyResourceContoller dummyResourceCtlEmerald; protected ResourceType resourceDummyEmeraldType; protected PrismObject resourceDummyEmerald; - + protected DummyResource dummyResourceUpcase; protected DummyResourceContoller dummyResourceCtlUpcase; protected ResourceType resourceDummyUpcaseType; @@ -112,7 +112,7 @@ public class AbstractInitializedModelIntegrationTest extends AbstractConfiguredM protected ResourceType resourceDummySchemalessType; protected PrismObject resourceDummySchemaless; - + public AbstractInitializedModelIntegrationTest() { super(); } @@ -128,39 +128,39 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti lensDebugListener = new ProfilingLensDebugListener(); clockwork.setDebugListener(lensDebugListener); checkingProgressListener = new CheckingProgressListener(); - + // Resources - - dummyResourceCtl = initDummyResource(null, getResourceDummyFile(), RESOURCE_DUMMY_OID, + + dummyResourceCtl = initDummyResource(null, getResourceDummyFile(), RESOURCE_DUMMY_OID, controller -> { controller.extendSchemaPirate(); controller.addAttrDef(controller.getDummyResource().getAccountObjectClass(), DUMMY_ACCOUNT_ATTRIBUTE_SEA_NAME, String.class, false, false); }, initTask, initResult); - - initDummyResourcePirate(RESOURCE_DUMMY_RED_NAME, + + initDummyResourcePirate(RESOURCE_DUMMY_RED_NAME, RESOURCE_DUMMY_RED_FILE, RESOURCE_DUMMY_RED_OID, initTask, initResult); - - initDummyResourcePirate(RESOURCE_DUMMY_BLUE_NAME, + + initDummyResourcePirate(RESOURCE_DUMMY_BLUE_NAME, getResourceDummyBlueFile(), RESOURCE_DUMMY_BLUE_OID, initTask, initResult); - - initDummyResourcePirate(RESOURCE_DUMMY_YELLOW_NAME, + + initDummyResourcePirate(RESOURCE_DUMMY_YELLOW_NAME, RESOURCE_DUMMY_YELLOW_FILE, RESOURCE_DUMMY_YELLOW_OID, initTask, initResult); - - initDummyResourcePirate(RESOURCE_DUMMY_BLACK_NAME, + + initDummyResourcePirate(RESOURCE_DUMMY_BLACK_NAME, RESOURCE_DUMMY_BLACK_FILE, RESOURCE_DUMMY_BLACK_OID, initTask, initResult); - - initDummyResourcePirate(RESOURCE_DUMMY_RELATIVE_NAME, + + initDummyResourcePirate(RESOURCE_DUMMY_RELATIVE_NAME, RESOURCE_DUMMY_RELATIVE_FILE, RESOURCE_DUMMY_RELATIVE_OID, initTask, initResult); - + dummyResourceCtlCyan = DummyResourceContoller.create(RESOURCE_DUMMY_CYAN_NAME, resourceDummyCyan); dummyResourceCtlCyan.extendSchemaPirate(); dummyResourceCyan = dummyResourceCtlCyan.getDummyResource(); - resourceDummyCyan = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_CYAN_FILE, RESOURCE_DUMMY_CYAN_OID, initTask, initResult); + resourceDummyCyan = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_CYAN_FILE, RESOURCE_DUMMY_CYAN_OID, initTask, initResult); resourceDummyCyanType = resourceDummyCyan.asObjectable(); - dummyResourceCtlCyan.setResource(resourceDummyCyan); - + dummyResourceCtlCyan.setResource(resourceDummyCyan); + dummyResourceCtlWhite = DummyResourceContoller.create(RESOURCE_DUMMY_WHITE_NAME, resourceDummyWhite); dummyResourceCtlWhite.extendSchemaPirate(); dummyResourceWhite = dummyResourceCtlWhite.getDummyResource(); @@ -174,23 +174,23 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti resourceDummyGreen = importAndGetObjectFromFile(ResourceType.class, getResourceDummyGreenFile(), RESOURCE_DUMMY_GREEN_OID, initTask, initResult); resourceDummyGreenType = resourceDummyGreen.asObjectable(); dummyResourceCtlGreen.setResource(resourceDummyGreen); - + dummyResourceCtlEmerald = DummyResourceContoller.create(RESOURCE_DUMMY_EMERALD_NAME, resourceDummyEmerald); dummyResourceCtlEmerald.extendSchemaPirate(); dummyResourceCtlEmerald.extendSchemaPosix(); dummyResourceEmerald = dummyResourceCtlEmerald.getDummyResource(); - resourceDummyEmerald = importAndGetObjectFromFile(ResourceType.class, getResourceDummyEmeraldFile(), RESOURCE_DUMMY_EMERALD_OID, initTask, initResult); + resourceDummyEmerald = importAndGetObjectFromFile(ResourceType.class, getResourceDummyEmeraldFile(), RESOURCE_DUMMY_EMERALD_OID, initTask, initResult); resourceDummyEmeraldType = resourceDummyEmerald.asObjectable(); dummyResourceCtlEmerald.setResource(resourceDummyEmerald); - initDummyResource(RESOURCE_DUMMY_ORANGE_NAME, RESOURCE_DUMMY_ORANGE_FILE, RESOURCE_DUMMY_ORANGE_OID, + initDummyResource(RESOURCE_DUMMY_ORANGE_NAME, RESOURCE_DUMMY_ORANGE_FILE, RESOURCE_DUMMY_ORANGE_OID, controller -> { controller.extendSchemaPirate(); controller.addAttrDef(controller.getDummyResource().getAccountObjectClass(), DUMMY_ACCOUNT_ATTRIBUTE_MATE_NAME, String.class, false, true); }, initTask, initResult); - + dummyResourceCtlUpcase = DummyResourceContoller.create(RESOURCE_DUMMY_UPCASE_NAME, resourceDummyUpcase); dummyResourceCtlUpcase.extendSchemaPirate(); dummyResourceUpcase = dummyResourceCtlUpcase.getDummyResource(); @@ -199,25 +199,25 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti dummyResourceCtlUpcase.setResource(resourceDummyUpcase); dummyResourceCtlUpcase.addGroup(GROUP_JOKER_DUMMY_UPCASE_NAME); - resourceDummySchemaless = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_SCHEMALESS_FILENAME, RESOURCE_DUMMY_SCHEMALESS_OID, initTask, initResult); + resourceDummySchemaless = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_SCHEMALESS_FILENAME, RESOURCE_DUMMY_SCHEMALESS_OID, initTask, initResult); resourceDummySchemalessType = resourceDummySchemaless.asObjectable(); - + postInitDummyResouce(); - + dummyResourceCtl.addAccount(ACCOUNT_HERMAN_DUMMY_USERNAME, "Herman Toothrot", "Monkey Island"); dummyResourceCtl.addAccount(ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood", "Melee Island"); dummyResourceCtl.addAccount(ACCOUNT_DAVIEJONES_DUMMY_USERNAME, "Davie Jones", "Davie Jones' Locker"); dummyResourceCtl.addAccount(ACCOUNT_CALYPSO_DUMMY_USERNAME, "Tia Dalma", "Pantano River"); - + dummyResourceCtl.addAccount(ACCOUNT_ELAINE_DUMMY_USERNAME, "Elaine Marley", "Melee Island"); getDummyResourceController(RESOURCE_DUMMY_RED_NAME).addAccount(ACCOUNT_ELAINE_DUMMY_USERNAME, "Elaine Marley", "Melee Island"); getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).addAccount(ACCOUNT_ELAINE_DUMMY_USERNAME, "Elaine Marley", "Melee Island"); - + repoAddObjectFromFile(LOOKUP_LANGUAGES_FILE, initResult); - + repoAddObjectFromFile(SECURITY_POLICY_FILE, initResult); - + // User Templates repoAddObjectFromFile(USER_TEMPLATE_FILENAME, initResult); repoAddObjectFromFile(USER_TEMPLATE_COMPLEX_FILE, initResult); @@ -231,13 +231,13 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti repoAddObjectFromFile(ACCOUNT_SHADOW_ELAINE_DUMMY_RED_FILE, initResult); repoAddObjectFromFile(ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_FILE, initResult); repoAddObjectFromFile(GROUP_SHADOW_JOKER_DUMMY_UPCASE_FILE, initResult); - + // Users userTypeJack = repoAddObjectFromFile(USER_JACK_FILE, UserType.class, true, initResult).asObjectable(); userTypeBarbossa = repoAddObjectFromFile(USER_BARBOSSA_FILE, UserType.class, initResult).asObjectable(); userTypeGuybrush = repoAddObjectFromFile(USER_GUYBRUSH_FILE, UserType.class, initResult).asObjectable(); userTypeElaine = repoAddObjectFromFile(USER_ELAINE_FILE, UserType.class, initResult).asObjectable(); - + // Roles repoAddObjectFromFile(ROLE_PIRATE_FILE, initResult); repoAddObjectFromFile(ROLE_PIRATE_GREEN_FILE, initResult); @@ -254,15 +254,15 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti repoAddObjectFromFile(ROLE_RED_SAILOR_FILE, initResult); repoAddObjectFromFile(ROLE_CYAN_SAILOR_FILE, initResult); repoAddObjectFromFile(ROLE_STRONG_SAILOR_FILE, initResult); - + // Orgstruct if (doAddOrgstruct()) { repoAddObjectsFromFile(ORG_MONKEY_ISLAND_FILE, OrgType.class, initResult); } - + // Services repoAddObjectFromFile(SERVICE_SHIP_SEA_MONKEY_FILE, initResult); - + repoAddObjectFromFile(PASSWORD_POLICY_BENEVOLENT_FILE, initResult); } @@ -273,7 +273,7 @@ protected ConflictResolutionActionType getDefaultConflictResolutionAction() { protected int getNumberOfRoles() { return super.getNumberOfRoles() + NUMBER_OF_IMPORTED_ROLES; } - + protected boolean doAddOrgstruct() { return true; } @@ -289,7 +289,7 @@ protected File getResourceDummyBlueFile() { protected File getResourceDummyGreenFile() { return RESOURCE_DUMMY_GREEN_FILE; } - + protected File getResourceDummyEmeraldFile() { return RESOURCE_DUMMY_EMERALD_FILE; } @@ -301,15 +301,15 @@ protected void postInitDummyResouce() { protected void assertUserJack(PrismObject user) { assertUserJack(user, USER_JACK_FULL_NAME, USER_JACK_GIVEN_NAME, USER_JACK_FAMILY_NAME); } - + protected void assertUserJack(PrismObject user, String fullName) { assertUserJack(user, fullName, USER_JACK_GIVEN_NAME, USER_JACK_FAMILY_NAME); } - + protected void assertUserJack(PrismObject user, String fullName, String givenName, String familyName) { assertUserJack(user, fullName, givenName, familyName, "Caribbean"); } - + protected void assertUserJack(PrismObject user, String name, String fullName, String givenName, String familyName, String locality) { assertUser(user, USER_JACK_OID, name, fullName, givenName, familyName, locality); UserType userType = user.asObjectable(); @@ -325,11 +325,11 @@ protected void assertUserJack(PrismObject user, String name, String fu PrismAsserts.assertEqualsPolyString("Wrong jack locality", locality, userType.getLocality()); } } - + protected void assertUserJack(PrismObject user, String fullName, String givenName, String familyName, String locality) { assertUserJack(user, USER_JACK_USERNAME, fullName, givenName, familyName, locality); } - + protected void assertDummyAccountShadowRepo(PrismObject accountShadow, String oid, String username) throws SchemaException { assertAccountShadowRepo(accountShadow, oid, username, dummyResourceCtl.getResource().asObjectable()); } @@ -337,7 +337,7 @@ protected void assertDummyAccountShadowRepo(PrismObject accountShado protected void assertDummyGroupShadowRepo(PrismObject accountShadow, String oid, String username) throws SchemaException { assertShadowRepo(accountShadow, oid, username, dummyResourceCtl.getResourceType(), dummyResourceCtl.getGroupObjectClass()); } - + protected void assertDummyAccountShadowModel(PrismObject accountShadow, String oid, String username) throws SchemaException { assertShadowModel(accountShadow, oid, username, dummyResourceCtl.getResourceType(), dummyResourceCtl.getAccountObjectClass()); } @@ -345,12 +345,12 @@ protected void assertDummyAccountShadowModel(PrismObject accountShad protected void assertDummyGroupShadowModel(PrismObject accountShadow, String oid, String username) throws SchemaException { assertShadowModel(accountShadow, oid, username, dummyResourceCtl.getResourceType(), dummyResourceCtl.getGroupObjectClass()); } - + protected void assertDummyAccountShadowModel(PrismObject accountShadow, String oid, String username, String fullname) throws SchemaException { assertDummyAccountShadowModel(accountShadow, oid, username); IntegrationTestTools.assertAttribute(accountShadow, dummyResourceCtl.getAttributeFullnameQName(), fullname); } - + protected void setDefaultUserTemplate(String userTemplateOid) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { setDefaultObjectTemplate(UserType.COMPLEX_TYPE, userTemplateOid); @@ -359,21 +359,21 @@ protected void setDefaultUserTemplate(String userTemplateOid) protected void assertMonkeyIslandOrgSanity() throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { assertMonkeyIslandOrgSanity(0); } - + protected void assertMonkeyIslandOrgSanity(int expectedFictional) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { Task task = taskManager.createTaskInstance(AbstractInitializedModelIntegrationTest.class.getName() + ".assertMonkeyIslandOrgSanity"); OperationResult result = task.getResult(); - + PrismObject orgGovernorOffice = modelService.getObject(OrgType.class, ORG_GOVERNOR_OFFICE_OID, null, task, result); result.computeStatus(); TestUtil.assertSuccess(result); OrgType orgGovernorOfficeType = orgGovernorOffice.asObjectable(); assertEquals("Wrong governor office name", PrismTestUtil.createPolyStringType("F0001"), orgGovernorOfficeType.getName()); - + List> governorSubOrgs = searchOrg(ORG_GOVERNOR_OFFICE_OID, OrgFilter.Scope.ONE_LEVEL, task, result); if (verbose) display("governor suborgs", governorSubOrgs); assertEquals("Unexpected number of governor suborgs", 3, governorSubOrgs.size()); - + List> functionalOrgs = searchOrg(ORG_GOVERNOR_OFFICE_OID, OrgFilter.Scope.SUBTREE, task, result); if (verbose) display("functional orgs (null)", functionalOrgs); assertEquals("Unexpected number of functional orgs (null)", NUM_FUNCTIONAL_ORGS - 1 + expectedFictional, functionalOrgs.size()); @@ -381,7 +381,7 @@ protected void assertMonkeyIslandOrgSanity(int expectedFictional) throws ObjectN List> prootSubOrgs = searchOrg(ORG_PROJECT_ROOT_OID, OrgFilter.Scope.ONE_LEVEL, task, result); if (verbose) display("project root suborgs", prootSubOrgs); assertEquals("Unexpected number of governor suborgs", 2, prootSubOrgs.size()); - + List> projectOrgs = searchOrg(ORG_PROJECT_ROOT_OID, OrgFilter.Scope.SUBTREE, task, result); if (verbose) display("project orgs (null)", projectOrgs); assertEquals("Unexpected number of functional orgs (null)", NUM_PROJECT_ORGS - 1, projectOrgs.size()); @@ -389,13 +389,13 @@ protected void assertMonkeyIslandOrgSanity(int expectedFictional) throws ObjectN PrismObject orgScummBar = modelService.getObject(OrgType.class, ORG_SCUMM_BAR_OID, null, task, result); List scummBarInducements = orgScummBar.asObjectable().getInducement(); assertEquals("Unexpected number of scumm bar inducements: "+scummBarInducements, 1, scummBarInducements.size()); - + ResultHandler handler = getOrgSanityCheckHandler(); if (handler != null) { modelService.searchObjectsIterative(OrgType.class, null, handler, null, task, result); } } - + protected ResultHandler getOrgSanityCheckHandler() { return null; } @@ -412,7 +412,7 @@ protected void assertShadowOperationalData(PrismObject shadow, Synch } // TODO: assert sync description } - + protected Collection getCheckingProgressListenerCollection() { return Collections.singleton((ProgressListener)checkingProgressListener); } 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 3dfbcbe97bf..ba9c1a7237d 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 @@ -86,7 +86,7 @@ /** * @author semancik - * + * * @see TestValidityRecomputeTask */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @@ -94,7 +94,7 @@ public class TestActivation extends AbstractInitializedModelIntegrationTest { private static final File TEST_DIR = new File("src/test/resources/activation"); - + // This resource does not support native activation. It has simulated activation instead. // + unusual validTo and validFrom mappings protected static final File RESOURCE_DUMMY_KHAKI_FILE = new File(TEST_DIR, "resource-dummy-khaki.xml"); @@ -103,7 +103,7 @@ public class TestActivation extends AbstractInitializedModelIntegrationTest { protected static final String RESOURCE_DUMMY_KHAKI_NAMESPACE = MidPointConstants.NS_RI; // This resource does not support native activation. It has simulated activation instead. - // + unusual validTo and validFrom mappings + // + unusual validTo and validFrom mappings protected static final File RESOURCE_DUMMY_CORAL_FILE = new File(TEST_DIR, "resource-dummy-coral.xml"); protected static final String RESOURCE_DUMMY_CORAL_OID = "10000000-0000-0000-0000-0000000b1004"; protected static final String RESOURCE_DUMMY_CORAL_NAME = "coral"; @@ -120,7 +120,7 @@ public class TestActivation extends AbstractInitializedModelIntegrationTest { private String accountMancombOid; private String userMancombOid; private XMLGregorianCalendar manana; - + protected DummyResource dummyResourceKhaki; protected DummyResourceContoller dummyResourceCtlKhaki; protected ResourceType resourceDummyKhakiType; @@ -135,11 +135,11 @@ public class TestActivation extends AbstractInitializedModelIntegrationTest { public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + dummyResourceCtlKhaki = DummyResourceContoller.create(RESOURCE_DUMMY_KHAKI_NAME, resourceDummyKhaki); dummyResourceCtlKhaki.extendSchemaPirate(); dummyResourceKhaki = dummyResourceCtlKhaki.getDummyResource(); - resourceDummyKhaki = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_KHAKI_FILE, RESOURCE_DUMMY_KHAKI_OID, initTask, initResult); + resourceDummyKhaki = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_KHAKI_FILE, RESOURCE_DUMMY_KHAKI_OID, initTask, initResult); resourceDummyKhakiType = resourceDummyKhaki.asObjectable(); dummyResourceCtlKhaki.setResource(resourceDummyKhaki); @@ -159,12 +159,12 @@ public void test050CheckJackEnabled() throws Exception { // GIVEN, WHEN // this happens during test initialization when user-jack.xml is added - + // THEN PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); - + assertAdministrativeStatusEnabled(userJack); // Cannot assert validity or effective status here. The user was added through repo and was not recomputed yet. } @@ -178,29 +178,29 @@ public void test051ModifyUserJackDisable() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modifyUserReplace(USER_JACK_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.DISABLED); - + // THEN XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); - + assertAdministrativeStatusDisabled(userJack); assertValidity(userJack, null); assertEffectiveStatus(userJack, ActivationStatusType.DISABLED); assertDisableTimestampFocus(userJack, start, end); - + TestUtil.assertModifyTimestamp(userJack, start, end); } - + @Test public void test052ModifyUserJackNull() throws Exception { final String TEST_NAME = "test052ModifyUserJackNull"; @@ -210,28 +210,28 @@ public void test052ModifyUserJackNull() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modifyUserReplace(USER_JACK_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result); - + // THEN XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); - + assertAdministrativeStatus(userJack, null); assertValidity(userJack, null); assertEffectiveStatus(userJack, ActivationStatusType.ENABLED); - + TestUtil.assertModifyTimestamp(userJack, start, end); } - + @Test public void test055ModifyUserJackEnable() throws Exception { final String TEST_NAME = "test055ModifyUserJackEnable"; @@ -241,29 +241,29 @@ public void test055ModifyUserJackEnable() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modifyUserReplace(USER_JACK_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.ENABLED); - + // THEN XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); - + assertAdministrativeStatusEnabled(userJack); assertValidity(userJack, null); assertEffectiveStatus(userJack, ActivationStatusType.ENABLED); assertEnableTimestampFocus(userJack, null, start); - + TestUtil.assertModifyTimestamp(userJack, start, end); } - + @Test public void test056RecomputeUserJackEffectiveEnable() throws Exception { final String TEST_NAME = "test056RecomputeUserJackEffectiveEnable"; @@ -273,50 +273,50 @@ public void test056RecomputeUserJackEffectiveEnable() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + PrismObject userJackBefore = getUser(USER_JACK_OID); display("User after change execution", userJackBefore); assertUserJack(userJackBefore, "Jack Sparrow"); - + assertAdministrativeStatusEnabled(userJackBefore); assertValidity(userJackBefore, null); assertEffectiveStatus(userJackBefore, ActivationStatusType.ENABLED); assertEnableTimestampFocus(userJackBefore, null, start); - + // WHEN modifyUserReplace(USER_JACK_OID, SchemaConstants.PATH_ACTIVATION_EFFECTIVE_STATUS, ModelExecuteOptions.createRaw(), task, result, ActivationStatusType.DISABLED); PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); - + assertAdministrativeStatusEnabled(userJack); assertValidity(userJack, null); assertEffectiveStatus(userJack, ActivationStatusType.DISABLED); - + recomputeUser(USER_JACK_OID, task, result); - + // THEN XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJackAfter = getUser(USER_JACK_OID); display("User after change execution", userJackAfter); assertUserJack(userJackAfter, "Jack Sparrow"); - + assertAdministrativeStatusEnabled(userJackAfter); assertValidity(userJackAfter, null); assertEffectiveStatus(userJackAfter, ActivationStatusType.ENABLED); - - + + TestUtil.assertModifyTimestamp(userJackAfter, start, end); - - - + + + } - + @Test public void test060ModifyUserJackLifecycleActive() throws Exception { final String TEST_NAME = "test060ModifyUserJackLifecycleActive"; @@ -326,29 +326,29 @@ public void test060ModifyUserJackLifecycleActive() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_LIFECYCLE_STATE, task, result, SchemaConstants.LIFECYCLE_ACTIVE); - + // THEN XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); - + assertAdministrativeStatusEnabled(userJack); assertValidity(userJack, null); assertEffectiveStatus(userJack, ActivationStatusType.ENABLED); assertEnableTimestampFocus(userJack, null, start); - + TestUtil.assertModifyTimestamp(userJack, start, end); } - + @Test public void test061ModifyUserJackLifecycleDraft() throws Exception { final String TEST_NAME = "test061ModifyUserJackLifecycleDraft"; @@ -358,29 +358,29 @@ public void test061ModifyUserJackLifecycleDraft() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_LIFECYCLE_STATE, task, result, SchemaConstants.LIFECYCLE_DRAFT); - + // THEN XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); - + assertAdministrativeStatusEnabled(userJack); assertValidity(userJack, null); assertEffectiveStatus(userJack, ActivationStatusType.DISABLED); assertDisableTimestampFocus(userJack, start, end); - + TestUtil.assertModifyTimestamp(userJack, start, end); } - + @Test public void test065ModifyUserJackLifecycleDeprecated() throws Exception { final String TEST_NAME = "test065ModifyUserJackLifecycleDeprecated"; @@ -390,29 +390,29 @@ public void test065ModifyUserJackLifecycleDeprecated() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_LIFECYCLE_STATE, task, result, SchemaConstants.LIFECYCLE_DEPRECATED); - + // THEN XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); - + assertAdministrativeStatusEnabled(userJack); assertValidity(userJack, null); assertEffectiveStatus(userJack, ActivationStatusType.ENABLED); assertEnableTimestampFocus(userJack, start, end); - + TestUtil.assertModifyTimestamp(userJack, start, end); } - + @Test public void test068ModifyUserJackLifecycleArchived() throws Exception { final String TEST_NAME = "test068ModifyUserJackLifecycleArchived"; @@ -422,28 +422,28 @@ public void test068ModifyUserJackLifecycleArchived() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_LIFECYCLE_STATE, task, result, SchemaConstants.LIFECYCLE_ARCHIVED); - + // THEN XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); - + assertAdministrativeStatusEnabled(userJack); assertValidity(userJack, null); assertEffectiveStatus(userJack, ActivationStatusType.ARCHIVED); - + TestUtil.assertModifyTimestamp(userJack, start, end); } - + @Test public void test069ModifyUserJackLifecycleNull() throws Exception { final String TEST_NAME = "test069ModifyUserJackLifecycleNull"; @@ -453,28 +453,28 @@ public void test069ModifyUserJackLifecycleNull() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_LIFECYCLE_STATE, task, result); - + // THEN XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); - + assertAdministrativeStatusEnabled(userJack); assertValidity(userJack, null); assertEffectiveStatus(userJack, ActivationStatusType.ENABLED); - + TestUtil.assertModifyTimestamp(userJack, start, end); } - + @Test public void test100ModifyUserJackAssignAccount() throws Exception { final String TEST_NAME = "test100ModifyUserJackAssignAccount"; @@ -484,48 +484,48 @@ public void test100ModifyUserJackAssignAccount() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, null, true); deltas.add(accountAssignmentUserDelta); - + dummyAuditService.clear(); XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); accountOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Shadow (repo)", accountShadow); assertDummyAccountShadowRepo(accountShadow, accountOid, "jack"); TestUtil.assertCreateTimestamp(accountShadow, start, end); assertEnableTimestampShadow(accountShadow, start, end); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("Shadow (model)", accountModel); assertDummyAccountShadowModel(accountModel, accountOid, "jack", "Jack Sparrow"); TestUtil.assertCreateTimestamp(accountModel, start, end); assertEnableTimestampShadow(accountModel, start, end); - + // Check account in dummy resource assertDefaultDummyAccount("jack", "Jack Sparrow", true); - + assertDummyEnabled("jack"); - + TestUtil.assertModifyTimestamp(userJack, start, end); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -549,7 +549,7 @@ public void test100ModifyUserJackAssignAccount() throws Exception { } assertTrue("Shadow delta not found", found); } - + @Test public void test101ModifyUserJackDisable() throws Exception { final String TEST_NAME = "test101ModifyUserJackDisable"; @@ -560,29 +560,29 @@ public void test101ModifyUserJackDisable() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modifyUserReplace(USER_JACK_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.DISABLED); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); - + assertAdministrativeStatusDisabled(userJack); assertDummyDisabled("jack"); assertDisableTimestampFocus(userJack, startTime, endTime); - + String accountOid = getLinkRefOid(userJack, RESOURCE_DUMMY_OID); PrismObject accountShadow = getShadowModel(accountOid); assertDisableTimestampShadow(accountShadow, startTime, endTime); assertDisableReasonShadow(accountShadow, SchemaConstants.MODEL_DISABLE_REASON_MAPPED); } - + @Test public void test102ModifyUserJackEnable() throws Exception { TestUtil.displayTestTitle(this, "test102ModifyUserJackEnable"); @@ -592,24 +592,24 @@ public void test102ModifyUserJackEnable() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modifyUserReplace(USER_JACK_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.ENABLED); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); - + assertAdministrativeStatusEnabled(userJack); assertDummyEnabled("jack"); assertEnableTimestampFocus(userJack, startTime, endTime); } - + /** * Modify account activation. User's activation should be unchanged @@ -623,29 +623,29 @@ public void test111ModifyAccountJackDisable() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modifyAccountShadowReplace(accountOid, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.DISABLED); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); - + String accountOid = getLinkRefOid(userJack, RESOURCE_DUMMY_OID); PrismObject accountShadow = getShadowModel(accountOid); assertAdministrativeStatusDisabled(accountShadow); assertDisableTimestampShadow(accountShadow, startTime, endTime); assertDisableReasonShadow(accountShadow, SchemaConstants.MODEL_DISABLE_REASON_EXPLICIT); - + assertAdministrativeStatusEnabled(userJack); assertDummyDisabled("jack"); } - + /** * Make sure that recompute does not destroy anything. */ @@ -660,32 +660,32 @@ public void test112UserJackRecompute() throws Exception { assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); dummyAuditService.clear(); - + // WHEN recomputeUser(USER_JACK_OID, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("recompute result", result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); - + String accountOid = getLinkRefOid(userJack, RESOURCE_DUMMY_OID); PrismObject accountShadow = getShadowModel(accountOid); assertAdministrativeStatusDisabled(accountShadow); assertDisableTimestampShadow(accountShadow, null, startTime); assertDisableReasonShadow(accountShadow, SchemaConstants.MODEL_DISABLE_REASON_EXPLICIT); - + assertAdministrativeStatusEnabled(userJack); assertDummyDisabled("jack"); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertNoRecord(); } - + /** * Re-enabling the user should enable the account as well. Even if the user is already enabled. */ @@ -699,31 +699,31 @@ public void test114ModifyUserJackEnable() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modifyUserReplace(USER_JACK_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.ENABLED); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, USER_JACK_FULL_NAME); - + assertAdministrativeStatusEnabled(userJack); assertDummyEnabled(ACCOUNT_JACK_DUMMY_USERNAME); // No real change in effective status, therefore the enableTimestamp should be unchanged assertEnableTimestampFocus(userJack, null, startTime); - + assertAccounts(USER_JACK_OID, 1); PrismObject account = getShadowModel(accountOid); assertAccountShadowModel(account, accountOid, ACCOUNT_JACK_DUMMY_USERNAME, getDummyResourceType()); assertAdministrativeStatusEnabled(account); assertEnableTimestampShadow(account, startTime, endTime); } - + /** * Re-enabling the user should enable the account as well. Even if the user is already enabled. */ @@ -737,33 +737,33 @@ public void test115ModifyUserJackAdministrativeStatusNull() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modifyUserReplace(USER_JACK_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); DummyAccount account = getDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME); display("Account after change", account); - + assertUserJack(userJack, USER_JACK_FULL_NAME); - + assertAdministrativeStatus(userJack, null); // Dummy account should still be enabled. It does not support validity, therefore // the account/administrativeStatus is mapped from user.effectiveStatus assertDummyActivationEnabledState(ACCOUNT_JACK_DUMMY_USERNAME, true); - + assertAccounts(USER_JACK_OID, 1); PrismObject shadow = getShadowModel(accountOid); assertAccountShadowModel(shadow, accountOid, ACCOUNT_JACK_DUMMY_USERNAME, getDummyResourceType()); assertAdministrativeStatus(shadow, ActivationStatusType.ENABLED); } - + /** * Modify both user and account activation. As outbound mapping is weak the user should have its own state * and account should have its own state. @@ -777,32 +777,32 @@ public void test118ModifyJackActivationUserAndAccount() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + ObjectDelta userDelta = createModifyUserReplaceDelta(USER_JACK_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, ActivationStatusType.ENABLED); - ObjectDelta accountDelta = createModifyAccountShadowReplaceDelta(accountOid, getDummyResourceObject(), + ObjectDelta accountDelta = createModifyAccountShadowReplaceDelta(accountOid, getDummyResourceObject(), ACTIVATION_ADMINISTRATIVE_STATUS_PATH, ActivationStatusType.DISABLED); - + Collection> deltas = MiscSchemaUtil.createCollection(userDelta, accountDelta); - + XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); // No real change in effective status, therefore the enableTimestamp should be unchanged assertEnableTimestampFocus(userJack, null, startTime); assertAdministrativeStatusEnabled(userJack); - + assertDummyDisabled("jack"); assertAccounts(USER_JACK_OID, 1); PrismObject account = getShadowModel(accountOid); @@ -811,7 +811,7 @@ public void test118ModifyJackActivationUserAndAccount() throws Exception { assertDisableTimestampShadow(account, startTime, endTime); assertDisableReasonShadow(account, SchemaConstants.MODEL_DISABLE_REASON_EXPLICIT); } - + /** * Add red dummy resource to the mix. This will be fun. */ @@ -826,43 +826,43 @@ public void test120ModifyUserJackAssignAccountDummyRed() throws Exception { assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignAccount(USER_JACK_OID, RESOURCE_DUMMY_RED_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); assertAccounts(USER_JACK_OID, 2); accountRedOid = getLinkRefOid(userJack, RESOURCE_DUMMY_RED_OID); - + PrismObject accountRedRepo = repositoryService.getObject(ShadowType.class, accountRedOid, null, result); display("Account red (repo)", accountRedRepo); assertEnableTimestampShadow(accountRedRepo, startTime, endTime); - + PrismObject accountRed = getShadowModel(accountRedOid); display("Account red (model)", accountRed); - assertAccountShadowModel(accountRed, accountRedOid, ACCOUNT_JACK_DUMMY_USERNAME, + assertAccountShadowModel(accountRed, accountRedOid, ACCOUNT_JACK_DUMMY_USERNAME, getDummyResourceType(RESOURCE_DUMMY_RED_NAME)); assertAdministrativeStatusEnabled(accountRed); assertEnableTimestampShadow(accountRed, startTime, endTime); - + // Check account in dummy resource assertDummyAccount(RESOURCE_DUMMY_RED_NAME, "jack", "Jack Sparrow", true); - + assertAdministrativeStatusEnabled(userJack); assertDummyDisabled("jack"); assertDummyEnabled(RESOURCE_DUMMY_RED_NAME, "jack"); - + } - + /** * Modify both user and account activation. Red dummy has a strong mapping. User change should override account * change. @@ -876,44 +876,44 @@ public void test121ModifyJackUserAndAccountRed() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + ObjectDelta userDelta = createModifyUserReplaceDelta(USER_JACK_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, ActivationStatusType.DISABLED); - - ObjectDelta accountDelta = createModifyAccountShadowReplaceDelta(accountRedOid, getDummyResourceObject(), + + ObjectDelta accountDelta = createModifyAccountShadowReplaceDelta(accountRedOid, getDummyResourceObject(), ACTIVATION_ADMINISTRATIVE_STATUS_PATH, ActivationStatusType.ENABLED); - + Collection> deltas = MiscSchemaUtil.createCollection(userDelta, accountDelta); XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); - + assertAdministrativeStatusDisabled(userJack); assertDummyDisabled("jack"); assertDummyDisabled(RESOURCE_DUMMY_RED_NAME, "jack"); - + assertAccounts(USER_JACK_OID, 2); accountRedOid = getLinkRefOid(userJack, RESOURCE_DUMMY_RED_OID); PrismObject accountRed = getShadowModel(accountRedOid); - assertAccountShadowModel(accountRed, accountRedOid, ACCOUNT_JACK_DUMMY_USERNAME, + assertAccountShadowModel(accountRed, accountRedOid, ACCOUNT_JACK_DUMMY_USERNAME, getDummyResourceType(RESOURCE_DUMMY_RED_NAME)); assertAdministrativeStatusDisabled(accountRed); assertDisableTimestampShadow(accountRed, startTime, endTime); assertDisableReasonShadow(accountRed, SchemaConstants.MODEL_DISABLE_REASON_MAPPED); } - + @Test public void test130ModifyAccountDefaultAndRed() throws Exception { TestUtil.displayTestTitle(this, "test130ModifyAccountDefaultAndRed"); @@ -922,20 +922,20 @@ public void test130ModifyAccountDefaultAndRed() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + ".test121ModifyJackPasswordUserAndAccountRed"); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - - ObjectDelta accountDeltaDefault = createModifyAccountShadowReplaceDelta(accountOid, + + ObjectDelta accountDeltaDefault = createModifyAccountShadowReplaceDelta(accountOid, getDummyResourceObject(), ACTIVATION_ADMINISTRATIVE_STATUS_PATH, ActivationStatusType.ENABLED); - ObjectDelta accountDeltaRed = createModifyAccountShadowReplaceDelta(accountRedOid, + ObjectDelta accountDeltaRed = createModifyAccountShadowReplaceDelta(accountRedOid, getDummyResourceObject(RESOURCE_DUMMY_RED_NAME), ACTIVATION_ADMINISTRATIVE_STATUS_PATH, ActivationStatusType.ENABLED); Collection> deltas = MiscSchemaUtil.createCollection(accountDeltaDefault, accountDeltaRed); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); @@ -944,7 +944,7 @@ public void test130ModifyAccountDefaultAndRed() throws Exception { assertDummyEnabled("jack"); assertDummyEnabled(RESOURCE_DUMMY_RED_NAME, "jack"); } - + /** * Let's make a clean slate for the next test */ @@ -957,16 +957,16 @@ public void test138ModifyJackEnabled() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.ENABLED); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); @@ -975,7 +975,7 @@ public void test138ModifyJackEnabled() throws Exception { assertDummyEnabled("jack"); assertDummyEnabled(RESOURCE_DUMMY_RED_NAME, "jack"); } - + /** * Red dummy resource disables account instead of deleting it. */ @@ -988,28 +988,28 @@ public void test139ModifyUserJackUnAssignAccountDummyRed() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + // WHEN unassignAccount(USER_JACK_OID, RESOURCE_DUMMY_RED_OID, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); assertAccounts(USER_JACK_OID, 2); accountRedOid = getLinkRefOid(userJack, RESOURCE_DUMMY_RED_OID); PrismObject accountRed = getShadowModel(accountRedOid); - assertAccountShadowModel(accountRed, accountRedOid, ACCOUNT_JACK_DUMMY_USERNAME, + assertAccountShadowModel(accountRed, accountRedOid, ACCOUNT_JACK_DUMMY_USERNAME, getDummyResourceType(RESOURCE_DUMMY_RED_NAME)); assertAdministrativeStatusDisabled(accountRed); assertDisableReasonShadow(accountRed, SchemaConstants.MODEL_DISABLE_REASON_DEPROVISION); - + // Check account in dummy resource assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", false); - + assertAdministrativeStatusEnabled(userJack); assertDummyEnabled("jack"); assertDummyDisabled(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME); @@ -1050,12 +1050,12 @@ public void test150ModifyUserJackAssignYellowAccount() throws Exception { // Check account in dummy resource assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "Bla bla bla administrator -- administrator"); // Check shadow PrismObject accountShadowYellow = getShadowModel(accountYellowOid); - assertAccountShadowModel(accountShadowYellow, accountYellowOid, ACCOUNT_JACK_DUMMY_USERNAME, + assertAccountShadowModel(accountShadowYellow, accountYellowOid, ACCOUNT_JACK_DUMMY_USERNAME, getDummyResourceType(RESOURCE_DUMMY_YELLOW_NAME)); assertAdministrativeStatusEnabled(accountShadowYellow); TestUtil.assertCreateTimestamp(accountShadowYellow, start, end); @@ -1094,12 +1094,12 @@ public void test151ReconcileJack() throws Exception { // Check account in dummy resource assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "Bla bla bla administrator -- administrator"); // Check shadow PrismObject accountShadowYellow = getShadowModel(accountYellowOid); - assertAccountShadowModel(accountShadowYellow, accountYellowOid, ACCOUNT_JACK_DUMMY_USERNAME, + assertAccountShadowModel(accountShadowYellow, accountYellowOid, ACCOUNT_JACK_DUMMY_USERNAME, getDummyResourceType(RESOURCE_DUMMY_YELLOW_NAME)); assertAdministrativeStatusEnabled(accountShadowYellow); @@ -1122,7 +1122,7 @@ public void test152ModifyAccountsJackDisable() throws Exception { ObjectDelta dummyDelta = createModifyAccountShadowReplaceDelta(accountOid, null, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, ActivationStatusType.DISABLED); ObjectDelta yellowDelta = createModifyAccountShadowReplaceDelta(accountYellowOid, null, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, ActivationStatusType.DISABLED); - + // WHEN displayWhen(TEST_NAME); @@ -1140,7 +1140,7 @@ public void test152ModifyAccountsJackDisable() throws Exception { // WHEN (2) - now let's do a reconciliation on both resources displayWhen(TEST_NAME); - ObjectDelta innocentDelta = createModifyUserReplaceDelta(USER_JACK_OID, UserType.F_LOCALITY, + ObjectDelta innocentDelta = createModifyUserReplaceDelta(USER_JACK_OID, UserType.F_LOCALITY, userJack.asObjectable().getLocality().toPolyString()); modelService.executeChanges(MiscSchemaUtil.createCollection(innocentDelta), ModelExecuteOptions.createReconcile(), task, result); @@ -1184,7 +1184,7 @@ public void test153ModifyAccountsJackEnable() throws Exception { // WHEN (2) - now let's do a reconciliation on both resources - ObjectDelta innocentDelta = createModifyUserReplaceDelta(USER_JACK_OID, UserType.F_LOCALITY, + ObjectDelta innocentDelta = createModifyUserReplaceDelta(USER_JACK_OID, UserType.F_LOCALITY, userJack.asObjectable().getLocality().toPolyString()); modelService.executeChanges(MiscSchemaUtil.createCollection(innocentDelta), ModelExecuteOptions.createReconcile(), task, result); @@ -1199,18 +1199,18 @@ public void test153ModifyAccountsJackEnable() throws Exception { private void checkAdminStatusFor15x(PrismObject user, boolean userStatus, boolean accountStatus, boolean accountStatusYellow) throws Exception { PrismObject account = getShadowModel(accountOid); PrismObject accountYellow = getShadowModel(accountYellowOid); - + assertAccountShadowModel(account, accountOid, ACCOUNT_JACK_DUMMY_USERNAME, getDummyResourceType()); assertAdministrativeStatus(account, accountStatus ? ActivationStatusType.ENABLED : ActivationStatusType.DISABLED); if (!accountStatus) { assertDisableReasonShadow(account, SchemaConstants.MODEL_DISABLE_REASON_EXPLICIT); } - - assertAccountShadowModel(accountYellow, accountYellowOid, ACCOUNT_JACK_DUMMY_USERNAME, + + assertAccountShadowModel(accountYellow, accountYellowOid, ACCOUNT_JACK_DUMMY_USERNAME, getDummyResourceType(RESOURCE_DUMMY_YELLOW_NAME)); if (accountStatusYellow) { assertAdministrativeStatus(accountYellow, ActivationStatusType.ENABLED); - assertDummyAccountAttribute(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "Bla bla bla administrator -- administrator"); } else { assertAdministrativeStatus(accountYellow, ActivationStatusType.DISABLED); @@ -1237,48 +1237,48 @@ public void test160ModifyUserJackAssignAccountKhaki() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + dummyAuditService.clear(); XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); assignAccount(USER_JACK_OID, RESOURCE_DUMMY_KHAKI_OID, null, task, result); - + // THEN displayThen(TEST_NAME); XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", userAfter); assertUserJack(userAfter); String accountKhakiOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_KHAKI_OID); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountKhakiOid, null, result); display("Shadow (repo)", accountShadow); assertAccountShadowRepo(accountShadow, accountKhakiOid, "jack", resourceDummyKhakiType); TestUtil.assertCreateTimestamp(accountShadow, start, end); assertEnableTimestampShadow(accountShadow, start, end); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountKhakiOid, null, task, result); display("Shadow (model)", accountModel); assertAccountShadowModel(accountModel, accountKhakiOid, "jack", resourceDummyKhakiType); TestUtil.assertCreateTimestamp(accountModel, start, end); assertEnableTimestampShadow(accountModel, start, end); - + // Check account in dummy resource assertDummyAccount(RESOURCE_DUMMY_KHAKI_NAME, "jack", "Jack Sparrow", true); - + assertDummyEnabled(RESOURCE_DUMMY_KHAKI_NAME, "jack"); - + TestUtil.assertModifyTimestamp(userAfter, start, end); - + checkAdminStatusFor15x(userAfter, true, true, true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -1306,7 +1306,7 @@ public void test160ModifyUserJackAssignAccountKhaki() throws Exception { } assertTrue("Shadow delta not found", found); } - + @Test public void test170GetAccountUnlocked() throws Exception { final String TEST_NAME = "test170GetAccountUnlocked"; @@ -1323,14 +1323,14 @@ public void test170GetAccountUnlocked() throws Exception { // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - + PrismAsserts.assertNoItem(shadow, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", userAfter); checkAdminStatusFor15x(userAfter, true, true, true); } - + @Test public void test172GetAccountLocked() throws Exception { final String TEST_NAME = "test172GetAccountLocked"; @@ -1340,7 +1340,7 @@ public void test172GetAccountLocked() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + DummyAccount dummyAccount = getDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME); dummyAccount.setLockout(true); @@ -1350,15 +1350,15 @@ public void test172GetAccountLocked() throws Exception { // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - - PrismAsserts.assertPropertyValue(shadow, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, + + PrismAsserts.assertPropertyValue(shadow, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, LockoutStatusType.LOCKED); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", userAfter); checkAdminStatusFor15x(userAfter, true, true, true); } - + @Test public void test174ModifyAccountUnlock() throws Exception { final String TEST_NAME = "test174ModifyAccountUnlock"; @@ -1370,7 +1370,7 @@ public void test174ModifyAccountUnlock() throws Exception { assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); // WHEN - ObjectDelta dummyDelta = createModifyAccountShadowReplaceDelta(accountOid, null, + ObjectDelta dummyDelta = createModifyAccountShadowReplaceDelta(accountOid, null, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, LockoutStatusType.NORMAL); Collection> deltas = MiscSchemaUtil.createCollection(dummyDelta); @@ -1379,21 +1379,21 @@ public void test174ModifyAccountUnlock() throws Exception { // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - + DummyAccount dummyAccount = getDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME); assertFalse("Dummy account was not unlocked", dummyAccount.isLockout()); PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); - + PrismObject shadow = modelService.getObject(ShadowType.class, accountOid, null, task, result); - PrismAsserts.assertPropertyValue(shadow, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, + PrismAsserts.assertPropertyValue(shadow, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, LockoutStatusType.NORMAL); checkAdminStatusFor15x(userJack, true, true, true); } - + @Test public void test176ModifyUserUnlock() throws Exception { final String TEST_NAME = "test176ModifyUserUnlock"; @@ -1403,27 +1403,27 @@ public void test176ModifyUserUnlock() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + DummyAccount dummyAccount = getDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME); dummyAccount.setLockout(true); // WHEN - modifyUserReplace(USER_JACK_OID, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, task, result, + modifyUserReplace(USER_JACK_OID, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, task, result, LockoutStatusType.NORMAL); // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - + DummyAccount dummyAccountAfter = getDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME); assertFalse("Dummy account was not unlocked", dummyAccountAfter.isLockout()); PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); - + PrismObject shadow = modelService.getObject(ShadowType.class, accountOid, null, task, result); - PrismAsserts.assertPropertyValue(shadow, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, + PrismAsserts.assertPropertyValue(shadow, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, LockoutStatusType.NORMAL); checkAdminStatusFor15x(userJack, true, true, true); @@ -1439,30 +1439,30 @@ public void test199DeleteUserJack() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + Collection> deltas = new ArrayList>(); ObjectDelta userDelta = ObjectDelta.createDeleteDelta(UserType.class, USER_JACK_OID, prismContext); deltas.add(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - + try { PrismObject userJack = getUser(USER_JACK_OID); AssertJUnit.fail("Jack is still alive!"); } catch (ObjectNotFoundException ex) { // This is OK } - + // Check that the accounts are gone assertNoDummyAccount(null, "jack"); assertNoDummyAccount(RESOURCE_DUMMY_RED_NAME, "jack"); } - + @Test public void test200AddUserLargo() throws Exception { final String TEST_NAME = "test200AddUserLargo"; @@ -1472,23 +1472,23 @@ public void test200AddUserLargo() throws Exception { long startMillis = System.currentTimeMillis(); Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userLargo = PrismTestUtil.parseObject(USER_LARGO_FILE); ObjectDelta addDelta = userLargo.createAddDelta(); Collection> deltas = MiscSchemaUtil.createCollection(addDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN userLargo = getUser(USER_LARGO_OID); display("User after change execution", userLargo); - + assertValidity(userLargo, TimeIntervalStatusType.IN); assertValidityTimestamp(userLargo, startMillis, System.currentTimeMillis()); assertEffectiveStatus(userLargo, ActivationStatusType.ENABLED); } - + @Test public void test205ModifyUserLargoAssignAccount() throws Exception { final String TEST_NAME = "test205ModifyUserLargoAssignAccount"; @@ -1498,36 +1498,36 @@ public void test205ModifyUserLargoAssignAccount() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_LARGO_OID, RESOURCE_DUMMY_OID, null, true); accountAssignmentUserDelta.addModificationAddProperty(UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Largo LaGrande")); deltas.add(accountAssignmentUserDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - + PrismObject userLargo = getUser(USER_LARGO_OID); display("User after change execution", userLargo); assertUser(userLargo, USER_LARGO_OID, USER_LARGO_USERNAME, "Largo LaGrande", "Largo", "LaGrande"); accountOid = getSingleLinkOid(userLargo); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountOid, USER_LARGO_USERNAME); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, USER_LARGO_USERNAME, "Largo LaGrande"); - + // Check account in dummy resource assertDefaultDummyAccount(USER_LARGO_USERNAME, "Largo LaGrande", true); } - + @Test public void test210ModifyLargoValidTo10MinsAgo() throws Exception { final String TEST_NAME = "test210ModifyLargoValidTo10MinsAgo"; @@ -1537,35 +1537,35 @@ public void test210ModifyLargoValidTo10MinsAgo() throws Exception { long startMillis = System.currentTimeMillis(); Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + XMLGregorianCalendar tenMinutesAgo = XmlTypeConverter.createXMLGregorianCalendar(System.currentTimeMillis() - 10 * 60 * 1000); - + // WHEN modifyUserReplace(USER_LARGO_OID, ACTIVATION_VALID_TO_PATH, task, result, tenMinutesAgo); - + // THEN PrismObject userLargo = getUser(USER_LARGO_OID); display("User after change execution", userLargo); - + assertValidity(userLargo, TimeIntervalStatusType.AFTER); assertValidityTimestamp(userLargo, startMillis, System.currentTimeMillis()); assertEffectiveStatus(userLargo, ActivationStatusType.DISABLED); - + assertUser(userLargo, USER_LARGO_OID, USER_LARGO_USERNAME, "Largo LaGrande", "Largo", "LaGrande"); accountOid = getSingleLinkOid(userLargo); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountOid, USER_LARGO_USERNAME); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, USER_LARGO_USERNAME, "Largo LaGrande"); - + // Check account in dummy resource assertDefaultDummyAccount(USER_LARGO_USERNAME, "Largo LaGrande", false); } - + @Test public void test211ModifyLargoValidToManana() throws Exception { final String TEST_NAME = "test211ModifyLargoValidToManana"; @@ -1575,36 +1575,36 @@ public void test211ModifyLargoValidToManana() throws Exception { long startMillis = System.currentTimeMillis(); Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + manana = XmlTypeConverter.createXMLGregorianCalendar(System.currentTimeMillis() + 10 * 24 * 60 * 60 * 1000); - + // WHEN modifyUserReplace(USER_LARGO_OID, ACTIVATION_VALID_TO_PATH, task, result, manana); - + // THEN PrismObject userLargo = getUser(USER_LARGO_OID); display("User after change execution", userLargo); - + assertValidity(userLargo, TimeIntervalStatusType.IN); assertValidityTimestamp(userLargo, startMillis, System.currentTimeMillis()); lastValidityChangeTimestamp = userLargo.asObjectable().getActivation().getValidityChangeTimestamp(); assertEffectiveStatus(userLargo, ActivationStatusType.ENABLED); - + assertUser(userLargo, USER_LARGO_OID, USER_LARGO_USERNAME, "Largo LaGrande", "Largo", "LaGrande"); accountOid = getSingleLinkOid(userLargo); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountOid, USER_LARGO_USERNAME); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, USER_LARGO_USERNAME, "Largo LaGrande"); - + // Check account in dummy resource assertDefaultDummyAccount(USER_LARGO_USERNAME, "Largo LaGrande", true); } - + /** * Move time to tomorrow. Nothing should change yet. It is not yet manana. */ @@ -1617,37 +1617,37 @@ public void test212SeeLargoTomorrow() throws Exception { long startMillis = System.currentTimeMillis(); Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // Let's play with the clock, move the time to tomorrow long crrentNow = System.currentTimeMillis() + 24 * 60 * 60 * 1000; clock.override(crrentNow); - + // WHEN recomputeUser(USER_LARGO_OID, task, result); - + // THEN PrismObject userLargo = getUser(USER_LARGO_OID); display("User after change execution", userLargo); - + assertValidity(userLargo, TimeIntervalStatusType.IN); assertEffectiveStatus(userLargo, ActivationStatusType.ENABLED); assertValidityTimestamp(userLargo, lastValidityChangeTimestamp); - + assertUser(userLargo, USER_LARGO_OID, USER_LARGO_USERNAME, "Largo LaGrande", "Largo", "LaGrande"); accountOid = getSingleLinkOid(userLargo); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountOid, USER_LARGO_USERNAME); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, USER_LARGO_USERNAME, "Largo LaGrande"); - + // Check account in dummy resource assertDefaultDummyAccount(USER_LARGO_USERNAME, "Largo LaGrande", true); } - + /** * Move time after manana. Largo should be invalid. */ @@ -1660,37 +1660,37 @@ public void test213HastaLaMananaLargo() throws Exception { long startMillis = System.currentTimeMillis(); Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); 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; clock.override(crrentNow); - + // WHEN modelService.recompute(UserType.class, USER_LARGO_OID, null, task, result); - + // THEN PrismObject userLargo = getUser(USER_LARGO_OID); display("User after change execution", userLargo); - + assertValidity(userLargo, TimeIntervalStatusType.AFTER); assertValidityTimestamp(userLargo, crrentNow); assertEffectiveStatus(userLargo, ActivationStatusType.DISABLED); - + assertUser(userLargo, USER_LARGO_OID, USER_LARGO_USERNAME, "Largo LaGrande", "Largo", "LaGrande"); accountOid = getSingleLinkOid(userLargo); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountOid, USER_LARGO_USERNAME); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, USER_LARGO_USERNAME, "Largo LaGrande"); - + // Check account in dummy resource assertDefaultDummyAccount(USER_LARGO_USERNAME, "Largo LaGrande", false); } - + @Test public void test215ModifyLargoRemoveValidTo() throws Exception { final String TEST_NAME = "test215ModifyLargoRemoveValidTo"; @@ -1700,34 +1700,34 @@ public void test215ModifyLargoRemoveValidTo() throws Exception { long startMillis = clock.currentTimeMillis(); Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN modifyUserDelete(USER_LARGO_OID, ACTIVATION_VALID_TO_PATH, task, result, manana); - + // THEN PrismObject userLargo = getUser(USER_LARGO_OID); display("User after change execution", userLargo); - + assertValidity(userLargo, TimeIntervalStatusType.IN); assertValidityTimestamp(userLargo, startMillis, clock.currentTimeMillis()); lastValidityChangeTimestamp = userLargo.asObjectable().getActivation().getValidityChangeTimestamp(); assertEffectiveStatus(userLargo, ActivationStatusType.ENABLED); - + assertUser(userLargo, USER_LARGO_OID, USER_LARGO_USERNAME, "Largo LaGrande", "Largo", "LaGrande"); accountOid = getSingleLinkOid(userLargo); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountOid, USER_LARGO_USERNAME); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, USER_LARGO_USERNAME, "Largo LaGrande"); - + // Check account in dummy resource assertDefaultDummyAccount(USER_LARGO_USERNAME, "Largo LaGrande", true); } - + @Test public void test217ModifyLargoRemoveValidFrom() throws Exception { final String TEST_NAME = "test217ModifyLargoRemoveValidFrom"; @@ -1737,36 +1737,36 @@ public void test217ModifyLargoRemoveValidFrom() throws Exception { long startMillis = clock.currentTimeMillis(); Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN modifyUserReplace(USER_LARGO_OID, ACTIVATION_VALID_FROM_PATH, task, result); - + // THEN PrismObject userLargo = getUser(USER_LARGO_OID); display("User after change execution", userLargo); - + assertValidity(userLargo, null); assertValidityTimestamp(userLargo, startMillis, clock.currentTimeMillis()); lastValidityChangeTimestamp = userLargo.asObjectable().getActivation().getValidityChangeTimestamp(); assertEffectiveStatus(userLargo, ActivationStatusType.ENABLED); - + assertUser(userLargo, USER_LARGO_OID, USER_LARGO_USERNAME, "Largo LaGrande", "Largo", "LaGrande"); accountOid = getSingleLinkOid(userLargo); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountOid, USER_LARGO_USERNAME); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, USER_LARGO_USERNAME, "Largo LaGrande"); - + // Check account in dummy resource assertDefaultDummyAccount(USER_LARGO_USERNAME, "Largo LaGrande", true); } - + /** - * Delete assignment from repo. Model should not notice. + * Delete assignment from repo. Model should not notice. * The change should be NOT applied after recompute. * Accounts are not retrieved, therefore the change is not noticed. */ @@ -1778,25 +1778,25 @@ public void test230JackUnassignRepoRecompute() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + addObject(USER_JACK_FILE); assignAccount(USER_JACK_OID, RESOURCE_DUMMY_RED_OID, null, task, result); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); - + // Delete the assignment from the repo. Really use the repo directly. We do not want the model to notice. ObjectDelta userDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_RED_OID, null, false); repositoryService.modifyObject(UserType.class, userDelta.getOid(), userDelta.getModifications(), result); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); - + // WHEN TestUtil.displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); } @@ -1812,16 +1812,16 @@ public void test231JackRecomputeReconcile() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, ModelExecuteOptions.createReconcile(), task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", false); } @@ -1835,10 +1835,10 @@ public void test231JackRecomputeReconcile() throws Exception { public void test240AddUserRappDraft() throws Exception { final String TEST_NAME = "test240AddUserRappDraft"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = PrismTestUtil.parseObject(USER_RAPP_FILE); UserType userTypeBefore = userBefore.asObjectable(); userTypeBefore.setLifecycleState(SchemaConstants.LIFECYCLE_DRAFT); @@ -1858,33 +1858,33 @@ public void test240AddUserRappDraft() throws Exception { // WHEN TestUtil.displayWhen(TEST_NAME); addObject(userBefore, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_RAPP_OID); display("user after", userAfter); - + display("Dummy", getDummyResource()); - + assertEffectiveActivation(userAfter, ActivationStatusType.DISABLED); - + assertAssignedRole(userAfter, ROLE_CARIBBEAN_PIRATE_OID); assertAssignments(userAfter, 1); - + // assignments are not active due to lifecycle, there should // be no roles in roleMembershipRef // MID-3741 assertRoleMembershipRef(userAfter); - + assertLinks(userAfter, 0); - + assertNoDummyAccount(USER_RAPP_USERNAME); - + } - + /** * Still draft. Still no accounts. * MID-3689, MID-3737 @@ -1893,40 +1893,40 @@ public void test240AddUserRappDraft() throws Exception { public void test241RecomputeRappDraft() throws Exception { final String TEST_NAME = "test240AddUserRappDraft"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); recomputeUser(USER_RAPP_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_RAPP_OID); display("user after", userAfter); - + display("Dummy", getDummyResource()); - + assertEffectiveActivation(userAfter, ActivationStatusType.DISABLED); - + assertAssignedRole(userAfter, ROLE_CARIBBEAN_PIRATE_OID); assertAssignments(userAfter, 1); - + // assignments are not active due to lifecycle, there should // be no roles in roleMembershipRef // MID-3741 assertRoleMembershipRef(userAfter); - + assertLinks(userAfter, 0); - + assertNoDummyAccount(USER_RAPP_USERNAME); - + } - + /** * Even though Captain role gives dummy account the user is in the draft * state. No account should be created. @@ -1936,35 +1936,35 @@ public void test241RecomputeRappDraft() throws Exception { public void test242RappAssignCaptain() throws Exception { final String TEST_NAME = "test242RappAssignCaptain"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_RAPP_OID, ROLE_CAPTAIN_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_RAPP_OID); display("user after", userAfter); assertEffectiveActivation(userAfter, ActivationStatusType.DISABLED); - + assertAssignedRoles(userAfter, ROLE_CARIBBEAN_PIRATE_OID, ROLE_CAPTAIN_OID); assertAssignments(userAfter, 2); assertLinks(userAfter, 0); - + // assignments are not active due to lifecycle, there should // be no roles in roleMembershipRef // MID-3741 assertRoleMembershipRef(userAfter); - + assertNoDummyAccount(USER_RAPP_USERNAME); } - + /** * Switch Rapp to active state. The assignments should be * activated as well. @@ -1974,40 +1974,40 @@ public void test242RappAssignCaptain() throws Exception { public void test245ActivateRapp() throws Exception { final String TEST_NAME = "test245ActivateRapp"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyUserReplace(USER_RAPP_OID, UserType.F_LIFECYCLE_STATE, task, result, + modifyUserReplace(USER_RAPP_OID, UserType.F_LIFECYCLE_STATE, task, result, SchemaConstants.LIFECYCLE_ACTIVE); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_RAPP_OID); display("user after", userAfter); assertEffectiveActivation(userAfter, ActivationStatusType.ENABLED); - + assertAssignedRoles(userAfter, ROLE_CARIBBEAN_PIRATE_OID, ROLE_CAPTAIN_OID); assertAssignments(userAfter, 2); assertLinks(userAfter, 1); - + assertRoleMembershipRef(userAfter, ROLE_CARIBBEAN_PIRATE_OID, ROLE_PIRATE_OID, ROLE_CAPTAIN_OID); - + DummyAccount dummyAccount = assertDummyAccount(null, USER_RAPP_USERNAME); display("dummy account", dummyAccount); - assertDummyAccountAttribute(null, USER_RAPP_USERNAME, + assertDummyAccountAttribute(null, USER_RAPP_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, ROLE_PIRATE_WEAPON); - assertDummyAccountAttribute(null, USER_RAPP_USERNAME, + assertDummyAccountAttribute(null, USER_RAPP_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, RESOURCE_DUMMY_QUOTE); - assertDummyAccountAttribute(null, USER_RAPP_USERNAME, + assertDummyAccountAttribute(null, USER_RAPP_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, ROLE_PIRATE_TITLE); } - + /** * Switch Rapp to archived state. The assignments should be * deactivated as well. @@ -2017,36 +2017,36 @@ public void test245ActivateRapp() throws Exception { public void test248DeactivateRapp() throws Exception { final String TEST_NAME = "test248DeactivateRapp"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyUserReplace(USER_RAPP_OID, UserType.F_LIFECYCLE_STATE, task, result, + modifyUserReplace(USER_RAPP_OID, UserType.F_LIFECYCLE_STATE, task, result, SchemaConstants.LIFECYCLE_ARCHIVED); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_RAPP_OID); display("user after", userAfter); assertEffectiveActivation(userAfter, ActivationStatusType.ARCHIVED); - + assertAssignedRoles(userAfter, ROLE_CARIBBEAN_PIRATE_OID, ROLE_CAPTAIN_OID); assertAssignments(userAfter, 2); assertLinks(userAfter, 0); - + // assignments are not active due to lifecycle, there should // be no roles in roleMembershipRef // MID-3741 assertRoleMembershipRef(userAfter); - + assertNoDummyAccount(USER_RAPP_USERNAME); } - + /** * MID-3689 */ @@ -2054,24 +2054,24 @@ public void test248DeactivateRapp() throws Exception { public void test249DeleteUserRapp() throws Exception { final String TEST_NAME = "test249DeleteUserRapp"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); // WHEN TestUtil.displayWhen(TEST_NAME); deleteObject(UserType.class, USER_RAPP_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertNoObject(UserType.class, USER_RAPP_OID); assertNoDummyAccount(USER_RAPP_USERNAME); } - - + + /** * Test reading of validity data through shadow */ @@ -2090,31 +2090,31 @@ public void test300AddDummyGreenAccountMancomb() throws Exception { account.setValidTo(ACCOUNT_MANCOMB_VALID_TO_DATE); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Mancomb Seepgood"); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Melee Island"); - + /// WHEN TestUtil.displayWhen(TEST_NAME); - + dummyResourceGreen.addAccount(account); - + // THEN TestUtil.displayThen(TEST_NAME); - + PrismObject accountMancomb = findAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME, resourceDummyGreen); display("Account shadow after", accountMancomb); - + DummyAccount dummyAccountAfter = dummyResourceGreen.getAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); display("Account after", dummyAccountAfter); - + assertNotNull("No mancomb account shadow", accountMancomb); accountMancombOid = accountMancomb.getOid(); - assertEquals("Wrong resourceRef in mancomb account", RESOURCE_DUMMY_GREEN_OID, + assertEquals("Wrong resourceRef in mancomb account", RESOURCE_DUMMY_GREEN_OID, accountMancomb.asObjectable().getResourceRef().getOid()); assertValidFrom(accountMancomb, ACCOUNT_MANCOMB_VALID_FROM_DATE); - assertValidTo(accountMancomb, ACCOUNT_MANCOMB_VALID_TO_DATE); + assertValidTo(accountMancomb, ACCOUNT_MANCOMB_VALID_TO_DATE); } - + /** - * Testing of inbound mappings for validity data. Done by initiating an import of accouts from green resource. + * Testing of inbound mappings for validity data. Done by initiating an import of accouts from green resource. */ @Test public void test310ImportAccountsFromDummyGreen() throws Exception { @@ -2124,36 +2124,36 @@ public void test310ImportAccountsFromDummyGreen() throws Exception { // GIVEN Task task = createTask(AbstractSynchronizationStoryTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // Preconditions assertUsers(6); PrismObject userMancomb = findUserByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); assertNull("Unexpected user mancomb before import", userMancomb); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.importFromResource(RESOURCE_DUMMY_GREEN_OID, new QName(dummyResourceCtlGreen.getNamespace(), "AccountObjectClass"), task, result); - + // THEN TestUtil.displayThen(TEST_NAME); OperationResult subresult = result.getLastSubresult(); TestUtil.assertInProgress("importAccountsFromResource result", subresult); - + waitForTaskFinish(task, true, 40000); - + TestUtil.displayThen(TEST_NAME); - + userMancomb = findUserByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); assertNotNull("No user mancomb after import", userMancomb); userMancombOid = userMancomb.getOid(); - + assertUsers(7); - + assertAdministrativeStatusEnabled(userMancomb); assertValidFrom(userMancomb, ACCOUNT_MANCOMB_VALID_FROM_DATE); assertValidTo(userMancomb, ACCOUNT_MANCOMB_VALID_TO_DATE); } - + @Test public void test350AssignMancombBlueAccount() throws Exception { final String TEST_NAME = "test350AssignMancombBlueAccount"; @@ -2162,25 +2162,25 @@ public void test350AssignMancombBlueAccount() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignAccount(userMancombOid, RESOURCE_DUMMY_BLUE_OID, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userMancomb = getUser(userMancombOid); display("User after change execution", userMancomb); assertAccounts(userMancombOid, 2); - + DummyAccount mancombBlueAccount = getDummyAccount(RESOURCE_DUMMY_BLUE_NAME, ACCOUNT_MANCOMB_DUMMY_USERNAME); assertNotNull("No mancomb blue account", mancombBlueAccount); assertTrue("mancomb blue account not enabled", mancombBlueAccount.isEnabled()); assertEquals("Wrong validFrom in mancomb blue account", ACCOUNT_MANCOMB_VALID_FROM_DATE, mancombBlueAccount.getValidFrom()); assertEquals("Wrong validTo in mancomb blue account", ACCOUNT_MANCOMB_VALID_TO_DATE, mancombBlueAccount.getValidTo()); } - + @Test public void test352AssignMancombBlackAccount() throws Exception { final String TEST_NAME = "test352AssignMancombBlackAccount"; @@ -2189,31 +2189,31 @@ public void test352AssignMancombBlackAccount() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignAccount(userMancombOid, RESOURCE_DUMMY_BLACK_OID, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userMancomb = getUser(userMancombOid); display("User after change execution", userMancomb); assertAccounts(userMancombOid, 3); - + DummyAccount mancombBlueAccount = getDummyAccount(RESOURCE_DUMMY_BLUE_NAME, ACCOUNT_MANCOMB_DUMMY_USERNAME); assertNotNull("No mancomb blue account", mancombBlueAccount); assertTrue("mancomb blue account not enabled", mancombBlueAccount.isEnabled()); assertEquals("Wrong validFrom in mancomb blue account", ACCOUNT_MANCOMB_VALID_FROM_DATE, mancombBlueAccount.getValidFrom()); assertEquals("Wrong validTo in mancomb blue account", ACCOUNT_MANCOMB_VALID_TO_DATE, mancombBlueAccount.getValidTo()); - + DummyAccount mancombBlackAccount = getDummyAccount(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_MANCOMB_DUMMY_USERNAME); assertNotNull("No mancomb black account", mancombBlackAccount); assertTrue("mancomb black account not enabled", mancombBlackAccount.isEnabled()); assertEquals("Wrong validFrom in mancomb black account", ACCOUNT_MANCOMB_VALID_FROM_DATE, mancombBlackAccount.getValidFrom()); assertEquals("Wrong validTo in mancomb black account", ACCOUNT_MANCOMB_VALID_TO_DATE, mancombBlackAccount.getValidTo()); } - + @Test public void test355MancombModifyAdministrativeStatusNull() throws Exception { final String TEST_NAME = "test355MancombModifyAdministrativeStatusNull"; @@ -2222,18 +2222,18 @@ public void test355MancombModifyAdministrativeStatusNull() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN modifyUserReplace(userMancombOid, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userMancomb = getUser(userMancombOid); display("User after change execution", userMancomb); assertAccounts(userMancombOid, 3); - + DummyAccount mancombBlueAccount = getDummyAccount(RESOURCE_DUMMY_BLUE_NAME, ACCOUNT_MANCOMB_DUMMY_USERNAME); assertNotNull("No mancomb blue account", mancombBlueAccount); // Blue resouce has only weak administrativeStatus mapping. The values is not reset to null. @@ -2241,14 +2241,14 @@ public void test355MancombModifyAdministrativeStatusNull() throws Exception { // assertEquals("Wring mancomb blue account enabled flag", Boolean.TRUE, mancombBlueAccount.isEnabled()); assertEquals("Wrong validFrom in mancomb blue account", ACCOUNT_MANCOMB_VALID_FROM_DATE, mancombBlueAccount.getValidFrom()); assertEquals("Wrong validTo in mancomb blue account", ACCOUNT_MANCOMB_VALID_TO_DATE, mancombBlueAccount.getValidTo()); - + DummyAccount mancombBlackAccount = getDummyAccount(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_MANCOMB_DUMMY_USERNAME); assertNotNull("No mancomb black account", mancombBlackAccount); assertEquals("Wring mancomb black account enabled flag", null, mancombBlackAccount.isEnabled()); assertEquals("Wrong validFrom in mancomb black account", ACCOUNT_MANCOMB_VALID_FROM_DATE, mancombBlackAccount.getValidFrom()); assertEquals("Wrong validTo in mancomb black account", ACCOUNT_MANCOMB_VALID_TO_DATE, mancombBlackAccount.getValidTo()); } - + @Test public void test400AddHerman() throws Exception { final String TEST_NAME = "test400AddHerman"; @@ -2256,13 +2256,13 @@ public void test400AddHerman() throws Exception { // WHEN addObject(USER_HERMAN_FILE); - + // THEN // Make sure that it is effectivelly enabled PrismObject userHermanAfter = getUser(USER_HERMAN_OID); assertEffectiveActivation(userHermanAfter, ActivationStatusType.ENABLED); } - + /** * Herman has validTo/validFrom. Khaki resource has strange mappings for these. */ @@ -2274,18 +2274,18 @@ public void test410AssignHermanKhakiAccount() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignAccount(USER_HERMAN_OID, RESOURCE_DUMMY_KHAKI_OID, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject user = getUser(USER_HERMAN_OID); display("User after change execution", user); assertLinks(user, 1); - + DummyAccount khakiAccount = getDummyAccount(RESOURCE_DUMMY_KHAKI_NAME, USER_HERMAN_USERNAME); assertNotNull("No khaki account", khakiAccount); assertTrue("khaki account not enabled", khakiAccount.isEnabled()); @@ -2294,54 +2294,54 @@ public void test410AssignHermanKhakiAccount() throws Exception { assertEquals("Wrong drink (validTo) in khaki account", "to: 2233-03-23T18:30:00.000Z", khakiAccount.getAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME)); } - - + + @Test public void test500CheckRolePirateInitial() throws Exception { test5X0CheckInitial("test500CheckRolePirateInitial", RoleType.class, ROLE_PIRATE_OID); } - + @Test public void test501RolePirateRecompute() throws Exception { test5X1Recompute("test501RolePirateRecompute", RoleType.class, ROLE_PIRATE_OID); } - + @Test public void test502ModifyRolePirateDisable() throws Exception { test5X2ModifyDisable("test502ModifyRolePirateDisable", RoleType.class, ROLE_PIRATE_OID); } - + @Test public void test504ModifyRolePirateEnable() throws Exception { test5X4ModifyEnable("test504ModifyRolePirateEnable", RoleType.class, ROLE_PIRATE_OID); } - + @Test public void test505RolePirateRecompute() throws Exception { test5X5Recompute("test505RolePirateRecompute", RoleType.class, ROLE_PIRATE_OID); } - - + + @Test public void test510CheckOrgScummBarInitial() throws Exception { test5X0CheckInitial("test510CheckOrgScummBarInitial", OrgType.class, ORG_SCUMM_BAR_OID); } - + @Test public void test511OrgScummBarRecompute() throws Exception { test5X1Recompute("test511OrgScummBarRecompute", OrgType.class, ORG_SCUMM_BAR_OID); } - + @Test public void test512ModifyOrgScummBarDisable() throws Exception { test5X2ModifyDisable("test512ModifyOrgScummBarDisable", OrgType.class, ORG_SCUMM_BAR_OID); } - + @Test public void test514ModifyOrgScummBarEnable() throws Exception { test5X4ModifyEnable("test514ModifyOrgScummBarEnable", OrgType.class, ORG_SCUMM_BAR_OID); } - + @Test public void test515OrgScummBarRecompute() throws Exception { test5X5Recompute("test515OrgScummBarRecompute", OrgType.class, ORG_SCUMM_BAR_OID); @@ -2352,22 +2352,22 @@ public void test515OrgScummBarRecompute() throws Exception { public void test520CheckSerivceSeaMonkeyInitial() throws Exception { test5X0CheckInitial("test520CheckSerivceSeaMonkeyInitial", ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); } - + @Test public void test521SerivceSeaMonkeyRecompute() throws Exception { test5X1Recompute("test521SerivceSeaMonkeyRecompute", ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); } - + @Test public void test522ModifySerivceSeaMonkeyDisable() throws Exception { test5X2ModifyDisable("test522ModifySerivceSeaMonkeyDisable", ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); } - + @Test public void test524ModifySerivceSeaMonkeyEnable() throws Exception { test5X4ModifyEnable("test524ModifySerivceSeaMonkeyEnable", ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); } - + @Test public void test525SerivceSeaMonkeyRecompute() throws Exception { test5X5Recompute("test525SerivceSeaMonkeyRecompute", ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); @@ -2378,15 +2378,15 @@ private void test5X0CheckInitial(final String TEST_NAME, C // GIVEN, WHEN // this happens during test initialization when the role is added - - // THEN + + // THEN PrismObject objectAfter = getObject(type, oid); display("Object after", objectAfter); - + assertAdministrativeStatus(objectAfter, null); // Cannot assert validity or effective status here. The object was added through repo and was not recomputed yet. } - + /** * Make sure that recompute properly updates the effective status. * MID-2877 @@ -2399,22 +2399,22 @@ private void test5X1Recompute(final String TEST_NAME, Clas OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - + // WHEN modelService.recompute(type, oid, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject objectAfter = getObject(type, oid); display("Object after", objectAfter); - + assertAdministrativeStatus(objectAfter, null); assertValidity(objectAfter, null); - assertEffectiveStatus(objectAfter, ActivationStatusType.ENABLED); + assertEffectiveStatus(objectAfter, ActivationStatusType.ENABLED); } - + /** * MID-2877 */ @@ -2424,29 +2424,29 @@ private void test5X2ModifyDisable(final String TEST_NAME, // GIVEN Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); - + // WHEN - modifyObjectReplaceProperty(type, oid, + modifyObjectReplaceProperty(type, oid, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.DISABLED); - + // THEN XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject objectAfter = getObject(type, oid); display("Object after", objectAfter); - + assertAdministrativeStatusDisabled(objectAfter); assertValidity(objectAfter, null); assertEffectiveStatus(objectAfter, ActivationStatusType.DISABLED); assertDisableTimestampFocus(objectAfter, start, end); - + TestUtil.assertModifyTimestamp(objectAfter, start, end); } - + /** * MID-2877 */ @@ -2456,29 +2456,29 @@ private void test5X4ModifyEnable(final String TEST_NAME, C // GIVEN Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); - + // WHEN - modifyObjectReplaceProperty(type, oid, + modifyObjectReplaceProperty(type, oid, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.ENABLED); - + // THEN XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject objectAfter = getObject(type, oid); display("Object after", objectAfter); - + assertAdministrativeStatusEnabled(objectAfter); assertValidity(objectAfter, null); assertEffectiveStatus(objectAfter, ActivationStatusType.ENABLED); assertEnableTimestampFocus(objectAfter, start, end); - + TestUtil.assertModifyTimestamp(objectAfter, start, end); } - + /** * Make sure that recompute does not destroy anything. */ @@ -2490,21 +2490,21 @@ public void test5X5Recompute(final String TEST_NAME, Class OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - + // WHEN modelService.recompute(type, oid, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject objectAfter = getObject(type, oid); display("Object after", objectAfter); - + assertAdministrativeStatusEnabled(objectAfter); assertValidity(objectAfter, null); assertEffectiveStatus(objectAfter, ActivationStatusType.ENABLED); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertNoRecord(); @@ -2589,7 +2589,7 @@ public void test610EnableUser1() throws Exception { // TODO check real state of the account and shadow } - + /** * MID-3695 */ @@ -2602,42 +2602,42 @@ public void test700ModifyJackRemoveAdministrativeStatus() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + setDefaultObjectTemplate(UserType.COMPLEX_TYPE, USER_TEMPLATE_COMPLEX_OID, result); PrismObject userBefore = getUser(USER_JACK_OID); display("User before", userBefore); - + assertNoAssignments(userBefore); - + // Disabled RED account. RED resource has disable instead delete assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", false); - + assertAdministrativeStatusEnabled(userBefore); assertEffectiveActivation(userBefore, ActivationStatusType.ENABLED); assertValidityStatus(userBefore, null); PrismAsserts.assertNoItem(userBefore, SchemaConstants.PATH_ACTIVATION_VALID_FROM); PrismAsserts.assertNoItem(userBefore, SchemaConstants.PATH_ACTIVATION_VALID_TO); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", userAfter); assertUserJack(userAfter, "Jack Sparrow"); - + assertAdministrativeStatus(userAfter, null); assertEffectiveActivation(userAfter, ActivationStatusType.ENABLED); assertValidityStatus(userAfter, null); PrismAsserts.assertNoItem(userAfter, SchemaConstants.PATH_ACTIVATION_VALID_FROM); PrismAsserts.assertNoItem(userAfter, SchemaConstants.PATH_ACTIVATION_VALID_TO); - + // Unconditional automatic assignment of Blue Dummy resource in user-template-complex-include assertAssignments(userAfter, 1); } @@ -2654,37 +2654,37 @@ public void test702ModifyJackFuneralTimestampBeforeNow() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + setDefaultObjectTemplate(UserType.COMPLEX_TYPE, USER_TEMPLATE_COMPLEX_OID, result); PrismObject userBefore = getUser(USER_JACK_OID); display("User before", userBefore); - + assertAssignments(userBefore, 1); - + XMLGregorianCalendar hourAgo = XmlTypeConverter.createXMLGregorianCalendar(clock.currentTimeMillis() - 60 * 60 * 1000); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, getExtensionPath(PIRACY_FUNERAL_TIMESTAMP), task, result, hourAgo); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", userAfter); assertUserJack(userAfter, "Jack Sparrow"); - + PrismAsserts.assertNoItem(userAfter, SchemaConstants.PATH_ACTIVATION_VALID_FROM); assertEquals("Wrong validTo in user", hourAgo, getActivation(userAfter).getValidTo()); - + assertAdministrativeStatus(userAfter, null); assertValidityStatus(userAfter, TimeIntervalStatusType.AFTER); assertEffectiveActivation(userAfter, ActivationStatusType.DISABLED); } - + /** * This is where MID-3695 is really reproduced. * MID-3695 @@ -2698,70 +2698,70 @@ public void test704ModifyJackFuneralTimestampAfterNow() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + setDefaultObjectTemplate(UserType.COMPLEX_TYPE, USER_TEMPLATE_COMPLEX_OID, result); PrismObject userBefore = getUser(USER_JACK_OID); display("User before", userBefore); - + assertAssignments(userBefore, 1); - + XMLGregorianCalendar hourAhead = XmlTypeConverter.createXMLGregorianCalendar(clock.currentTimeMillis() + 60 * 60 * 1000); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, getExtensionPath(PIRACY_FUNERAL_TIMESTAMP), task, result, hourAhead); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", userAfter); assertUserJack(userAfter, "Jack Sparrow"); - + PrismAsserts.assertNoItem(userAfter, SchemaConstants.PATH_ACTIVATION_VALID_FROM); assertEquals("Wrong validTo in user", hourAhead, getActivation(userAfter).getValidTo()); - + assertAdministrativeStatus(userAfter, null); assertValidityStatus(userAfter, TimeIntervalStatusType.IN); assertEffectiveActivation(userAfter, ActivationStatusType.ENABLED); } - + private void assertDummyActivationEnabledState(String userId, Boolean expectedEnabled) throws SchemaViolationException, ConflictException { assertDummyActivationEnabledState(null, userId, expectedEnabled); } - + private void assertDummyActivationEnabledState(String instance, String userId, Boolean expectedEnabled) throws SchemaViolationException, ConflictException { DummyAccount account = getDummyAccount(instance, userId); 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 { assertDummyActivationEnabledState(userId, true); } - + private void assertDummyDisabled(String userId) throws SchemaViolationException, ConflictException { assertDummyActivationEnabledState(userId, false); } - + private void assertDummyEnabled(String instance, String userId) throws SchemaViolationException, ConflictException { assertDummyActivationEnabledState(instance, userId, true); } - + private void assertDummyDisabled(String instance, String userId) throws SchemaViolationException, ConflictException { assertDummyActivationEnabledState(instance, userId, false); } - + 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()); } - + private void assertValidityTimestamp(PrismObject user, long expected) { ActivationType activation = user.asObjectable().getActivation(); assertNotNull("No activation in "+user, activation); @@ -2769,7 +2769,7 @@ private void assertValidityTimestamp(PrismObject user, long expected) 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); @@ -2777,7 +2777,7 @@ private void assertValidityTimestamp(PrismObject user, XMLGregorianCal 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); @@ -2789,12 +2789,12 @@ private void assertValidityTimestamp(PrismObject user, long lowerBound } AssertJUnit.fail("Expected validityChangeTimestamp to be between "+lowerBound+" and "+upperBound+", but it was "+validityMillis); } - + private void assertEffectiveStatus(PrismObject focus, ActivationStatusType expected) { ActivationType activation = focus.asObjectable().getActivation(); assertNotNull("No activation in "+focus, activation); assertEquals("Unexpected effective activation status in "+focus, expected, activation.getEffectiveStatus()); } - - + + } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestAudit.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestAudit.java index 715029d50bf..65143b6b44d 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestAudit.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestAudit.java @@ -57,28 +57,28 @@ /** * Test of Model Audit Service. - * + * * Two users, interlaced events: jack and herman. - * + * * Jack already exists, but there is no create audit record for him. This simulates trimmed * audit log. There are several fresh modify operations. - * + * * Herman is properly created and modified. We have all the audit records. - * + * * The tests check if audit records are created and that they can be listed. * The other tests check that the state can be reconstructed by the time machine (object history). - * + * * @author Radovan Semancik * */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestAudit extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/audit"); - + public static final int INITIAL_NUMBER_OF_AUDIT_RECORDS = 26; - + private XMLGregorianCalendar initialTs; private XMLGregorianCalendar jackKidTs; private String jackKidEid; @@ -95,27 +95,27 @@ public class TestAudit extends AbstractInitializedModelIntegrationTest { private String hermanHermitEid; private XMLGregorianCalendar hermanCivilisedHermitTs; private String hermanCivilisedHermitEid; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); } - + @Test public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; TestUtil.displayTestTitle(this, TEST_NAME); assertTrue(modelAuditService.supportsRetrieval()); - + // WHEN List allRecords = modelAuditService.listRecords("from RAuditEventRecord as aer where 1=1 ", new HashMap<>(), new OperationResult(TEST_NAME)); - + // THEN display("all records", allRecords); - + assertEquals("Wrong initial number of audit records", INITIAL_NUMBER_OF_AUDIT_RECORDS, allRecords.size()); } @@ -123,13 +123,13 @@ public void test000Sanity() throws Exception { public void test010SanityJack() throws Exception { final String TEST_NAME = "test010SanityJack"; TestUtil.displayTestTitle(this, TEST_NAME); - + // WHEN List auditRecords = getObjectAuditRecords(USER_JACK_OID); - + // THEN display("Jack records", auditRecords); - + assertEquals("Wrong initial number of jack audit records", 0, auditRecords.size()); } @@ -137,22 +137,22 @@ public void test010SanityJack() throws Exception { public void test100ModifyUserJackKid() throws Exception { final String TEST_NAME = "test100ModifyUserJackKid"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestAudit.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + initialTs = getTimeSafely(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + modifyUserReplace(USER_JACK_OID, UserType.F_TITLE, task, result, createPolyString("Kid")); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + jackKidTs = getTimeSafely(); jackKidEid = assertObjectAuditRecords(USER_JACK_OID, 2); assertRecordsFromInitial(jackKidTs, 2); @@ -166,29 +166,29 @@ public void test100ModifyUserJackKid() throws Exception { public void test105CreateUserHerman() throws Exception { final String TEST_NAME = "test105CreateUserHerman"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestAudit.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userHermanBefore = PrismTestUtil.parseObject(USER_HERMAN_FILE); userHermanBefore.asObjectable().setDescription("Unknown"); userHermanBefore.asObjectable().setNickName(createPolyStringType("HT")); - + hermanInitialTs = getTimeSafely(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + addObject(userHermanBefore, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject user = getUser(USER_HERMAN_OID); display("Herman (created)", user); - + hermanCreatedTs = getTimeSafely(); hermanCreatedEid = assertObjectAuditRecords(USER_HERMAN_OID, 2); assertRecordsFromInitial(hermanCreatedTs, 4); @@ -198,53 +198,53 @@ public void test105CreateUserHerman() throws Exception { public void test110ModifyUserJackSailor() throws Exception { final String TEST_NAME = "test110ModifyUserJackSailor"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestAudit.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - - - ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_JACK_OID, UserType.F_TITLE, + + + ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_JACK_OID, UserType.F_TITLE, createPolyString("Sailor")); objectDelta.addModificationReplaceProperty(UserType.F_DESCRIPTION, "Hermit on Monkey Island"); - objectDelta.addModificationReplaceProperty(SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, + objectDelta.addModificationReplaceProperty(SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, ActivationStatusType.DISABLED); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + modelService.executeChanges(MiscSchemaUtil.createCollection(objectDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + jackSailorTs = getTimeSafely(); jackSailorEid = assertObjectAuditRecords(USER_JACK_OID, 4); - + assertRecordsFromPrevious(hermanCreatedTs, jackSailorTs, 2); assertRecordsFromPrevious(jackKidTs, jackSailorTs, 4); - assertRecordsFromInitial(jackSailorTs, 6); + assertRecordsFromInitial(jackSailorTs, 6); } - + @Test public void test115ModifyUserHermanMarooned() throws Exception { final String TEST_NAME = "test115ModifyUserHermanMarooned"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestAudit.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - - ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_HERMAN_OID, UserType.F_TITLE, + + ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_HERMAN_OID, UserType.F_TITLE, createPolyString("Marooned")); objectDelta.addModificationReplaceProperty(UserType.F_DESCRIPTION, "Marooned on Monkey Island"); objectDelta.addModification(createAssignmentModification(RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, null, true)); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + modelService.executeChanges(MiscSchemaUtil.createCollection(objectDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -252,10 +252,10 @@ public void test115ModifyUserHermanMarooned() throws Exception { PrismObject user = getUser(USER_HERMAN_OID); display("Herman (marooned)", user); - + hermanMaroonedTs = getTimeSafely(); hermanMaroonedEid = assertObjectAuditRecords(USER_HERMAN_OID, 4); - assertRecordsFromInitial(hermanMaroonedTs, 8); + assertRecordsFromInitial(hermanMaroonedTs, 8); } @@ -263,59 +263,59 @@ public void test115ModifyUserHermanMarooned() throws Exception { public void test120ModifyUserJackCaptain() throws Exception { final String TEST_NAME = "test120ModifyUserJackCaptain"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestAudit.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - - ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_JACK_OID, UserType.F_TITLE, + + ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_JACK_OID, UserType.F_TITLE, createPolyString("Captain")); objectDelta.addModificationReplaceProperty(UserType.F_DESCRIPTION, "Hermit on Monkey Island"); - objectDelta.addModificationReplaceProperty(SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, + objectDelta.addModificationReplaceProperty(SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, ActivationStatusType.ENABLED); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + modelService.executeChanges(MiscSchemaUtil.createCollection(objectDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + jackCaptainTs = getTimeSafely(); jackCaptainEid = assertObjectAuditRecords(USER_JACK_OID, 6); - + assertRecordsFromPrevious(hermanMaroonedTs, jackCaptainTs, 2); assertRecordsFromPrevious(jackSailorTs, jackCaptainTs, 4); - assertRecordsFromInitial(jackCaptainTs, 10); + assertRecordsFromInitial(jackCaptainTs, 10); } - + @Test public void test125ModifyUserHermanHermit() throws Exception { final String TEST_NAME = "test125ModifyUserHermanHermit"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestAudit.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - - ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_HERMAN_OID, UserType.F_TITLE, + + ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_HERMAN_OID, UserType.F_TITLE, createPolyString("Hermit")); objectDelta.addModificationReplaceProperty(UserType.F_DESCRIPTION, "Hermit on Monkey Island"); objectDelta.addModificationReplaceProperty(UserType.F_HONORIFIC_PREFIX, createPolyString("His Loneliness")); objectDelta.addModificationReplaceProperty(UserType.F_NICK_NAME); objectDelta.addModification(createAssignmentModification(RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, null, false)); - objectDelta.addModification(createAssignmentModification(ROLE_JUDGE_OID, RoleType.COMPLEX_TYPE, + objectDelta.addModification(createAssignmentModification(ROLE_JUDGE_OID, RoleType.COMPLEX_TYPE, null, null, null, true)); - objectDelta.addModification(createAssignmentModification(ROLE_RED_SAILOR_OID, RoleType.COMPLEX_TYPE, + objectDelta.addModification(createAssignmentModification(ROLE_RED_SAILOR_OID, RoleType.COMPLEX_TYPE, null, null, null, true)); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + modelService.executeChanges(MiscSchemaUtil.createCollection(objectDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -323,32 +323,32 @@ public void test125ModifyUserHermanHermit() throws Exception { PrismObject user = getUser(USER_HERMAN_OID); display("Herman (hermit)", user); - + hermanHermitTs = getTimeSafely(); hermanHermitEid = assertObjectAuditRecords(USER_HERMAN_OID, 6); - assertRecordsFromInitial(hermanHermitTs, 12); + assertRecordsFromInitial(hermanHermitTs, 12); } - + @Test public void test135ModifyUserHermanCivilisedHermit() throws Exception { final String TEST_NAME = "test135ModifyUserHermanCivilisedHermit"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestAudit.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - - ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_HERMAN_OID, UserType.F_TITLE, + + ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_HERMAN_OID, UserType.F_TITLE, createPolyString("Civilised Hermit")); objectDelta.addModificationReplaceProperty(UserType.F_DESCRIPTION, "Civilised Hermit on Monkey Island"); - objectDelta.addModification(createAssignmentModification(ROLE_RED_SAILOR_OID, RoleType.COMPLEX_TYPE, + objectDelta.addModification(createAssignmentModification(ROLE_RED_SAILOR_OID, RoleType.COMPLEX_TYPE, null, null, null, false)); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + modelService.executeChanges(MiscSchemaUtil.createCollection(objectDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -356,75 +356,75 @@ public void test135ModifyUserHermanCivilisedHermit() throws Exception { PrismObject user = getUser(USER_HERMAN_OID); display("Herman (civilised hermit)", user); - + hermanCivilisedHermitTs = getTimeSafely(); hermanCivilisedHermitEid = assertObjectAuditRecords(USER_HERMAN_OID, 8); - assertRecordsFromInitial(hermanCivilisedHermitTs, 14); + assertRecordsFromInitial(hermanCivilisedHermitTs, 14); } - + @Test public void test200ReconstructJackSailor() throws Exception { final String TEST_NAME = "test200ReconstructJackSailor"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestAudit.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User before", userBefore); // precondition PrismAsserts.assertPropertyValue(userBefore, UserType.F_TITLE, createPolyString("Captain")); - + // WHEN TestUtil.displayWhen(TEST_NAME); - - PrismObject jackReconstructed = modelAuditService.reconstructObject(UserType.class, USER_JACK_OID, + + PrismObject jackReconstructed = modelAuditService.reconstructObject(UserType.class, USER_JACK_OID, jackSailorEid, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); display("Reconstructed jack", jackReconstructed); - + PrismAsserts.assertPropertyValue(jackReconstructed, UserType.F_TITLE, createPolyString("Sailor")); assertAdministrativeStatusDisabled(jackReconstructed); - + // TODO } - + @Test public void test210ReconstructJackKid() throws Exception { final String TEST_NAME = "test210ReconstructJackKid"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestAudit.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User before", userBefore); // precondition PrismAsserts.assertPropertyValue(userBefore, UserType.F_TITLE, createPolyString("Captain")); - + // WHEN TestUtil.displayWhen(TEST_NAME); - - PrismObject jackReconstructed = modelAuditService.reconstructObject(UserType.class, USER_JACK_OID, + + PrismObject jackReconstructed = modelAuditService.reconstructObject(UserType.class, USER_JACK_OID, jackKidEid, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); display("Reconstructed jack", jackReconstructed); - + PrismAsserts.assertPropertyValue(jackReconstructed, UserType.F_TITLE, createPolyString("Kid")); - + // TODO } - + /** * This is supposed to get the objectToAdd directly from the create delta. */ @@ -432,10 +432,10 @@ public void test210ReconstructJackKid() throws Exception { public void test250ReconstructHermanCreated() throws Exception { final String TEST_NAME = "test250ReconstructHermanCreated"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestAudit.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_HERMAN_OID); display("User before", userBefore); // precondition @@ -443,29 +443,29 @@ public void test250ReconstructHermanCreated() throws Exception { PrismAsserts.assertPropertyValue(userBefore, UserType.F_HONORIFIC_PREFIX, createPolyString("His Loneliness")); PrismAsserts.assertNoItem(userBefore, UserType.F_NICK_NAME); assertAssignments(userBefore, 1); - + // WHEN TestUtil.displayWhen(TEST_NAME); - - PrismObject hermanReconstructed = modelAuditService.reconstructObject(UserType.class, USER_HERMAN_OID, + + PrismObject hermanReconstructed = modelAuditService.reconstructObject(UserType.class, USER_HERMAN_OID, hermanCreatedEid, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); display("Reconstructed herman", hermanReconstructed); - + PrismAsserts.assertPropertyValue(hermanReconstructed, UserType.F_DESCRIPTION, "Unknown"); PrismAsserts.assertPropertyValue(hermanReconstructed, UserType.F_NICK_NAME, createPolyString("HT")); PrismAsserts.assertNoItem(hermanReconstructed, UserType.F_TITLE); PrismAsserts.assertNoItem(hermanReconstructed, UserType.F_HONORIFIC_PREFIX); PrismAsserts.assertPropertyValue(hermanReconstructed, UserType.F_LOCALITY, createPolyString("Monkey Island")); - + assertNoAssignments(hermanReconstructed); } - + /** * Rolling back the deltas from the current state. */ @@ -473,33 +473,33 @@ public void test250ReconstructHermanCreated() throws Exception { public void test252ReconstructHermanMarooned() throws Exception { final String TEST_NAME = "test252ReconstructHermanMarooned"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestAudit.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - - PrismObject hermanReconstructed = modelAuditService.reconstructObject(UserType.class, USER_HERMAN_OID, + + PrismObject hermanReconstructed = modelAuditService.reconstructObject(UserType.class, USER_HERMAN_OID, hermanMaroonedEid, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); display("Reconstructed herman", hermanReconstructed); - + PrismAsserts.assertPropertyValue(hermanReconstructed, UserType.F_TITLE, createPolyString("Marooned")); PrismAsserts.assertPropertyValue(hermanReconstructed, UserType.F_DESCRIPTION, "Marooned on Monkey Island"); PrismAsserts.assertPropertyValue(hermanReconstructed, UserType.F_NICK_NAME, createPolyString("HT")); PrismAsserts.assertPropertyValue(hermanReconstructed, UserType.F_LOCALITY, createPolyString("Monkey Island")); PrismAsserts.assertNoItem(hermanReconstructed, UserType.F_HONORIFIC_PREFIX); - + assertAssignedAccount(hermanReconstructed, RESOURCE_DUMMY_OID); assertAssignments(hermanReconstructed, 1); } - + /** * Rolling back the deltas from the current state. */ @@ -507,29 +507,29 @@ public void test252ReconstructHermanMarooned() throws Exception { public void test254ReconstructHermanHermit() throws Exception { final String TEST_NAME = "test254ReconstructHermanHermit"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestAudit.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - - PrismObject hermanReconstructed = modelAuditService.reconstructObject(UserType.class, USER_HERMAN_OID, + + PrismObject hermanReconstructed = modelAuditService.reconstructObject(UserType.class, USER_HERMAN_OID, hermanHermitEid, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); display("Reconstructed herman", hermanReconstructed); - + PrismAsserts.assertPropertyValue(hermanReconstructed, UserType.F_TITLE, createPolyString("Hermit")); PrismAsserts.assertPropertyValue(hermanReconstructed, UserType.F_DESCRIPTION, "Hermit on Monkey Island"); PrismAsserts.assertNoItem(hermanReconstructed, UserType.F_NICK_NAME); PrismAsserts.assertPropertyValue(hermanReconstructed, UserType.F_LOCALITY, createPolyString("Monkey Island")); PrismAsserts.assertPropertyValue(hermanReconstructed, UserType.F_HONORIFIC_PREFIX, createPolyString("His Loneliness")); - + assertAssignedRole(hermanReconstructed, ROLE_RED_SAILOR_OID); assertAssignedRole(hermanReconstructed, ROLE_JUDGE_OID); assertAssignments(hermanReconstructed, 2); @@ -542,17 +542,17 @@ private String assertObjectAuditRecords(String oid, int expectedNumberOfRecords) return auditRecords.get(auditRecords.size() - 1).getEventIdentifier(); } - private void assertRecordsFromPrevious(XMLGregorianCalendar from, XMLGregorianCalendar to, + private void assertRecordsFromPrevious(XMLGregorianCalendar from, XMLGregorianCalendar to, int expectedNumberOfRecords) throws SecurityViolationException, SchemaException { List auditRecordsSincePrevious = getAuditRecordsFromTo(from, to); display("From/to records (previous)", auditRecordsSincePrevious); - assertEquals("Wrong number of audit records (previous)", expectedNumberOfRecords, auditRecordsSincePrevious.size()); + assertEquals("Wrong number of audit records (previous)", expectedNumberOfRecords, auditRecordsSincePrevious.size()); } private void assertRecordsFromInitial(XMLGregorianCalendar to, int expectedNumberOfRecords) throws SecurityViolationException, SchemaException { List auditRecordsSincePrevious = getAuditRecordsFromTo(initialTs, to); display("From/to records (initial)", auditRecordsSincePrevious); - assertEquals("Wrong number of audit records (initial)", expectedNumberOfRecords, auditRecordsSincePrevious.size()); + assertEquals("Wrong number of audit records (initial)", expectedNumberOfRecords, auditRecordsSincePrevious.size()); } /** @@ -660,7 +660,7 @@ public void test310ConcurrentAuditsRaw() throws Exception { try { login(userAdministrator); Task threadTask = taskManager.createTaskInstance(TestAudit.class.getName() + "." + TEST_NAME); - OperationResult threadResult = threadTask.getResult(); + OperationResult threadResult = threadTask.getResult(); for (int iteration = 0; iteration < ITERATIONS; iteration++) { display("Executing iteration " + iteration + " in worker " + index); AuditEventRecord record = new AuditEventRecord(AuditEventType.MODIFY_OBJECT, AuditEventStage.EXECUTION); 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 57e4f9d158a..3dc3c7124d3 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 @@ -58,24 +58,24 @@ /** * Test various case ignore and case transformation scenarios. - * + * * @author semancik */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestCaseIgnore extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/caseignore"); - + protected static final String ACCOUNT_JACK_DUMMY_UPCASE_NAME = "JACK"; protected static final String ACCOUNT_GUYBRUSH_DUMMY_UPCASE_NAME = "GUYBRUSH"; - + protected static final File ROLE_X_FILE = new File(TEST_DIR, "role-x.xml"); protected static final String ROLE_X_OID = "ef7edff4-813c-11e4-b893-3c970e467874"; - + protected static final File ROLE_JOKER_FILE = new File(TEST_DIR, "role-joker.xml"); protected static final String ROLE_JOKER_OID = "0a736ff6-9ca8-11e4-b820-001e8c717e5b"; - + protected static final File ROLE_UPCASE_BASIC_FILE = new File(TEST_DIR, "role-upcase-basic.xml"); protected static final String ROLE_UPCASE_BASIC_OID = "008a071a-9cc2-11e4-913d-001e8c717e5b"; @@ -83,39 +83,39 @@ public class TestCaseIgnore extends AbstractInitializedModelIntegrationTest { protected static final String ROLE_FOOL_OID = "97c24f16-e082-11e5-be34-13ace5aaad31"; private static final String GROUP_DUMMY_FOOLS_NAME = "FoOlS"; - + @Autowired(required = true) protected MatchingRuleRegistry matchingRuleRegistry; - + private MatchingRule caseIgnoreMatchingRule; - + private static String accountOid; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); caseIgnoreMatchingRule = matchingRuleRegistry.getMatchingRule(StringIgnoreCaseMatchingRule.NAME, DOMUtil.XSD_STRING); preTestCleanup(AssignmentPolicyEnforcementType.FULL); - + repoAddObjectFromFile(ROLE_X_FILE, initResult); repoAddObjectFromFile(ROLE_JOKER_FILE, initResult); repoAddObjectFromFile(ROLE_UPCASE_BASIC_FILE, initResult); repoAddObjectFromFile(ROLE_FOOL_FILE, initResult); - + InternalMonitor.reset(); InternalMonitor.setTrace(InternalOperationClasses.SHADOW_FETCH_OPERATIONS, false); InternalMonitor.setTrace(InternalOperationClasses.RESOURCE_SCHEMA_OPERATIONS, false); } - + @Test public void test000Sanity() throws Exception { final String TEST_NAME="test000Sanity"; TestUtil.displayTestTitle(this, TEST_NAME); - + assertShadows(5); } - + @Test public void test131ModifyUserJackAssignAccount() throws Exception { final String TEST_NAME="test131ModifyUserJackAssignAccount"; @@ -124,29 +124,29 @@ public void test131ModifyUserJackAssignAccount() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestCaseIgnore.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_UPCASE_OID, null, true); deltas.add(accountAssignmentUserDelta); - + XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); accountOid = getSingleLinkOid(userJack); - + // Check shadow rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); @@ -154,7 +154,7 @@ public void test131ModifyUserJackAssignAccount() throws Exception { assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); assertAccountShadowRepo(accountShadow, accountOid, "jack", resourceDummyUpcaseType, caseIgnoreMatchingRule); assertEnableTimestampShadow(accountShadow, startTime, endTime); - + // Check account rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); @@ -162,12 +162,12 @@ public void test131ModifyUserJackAssignAccount() throws Exception { assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); assertAccountShadowModel(accountModel, accountOid, ACCOUNT_JACK_DUMMY_UPCASE_NAME, resourceDummyUpcaseType, caseIgnoreMatchingRule); assertEnableTimestampShadow(accountModel, startTime, endTime); - + // Check account in dummy resource assertDummyAccount(RESOURCE_DUMMY_UPCASE_NAME, "jack", "Jack Sparrow", true); - + assertShadows(6); - + assertSteadyResources(); } @@ -179,52 +179,52 @@ public void test133SeachAccountShadows() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestCaseIgnore.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_UPCASE_OID, + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_UPCASE_OID, new QName(ResourceTypeUtil.getResourceNamespace(resourceDummyUpcaseType), SchemaConstants.ACCOUNT_OBJECT_CLASS_LOCAL_NAME), prismContext); - rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); + // WHEN TestUtil.displayWhen(TEST_NAME); SearchResultList> foundShadows = modelService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + display("Shadows", foundShadows); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); assertEquals("Wrong number of shadows found", 1, foundShadows.size()); PrismObject foundShadow = foundShadows.get(0); assertAccountShadowModel(foundShadow, accountOid, ACCOUNT_JACK_DUMMY_UPCASE_NAME, resourceDummyUpcaseType, caseIgnoreMatchingRule); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); accountOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Repo shadow", accountShadow); assertAccountShadowRepo(accountShadow, accountOid, ACCOUNT_JACK_DUMMY_UPCASE_NAME, resourceDummyUpcaseType, caseIgnoreMatchingRule); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("Model shadow", accountModel); assertAccountShadowModel(accountModel, accountOid, ACCOUNT_JACK_DUMMY_UPCASE_NAME, resourceDummyUpcaseType, caseIgnoreMatchingRule); - + // Check account in dummy resource assertDummyAccount(RESOURCE_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_UPCASE_NAME, "Jack Sparrow", true); - + assertShadows(6); - + assertSteadyResources(); } - + // TODO: searchGroupShadows - + @Test public void test139ModifyUserJackUnassignAccount() throws Exception { final String TEST_NAME = "test139ModifyUserJackUnassignAccount"; @@ -234,37 +234,37 @@ public void test139ModifyUserJackUnassignAccount() throws Exception { Task task = taskManager.createTaskInstance(TestCaseIgnore.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_UPCASE_OID, null, false); deltas.add(accountAssignmentUserDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userJack = getUser(USER_JACK_OID); assertUserJack(userJack, "Jack Sparrow", "Jack", "Sparrow"); // Check accountRef assertUserNoAccountRefs(userJack); - + // Check is shadow is gone assertNoShadow(accountOid); - + // Check if dummy resource account is gone assertNoDummyAccount(RESOURCE_DUMMY_UPCASE_NAME, "jack"); assertNoDummyAccount(RESOURCE_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_UPCASE_NAME); - + assertShadows(5); - + assertSteadyResources(); } - + @Test public void test150JackAssignRoleX() throws Exception { final String TEST_NAME = "test150JackAssignRoleX"; @@ -272,13 +272,13 @@ public void test150JackAssignRoleX() throws Exception { Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN assignRole(USER_JACK_OID, ROLE_X_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -286,29 +286,29 @@ public void test150JackAssignRoleX() throws Exception { // Make sure this is repository so we do not destroy the "evidence" yet. PrismObject userJack = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); - + display("User after change execution", userJack); assertUserJack(userJack); assertAssignedRole(userJack, ROLE_X_OID); accountOid = getSingleLinkOid(userJack); - + // Check shadow rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Repo shadow", accountShadow); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); assertAccountShadowRepo(accountShadow, accountOid, "X-jack", resourceDummyUpcaseType, caseIgnoreMatchingRule); - + // Check account rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("Model shadow", accountModel); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); assertAccountShadowModel(accountModel, accountOid, "X-"+ACCOUNT_JACK_DUMMY_UPCASE_NAME, resourceDummyUpcaseType, caseIgnoreMatchingRule); - + assertDummyAccount(RESOURCE_DUMMY_UPCASE_NAME, "X-"+ACCOUNT_JACK_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyAccountAttribute(RESOURCE_DUMMY_UPCASE_NAME, "X-"+ACCOUNT_JACK_DUMMY_UPCASE_NAME, "title", "XXX"); - + assertShadows(6); } @@ -319,10 +319,10 @@ public void test152GetJack() throws Exception { Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -333,27 +333,27 @@ public void test152GetJack() throws Exception { assertAssignedRole(userJack, ROLE_X_OID); String accountOidAfter = getSingleLinkOid(userJack); assertEquals("Account OID has changed", accountOid, accountOidAfter); - + // Check shadow rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Repo shadow", accountShadow); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); assertAccountShadowRepo(accountShadow, accountOid, "X-JACK", resourceDummyUpcaseType, caseIgnoreMatchingRule); - + // Check account rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("Model shadow", accountModel); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); assertAccountShadowModel(accountModel, accountOid, "X-JACK", resourceDummyUpcaseType, caseIgnoreMatchingRule); - + assertDummyAccount(RESOURCE_DUMMY_UPCASE_NAME, "X-"+ACCOUNT_JACK_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyAccountAttribute(RESOURCE_DUMMY_UPCASE_NAME, "X-"+ACCOUNT_JACK_DUMMY_UPCASE_NAME, "title", "XXX"); - + assertShadows(6); } - + @Test public void test159JackUnAssignRoleX() throws Exception { final String TEST_NAME = "test159JackUnAssignRoleX"; @@ -361,13 +361,13 @@ public void test159JackUnAssignRoleX() throws Exception { Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN unassignRole(USER_JACK_OID, ROLE_X_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -375,14 +375,14 @@ public void test159JackUnAssignRoleX() throws Exception { // Make sure this is repository so we do not destroy the "evidence" yet. PrismObject userJack = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); - + display("User after change execution", userJack); assertUserJack(userJack); assertNoAssignments(userJack); assertLinks(userJack, 0); - + assertNoDummyAccount(RESOURCE_DUMMY_UPCASE_NAME, "X-"+ACCOUNT_JACK_DUMMY_UPCASE_NAME); - + assertShadows(5); } @@ -393,14 +393,14 @@ public void test160JackAssignRoleBasic() throws Exception { Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_UPCASE_BASIC_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -408,33 +408,33 @@ public void test160JackAssignRoleBasic() throws Exception { // Make sure this is repository so we do not destroy the "evidence" yet. PrismObject userJack = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); - + display("User after change execution", userJack); assertUserJack(userJack); assertAssignedRole(userJack, ROLE_UPCASE_BASIC_OID); accountOid = getSingleLinkOid(userJack); - + // Check shadow rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Repo shadow", accountShadow); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); assertAccountShadowRepo(accountShadow, accountOid, ACCOUNT_JACK_DUMMY_USERNAME, resourceDummyUpcaseType, caseIgnoreMatchingRule); - + // Check account rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("Model shadow", accountModel); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); assertAccountShadowModel(accountModel, accountOid, ACCOUNT_JACK_DUMMY_UPCASE_NAME, resourceDummyUpcaseType, caseIgnoreMatchingRule); - + assertDummyAccount(RESOURCE_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertNoDummyAccountAttribute(RESOURCE_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_UPCASE_NAME, "title"); assertNoDummyGroupMember(RESOURCE_DUMMY_UPCASE_NAME, GROUP_JOKER_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_UPCASE_NAME); - + assertShadows(6); } - + @Test public void test161JackAssignRoleJoker() throws Exception { final String TEST_NAME = "test161JackAssignRoleJoker"; @@ -442,14 +442,14 @@ public void test161JackAssignRoleJoker() throws Exception { Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_JOKER_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -457,37 +457,37 @@ public void test161JackAssignRoleJoker() throws Exception { // Make sure this is repository so we do not destroy the "evidence" yet. PrismObject userJack = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); - + display("User after change execution", userJack); assertUserJack(userJack); assertAssignedRole(userJack, ROLE_JOKER_OID); assertAssignedRole(userJack, ROLE_UPCASE_BASIC_OID); accountOid = getSingleLinkOid(userJack); - + // Check shadow rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); PrismObject accountRepoShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Repo shadow", accountRepoShadow); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); assertAccountShadowRepo(accountRepoShadow, accountOid, ACCOUNT_JACK_DUMMY_UPCASE_NAME, resourceDummyUpcaseType, caseIgnoreMatchingRule); - + // Check account rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); PrismObject accountModelShadow = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("Model shadow", accountModelShadow); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); assertAccountShadowModel(accountModelShadow, accountOid, ACCOUNT_JACK_DUMMY_UPCASE_NAME, resourceDummyUpcaseType, caseIgnoreMatchingRule); - + assertDummyAccount(RESOURCE_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyAccountAttribute(RESOURCE_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_UPCASE_NAME, "title", "JoKeR"); assertDummyGroupMember(RESOURCE_DUMMY_UPCASE_NAME, GROUP_JOKER_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_UPCASE_NAME); - - IntegrationTestTools.assertAssociation(accountModelShadow, RESOURCE_DUMMY_UPCASE_ASSOCIATION_GROUP_QNAME, + + IntegrationTestTools.assertAssociation(accountModelShadow, RESOURCE_DUMMY_UPCASE_ASSOCIATION_GROUP_QNAME, GROUP_SHADOW_JOKER_DUMMY_UPCASE_OID); - + assertShadows(6); } - + @Test public void test165JackUnAssignRoleJoker() throws Exception { final String TEST_NAME = "test165JackUnAssignRoleJoker"; @@ -495,14 +495,14 @@ public void test165JackUnAssignRoleJoker() throws Exception { Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN TestUtil.displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_JOKER_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -510,33 +510,33 @@ public void test165JackUnAssignRoleJoker() throws Exception { // Make sure this is repository so we do not destroy the "evidence" yet. PrismObject userJack = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); - + display("User after change execution", userJack); assertUserJack(userJack); assertAssignedRole(userJack, ROLE_UPCASE_BASIC_OID); accountOid = getSingleLinkOid(userJack); - + // Check shadow rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Repo shadow", accountShadow); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); assertAccountShadowRepo(accountShadow, accountOid, ACCOUNT_JACK_DUMMY_UPCASE_NAME, resourceDummyUpcaseType, caseIgnoreMatchingRule); - + // Check account rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("Model shadow", accountModel); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); assertAccountShadowModel(accountModel, accountOid, ACCOUNT_JACK_DUMMY_UPCASE_NAME, resourceDummyUpcaseType, caseIgnoreMatchingRule); - + assertDummyAccount(RESOURCE_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertNoDummyAccountAttribute(RESOURCE_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_UPCASE_NAME, "title"); assertNoDummyGroupMember(RESOURCE_DUMMY_UPCASE_NAME, GROUP_JOKER_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_UPCASE_NAME); - + assertShadows(6); } - + @Test public void test169JackUnAssignRoleBasic() throws Exception { final String TEST_NAME = "test169JackUnAssignRoleBasic"; @@ -544,14 +544,14 @@ public void test169JackUnAssignRoleBasic() throws Exception { Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN TestUtil.displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_UPCASE_BASIC_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -559,19 +559,19 @@ public void test169JackUnAssignRoleBasic() throws Exception { // Make sure this is repository so we do not destroy the "evidence" yet. PrismObject userJack = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); - + display("User after change execution", userJack); assertUserJack(userJack); assertUserJack(userJack); assertNoAssignments(userJack); assertLinks(userJack, 0); - + assertNoDummyAccount(RESOURCE_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_UPCASE_NAME); assertNoDummyGroupMember(RESOURCE_DUMMY_UPCASE_NAME, GROUP_JOKER_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_UPCASE_NAME); - + assertShadows(5); } - + @Test public void test170JackAssignRoleJoker() throws Exception { final String TEST_NAME = "test170JackAssignRoleJoker"; @@ -579,14 +579,14 @@ public void test170JackAssignRoleJoker() throws Exception { Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_JOKER_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -594,33 +594,33 @@ public void test170JackAssignRoleJoker() throws Exception { // Make sure this is repository so we do not destroy the "evidence" yet. PrismObject userJack = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); - + display("User after change execution", userJack); assertUserJack(userJack); assertAssignedRole(userJack, ROLE_JOKER_OID); accountOid = getSingleLinkOid(userJack); - + // Check shadow rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Repo shadow", accountShadow); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); assertAccountShadowRepo(accountShadow, accountOid, ACCOUNT_JACK_DUMMY_USERNAME, resourceDummyUpcaseType, caseIgnoreMatchingRule); - + // Check account rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("Model shadow", accountModel); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); assertAccountShadowModel(accountModel, accountOid, ACCOUNT_JACK_DUMMY_UPCASE_NAME, resourceDummyUpcaseType, caseIgnoreMatchingRule); - + assertDummyAccount(RESOURCE_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyAccountAttribute(RESOURCE_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_UPCASE_NAME, "title", "JoKeR"); assertDummyGroupMember(RESOURCE_DUMMY_UPCASE_NAME, GROUP_JOKER_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_UPCASE_NAME); - + assertShadows(6); } - + @Test public void test179JackUnAssignRoleJoker() throws Exception { final String TEST_NAME = "test179JackUnAssignRoleJoker"; @@ -628,14 +628,14 @@ public void test179JackUnAssignRoleJoker() throws Exception { Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN TestUtil.displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_JOKER_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -643,21 +643,21 @@ public void test179JackUnAssignRoleJoker() throws Exception { // Make sure this is repository so we do not destroy the "evidence" yet. PrismObject userJack = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); - + display("User after change execution", userJack); assertUserJack(userJack); assertUserJack(userJack); assertNoAssignments(userJack); assertLinks(userJack, 0); - + assertNoDummyAccount(RESOURCE_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_UPCASE_NAME); // MID-2147 assertNoDummyGroupMember(RESOURCE_DUMMY_UPCASE_NAME, GROUP_JOKER_DUMMY_UPCASE_NAME, ACCOUNT_JACK_DUMMY_UPCASE_NAME); - + assertShadows(5); } - - + + /** * Create group no resource in such a way that midpoint does not know about it. * The assign a role that refers to this group by using associationTargetSearch. @@ -672,36 +672,36 @@ public void test200GuybrushAssignRoleFools() throws Exception { Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + assertShadows(5); assertNoDummyAccount(RESOURCE_DUMMY_UPCASE_NAME, ACCOUNT_GUYBRUSH_DUMMY_UPCASE_NAME); - + DummyGroup dummyGroupFools = new DummyGroup(GROUP_DUMMY_FOOLS_NAME); dummyResourceUpcase.addGroup(dummyGroupFools); - + recomputeUser(USER_GUYBRUSH_OID, task, result); - + assertShadows(4); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); - + assertShadows(4); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_FOOL_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); assertShadows(6); - + // Make sure this is repository so we do not destroy the "evidence" yet. PrismObject userAfter = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, result); - + display("User after change execution", userAfter); assertAssignedRole(userAfter, ROLE_FOOL_OID); accountOid = getSingleLinkOid(userAfter); @@ -714,37 +714,37 @@ public void test200GuybrushAssignRoleFools() throws Exception { display("Repo shadow", accountShadow); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); assertAccountShadowRepo(accountShadow, accountOid, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, resourceDummyUpcaseType, caseIgnoreMatchingRule); - + assertShadows(6); - + // Check account rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("Model shadow", accountModel); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); assertAccountShadowModel(accountModel, accountOid, ACCOUNT_GUYBRUSH_DUMMY_UPCASE_NAME, resourceDummyUpcaseType, caseIgnoreMatchingRule); - + // assertShadows(6); - + assertDummyAccount(RESOURCE_DUMMY_UPCASE_NAME, ACCOUNT_GUYBRUSH_DUMMY_UPCASE_NAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); assertDummyAccountAttribute(RESOURCE_DUMMY_UPCASE_NAME, ACCOUNT_GUYBRUSH_DUMMY_UPCASE_NAME, "title", "FOOL!"); assertDummyGroupMember(RESOURCE_DUMMY_UPCASE_NAME, GROUP_DUMMY_FOOLS_NAME, ACCOUNT_GUYBRUSH_DUMMY_UPCASE_NAME); - + assertEquals(1, accountModel.asObjectable().getAssociation().size()); ObjectReferenceType shadowRef = accountModel.asObjectable().getAssociation().get(0).getShadowRef(); PrismObject groupFoolsRepoShadow = repositoryService.getObject(ShadowType.class, shadowRef.getOid(), null, result); display("group fools repo shadow", groupFoolsRepoShadow); - PrismAsserts.assertPropertyValue(groupFoolsRepoShadow, new ItemPath(ShadowType.F_ATTRIBUTES, SchemaConstants.ICFS_NAME), + PrismAsserts.assertPropertyValue(groupFoolsRepoShadow, new ItemPath(ShadowType.F_ATTRIBUTES, SchemaConstants.ICFS_NAME), GROUP_DUMMY_FOOLS_NAME.toLowerCase()); - PrismAsserts.assertPropertyValue(groupFoolsRepoShadow, new ItemPath(ShadowType.F_ATTRIBUTES, SchemaConstants.ICFS_UID), + PrismAsserts.assertPropertyValue(groupFoolsRepoShadow, new ItemPath(ShadowType.F_ATTRIBUTES, SchemaConstants.ICFS_UID), GROUP_DUMMY_FOOLS_NAME.toLowerCase()); assertShadowKindIntent(groupFoolsRepoShadow, ShadowKindType.ENTITLEMENT, INTENT_DUMMY_GROUP); - + assertShadows(6); } - + private void preTestCleanup(AssignmentPolicyEnforcementType enforcementPolicy) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { assumeAssignmentPolicy(enforcementPolicy); dummyAuditService.clear(); @@ -752,5 +752,5 @@ private void preTestCleanup(AssignmentPolicyEnforcementType enforcementPolicy) t purgeProvisioningScriptHistory(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); } - + } 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 b567f831289..220a415ad4c 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 @@ -59,17 +59,17 @@ /** * Test various connector change and usage scenarios with dummy connector and * fake dummy connector. Test upgrades and downgrades of connector version. - * + * * @author semancik * */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestConnectorDummyFake extends AbstractConfiguredModelIntegrationTest { - + private String connectorDummyOid; private String connectorDummyFakeOid; - + private PrismObject resourceDummy; private PrismObject resourceDummyFake; @@ -80,21 +80,21 @@ public class TestConnectorDummyFake extends AbstractConfiguredModelIntegrationTe public void initSystem(Task initTask, OperationResult initResult) throws Exception { // Make sure that the connectors are discovered modelService.postInit(initResult); - + // Make sure to call postInit first. This add system config to repo. // If system is initialized after that then the logging config from system config // will be used instead of test logging config super.initSystem(initTask, initResult); - + dummyResourceCtl = DummyResourceContoller.create(null, resourceDummy); dummyResourceCtl.extendSchemaPirate(); dummyResource = dummyResourceCtl.getDummyResource(); - + dummyResourceCtl.addAccount(ACCOUNT_HERMAN_DUMMY_USERNAME, "Herman Toothrot"); dummyResourceCtl.addAccount(ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood"); dummyResourceCtl.addAccount(ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow"); } - + @Test public void test010ListConnectors() throws Exception { final String TEST_NAME = "test010ListConnectors"; @@ -103,15 +103,15 @@ public void test010ListConnectors() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN List> connectors = modelService.searchObjects(ConnectorType.class, null, null, task, result); - + // THEN display("Connectors", connectors); result.computeStatus(); TestUtil.assertSuccess("getObject result", result); - + assertEquals("Unexpected number of connectors", 8, connectors.size()); for(PrismObject connector: connectors) { display("Connector", connector); @@ -127,12 +127,12 @@ public void test010ListConnectors() throws Exception { } } } - + assertNotNull("No dummy connector", connectorDummyOid); assertNotNull("No fake dummy connector", connectorDummyFakeOid); } - + @Test public void test020ImportFakeResource() throws Exception { final String TEST_NAME = "test020ImportFakeResource"; @@ -141,23 +141,23 @@ public void test020ImportFakeResource() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN importObjectFromFile(RESOURCE_DUMMY_FAKE_FILENAME, result); - + // THEN result.computeStatus(); display("Import result", result); TestUtil.assertSuccess("import result", result, 2); - + resourceDummyFake = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_FAKE_OID, null, task, result); display("Imported resource", resourceDummyFake); assertNotNull("Null fake resource after getObject", resourceDummyFake); - assertEquals("Wrong connectorRef in fake resource", connectorDummyFakeOid, + assertEquals("Wrong connectorRef in fake resource", connectorDummyFakeOid, resourceDummyFake.asObjectable().getConnectorRef().getOid()); } - + @Test public void test021TestFakeResource() throws Exception { final String TEST_NAME = "test021TestFakeResource"; @@ -166,15 +166,15 @@ public void test021TestFakeResource() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN OperationResult testResult = modelService.testResource(RESOURCE_DUMMY_FAKE_OID, task); - + // THEN display("testResource result", testResult); TestUtil.assertSuccess("testResource result", testResult); } - + @Test public void test022ListAccountsFakeResource() throws Exception { final String TEST_NAME = "test022ListAccountsFakeResource"; @@ -183,15 +183,15 @@ public void test022ListAccountsFakeResource() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN Collection> accounts = listAccounts(resourceDummyFake, task, result); - + // THEN result.computeStatus(); display("listAccounts result", result); TestUtil.assertSuccess("listAccounts result", result); - + assertEquals("Unexpected number of accounts: "+accounts, 1, accounts.size()); } @@ -203,23 +203,23 @@ public void test030ImportDummyResource() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN importObjectFromFile(RESOURCE_DUMMY_FILE, result); - + // THEN result.computeStatus(); display("Import result", result); TestUtil.assertSuccess("import result", result, 2); - + resourceDummy = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, task, result); display("Imported resource", resourceDummy); assertNotNull("Null fake resource after getObject", resourceDummy); - assertEquals("Wrong connectorRef in fake resource", connectorDummyOid, + assertEquals("Wrong connectorRef in fake resource", connectorDummyOid, resourceDummy.asObjectable().getConnectorRef().getOid()); } - + @Test public void test031TestDummyResource() throws Exception { final String TEST_NAME = "test031TestDummyResource"; @@ -228,15 +228,15 @@ public void test031TestDummyResource() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN OperationResult testResult = modelService.testResource(RESOURCE_DUMMY_OID, task); - + // THEN display("testResource result", testResult); TestUtil.assertSuccess("testResource result", testResult); } - + @Test public void test032ListAccountsDummyResource() throws Exception { final String TEST_NAME = "test032ListAccountsDummyResource"; @@ -245,18 +245,18 @@ public void test032ListAccountsDummyResource() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN Collection> accounts = listAccounts(resourceDummy, task, result); - + // THEN result.computeStatus(); display("listAccounts result", result); TestUtil.assertSuccess("listAccounts result", result); - + assertEquals("Unexpected number of accounts: "+accounts, 3, accounts.size()); } - + /** * Upgrading connector in RESOURCE_DUMMY_FAKE by changing the connectorRef in resource (add/delete case) * The connectorRef is changed from fake to real dummy. @@ -269,35 +269,35 @@ public void test100UpgradeModelAddDelete() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject dummyResourceModelBefore = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, task, result); - - ObjectDelta resourceDelta = ObjectDelta.createEmptyModifyDelta(ResourceType.class, RESOURCE_DUMMY_FAKE_OID, + + ObjectDelta resourceDelta = ObjectDelta.createEmptyModifyDelta(ResourceType.class, RESOURCE_DUMMY_FAKE_OID, prismContext); PrismReference connectorRef = resourceDummyFake.findReference(ResourceType.F_CONNECTOR_REF); - ReferenceDelta connectorRefDeltaDel = ReferenceDelta.createModificationDelete(ResourceType.F_CONNECTOR_REF, + ReferenceDelta connectorRefDeltaDel = ReferenceDelta.createModificationDelete(ResourceType.F_CONNECTOR_REF, getResourceDefinition(), connectorRef.getValue().clone()); resourceDelta.addModification(connectorRefDeltaDel); - ReferenceDelta connectorRefDeltaAdd = ReferenceDelta.createModificationAdd(ResourceType.F_CONNECTOR_REF, + ReferenceDelta connectorRefDeltaAdd = ReferenceDelta.createModificationAdd(ResourceType.F_CONNECTOR_REF, getResourceDefinition(), connectorDummyOid); resourceDelta.addModification(connectorRefDeltaAdd); // Purge the schema. New connector schema is not compatible. resourceDelta.addModificationReplaceContainer(ResourceType.F_SCHEMA); display("Delta", resourceDelta); Collection> deltas = MiscSchemaUtil.createCollection(resourceDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); display("executeChanges result", result); TestUtil.assertSuccess("executeChanges result", result); - + assertUpgrade(dummyResourceModelBefore); } - - + + @Test public void test150DowngradeModelAddDelete() throws Exception { final String TEST_NAME = "test150DowngradeModelAddDelete"; @@ -306,30 +306,30 @@ public void test150DowngradeModelAddDelete() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject dummyResourceModelBefore = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, task, result); - - ObjectDelta resourceDelta = ObjectDelta.createEmptyModifyDelta(ResourceType.class, RESOURCE_DUMMY_FAKE_OID, + + ObjectDelta resourceDelta = ObjectDelta.createEmptyModifyDelta(ResourceType.class, RESOURCE_DUMMY_FAKE_OID, prismContext); - ReferenceDelta connectorRefDeltaDel = ReferenceDelta.createModificationDelete(ResourceType.F_CONNECTOR_REF, + ReferenceDelta connectorRefDeltaDel = ReferenceDelta.createModificationDelete(ResourceType.F_CONNECTOR_REF, getResourceDefinition(), connectorDummyOid); resourceDelta.addModification(connectorRefDeltaDel); - ReferenceDelta connectorRefDeltaAdd = ReferenceDelta.createModificationAdd(ResourceType.F_CONNECTOR_REF, + ReferenceDelta connectorRefDeltaAdd = ReferenceDelta.createModificationAdd(ResourceType.F_CONNECTOR_REF, getResourceDefinition(), connectorDummyFakeOid); resourceDelta.addModification(connectorRefDeltaAdd); Collection> deltas = MiscSchemaUtil.createCollection(resourceDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); display("executeChanges result", result); TestUtil.assertSuccess("executeChanges result", result); - - assertDowngrade(dummyResourceModelBefore); + + assertDowngrade(dummyResourceModelBefore); } - + @Test public void test200UpgradeModelReplace() throws Exception { final String TEST_NAME = "test200UpgradeModelReplace"; @@ -338,28 +338,28 @@ public void test200UpgradeModelReplace() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject dummyResourceModelBefore = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, task, result); - - ObjectDelta resourceDelta = ObjectDelta.createEmptyModifyDelta(ResourceType.class, RESOURCE_DUMMY_FAKE_OID, + + ObjectDelta resourceDelta = ObjectDelta.createEmptyModifyDelta(ResourceType.class, RESOURCE_DUMMY_FAKE_OID, prismContext); - ReferenceDelta connectorRefDeltaReplace = ReferenceDelta.createModificationReplace(ResourceType.F_CONNECTOR_REF, + ReferenceDelta connectorRefDeltaReplace = ReferenceDelta.createModificationReplace(ResourceType.F_CONNECTOR_REF, getResourceDefinition(), connectorDummyOid); resourceDelta.addModification(connectorRefDeltaReplace); Collection> deltas = MiscSchemaUtil.createCollection(resourceDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); display("executeChanges result", result); TestUtil.assertSuccess("executeChanges result", result); - + assertUpgrade(dummyResourceModelBefore); } - - + + @Test public void test250DowngradeModelReplace() throws Exception { final String TEST_NAME = "test250DowngradeModelReplace"; @@ -368,27 +368,27 @@ public void test250DowngradeModelReplace() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject dummyResourceModelBefore = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, task, result); - - ObjectDelta resourceDelta = ObjectDelta.createEmptyModifyDelta(ResourceType.class, RESOURCE_DUMMY_FAKE_OID, + + ObjectDelta resourceDelta = ObjectDelta.createEmptyModifyDelta(ResourceType.class, RESOURCE_DUMMY_FAKE_OID, prismContext); - ReferenceDelta connectorRefDeltaReplace = ReferenceDelta.createModificationReplace(ResourceType.F_CONNECTOR_REF, + ReferenceDelta connectorRefDeltaReplace = ReferenceDelta.createModificationReplace(ResourceType.F_CONNECTOR_REF, getResourceDefinition(), connectorDummyFakeOid); resourceDelta.addModification(connectorRefDeltaReplace); Collection> deltas = MiscSchemaUtil.createCollection(resourceDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); display("executeChanges result", result); TestUtil.assertSuccess("executeChanges result", result); - - assertDowngrade(dummyResourceModelBefore); + + assertDowngrade(dummyResourceModelBefore); } - + @Test public void test300UpgradeRawAddDelete() throws Exception { final String TEST_NAME = "test300UpgradeRawAddDelete"; @@ -397,33 +397,33 @@ public void test300UpgradeRawAddDelete() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject dummyResourceModelBefore = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, task, result); - - ObjectDelta resourceDelta = ObjectDelta.createEmptyModifyDelta(ResourceType.class, RESOURCE_DUMMY_FAKE_OID, + + ObjectDelta resourceDelta = ObjectDelta.createEmptyModifyDelta(ResourceType.class, RESOURCE_DUMMY_FAKE_OID, prismContext); - ReferenceDelta connectorRefDeltaDel = ReferenceDelta.createModificationDelete(ResourceType.F_CONNECTOR_REF, + ReferenceDelta connectorRefDeltaDel = ReferenceDelta.createModificationDelete(ResourceType.F_CONNECTOR_REF, getResourceDefinition(), connectorDummyFakeOid); resourceDelta.addModification(connectorRefDeltaDel); - ReferenceDelta connectorRefDeltaAdd = ReferenceDelta.createModificationAdd(ResourceType.F_CONNECTOR_REF, + ReferenceDelta connectorRefDeltaAdd = ReferenceDelta.createModificationAdd(ResourceType.F_CONNECTOR_REF, getResourceDefinition(), connectorDummyOid); resourceDelta.addModification(connectorRefDeltaAdd); Collection> deltas = MiscSchemaUtil.createCollection(resourceDelta); - + ModelExecuteOptions options = ModelExecuteOptions.createRaw(); - + // WHEN modelService.executeChanges(deltas, options, task, result); - + // THEN result.computeStatus(); display("executeChanges result", result); TestUtil.assertSuccess("executeChanges result", result); - + assertUpgrade(dummyResourceModelBefore); } - - + + @Test public void test350DowngradeRawAddDelete() throws Exception { final String TEST_NAME = "test350DowngradeRawAddDelete"; @@ -432,32 +432,32 @@ public void test350DowngradeRawAddDelete() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject dummyResourceModelBefore = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, task, result); - - ObjectDelta resourceDelta = ObjectDelta.createEmptyModifyDelta(ResourceType.class, RESOURCE_DUMMY_FAKE_OID, + + ObjectDelta resourceDelta = ObjectDelta.createEmptyModifyDelta(ResourceType.class, RESOURCE_DUMMY_FAKE_OID, prismContext); - ReferenceDelta connectorRefDeltaDel = ReferenceDelta.createModificationDelete(ResourceType.F_CONNECTOR_REF, + ReferenceDelta connectorRefDeltaDel = ReferenceDelta.createModificationDelete(ResourceType.F_CONNECTOR_REF, getResourceDefinition(), connectorDummyOid); resourceDelta.addModification(connectorRefDeltaDel); - ReferenceDelta connectorRefDeltaAdd = ReferenceDelta.createModificationAdd(ResourceType.F_CONNECTOR_REF, + ReferenceDelta connectorRefDeltaAdd = ReferenceDelta.createModificationAdd(ResourceType.F_CONNECTOR_REF, getResourceDefinition(), connectorDummyFakeOid); resourceDelta.addModification(connectorRefDeltaAdd); Collection> deltas = MiscSchemaUtil.createCollection(resourceDelta); - + ModelExecuteOptions options = ModelExecuteOptions.createRaw(); - + // WHEN modelService.executeChanges(deltas, options, task, result); - + // THEN result.computeStatus(); display("executeChanges result", result); TestUtil.assertSuccess("executeChanges result", result); - - assertDowngrade(dummyResourceModelBefore); + + assertDowngrade(dummyResourceModelBefore); } - + @Test public void test400UpgradeRawReplace() throws Exception { final String TEST_NAME = "test400UpgradeRawReplace"; @@ -466,30 +466,30 @@ public void test400UpgradeRawReplace() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject dummyResourceModelBefore = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, task, result); - - ObjectDelta resourceDelta = ObjectDelta.createEmptyModifyDelta(ResourceType.class, RESOURCE_DUMMY_FAKE_OID, + + ObjectDelta resourceDelta = ObjectDelta.createEmptyModifyDelta(ResourceType.class, RESOURCE_DUMMY_FAKE_OID, prismContext); - ReferenceDelta connectorRefDeltaReplace = ReferenceDelta.createModificationReplace(ResourceType.F_CONNECTOR_REF, + ReferenceDelta connectorRefDeltaReplace = ReferenceDelta.createModificationReplace(ResourceType.F_CONNECTOR_REF, getResourceDefinition(), connectorDummyOid); resourceDelta.addModification(connectorRefDeltaReplace); Collection> deltas = MiscSchemaUtil.createCollection(resourceDelta); - + ModelExecuteOptions options = ModelExecuteOptions.createRaw(); - + // WHEN modelService.executeChanges(deltas, options, task, result); - + // THEN result.computeStatus(); display("executeChanges result", result); TestUtil.assertSuccess("executeChanges result", result); - + assertUpgrade(dummyResourceModelBefore); } - - + + @Test public void test450DowngradeRawReplace() throws Exception { final String TEST_NAME = "test450DowngradeRawReplace"; @@ -498,41 +498,41 @@ public void test450DowngradeRawReplace() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject dummyResourceModelBefore = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, task, result); - - ObjectDelta resourceDelta = ObjectDelta.createEmptyModifyDelta(ResourceType.class, RESOURCE_DUMMY_FAKE_OID, + + ObjectDelta resourceDelta = ObjectDelta.createEmptyModifyDelta(ResourceType.class, RESOURCE_DUMMY_FAKE_OID, prismContext); - ReferenceDelta connectorRefDeltaReplace = ReferenceDelta.createModificationReplace(ResourceType.F_CONNECTOR_REF, + ReferenceDelta connectorRefDeltaReplace = ReferenceDelta.createModificationReplace(ResourceType.F_CONNECTOR_REF, getResourceDefinition(), connectorDummyFakeOid); resourceDelta.addModification(connectorRefDeltaReplace); Collection> deltas = MiscSchemaUtil.createCollection(resourceDelta); - + ModelExecuteOptions options = ModelExecuteOptions.createRaw(); - + // WHEN modelService.executeChanges(deltas, options, task, result); - + // THEN result.computeStatus(); display("executeChanges result", result); TestUtil.assertSuccess("executeChanges result", result); - - assertDowngrade(dummyResourceModelBefore); + + assertDowngrade(dummyResourceModelBefore); } private void assertUpgrade(PrismObject dummyResourceModelBefore) throws ObjectNotFoundException, SchemaException, SecurityViolationException, ObjectAlreadyExistsException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException { Task task = taskManager.createTaskInstance(TestConnectorDummyFake.class.getName() + ".assertUpgrade"); OperationResult result = task.getResult(); - + // Check if the changes went well in the repo PrismObject repoResource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_FAKE_OID, null, result); display("Upgraded fake resource (repo)", repoResource); assertNotNull("Null fake resource after getObject (repo)", repoResource); assertEquals("Oooops. The OID of fake resource mysteriously changed. Call the police! (repo)", RESOURCE_DUMMY_FAKE_OID, repoResource.getOid()); - assertEquals("Wrong connectorRef in fake resource (repo)", connectorDummyOid, + assertEquals("Wrong connectorRef in fake resource (repo)", connectorDummyOid, repoResource.asObjectable().getConnectorRef().getOid()); - + // 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); @@ -540,9 +540,9 @@ private void assertUpgrade(PrismObject dummyResourceModelBefore) t display("Upgraded fake resource schema (model)", DOMUtil.serializeDOMToString(resourceDummyFakeSchemaElement)); assertNotNull("Null fake resource after getObject (model)", resourceDummyFake); assertEquals("Oooops. The OID of fake resource mysteriously changed. Call the police! (model)", RESOURCE_DUMMY_FAKE_OID, resourceDummyFake.getOid()); - assertEquals("Wrong connectorRef in fake resource (model)", connectorDummyOid, + assertEquals("Wrong connectorRef in fake resource (model)", connectorDummyOid, resourceDummyFake.asObjectable().getConnectorRef().getOid()); - + // Check if the other resource is still untouched PrismObject dummyResourceModelAfter = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, task, result); dummyResourceModelBefore.asObjectable().setFetchResult(null); @@ -550,7 +550,7 @@ private void assertUpgrade(PrismObject dummyResourceModelBefore) t 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()); - + testResources(3,3); } @@ -562,17 +562,17 @@ private void assertDowngrade(PrismObject dummyResourceModelBefore) display("Upgraded fake resource (repo)", repoResource); assertNotNull("Null fake resource after getObject (repo)", repoResource); assertEquals("Oooops. The OID of fake resource mysteriously changed. Call the police! (repo)", RESOURCE_DUMMY_FAKE_OID, repoResource.getOid()); - assertEquals("Wrong connectorRef in fake resource (repo)", connectorDummyFakeOid, + assertEquals("Wrong connectorRef in fake resource (repo)", connectorDummyFakeOid, repoResource.asObjectable().getConnectorRef().getOid()); - + // 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); assertNotNull("Null fake resource after getObject (model)", resourceDummyFake); assertEquals("Oooops. The OID of fake resource mysteriously changed. Call the police! (model)", RESOURCE_DUMMY_FAKE_OID, resourceDummyFake.getOid()); - assertEquals("Wrong connectorRef in fake resource (model)", connectorDummyFakeOid, + assertEquals("Wrong connectorRef in fake resource (model)", connectorDummyFakeOid, resourceDummyFake.asObjectable().getConnectorRef().getOid()); - + // Check if the other resource is still untouched PrismObject dummyResourceModelAfter = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, task, result); dummyResourceModelBefore.asObjectable().setFetchResult(null); @@ -580,43 +580,43 @@ private void assertDowngrade(PrismObject dummyResourceModelBefore) 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()); - + testResources(3,1); } private void testResources(int numDummyAccounts, int numFakeAccounts) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { Task task = taskManager.createTaskInstance(TestConnectorDummyFake.class.getName() + ".testResources"); - + // We have to purge fake resource schema here. As the new connector provides a different schema purgeResourceSchema(RESOURCE_DUMMY_FAKE_OID); - + OperationResult testResult = modelService.testResource(RESOURCE_DUMMY_FAKE_OID, task); display("testResource fake result", testResult); TestUtil.assertSuccess("testResource fake result", testResult); - + testResult = modelService.testResource(RESOURCE_DUMMY_OID, task); display("testResource dummy result", testResult); TestUtil.assertSuccess("testResource dummy result", testResult); - + assertResourceAccounts(resourceDummy, numDummyAccounts); assertResourceAccounts(resourceDummyFake, numFakeAccounts); } - + private void assertResourceAccounts(PrismObject resource, int numAccounts) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { Task task = taskManager.createTaskInstance(TestConnectorDummyFake.class.getName() + ".assertResourceAccounts"); OperationResult result = task.getResult(); - + // WHEN Collection> accounts = listAccounts(resource, task, result); - + // THEN result.computeStatus(); display("listAccounts result "+resource, result); TestUtil.assertSuccess("listAccounts result "+resource, result); - + 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/TestConnectorMultiInstance.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConnectorMultiInstance.java index 306a9857e81..f98bcec3dd5 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConnectorMultiInstance.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConnectorMultiInstance.java @@ -51,58 +51,58 @@ /** * Test behavior of connectors that have several instances (poolable connectors). - * + * * @author semancik * */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestConnectorMultiInstance extends AbstractConfiguredModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/multi"); private static Trace LOGGER = TraceManager.getTrace(TestConnectorMultiInstance.class); - + protected DummyResource dummyResourceYellow; protected DummyResourceContoller dummyResourceCtlYellow; - + private String accountJackYellowOid; private String initialConnectorStaticVal; private String initialConnectorToString; private String accountGuybrushBlackOid; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + dummyResourceCtlYellow = initDummyResourcePirate(RESOURCE_DUMMY_YELLOW_NAME, RESOURCE_DUMMY_YELLOW_FILE, RESOURCE_DUMMY_YELLOW_OID, initTask, initResult); dummyResourceYellow = dummyResourceCtlYellow.getDummyResource(); - + initDummyResourcePirate(RESOURCE_DUMMY_BLACK_NAME, RESOURCE_DUMMY_BLACK_FILE, RESOURCE_DUMMY_BLACK_OID, initTask, initResult); - + repoAddObjectFromFile(SECURITY_POLICY_FILE, initResult); repoAddObjectFromFile(PASSWORD_POLICY_BENEVOLENT_FILE, initResult); - + repoAddObjectFromFile(USER_JACK_FILE, true, initResult); repoAddObjectFromFile(USER_GUYBRUSH_FILE, true, initResult); repoAddObjectFromFile(USER_ELAINE_FILE, true, initResult); } - + @Test public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); - + // WHEN OperationResult testResult = modelService.testResource(RESOURCE_DUMMY_YELLOW_OID, task); - + // THEN display("Test result", testResult); TestUtil.assertSuccess("Yellow dummy test result", testResult); - + assertEquals("Wrong YELLOW useless string", IntegrationTestTools.CONST_USELESS, dummyResourceYellow.getUselessString()); } @@ -110,31 +110,31 @@ public void test000Sanity() throws Exception { public void test100JackAssignDummyYellow() throws Exception { final String TEST_NAME = "test100JackAssignDummyYellow"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignAccount(USER_JACK_OID, RESOURCE_DUMMY_YELLOW_OID, null, task, result); - + // THEN assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); accountJackYellowOid = getSingleLinkOid(userJack); - + assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - + PrismObject shadowYellow = getShadowModel(accountJackYellowOid); display("Shadow yellow", shadowYellow); - + assertConnectorInstances("yellow", RESOURCE_DUMMY_YELLOW_OID, 0, 1); - + initialConnectorToString = getConnectorToString(shadowYellow, dummyResourceCtlYellow); initialConnectorStaticVal = getConnectorStaticVal(shadowYellow, dummyResourceCtlYellow); } - + /** * This is sequential operation. Same connector instance should be reused. */ @@ -142,21 +142,21 @@ public void test100JackAssignDummyYellow() throws Exception { public void test102ReadJackDummyYellowAgain() throws Exception { final String TEST_NAME = "test102ReadJackDummyYellowAgain"; displayTestTitle(TEST_NAME); - + // WHEN PrismObject shadowYellow = getShadowModel(accountJackYellowOid); - + // THEN display("Shadow yellow", shadowYellow); - + assertConnectorInstances("yellow", RESOURCE_DUMMY_YELLOW_OID, 0, 1); - + assertConnectorToString(shadowYellow, dummyResourceCtlYellow, initialConnectorToString); assertConnectorStaticVal(shadowYellow, dummyResourceCtlYellow, initialConnectorStaticVal); - + assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); } - + /** * Block the operation during read. Just to make sure that the stats for active * connector instances work. @@ -165,43 +165,43 @@ public void test102ReadJackDummyYellowAgain() throws Exception { public void test110ReadJackDummyYellowBlocking() throws Exception { final String TEST_NAME = "test110ReadJackDummyYellowBlocking"; displayTestTitle(TEST_NAME); - + dummyResourceYellow.setBlockOperations(true); - final Holder> shadowHolder = new Holder<>(); - + final Holder> shadowHolder = new Holder<>(); + // WHEN Thread t = executeInNewThread("get1", () -> { PrismObject shadow = getShadowModel(accountJackYellowOid); LOGGER.trace("Got shadow {}", shadow); shadowHolder.setValue(shadow); }); - + // Give the new thread a chance to get blocked Thread.sleep(200); assertConnectorInstances("yellow (blocked)", RESOURCE_DUMMY_YELLOW_OID, 1, 0); - + assertNull("Unexpected shadow", shadowHolder.getValue()); - + dummyResourceYellow.unblock(); - + // THEN t.join(); - + dummyResourceYellow.setBlockOperations(false); - + PrismObject shadowYellow = shadowHolder.getValue(); assertNotNull("No shadow", shadowHolder.getValue()); - + display("Shadow yellow", shadowYellow); - + assertConnectorInstances("yellow", RESOURCE_DUMMY_YELLOW_OID, 0, 1); - + assertConnectorToString(shadowYellow, dummyResourceCtlYellow, initialConnectorToString); assertConnectorStaticVal(shadowYellow, dummyResourceCtlYellow, initialConnectorStaticVal); - + assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); } - + /** * Block one read operation and let go the other. Make sure that new connector instance is created * for the second operation and that it goes smoothly. @@ -210,29 +210,29 @@ public void test110ReadJackDummyYellowBlocking() throws Exception { public void test120ReadJackDummyYellowTwoOperationsOneBlocking() throws Exception { final String TEST_NAME = "test120ReadJackDummyYellowTwoOperationsOneBlocking"; displayTestTitle(TEST_NAME); - + dummyResourceYellow.setBlockOperations(true); - final Holder> shadowHolder1 = new Holder<>(); + final Holder> shadowHolder1 = new Holder<>(); final Holder> shadowHolder2 = new Holder<>(); - + // WHEN Thread t1 = executeInNewThread("get1", () -> { PrismObject shadow = getShadowModel(accountJackYellowOid); LOGGER.trace("Got shadow {}", shadow); shadowHolder1.setValue(shadow); }); - + // Give the new thread a chance to get blocked Thread.sleep(200); - + assertConnectorInstances("yellow (blocked)", RESOURCE_DUMMY_YELLOW_OID, 1, 0); assertNull("Unexpected shadow 1", shadowHolder1.getValue()); - + dummyResourceYellow.setBlockOperations(false); - + // This should not be blocked and it should proceed immediately - + Thread t2 = executeInNewThread("get2", () -> { PrismObject shadow = getShadowModel(accountJackYellowOid); LOGGER.trace("Got shadow {}", shadow); @@ -242,34 +242,34 @@ public void test120ReadJackDummyYellowTwoOperationsOneBlocking() throws Exceptio t2.join(1000); assertConnectorInstances("yellow (blocked)", RESOURCE_DUMMY_YELLOW_OID, 1, 1); - + assertNull("Unexpected shadow 1", shadowHolder1.getValue()); - + dummyResourceYellow.unblock(); - + t1.join(); - + // THEN - + PrismObject shadowYellow1 = shadowHolder1.getValue(); assertNotNull("No shadow 1", shadowHolder1.getValue()); display("Shadow yellow 1", shadowYellow1); - + PrismObject shadowYellow2 = shadowHolder2.getValue(); assertNotNull("No shadow 2", shadowHolder2.getValue()); display("Shadow yellow 2", shadowYellow2); - + assertConnectorInstances("yellow", RESOURCE_DUMMY_YELLOW_OID, 0, 2); - + assertConnectorToString(shadowYellow1, dummyResourceCtlYellow, initialConnectorToString); assertConnectorStaticVal(shadowYellow1, dummyResourceCtlYellow, initialConnectorStaticVal); - + assertConnectorToStringDifferent(shadowYellow2, dummyResourceCtlYellow, initialConnectorToString); assertConnectorStaticVal(shadowYellow2, dummyResourceCtlYellow, initialConnectorStaticVal); - + assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); } - + /** * Block two read operations. Make sure that new connector instance is created. */ @@ -277,18 +277,18 @@ public void test120ReadJackDummyYellowTwoOperationsOneBlocking() throws Exceptio public void test125ReadJackDummyYellowTwoBlocking() throws Exception { final String TEST_NAME = "test125ReadJackDummyYellowTwoBlocking"; displayTestTitle(TEST_NAME); - + dummyResourceYellow.setBlockOperations(true); - final Holder> shadowHolder1 = new Holder<>(); + final Holder> shadowHolder1 = new Holder<>(); final Holder> shadowHolder2 = new Holder<>(); - + // WHEN Thread t1 = executeInNewThread("get1", () -> { PrismObject shadow = getShadowModel(accountJackYellowOid); LOGGER.trace("Got shadow {}", shadow); shadowHolder1.setValue(shadow); }); - + Thread t2 = executeInNewThread("get2", new FailableRunnable() { @Override public void run() throws Exception { @@ -297,66 +297,66 @@ public void run() throws Exception { shadowHolder2.setValue(shadow); } }); - + // Give the new threads a chance to get blocked Thread.sleep(500); assertConnectorInstances("yellow (blocked)", RESOURCE_DUMMY_YELLOW_OID, 2, 0); - + assertNull("Unexpected shadow 1", shadowHolder1.getValue()); assertNull("Unexpected shadow 2", shadowHolder2.getValue()); - + dummyResourceYellow.unblockAll(); - + t1.join(); t2.join(); - + // THEN dummyResourceYellow.setBlockOperations(false); - + PrismObject shadowYellow1 = shadowHolder1.getValue(); assertNotNull("No shadow 1", shadowHolder1.getValue()); display("Shadow yellow 1", shadowYellow1); - + PrismObject shadowYellow2 = shadowHolder2.getValue(); assertNotNull("No shadow 2", shadowHolder2.getValue()); display("Shadow yellow 2", shadowYellow2); - + assertConnectorInstances("yellow", RESOURCE_DUMMY_YELLOW_OID, 0, 2); - + assertConnectorToStringDifferent(shadowYellow2, dummyResourceCtlYellow, getConnectorToString(shadowYellow1, dummyResourceCtlYellow)); assertConnectorStaticVal(shadowYellow1, dummyResourceCtlYellow, initialConnectorStaticVal); assertConnectorStaticVal(shadowYellow2, dummyResourceCtlYellow, initialConnectorStaticVal); - + assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); } - + @Test public void test200GuybrushAssignDummyBlack() throws Exception { final String TEST_NAME = "test200GuybrushAssignDummyBlack"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignAccount(USER_GUYBRUSH_OID, RESOURCE_DUMMY_BLACK_OID, null, task, result); - + // THEN assertSuccess(result); - + PrismObject userJack = getUser(USER_GUYBRUSH_OID); accountGuybrushBlackOid = getSingleLinkOid(userJack); - + assertDummyAccount(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); - + PrismObject shadowBlack = getShadowModel(accountGuybrushBlackOid); display("Shadow black", shadowBlack); - + assertConnectorInstances("black", RESOURCE_DUMMY_BLACK_OID, 0, 1); assertConnectorInstances("yellow", RESOURCE_DUMMY_YELLOW_OID, 0, 2); - + assertConnectorToStringDifferent(shadowBlack, getDummyResourceController(RESOURCE_DUMMY_BLACK_NAME), initialConnectorStaticVal); assertConnectorToStringDifferent(shadowBlack, getDummyResourceController(RESOURCE_DUMMY_BLACK_NAME), initialConnectorToString); assertConnectorStaticVal(shadowBlack, getDummyResourceController(RESOURCE_DUMMY_BLACK_NAME), initialConnectorStaticVal); @@ -376,27 +376,27 @@ private Thread executeInNewThread(final String threadName, final FailableRunnabl t.start(); return t; } - + private String getConnectorToString(PrismObject shadow, DummyResourceContoller ctl) throws SchemaException { return ShadowUtil.getAttributeValue(shadow, ctl.getAttributeQName(DummyResource.ATTRIBUTE_CONNECTOR_TO_STRING)); } - + private String getConnectorStaticVal(PrismObject shadow, DummyResourceContoller ctl) throws SchemaException { return ShadowUtil.getAttributeValue(shadow, ctl.getAttributeQName(DummyResource.ATTRIBUTE_CONNECTOR_STATIC_VAL)); } - + private void assertConnectorToString(PrismObject shadow, DummyResourceContoller ctl, String expectedVal) throws SchemaException { String connectorVal = ShadowUtil.getAttributeValue(shadow, ctl.getAttributeQName(DummyResource.ATTRIBUTE_CONNECTOR_TO_STRING)); assertEquals("Connector toString mismatch", expectedVal, connectorVal); } - + private void assertConnectorToStringDifferent(PrismObject shadow, DummyResourceContoller ctl, String expectedVal) throws SchemaException { String connectorVal = getConnectorToString(shadow, ctl); assertFalse("Unexpected Connector toString, expected a different value: "+connectorVal, expectedVal.equals(connectorVal)); } - + private void assertConnectorStaticVal(PrismObject shadow, DummyResourceContoller ctl, String expectedVal) throws SchemaException { String connectorStaticVal = getConnectorStaticVal(shadow, ctl); @@ -410,10 +410,10 @@ private void assertConnectorInstances(String msg, String resourceOid, int expect display("connector stats "+msg, opStats); assertConnectorInstances(msg, opStats.get(0), expectedActive, expectedIdle); } - + private void assertConnectorInstances(String msg, ConnectorOperationalStatus opStats, int expectedActive, int expectedIdle) { assertEquals(msg+" unexpected number of active connector instances", (Integer)expectedActive, opStats.getPoolStatusNumActive()); assertEquals(msg+" unexpected number of idle connector instances", (Integer)expectedIdle, opStats.getPoolStatusNumIdle()); } - + } 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 176058a7083..5669da28377 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 @@ -60,11 +60,11 @@ public class TestConsistencySimple extends AbstractInitializedModelIntegrationTest { private static final boolean ASSERT_SUCCESS = true; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + login(USER_ADMINISTRATOR_USERNAME); } 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 6116db87486..87909e3b786 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 @@ -51,34 +51,34 @@ /** * Test for deputy (delegation) mechanism. - * + * * MID-3472 - * + * * @author Radovan Semancik * */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestDeputy extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/deputy"); - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); } - + @Test public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; TestUtil.displayTestTitle(this, TEST_NAME); - + PrismObject userJack = getUser(USER_JACK_OID); display("User Jack", userJack); assertNoAssignments(userJack); assertLinks(userJack, 0); assertNoAuthorizations(userJack); - + PrismObject userBarbossa = getUser(USER_BARBOSSA_OID); display("User Barbossa", userBarbossa); assertNoAssignments(userBarbossa); @@ -94,35 +94,35 @@ public void test000Sanity() throws Exception { public void test100AssignDeputyNoBigDeal() throws Exception { final String TEST_NAME = "test100AssignDeputyNoBigDeal"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + assignDeputy(USER_BARBOSSA_OID, USER_JACK_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertAssignedDeputy(userBarbossaAfter, USER_JACK_OID); assertAssignments(userBarbossaAfter, 1); assertLinks(userBarbossaAfter, 0); assertNoAuthorizations(userBarbossaAfter); - + PrismObject userJackAfter = getUser(USER_JACK_OID); display("User Jack after", userJackAfter); assertNoAssignments(userJackAfter); assertLinks(userJackAfter, 0); assertNoAuthorizations(userJackAfter); - + } - + /** * Jack and Barbossa does not have any accounts or roles. * Unassign Barbossa as Jack's deputy. Not much should happen. @@ -131,34 +131,34 @@ public void test100AssignDeputyNoBigDeal() throws Exception { public void test109UnassignDeputyNoBigDeal() throws Exception { final String TEST_NAME = "test109UnassignDeputyNoBigDeal"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + unassignDeputy(USER_BARBOSSA_OID, USER_JACK_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); - display("User Barbossa after", userBarbossaAfter); + display("User Barbossa after", userBarbossaAfter); assertNoAssignments(userBarbossaAfter); assertLinks(userBarbossaAfter, 0); assertNoAuthorizations(userBarbossaAfter); - + PrismObject userJackAfter = getUser(USER_JACK_OID); display("User Jack after", userJackAfter); assertNoAssignments(userJackAfter); assertLinks(userJackAfter, 0); assertNoAuthorizations(userJackAfter); - + } - + /** * Still not much here. Just preparing Jack. * Make sure that Barbossa is not affected though. @@ -167,20 +167,20 @@ public void test109UnassignDeputyNoBigDeal() throws Exception { public void test110AssignJackPirate() throws Exception { final String TEST_NAME = "test110AssignJackPirate"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + assignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJackAfter = getUser(USER_JACK_OID); display("User Jack after", userJackAfter); assertAssignedRole(userJackAfter, ROLE_PIRATE_OID); @@ -188,15 +188,15 @@ public void test110AssignJackPirate() throws Exception { assertAccount(userJackAfter, RESOURCE_DUMMY_OID); assertLinks(userJackAfter, 1); assertAuthorizations(userJackAfter, AUTZ_LOOT_URL); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertNoAssignments(userBarbossaAfter); assertLinks(userBarbossaAfter, 0); - assertNoAuthorizations(userBarbossaAfter); - + assertNoAuthorizations(userBarbossaAfter); + } - + /** * Assign Barbossa as Jack's deputy. Barbossa should get equivalent * accounts and authorizations as Jack. @@ -205,20 +205,20 @@ public void test110AssignJackPirate() throws Exception { public void test112AssignDeputyPirate() throws Exception { final String TEST_NAME = "test112AssignDeputyPirate"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + assignDeputy(USER_BARBOSSA_OID, USER_JACK_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertAssignedDeputy(userBarbossaAfter, USER_JACK_OID); @@ -227,7 +227,7 @@ public void test112AssignDeputyPirate() throws Exception { assertAccount(userBarbossaAfter, RESOURCE_DUMMY_OID); assertLinks(userBarbossaAfter, 1); assertAuthorizations(userBarbossaAfter, AUTZ_LOOT_URL); - + PrismObject userJackAfter = getUser(USER_JACK_OID); display("User Jack after", userJackAfter); assertAssignedRole(userJackAfter, ROLE_PIRATE_OID); @@ -235,39 +235,39 @@ public void test112AssignDeputyPirate() throws Exception { assertAccount(userJackAfter, RESOURCE_DUMMY_OID); assertLinks(userJackAfter, 1); assertAuthorizations(userJackAfter, AUTZ_LOOT_URL); - + } - + // TODO: recompute barbossa, recompute jack - + /** - * Unassign Barbossa as Jack's deputy. Barbossa should get + * Unassign Barbossa as Jack's deputy. Barbossa should get * back to emptiness. */ @Test public void test119UnassignDeputyPirate() throws Exception { final String TEST_NAME = "test119UnassignDeputyPirate"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + unassignDeputy(USER_BARBOSSA_OID, USER_JACK_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); - display("User Barbossa after", userBarbossaAfter); + display("User Barbossa after", userBarbossaAfter); assertNoAssignments(userBarbossaAfter); assertLinks(userBarbossaAfter, 0); assertNoAuthorizations(userBarbossaAfter); - + PrismObject userJackAfter = getUser(USER_JACK_OID); display("User Jack after", userJackAfter); assertAssignedRole(userJackAfter, ROLE_PIRATE_OID); @@ -275,9 +275,9 @@ public void test119UnassignDeputyPirate() throws Exception { assertAccount(userJackAfter, RESOURCE_DUMMY_OID); assertLinks(userJackAfter, 1); assertAuthorizations(userJackAfter, AUTZ_LOOT_URL); - + } - + /** * Guybrush and Barbossa does not have any accounts or roles. Yet. * Assign Barbossa as Guybrush's deputy. Not much should happen. @@ -286,42 +286,42 @@ public void test119UnassignDeputyPirate() throws Exception { public void test120AssignbarbossaDeputyOfGuybrush() throws Exception { final String TEST_NAME = "test120AssignbarbossaDeputyOfGuybrush"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userGuybrushBefore = getUser(USER_GUYBRUSH_OID); display("User Guybrush before", userGuybrushBefore); assertLinks(userGuybrushBefore, 1); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + assignDeputy(USER_BARBOSSA_OID, USER_GUYBRUSH_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertAssignedDeputy(userBarbossaAfter, USER_GUYBRUSH_OID); assertAssignments(userBarbossaAfter, 1); assertLinks(userBarbossaAfter, 0); assertNoAuthorizations(userBarbossaAfter); - + PrismObject userGuybrushAfter = getUser(USER_GUYBRUSH_OID); display("User Guybrush after", userGuybrushAfter); assertNoAssignments(userGuybrushAfter); assertLinks(userGuybrushAfter, 1); assertNoAuthorizations(userGuybrushAfter); - + } - + /** * Assign Guybrush pirate role. Barbossa is Guybrushe's deputy, - * but Barbossa should be only partially affected yet. + * but Barbossa should be only partially affected yet. * Barbossa should not have the accounts, but he should have the * authorization. Barbossa will be completely affected after recompute. */ @@ -329,20 +329,20 @@ public void test120AssignbarbossaDeputyOfGuybrush() throws Exception { public void test122AssignGuybrushPirate() throws Exception { final String TEST_NAME = "test122AssignGuybrushPirate"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + assignRole(USER_GUYBRUSH_OID, ROLE_PIRATE_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userGuybrushAfter = getUser(USER_GUYBRUSH_OID); display("User Guybrush after", userGuybrushAfter); assertAssignedRole(userGuybrushAfter, ROLE_PIRATE_OID); @@ -350,16 +350,16 @@ public void test122AssignGuybrushPirate() throws Exception { assertAccount(userGuybrushAfter, RESOURCE_DUMMY_OID); assertLinks(userGuybrushAfter, 1); assertAuthorizations(userGuybrushAfter, AUTZ_LOOT_URL); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertAssignedDeputy(userBarbossaAfter, USER_GUYBRUSH_OID); assertAssignments(userBarbossaAfter, 1); assertLinks(userBarbossaAfter, 0); assertAuthorizations(userBarbossaAfter, AUTZ_LOOT_URL); - + } - + /** * Recompute Barbossa. Barbossa should get the deputy rights * from Guybrush after recompute. @@ -368,20 +368,20 @@ public void test122AssignGuybrushPirate() throws Exception { public void test124RecomputeBarbossa() throws Exception { final String TEST_NAME = "test124RecomputeBarbossa"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + recomputeUser(USER_BARBOSSA_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertAssignedDeputy(userBarbossaAfter, USER_GUYBRUSH_OID); @@ -390,7 +390,7 @@ public void test124RecomputeBarbossa() throws Exception { assertAccount(userBarbossaAfter, RESOURCE_DUMMY_OID); assertLinks(userBarbossaAfter, 1); assertAuthorizations(userBarbossaAfter, AUTZ_LOOT_URL); - + PrismObject userGuybrushAfter = getUser(USER_GUYBRUSH_OID); display("User Guybrush after", userGuybrushAfter); assertAssignedRole(userGuybrushAfter, ROLE_PIRATE_OID); @@ -398,37 +398,37 @@ public void test124RecomputeBarbossa() throws Exception { assertAccount(userGuybrushAfter, RESOURCE_DUMMY_OID); assertLinks(userGuybrushAfter, 1); assertAuthorizations(userGuybrushAfter, AUTZ_LOOT_URL); - + } - + /** * Unassign Guybrush pirate role. Barbossa is Guybrushe's deputy, - * but Barbossa should be only partially affected yet. + * but Barbossa should be only partially affected yet. */ @Test public void test126UnassignGuybrushPirate() throws Exception { final String TEST_NAME = "test126UnassignGuybrushPirate"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + unassignRole(USER_GUYBRUSH_OID, ROLE_PIRATE_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userGuybrushAfter = getUser(USER_GUYBRUSH_OID); display("User Guybrush after", userGuybrushAfter); assertNoAssignments(userGuybrushAfter); assertLinks(userGuybrushAfter, 0); assertNoAuthorizations(userGuybrushAfter); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertAssignedDeputy(userBarbossaAfter, USER_GUYBRUSH_OID); @@ -436,9 +436,9 @@ public void test126UnassignGuybrushPirate() throws Exception { assertAccount(userBarbossaAfter, RESOURCE_DUMMY_OID); assertLinks(userBarbossaAfter, 1); assertNoAuthorizations(userBarbossaAfter); - + } - + /** * Recompute Barbossa. Barbossa should get the deputy rights * from Guybrush after recompute. @@ -447,68 +447,68 @@ public void test126UnassignGuybrushPirate() throws Exception { public void test128RecomputeBarbossa() throws Exception { final String TEST_NAME = "test128RecomputeBarbossa"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + recomputeUser(USER_BARBOSSA_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertAssignedDeputy(userBarbossaAfter, USER_GUYBRUSH_OID); assertAssignments(userBarbossaAfter, 1); assertLinks(userBarbossaAfter, 0); assertNoAuthorizations(userBarbossaAfter); - + PrismObject userGuybrushAfter = getUser(USER_GUYBRUSH_OID); display("User Guybrush after", userGuybrushAfter); assertNoAssignments(userGuybrushAfter); assertLinks(userGuybrushAfter, 0); assertNoAuthorizations(userGuybrushAfter); - + } - + @Test public void test129UnassignBarbossaDeputyOfGuybrush() throws Exception { final String TEST_NAME = "test129UnassignBarbossaDeputyOfGuybrush"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + unassignDeputy(USER_BARBOSSA_OID, USER_GUYBRUSH_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertNoAssignments(userBarbossaAfter); assertLinks(userBarbossaAfter, 0); assertNoAuthorizations(userBarbossaAfter); - + PrismObject userGuybrushAfter = getUser(USER_GUYBRUSH_OID); display("User Guybrush after", userGuybrushAfter); assertNoAssignments(userGuybrushAfter); assertLinks(userGuybrushAfter, 0); assertNoAuthorizations(userGuybrushAfter); - + } - + /** * Assign more roles and orgs to Jack. We will use these for * selective delegation in subsequent tests. @@ -517,36 +517,36 @@ public void test129UnassignBarbossaDeputyOfGuybrush() throws Exception { public void test150AssignJackMoreRoles() throws Exception { final String TEST_NAME = "test150AssignJackMoreRoles"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - ObjectDelta userDelta = createAssignmentUserDelta(USER_JACK_OID, ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, + ObjectDelta userDelta = createAssignmentUserDelta(USER_JACK_OID, ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, null, (ActivationType) null, true); // Captain is NOT delegable - userDelta.addModification((createAssignmentModification(ROLE_CAPTAIN_OID, RoleType.COMPLEX_TYPE, + userDelta.addModification((createAssignmentModification(ROLE_CAPTAIN_OID, RoleType.COMPLEX_TYPE, null, null, (ActivationType) null, true))); - userDelta.addModification((createAssignmentModification(ROLE_RED_SAILOR_OID, RoleType.COMPLEX_TYPE, + 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, + 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, + 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, + 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, + userDelta.addModification((createAssignmentModification(ROLE_EMPTY_OID, RoleType.COMPLEX_TYPE, null, null, (ActivationType) null, true))); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJackAfter = getUser(USER_JACK_OID); display("User Jack after", userJackAfter); assertAssignedRole(userJackAfter, ROLE_PIRATE_OID); @@ -558,35 +558,35 @@ public void test150AssignJackMoreRoles() throws Exception { assertAccount(userJackAfter, RESOURCE_DUMMY_CYAN_OID); assertLinks(userJackAfter, 3); assertAuthorizations(userJackAfter, AUTZ_LOOT_URL, AUTZ_SAIL_URL, AUTZ_SAIL_URL, AUTZ_COMMAND_URL); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertNoAssignments(userBarbossaAfter); assertLinks(userBarbossaAfter, 0); - assertNoAuthorizations(userBarbossaAfter); - + assertNoAuthorizations(userBarbossaAfter); + } - + @Test public void test152AssignbarbossaDeputyLimitedDeputy() throws Exception { final String TEST_NAME = "test152AssignbarbossaDeputyLimitedDeputy"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + assignDeputyLimits(USER_BARBOSSA_OID, USER_JACK_OID, task, result, createRoleReference(ROLE_PIRATE_OID), createOrgReference(ORG_MINISTRY_OF_RUM_OID, SchemaConstants.ORG_MANAGER)); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertAssignedDeputy(userBarbossaAfter, USER_JACK_OID); @@ -595,70 +595,70 @@ public void test152AssignbarbossaDeputyLimitedDeputy() throws Exception { assertAccount(userBarbossaAfter, RESOURCE_DUMMY_OID); assertLinks(userBarbossaAfter, 1); assertAuthorizations(userBarbossaAfter, AUTZ_LOOT_URL); - + PrismObject userJackAfter = getUser(USER_JACK_OID); display("User Jack after", userJackAfter); assertAssignments(userJackAfter, 7); assertLinks(userJackAfter, 3); assertAuthorizations(userJackAfter, AUTZ_LOOT_URL, AUTZ_SAIL_URL, AUTZ_SAIL_URL, AUTZ_COMMAND_URL); - + } - + @Test public void test154UnassignbarbossaDeputyLimitedDeputy() throws Exception { final String TEST_NAME = "test154UnassignbarbossaDeputyLimitedDeputy"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + unassignDeputyLimits(USER_BARBOSSA_OID, USER_JACK_OID, task, result, createRoleReference(ROLE_PIRATE_OID), createOrgReference(ORG_MINISTRY_OF_RUM_OID, SchemaConstants.ORG_MANAGER)); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertNoAssignments(userBarbossaAfter); assertLinks(userBarbossaAfter, 0); - assertNoAuthorizations(userBarbossaAfter); - + assertNoAuthorizations(userBarbossaAfter); + PrismObject userJackAfter = getUser(USER_JACK_OID); display("User Jack after", userJackAfter); assertAssignments(userJackAfter, 7); assertLinks(userJackAfter, 3); assertAuthorizations(userJackAfter, AUTZ_LOOT_URL, AUTZ_SAIL_URL, AUTZ_SAIL_URL, AUTZ_COMMAND_URL); - + } - + @Test public void test156AssignbarbossaDeputyLimitedDeputyRed() throws Exception { final String TEST_NAME = "test156AssignbarbossaDeputyLimitedDeputyRed"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + assignDeputyLimits(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 ); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertAssignedDeputy(userBarbossaAfter, USER_JACK_OID); @@ -667,41 +667,41 @@ public void test156AssignbarbossaDeputyLimitedDeputyRed() throws Exception { assertAccount(userBarbossaAfter, RESOURCE_DUMMY_RED_OID); assertLinks(userBarbossaAfter, 1); assertAuthorizations(userBarbossaAfter, AUTZ_SAIL_URL); - + PrismObject userJackAfter = getUser(USER_JACK_OID); display("User Jack after", userJackAfter); assertAssignments(userJackAfter, 7); assertLinks(userJackAfter, 3); assertAuthorizations(userJackAfter, AUTZ_LOOT_URL, AUTZ_SAIL_URL, AUTZ_SAIL_URL, AUTZ_COMMAND_URL); - + } - + @Test public void test159UnassignbarbossaDeputyLimitedDeputyRed() throws Exception { final String TEST_NAME = "test159UnassignbarbossaDeputyLimitedDeputyRed"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + 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 ); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertNoAssignments(userBarbossaAfter); @@ -709,35 +709,35 @@ public void test159UnassignbarbossaDeputyLimitedDeputyRed() throws Exception { assertLinks(userBarbossaAfter, 1); assertNoAuthorizations(userBarbossaAfter); TestUtil.assertModifyTimestamp(userBarbossaAfter, startTs, endTs); - + PrismObject userJackAfter = getUser(USER_JACK_OID); display("User Jack after", userJackAfter); 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"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + assignDeputyLimits(USER_BARBOSSA_OID, USER_JACK_OID, task, result, createRoleReference(ROLE_EMPTY_OID) ); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertAssignedDeputy(userBarbossaAfter, USER_JACK_OID); @@ -746,40 +746,40 @@ public void test160AssignbarbossaDeputyLimitedDeputyEmpty() throws Exception { assertAccount(userBarbossaAfter, RESOURCE_DUMMY_RED_OID); assertLinks(userBarbossaAfter, 1); assertNoAuthorizations(userBarbossaAfter); - + PrismObject userJackAfter = getUser(USER_JACK_OID); display("User Jack after", userJackAfter); assertAssignments(userJackAfter, 7); assertLinks(userJackAfter, 3); assertAuthorizations(userJackAfter, AUTZ_LOOT_URL, AUTZ_SAIL_URL, AUTZ_SAIL_URL, AUTZ_COMMAND_URL); - + } - + @Test public void test162UnassignbarbossaDeputyLimitedDeputyEmpty() throws Exception { final String TEST_NAME = "test162UnassignbarbossaDeputyLimitedDeputyEmpty"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + unassignDeputyLimits(USER_BARBOSSA_OID, USER_JACK_OID, task, result, createRoleReference(ROLE_EMPTY_OID) ); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertNoAssignments(userBarbossaAfter); @@ -787,35 +787,35 @@ public void test162UnassignbarbossaDeputyLimitedDeputyEmpty() throws Exception { assertLinks(userBarbossaAfter, 1); assertNoAuthorizations(userBarbossaAfter); TestUtil.assertModifyTimestamp(userBarbossaAfter, startTs, endTs); - + PrismObject userJackAfter = getUser(USER_JACK_OID); display("User Jack after", userJackAfter); assertAssignments(userJackAfter, 7); assertLinks(userJackAfter, 3); assertAuthorizations(userJackAfter, AUTZ_LOOT_URL, AUTZ_SAIL_URL, AUTZ_SAIL_URL, AUTZ_COMMAND_URL); - + } @Test public void test170AddRoleDrinker() throws Exception { final String TEST_NAME = "test170AssignJackRoleDrinker"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject role = PrismTestUtil.parseObject(ROLE_DRINKER_FILE); display("Adding role", role); - + // WHEN TestUtil.displayWhen(TEST_NAME); addObject(role, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject roleAfter = getObject(RoleType.class, ROLE_DRINKER_OID); display("Role after", roleAfter); assertAssignedOrg(roleAfter, ORG_MINISTRY_OF_RUM_OID); @@ -826,19 +826,19 @@ public void test170AddRoleDrinker() throws Exception { public void test172AssignJackRoleDrinker() throws Exception { final String TEST_NAME = "test170AssignJackRoleDrinker"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_DRINKER_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJackAfter = getUser(USER_JACK_OID); display("User Jack after", userJackAfter); assertAssignedRole(userJackAfter, ROLE_PIRATE_OID); @@ -850,63 +850,63 @@ public void test172AssignJackRoleDrinker() throws Exception { assertAccount(userJackAfter, RESOURCE_DUMMY_RED_OID); assertAccount(userJackAfter, RESOURCE_DUMMY_CYAN_OID); assertLinks(userJackAfter, 3); - assertAuthorizations(userJackAfter, AUTZ_LOOT_URL, AUTZ_SAIL_URL, AUTZ_SAIL_URL, AUTZ_COMMAND_URL); + assertAuthorizations(userJackAfter, AUTZ_LOOT_URL, AUTZ_SAIL_URL, AUTZ_SAIL_URL, AUTZ_COMMAND_URL); } - + @Test public void test172AssignbarbossaDeputyLimitedDeputyDrinker() throws Exception { final String TEST_NAME = "test172AssignbarbossaDeputyLimitedDeputyDrinker"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + assignDeputyLimits(USER_BARBOSSA_OID, USER_JACK_OID, task, result, createRoleReference(ROLE_DRINKER_OID) ); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJackAfter = getUser(USER_JACK_OID); display("User Jack after", userJackAfter); assertAssignedRole(userJackAfter, ROLE_DRINKER_OID); assertAssignments(userJackAfter, 8); assertLinks(userJackAfter, 3); assertAuthorizations(userJackAfter, AUTZ_LOOT_URL, AUTZ_SAIL_URL, AUTZ_SAIL_URL, AUTZ_COMMAND_URL); - + } - + @Test public void test178UnassignbarbossaDeputyLimitedDeputyDrinker() throws Exception { final String TEST_NAME = "test178UnassignbarbossaDeputyLimitedDeputyDrinker"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + unassignDeputyLimits(USER_BARBOSSA_OID, USER_JACK_OID, task, result, createRoleReference(ROLE_DRINKER_OID) ); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertNoAssignments(userBarbossaAfter); @@ -914,36 +914,36 @@ public void test178UnassignbarbossaDeputyLimitedDeputyDrinker() throws Exception assertLinks(userBarbossaAfter, 1); assertNoAuthorizations(userBarbossaAfter); TestUtil.assertModifyTimestamp(userBarbossaAfter, startTs, endTs); - + PrismObject userJackAfter = getUser(USER_JACK_OID); display("User Jack after", userJackAfter); assertAssignments(userJackAfter, 8); assertLinks(userJackAfter, 3); assertAuthorizations(userJackAfter, AUTZ_LOOT_URL, AUTZ_SAIL_URL, AUTZ_SAIL_URL, AUTZ_COMMAND_URL); - + } @Test public void test180AssignbarbossaDeputyLimitedDeputyEmptyDrinker() throws Exception { final String TEST_NAME = "test180AssignbarbossaDeputyLimitedDeputyEmptyDrinker"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + assignDeputyLimits(USER_BARBOSSA_OID, USER_JACK_OID, task, result, createRoleReference(ROLE_EMPTY_OID), createRoleReference(ROLE_DRINKER_OID) ); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertAssignedDeputy(userBarbossaAfter, USER_JACK_OID); @@ -952,41 +952,41 @@ public void test180AssignbarbossaDeputyLimitedDeputyEmptyDrinker() throws Except assertAccount(userBarbossaAfter, RESOURCE_DUMMY_RED_OID); assertLinks(userBarbossaAfter, 1); assertNoAuthorizations(userBarbossaAfter); - + PrismObject userJackAfter = getUser(USER_JACK_OID); display("User Jack after", userJackAfter); assertAssignments(userJackAfter, 8); assertLinks(userJackAfter, 3); assertAuthorizations(userJackAfter, AUTZ_LOOT_URL, AUTZ_SAIL_URL, AUTZ_SAIL_URL, AUTZ_COMMAND_URL); - + } - + @Test public void test182UnassignbarbossaDeputyLimitedDeputyEmptyDrinker() throws Exception { final String TEST_NAME = "test182UnassignbarbossaDeputyLimitedDeputyEmptyDrinker"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + unassignDeputyLimits(USER_BARBOSSA_OID, USER_JACK_OID, task, result, createRoleReference(ROLE_EMPTY_OID), createRoleReference(ROLE_DRINKER_OID) ); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertNoAssignments(userBarbossaAfter); @@ -994,16 +994,16 @@ public void test182UnassignbarbossaDeputyLimitedDeputyEmptyDrinker() throws Exce assertLinks(userBarbossaAfter, 1); assertNoAuthorizations(userBarbossaAfter); TestUtil.assertModifyTimestamp(userBarbossaAfter, startTs, endTs); - + PrismObject userJackAfter = getUser(USER_JACK_OID); display("User Jack after", userJackAfter); assertAssignments(userJackAfter, 8); assertLinks(userJackAfter, 3); assertAuthorizations(userJackAfter, AUTZ_LOOT_URL, AUTZ_SAIL_URL, AUTZ_SAIL_URL, AUTZ_COMMAND_URL); - + } - + @Test public void test800ImportValidityScannerTask() throws Exception { final String TEST_NAME = "test800ImportValidityScannerTask"; @@ -1012,22 +1012,22 @@ public void test800ImportValidityScannerTask() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); - + /// WHEN TestUtil.displayWhen(TEST_NAME); importObjectFromFile(TASK_VALIDITY_SCANNER_FILENAME); waitForTaskStart(TASK_VALIDITY_SCANNER_OID, false); waitForTaskFinish(TASK_VALIDITY_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); XMLGregorianCalendar endCal = clock.currentTimeXMLGregorianCalendar(); - assertLastRecomputeTimestamp(TASK_VALIDITY_SCANNER_OID, startCal, endCal); + assertLastRecomputeTimestamp(TASK_VALIDITY_SCANNER_OID, startCal, endCal); } - + /** * Assign Barbossa as Jack's deputy. Barbossa should have all the privileges now. * But they will expire soon ... @@ -1036,34 +1036,34 @@ public void test800ImportValidityScannerTask() throws Exception { public void test802AssignBarbossaDeputyOfJack() throws Exception { final String TEST_NAME = "test802AssignBarbossaDeputyOfJack"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userJackBefore = getUser(USER_JACK_OID); display("User Jack before", userJackBefore); assertAssignments(userJackBefore, 8); assertLinks(userJackBefore, 3); assertAuthorizations(userJackBefore, AUTZ_LOOT_URL, AUTZ_SAIL_URL, AUTZ_SAIL_URL, AUTZ_COMMAND_URL); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - + ActivationType activationType = new ActivationType(); activationType.setValidTo(XmlTypeConverter.addDuration(startTs, "PT2H")); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + assignDeputy(USER_BARBOSSA_OID, USER_JACK_OID, assignment -> assignment.setActivation(activationType), task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertAssignedDeputy(userBarbossaAfter, USER_JACK_OID); @@ -1075,15 +1075,15 @@ public void test802AssignBarbossaDeputyOfJack() throws Exception { assertLinks(userBarbossaAfter, 3); // Command autz should NOT be here, it is not delegable MID-3550 assertAuthorizations(userBarbossaAfter, AUTZ_LOOT_URL, AUTZ_SAIL_URL, AUTZ_SAIL_URL); - + PrismObject userJackAfter = getUser(USER_JACK_OID); display("User Jack after", userJackAfter); assertAssignments(userJackAfter, 8); assertLinks(userJackAfter, 3); assertAuthorizations(userJackAfter, AUTZ_LOOT_URL, AUTZ_SAIL_URL, AUTZ_SAIL_URL, AUTZ_COMMAND_URL); - + } - + /** * Assign Barbossa as Jack's deputy. Barbossa should have all the privileges now. * But they will expire soon ... @@ -1092,26 +1092,26 @@ public void test802AssignBarbossaDeputyOfJack() throws Exception { public void test804BarbosaThreeHoursLater() throws Exception { final String TEST_NAME = "test804BarbosaThreeHoursLater"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestDeputy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + clock.overrideDuration("PT3H"); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertAssignedDeputy(userBarbossaAfter, USER_JACK_OID); @@ -1119,13 +1119,13 @@ public void test804BarbosaThreeHoursLater() throws Exception { assertAccount(userBarbossaAfter, RESOURCE_DUMMY_RED_OID); // Resource red has delayed delete assertLinks(userBarbossaAfter, 1); assertNoAuthorizations(userBarbossaAfter); - + PrismObject userJackAfter = getUser(USER_JACK_OID); display("User Jack after", userJackAfter); assertAssignments(userJackAfter, 8); assertLinks(userJackAfter, 3); assertAuthorizations(userJackAfter, AUTZ_LOOT_URL, AUTZ_SAIL_URL, AUTZ_SAIL_URL, AUTZ_COMMAND_URL); - + } - + } 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 bc06fbd8f20..76e97315d4c 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 @@ -58,7 +58,7 @@ /** * Test of account-entitlement association. - * + * * @author Radovan Semancik * */ @@ -89,7 +89,7 @@ public class TestEntitlements extends AbstractInitializedModelIntegrationTest { public static final String ROLE_THUG_OID = "10000000-0000-0000-0000-000000001607"; public static final String ROLE_THUG_NAME = "Thug"; public static final String GROUP_THUG_NAME = "thug"; - + public static final File ROLE_CREW_OF_GUYBRUSH_FILE = new File(TEST_DIR, "role-crew-of-guybrush.xml"); public static final String ROLE_CREW_OF_GUYBRUSH_OID = "93d3e436-3c6c-11e7-8168-23796882a64e"; @@ -122,7 +122,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti importObjectFromFile(ROLE_LANDLUBER_FILE); importObjectFromFile(ROLE_MAPMAKER_FILE); importObjectFromFile(ROLE_CREW_OF_GUYBRUSH_FILE); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); } @@ -875,7 +875,7 @@ public void test329UnAssignRoleBruteFromRapp() throws Exception { // Orange resource has explicit referential integrity switched off assertNoGroupMember(dummyGroupWimpsAtOrange, USER_RAPP_USERNAME); } - + @Test public void test350AssignOrangeAccountToGuybrushAndRapp() throws Exception { final String TEST_NAME = "test350AssignOrangeAccountToGuybrushAndRapp"; @@ -912,7 +912,7 @@ public void test351AssignRoleCrewOfGuybrushToRapp() throws Exception { PrismObject userRappBefore = getUser(USER_RAPP_OID); display("User rapp before", userRappBefore); - + // preconditions assertNotNull("No rapp", userRappBefore); assertDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); @@ -930,20 +930,20 @@ public void test351AssignRoleCrewOfGuybrushToRapp() throws Exception { String guybrushShadowOid = getLinkRefOid(userGuybrushAfter, RESOURCE_DUMMY_ORANGE_OID); PrismObject guybrushShadow = getShadowModel(guybrushShadowOid); display("Shadow guybrush", guybrushShadow); - + PrismObject userRappAfter = getUser(USER_RAPP_OID); display("User rapp after", userRappAfter); String rappShadowOid = getSingleLinkOid(userRappAfter); PrismObject rappShadow = getShadowModel(rappShadowOid); display("Shadow rapp", rappShadow); assertAssociation(rappShadow, RESOURCE_DUMMY_ORANGE_ASSOCIATION_CREW_QNAME, guybrushShadowOid); - + DummyAccount dummyOrangeAccountRapp = getDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_RAPP_USERNAME); display("Rapp account", dummyOrangeAccountRapp); - assertDummyAccountAttribute(RESOURCE_DUMMY_ORANGE_NAME, USER_RAPP_USERNAME, - DUMMY_ACCOUNT_ATTRIBUTE_MATE_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); + assertDummyAccountAttribute(RESOURCE_DUMMY_ORANGE_NAME, USER_RAPP_USERNAME, + DUMMY_ACCOUNT_ATTRIBUTE_MATE_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); } - + /** * MID-2668 */ @@ -957,7 +957,7 @@ public void test358UnassignRoleCrewOfGuybrushToRapp() throws Exception { PrismObject userRappBefore = getUser(USER_RAPP_OID); display("User rapp before", userRappBefore); - + // preconditions assertNotNull("No rapp", userRappBefore); assertDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); @@ -973,20 +973,20 @@ public void test358UnassignRoleCrewOfGuybrushToRapp() throws Exception { PrismObject userGuybrushAfter = getUser(USER_GUYBRUSH_OID); display("User guybrush after", userGuybrushAfter); String guybrushShadowOid = getLinkRefOid(userGuybrushAfter, RESOURCE_DUMMY_ORANGE_OID); - + PrismObject userRappAfter = getUser(USER_RAPP_OID); display("User rapp before", userRappAfter); String rappShadowOid = getSingleLinkOid(userRappAfter); PrismObject rappShadow = getShadowModel(rappShadowOid); display("Shadow rapp", rappShadow); assertNoAssociation(rappShadow, RESOURCE_DUMMY_ORANGE_ASSOCIATION_CREW_QNAME, guybrushShadowOid); - + DummyAccount dummyOrangeAccountRapp = getDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_RAPP_USERNAME); display("Rapp account", dummyOrangeAccountRapp); - assertNoDummyAccountAttribute(RESOURCE_DUMMY_ORANGE_NAME, USER_RAPP_USERNAME, - DUMMY_ACCOUNT_ATTRIBUTE_MATE_NAME); + assertNoDummyAccountAttribute(RESOURCE_DUMMY_ORANGE_NAME, USER_RAPP_USERNAME, + DUMMY_ACCOUNT_ATTRIBUTE_MATE_NAME); } - + @Test public void test359UnassignOrangeAccountFromGuybrushAndRapp() throws Exception { final String TEST_NAME = "test359UnassignOrangeAccountFromGuybrushAndRapp"; @@ -1007,7 +1007,7 @@ public void test359UnassignOrangeAccountFromGuybrushAndRapp() throws Exception { assertNoDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_RAPP_USERNAME); } - + @Test public void test600AssignRolePirateToJack() throws Exception { final String TEST_NAME = "test600AssignRolePirateToJack"; @@ -1264,7 +1264,7 @@ public void test650JackRoleSwashbucklerBecomesInvalid() throws Exception { assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Bloody Pirate", "Swashbuckler"); } - + @Test public void test659UnassignRoleSwashbucklerFromJack() throws Exception { final String TEST_NAME = "test659UnassignRoleSwashbucklerFromJack"; @@ -1302,7 +1302,7 @@ public void test659UnassignRoleSwashbucklerFromJack() throws Exception { assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Bloody Pirate"); } - + @Test public void test699UnassignRolePirateFromJack() throws Exception { final String TEST_NAME = "test699UnassignRolePirateFromJack"; @@ -1342,10 +1342,10 @@ public void test700ReconcileGuybrush() throws Exception { dumpOrangeGroups(task, result); // GIVEN - + DummyGroup dummyGroup = getDummyResource().getGroupByName(GROUP_DUMMY_SWASHBUCKLERS_NAME); dummyGroup.addMember(USER_GUYBRUSH_USERNAME); - + assertGroupMember(getDummyGroup(null, GROUP_DUMMY_SWASHBUCKLERS_NAME), USER_GUYBRUSH_USERNAME); // WHEN @@ -1454,7 +1454,7 @@ public void test720ReconcileGuybrush() throws Exception { 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)); } - + /** * MID-4021 */ @@ -1465,9 +1465,9 @@ public void test800AssignRoleSwashbucklerToJackNone() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + // preconditions assertJackClean(); @@ -1486,7 +1486,7 @@ public void test800AssignRoleSwashbucklerToJackNone() throws Exception { assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * MID-4021 */ @@ -1497,9 +1497,9 @@ public void test805ReconcileJackNone() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_JACK_OID, task, result); @@ -1528,7 +1528,7 @@ public void test809UnAssignRoleSwashbucklerFromJackNone() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_SWASHBUCKLER_OID, task, result); @@ -1541,9 +1541,9 @@ public void test809UnAssignRoleSwashbucklerFromJackNone() throws Exception { display("User after", userAfter); assertAssignments(userAfter, 0); - assertJackNoAccountNoSwashbuckler(); + assertJackNoAccountNoSwashbuckler(); } - + /** * MID-4021 */ @@ -1554,9 +1554,9 @@ public void test810AssignRoleSwashbucklerToJackPositive() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - + // preconditions assertJackClean(); @@ -1575,7 +1575,7 @@ public void test810AssignRoleSwashbucklerToJackPositive() throws Exception { assertJackAccountSwashbuckler(); } - + /** * MID-4021 */ @@ -1586,9 +1586,9 @@ public void test815ReconcileJackPositive() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_JACK_OID, task, result); @@ -1604,7 +1604,7 @@ public void test815ReconcileJackPositive() throws Exception { assertJackAccountSwashbuckler(); } - + /** * MID-4021 */ @@ -1617,7 +1617,7 @@ public void test817UnAssignRoleSwashbucklerFromJackPositive() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_SWASHBUCKLER_OID, task, result); @@ -1632,7 +1632,7 @@ public void test817UnAssignRoleSwashbucklerFromJackPositive() throws Exception { assertJackAccountSwashbuckler(); } - + /** * MID-4021 */ @@ -1643,9 +1643,9 @@ public void test819ReconcileJackPositive() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_JACK_OID, task, result); @@ -1658,12 +1658,12 @@ public void test819ReconcileJackPositive() throws Exception { display("User after", userAfter); assertAssignments(userAfter, 0); - // Group association is non-tolerant. + // Group association is non-tolerant. // So, account should remain, but the group should be gone // (removed by reconciliation) assertJackAccountNoSwashbuckler(); } - + /** * Jack has account and entitlement from previous test. Now we are in full * enforcement. Recompute should remove the account and entitlement. @@ -1676,9 +1676,9 @@ public void test820RecomputeJackFull() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + // preconditions assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); @@ -1696,7 +1696,7 @@ public void test820RecomputeJackFull() throws Exception { assertJackNoAccountNoSwashbuckler(); } - + /** * MID-4021 */ @@ -1707,9 +1707,9 @@ public void test822AssignRoleSwashbucklerToJackFull() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + // preconditions assertJackClean(); @@ -1728,7 +1728,7 @@ public void test822AssignRoleSwashbucklerToJackFull() throws Exception { assertJackAccountSwashbuckler(); } - + /** * MID-4021 */ @@ -1739,9 +1739,9 @@ public void test825ReconcileJackFull() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_JACK_OID, task, result); @@ -1757,7 +1757,7 @@ public void test825ReconcileJackFull() throws Exception { assertJackAccountSwashbuckler(); } - + /** * MID-4021 */ @@ -1770,7 +1770,7 @@ public void test827UnAssignRoleSwashbucklerFromJackFull() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_SWASHBUCKLER_OID, task, result); @@ -1785,7 +1785,7 @@ public void test827UnAssignRoleSwashbucklerFromJackFull() throws Exception { assertJackNoAccountNoSwashbuckler(); } - + /** * MID-4021 */ @@ -1796,9 +1796,9 @@ public void test829ReconcileJackFull() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_JACK_OID, task, result); @@ -1813,7 +1813,7 @@ public void test829ReconcileJackFull() throws Exception { assertJackNoAccountNoSwashbuckler(); } - + /** * For next few tests keep account assigned, add/remove just the entitlement assignment * MID-4021 @@ -1825,9 +1825,9 @@ public void test830AssignJackAccountDummy() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + // preconditions assertJackClean(); @@ -1845,7 +1845,7 @@ public void test830AssignJackAccountDummy() throws Exception { assertJackAccountNoSwashbuckler(); } - + /** * MID-4021 */ @@ -1856,9 +1856,9 @@ public void test840AssignRoleSwashbucklerToJackNone() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + // preconditions assertJackJustAccount(); @@ -1877,7 +1877,7 @@ public void test840AssignRoleSwashbucklerToJackNone() throws Exception { assertJackAccountNoSwashbuckler(); } - + /** * MID-4021 */ @@ -1888,9 +1888,9 @@ public void test849UnassignRoleSwashbucklerFromJackNone() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_SWASHBUCKLER_OID, task, result); @@ -1905,7 +1905,7 @@ public void test849UnassignRoleSwashbucklerFromJackNone() throws Exception { assertJackAccountNoSwashbuckler(); } - + /** * MID-4021 */ @@ -1916,9 +1916,9 @@ public void test850AssignRoleSwashbucklerToJackPositive() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - + // preconditions assertJackJustAccount(); @@ -1937,7 +1937,7 @@ public void test850AssignRoleSwashbucklerToJackPositive() throws Exception { assertJackAccountSwashbuckler(); } - + /** * MID-4021 */ @@ -1948,9 +1948,9 @@ public void test859UnassignRoleSwashbucklerToJackPositive() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_SWASHBUCKLER_OID, task, result); @@ -1965,7 +1965,7 @@ public void test859UnassignRoleSwashbucklerToJackPositive() throws Exception { assertJackAccountSwashbuckler(); } - + /** * Jack has account and entitlement from previous test. Now we are in full * enforcement. Recompute should remove the entitlement. @@ -1978,9 +1978,9 @@ public void test860RecomputeJackFull() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); @@ -1995,7 +1995,7 @@ public void test860RecomputeJackFull() throws Exception { assertJackAccountNoSwashbuckler(); } - + /** * MID-4021 */ @@ -2006,9 +2006,9 @@ public void test862AssignRoleSwashbucklerToJackFull() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + // preconditions assertJackJustAccount(); @@ -2027,7 +2027,7 @@ public void test862AssignRoleSwashbucklerToJackFull() throws Exception { assertJackAccountSwashbuckler(); } - + /** * MID-4021 */ @@ -2038,9 +2038,9 @@ public void test869UnassignRoleSwashbucklerToJackFull() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_SWASHBUCKLER_OID, task, result); @@ -2055,7 +2055,7 @@ public void test869UnassignRoleSwashbucklerToJackFull() throws Exception { assertJackAccountNoSwashbuckler(); } - + /** * MID-4021 */ @@ -2068,7 +2068,7 @@ public void test899UnAssignAccountJackDummy() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + // WHEN displayWhen(TEST_NAME); unassignAccount(USER_JACK_OID, RESOURCE_DUMMY_OID, null, task, result); @@ -2083,14 +2083,14 @@ public void test899UnAssignAccountJackDummy() throws Exception { assertJackNoAccountNoSwashbuckler(); } - + private void assertJackClean() throws SchemaViolationException, ConflictException, ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject userBefore = getUser(USER_JACK_OID); display("User before", userBefore); assertAssignments(userBefore, 0); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + private void assertJackJustAccount() throws SchemaViolationException, ConflictException, ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException, ConnectException, FileNotFoundException { PrismObject userBefore = getUser(USER_JACK_OID); display("User before", userBefore); @@ -2112,7 +2112,7 @@ private void assertJackAccountSwashbuckler() throws SchemaViolationException, Co dummyGroup.getAttributeValue(DummyResourceContoller.DUMMY_GROUP_ATTRIBUTE_DESCRIPTION)); assertGroupMember(dummyGroup, ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * Account: yes, group: no */ 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 07a0a519dc9..63f270001b6 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 @@ -56,12 +56,12 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestInbounds extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/contract"); private String jackEmployeeNumber; private String guybrushShadowOrangeOid; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -69,7 +69,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti setDefaultUserTemplate(USER_TEMPLATE_INBOUNDS_OID); assumeResourceAssigmentPolicy(RESOURCE_DUMMY_GREEN_OID, AssignmentPolicyEnforcementType.RELATIVE, false); } - + @Test public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; @@ -77,7 +77,7 @@ public void test000Sanity() throws Exception { // GIVEN Task task = createTask(TEST_NAME); - + // WHEN displayWhen(TEST_NAME); OperationResult testResult = modelService.testResource(RESOURCE_DUMMY_ORANGE_OID, task); @@ -85,7 +85,7 @@ public void test000Sanity() throws Exception { // THEN displayThen(TEST_NAME); TestUtil.assertSuccess("Test orange resource", testResult); - + DummyResource dummyResourceOrange = getDummyResource(RESOURCE_DUMMY_ORANGE_NAME); assertEquals("Wrong ORANGE useless string", IntegrationTestTools.CONST_USELESS, dummyResourceOrange.getUselessString()); } @@ -98,7 +98,7 @@ public void test101ModifyUserEmployeeTypePirate() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + Collection> deltas = new ArrayList>(); ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_JACK_OID, UserType.F_EMPLOYEE_TYPE, prismContext, "PIRATE"); @@ -107,7 +107,7 @@ public void test101ModifyUserEmployeeTypePirate() throws Exception { userDelta.addModificationAddProperty(SchemaConstants.PATH_ACTIVATION_VALID_FROM, XmlTypeConverter .createXMLGregorianCalendar(System.currentTimeMillis())); deltas.add(userDelta); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); @@ -116,24 +116,24 @@ public void test101ModifyUserEmployeeTypePirate() throws Exception { displayThen(TEST_NAME); 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?"); assertAssignedRole(userJack, ROLE_PIRATE_GREEN_OID); assertAssignments(userJack, 1); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - + assertSuccess(result); - + assertEquals("Unexpected number of organizationalUnits", 1, userJackType.getOrganizationalUnit().size()); assertEquals("Wrong organizationalUnit", PrismTestUtil.createPolyStringType("The crew of pirate"), userJackType.getOrganizationalUnit().get(0)); - - + + jackEmployeeNumber = userJackType.getEmployeeNumber(); assertNotNull("Wrong employee number. Expected not null value, got " + jackEmployeeNumber, jackEmployeeNumber); } - + /** * 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. @@ -146,32 +146,32 @@ public void test102ModifyUserEmployeeTypeBuccaneer() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + Collection> deltas = new ArrayList>(); ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_JACK_OID, UserType.F_EMPLOYEE_TYPE, prismContext, "BUCCANEER"); deltas.add(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); // THEN 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?"); assertAssignedRole(userJack, ROLE_BUCCANEER_GREEN_OID); assertAssignments(userJack, 1); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); PrismAsserts.assertEqualsCollectionUnordered("Wrong organizationalUnit", userJackType.getOrganizationalUnit(), PrismTestUtil.createPolyStringType("The crew of buccaneer")); assertEquals("Employee number has changed", jackEmployeeNumber, userJackType.getEmployeeNumber()); } - + @Test public void test103DeleteUserEmployeeTypeBartender() throws Exception { final String TEST_NAME = "test103ModifyUserEmployeeTypeBartender"; @@ -180,36 +180,36 @@ public void test103DeleteUserEmployeeTypeBartender() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + Collection> deltas = new ArrayList>(); ObjectDelta userDelta = ObjectDelta.createModificationDeleteProperty(UserType.class, USER_JACK_OID, UserType.F_EMPLOYEE_TYPE, prismContext, "BUCCANEER"); deltas.add(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); // THEN 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?"); assertNotAssignedRole(userJack, ROLE_PIRATE_GREEN_OID); assertNotAssignedRole(userJack, ROLE_BUCCANEER_GREEN_OID); assertNoAssignments(userJack); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 0, userJackType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - + assertEquals("Employee number has changed", jackEmployeeNumber, userJackType.getEmployeeNumber()); } /** * Not much happens here. Just ordinary account assign. Just make sure - * that the inbound mappings do not fail for empty values and that + * that the inbound mappings do not fail for empty values and that * we have a good environment for the following tests. * MID-2689 */ @@ -221,10 +221,10 @@ public void test200AssignAccountOrange() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); - + // WHEN displayWhen(TEST_NAME); assignAccount(USER_GUYBRUSH_OID, RESOURCE_DUMMY_ORANGE_OID, null, task, result); @@ -232,25 +232,25 @@ public void test200AssignAccountOrange() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_ORANGE_OID); assertAssignedNoRole(userAfter); assertAssignments(userAfter, 1); assertLinks(userAfter, 2); - + DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true); display("Orange account", dummyAccount); - + guybrushShadowOrangeOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_ORANGE_OID); PrismObject shadowOrange = getShadowModel(guybrushShadowOrangeOid); display("Orange shadow", shadowOrange); } - + /** * Modify 'gossip' on account (through shadow). That attribute has an inbound * expression that creates an assignment. Make sure it is processed properly. @@ -264,38 +264,38 @@ public void test202ModifyAccountOrangeGossip() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); - + // WHEN - modifyObjectAddProperty(ShadowType.class, guybrushShadowOrangeOid, + modifyObjectAddProperty(ShadowType.class, guybrushShadowOrangeOid, getDummyResourceController(RESOURCE_DUMMY_ORANGE_NAME).getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME), task, result, ROLE_PIRATE_OID); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_ORANGE_OID); assertAssignedRole(userAfter, ROLE_PIRATE_OID); assertAssignments(userAfter, 2); assertLinks(userAfter, 2); - + DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true); display("Orange account", dummyAccount); - + guybrushShadowOrangeOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_ORANGE_OID); PrismObject shadowOrange = getShadowModel(guybrushShadowOrangeOid); display("Orange shadow", shadowOrange); - + } - + /** * Discovered by accident. Just make sure that another change will not destroy anything. * MID-3080 @@ -308,38 +308,38 @@ public void test204AssignAccountOrangeAgain() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); - + // WHEN assignAccount(USER_GUYBRUSH_OID, RESOURCE_DUMMY_ORANGE_OID, null, task, result); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_ORANGE_OID); assertAssignedRole(userAfter, ROLE_PIRATE_OID); assertAssignments(userAfter, 2); assertLinks(userAfter, 2); - + DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true); display("Orange account", dummyAccount); - + guybrushShadowOrangeOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_ORANGE_OID); PrismObject shadowOrange = getShadowModel(guybrushShadowOrangeOid); display("Orange shadow", shadowOrange); - + } - + /** - * Remove the value of 'gossip' attribute on account (through shadow). + * Remove the value of 'gossip' attribute on account (through shadow). * That attribute has an inbound expression that removes an assignment. * Make sure it is processed properly. * MID-2689 @@ -352,38 +352,38 @@ public void test209ModifyAccountOrangeGossipRemove() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); - + // WHEN - modifyObjectDeleteProperty(ShadowType.class, guybrushShadowOrangeOid, + modifyObjectDeleteProperty(ShadowType.class, guybrushShadowOrangeOid, getDummyResourceController(RESOURCE_DUMMY_ORANGE_NAME).getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME), task, result, ROLE_PIRATE_OID); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_ORANGE_OID); assertAssignedNoRole(userAfter); assertAssignments(userAfter, 1); assertLinks(userAfter, 2); - + DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true); display("Orange account", dummyAccount); - + guybrushShadowOrangeOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_ORANGE_OID); PrismObject shadowOrange = getShadowModel(guybrushShadowOrangeOid); display("Orange shadow", shadowOrange); - + } - + /** * Modify 'quote' on account (through shadow). That attribute has an inbound * expression that passes some values to description user property. @@ -398,41 +398,41 @@ public void test210ModifyAccountOrangeQuoteMonkey() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); - + // WHEN - modifyObjectReplaceProperty(ShadowType.class, guybrushShadowOrangeOid, + modifyObjectReplaceProperty(ShadowType.class, guybrushShadowOrangeOid, getDummyResourceController(RESOURCE_DUMMY_ORANGE_NAME).getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME), task, result, "Look behind you, a Three-Headed Monkey!"); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, + 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()); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_ORANGE_OID); assertAssignedNoRole(userAfter); assertAssignments(userAfter, 1); assertLinks(userAfter, 2); - + // Second inbound expression should work here PrismAsserts.assertPropertyValue(userAfter, getExtensionPath(PIRACY_TALES), "Look behind you, a Three-Headed Monkey!"); - + DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true); display("Orange account", dummyAccount); - + guybrushShadowOrangeOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_ORANGE_OID); PrismObject shadowOrange = getShadowModel(guybrushShadowOrangeOid); display("Orange shadow", shadowOrange); - + } /** @@ -449,43 +449,43 @@ public void test211ModifyAccountOrangeQuotePirate() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); - + // WHEN - modifyObjectReplaceProperty(ShadowType.class, guybrushShadowOrangeOid, + modifyObjectReplaceProperty(ShadowType.class, guybrushShadowOrangeOid, getDummyResourceController(RESOURCE_DUMMY_ORANGE_NAME).getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME), task, result, "I wanna be a pirrrrrrate!"); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + assertEquals("Wrong description", "I wanna be a pirrrrrrate!", userAfter.asObjectable().getDescription()); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_ORANGE_OID); assertAssignedNoRole(userAfter); assertAssignments(userAfter, 1); assertLinks(userAfter, 2); - + // Second inbound expression should work here PrismAsserts.assertPropertyValue(userAfter, getExtensionPath(PIRACY_TALES), "I wanna be a pirrrrrrate!"); - + DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true); display("Orange account", dummyAccount); - + guybrushShadowOrangeOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_ORANGE_OID); PrismObject shadowOrange = getShadowModel(guybrushShadowOrangeOid); display("Orange shadow", shadowOrange); - + } - + /** * Modify 'quote' on account (through shadow). That attribute has an inbound * expression that passes some values to description user property. @@ -500,40 +500,40 @@ public void test214ModifyAccountOrangeQuoteWoodchuck() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); - + // WHEN - modifyObjectReplaceProperty(ShadowType.class, guybrushShadowOrangeOid, + modifyObjectReplaceProperty(ShadowType.class, guybrushShadowOrangeOid, getDummyResourceController(RESOURCE_DUMMY_ORANGE_NAME).getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME), task, result, "How much wood could a woodchuck chuck if a woodchuck could chuck wood?"); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, + 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()); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_ORANGE_OID); assertAssignedNoRole(userAfter); assertAssignments(userAfter, 1); assertLinks(userAfter, 2); - + DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true); display("Orange account", dummyAccount); - + guybrushShadowOrangeOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_ORANGE_OID); PrismObject shadowOrange = getShadowModel(guybrushShadowOrangeOid); display("Orange shadow", shadowOrange); - + } - + /** * Not much happens here. We just need to remove the dummy account to avoid * inbound expression interferences. We wanted to have the dummy account in @@ -547,38 +547,38 @@ public void test250UnlinkAccountDefaultDummy() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); - + ObjectDelta unlinkDelta = createModifyUserUnlinkAccount(USER_GUYBRUSH_OID, getDummyResourceObject()); - + // WHEN modelService.executeChanges(MiscSchemaUtil.createCollection(unlinkDelta), null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_ORANGE_OID); assertAssignedNoRole(userAfter); assertAssignments(userAfter, 1); assertLinks(userAfter, 1); - + DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true); display("Orange account", dummyAccount); - + guybrushShadowOrangeOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_ORANGE_OID); PrismObject shadowOrange = getShadowModel(guybrushShadowOrangeOid); display("Orange shadow", shadowOrange); - + } - + /** * Similar to test202ModifyAccountOrangeGossip, but uses direct account modification * and reconciliation. @@ -592,34 +592,34 @@ public void test252ModifyAccountOrangeGossipRecon() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME); dummyAccountBefore.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, ROLE_THIEF_OID); display("Account orange before", dummyAccountBefore); - + // WHEN reconcileUser(USER_GUYBRUSH_OID, task, result); // THEN assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_ORANGE_OID); assertAssignedRole(userAfter, ROLE_THIEF_OID); assertAssignments(userAfter, 2); assertLinks(userAfter, 1); - + DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true); display("Orange account", dummyAccount); - + guybrushShadowOrangeOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_ORANGE_OID); PrismObject shadowOrange = getShadowModel(guybrushShadowOrangeOid); display("Orange shadow", shadowOrange); @@ -638,40 +638,40 @@ public void test259ModifyAccountOrangeGossipRemoveRecon() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME); dummyAccountBefore.replaceAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME /* no value */); display("Account orange before", dummyAccountBefore); - + // WHEN reconcileUser(USER_GUYBRUSH_OID, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + // The inbound mapping is tolerant. It will NOT remove the value. assertAssignedAccount(userAfter, RESOURCE_DUMMY_ORANGE_OID); assertAssignedRole(userAfter, ROLE_THIEF_OID); assertAssignments(userAfter, 2); assertLinks(userAfter, 1); - + DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true); display("Orange account", dummyAccount); - + guybrushShadowOrangeOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_ORANGE_OID); PrismObject shadowOrange = getShadowModel(guybrushShadowOrangeOid); display("Orange shadow", shadowOrange); } - + /** * Similar to test210ModifyAccountOrangeQuoteMonkey, but uses direct account modification * and reconciliation. @@ -685,48 +685,48 @@ public void test260ModifyAccountOrangeQuoteMonkeyRecon() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); assertEquals("Wrong description", null, userBefore.asObjectable().getDescription()); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME); dummyAccountBefore.replaceAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "Look behind you, a Three-Headed Monkey!"); display("Account orange before", dummyAccountBefore); - + // WHEN reconcileUser(USER_GUYBRUSH_OID, task, result); - + // WHEN - modifyObjectReplaceProperty(ShadowType.class, guybrushShadowOrangeOid, + modifyObjectReplaceProperty(ShadowType.class, guybrushShadowOrangeOid, getDummyResourceController(RESOURCE_DUMMY_ORANGE_NAME).getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME), task, result, "Look behind you, a Three-Headed Monkey!"); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, + 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()); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_ORANGE_OID); assertAssignedRole(userAfter, ROLE_THIEF_OID); assertAssignments(userAfter, 2); assertLinks(userAfter, 1); - + DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true); display("Orange account", dummyAccount); - + guybrushShadowOrangeOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_ORANGE_OID); PrismObject shadowOrange = getShadowModel(guybrushShadowOrangeOid); display("Orange shadow", shadowOrange); } - + /** * Similar to test211ModifyAccountOrangeQuotePirate, but uses direct account modification * and reconciliation. @@ -740,38 +740,38 @@ public void test261ModifyAccountOrangeQuotePirateRecon() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME); dummyAccountBefore.replaceAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "I wanna be a pirrrrrrate!"); display("Account orange before", dummyAccountBefore); - + // WHEN reconcileUser(USER_GUYBRUSH_OID, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + assertEquals("Wrong description", "I wanna be a pirrrrrrate!", userAfter.asObjectable().getDescription()); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_ORANGE_OID); assertAssignedRole(userAfter, ROLE_THIEF_OID); assertAssignments(userAfter, 2); assertLinks(userAfter, 1); - + DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true); display("Account orange after", dummyAccount); display("Orange account", dummyAccount); - + guybrushShadowOrangeOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_ORANGE_OID); PrismObject shadowOrange = getShadowModel(guybrushShadowOrangeOid); display("Orange shadow", shadowOrange); @@ -790,43 +790,43 @@ public void test264ModifyAccountOrangeQuoteWoodchuckRecon() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME); dummyAccountBefore.replaceAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "How much wood could a woodchuck chuck if a woodchuck could chuck wood?"); display("Account orange before", dummyAccountBefore); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_GUYBRUSH_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, + 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()); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_ORANGE_OID); assertAssignedRole(userAfter, ROLE_THIEF_OID); assertAssignments(userAfter, 2); assertLinks(userAfter, 1); - + DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true); display("Orange account", dummyAccount); - + guybrushShadowOrangeOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_ORANGE_OID); PrismObject shadowOrange = getShadowModel(guybrushShadowOrangeOid); display("Orange shadow", shadowOrange); } - + /** * Cleanup */ @@ -838,14 +838,14 @@ public void test297ModifyAccountOrangeGossipRecon() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME); dummyAccountBefore.replaceAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME /* no value */); display("Account orange before", dummyAccountBefore); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_GUYBRUSH_OID, ROLE_THIEF_OID, task, result); @@ -853,25 +853,25 @@ public void test297ModifyAccountOrangeGossipRecon() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_ORANGE_OID); assertNotAssignedRole(userAfter, ROLE_THIEF_OID); assertAssignments(userAfter, 1); assertLinks(userAfter, 1); - + DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true); display("Orange account", dummyAccount); - + guybrushShadowOrangeOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_ORANGE_OID); PrismObject shadowOrange = getShadowModel(guybrushShadowOrangeOid); display("Orange shadow", shadowOrange); } - + @Test public void test299UnassignAccountOrange() throws Exception { final String TEST_NAME = "test299UnassignAccountOrange"; @@ -880,11 +880,11 @@ public void test299UnassignAccountOrange() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); assertAssignments(userBefore, 1); - + // WHEN displayWhen(TEST_NAME); unassignAccount(USER_GUYBRUSH_OID, RESOURCE_DUMMY_ORANGE_OID, null, task, result); @@ -892,14 +892,14 @@ public void test299UnassignAccountOrange() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); assertAssignments(userAfter, 0); assertLinks(userAfter, 0); - + assertNoDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME); assertNoShadow(guybrushShadowOrangeOid); 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 90a3a318249..00c3aeaf7f1 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 @@ -50,7 +50,7 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestIntent extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/xxxxxxxxxx"); private static final String ACCOUNT_INTENT_TEST = "test"; private String accountOid; @@ -58,9 +58,9 @@ public class TestIntent extends AbstractInitializedModelIntegrationTest { @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + addObject(SHADOW_GROUP_DUMMY_TESTERS_FILE, initTask, initResult); - + rememberSteadyResources(); } @@ -73,44 +73,44 @@ public void test131ModifyUserJackAssignAccountDefault() throws Exception { Task task = taskManager.createTaskInstance(TestIntent.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.RELATIVE); - + Collection> deltas = new ArrayList>(); - ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, + ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, null, true); deltas.add(accountAssignmentUserDelta); - + XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); assertLinks(userJack, 1); accountOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountOid, ACCOUNT_JACK_DUMMY_USERNAME); assertEnableTimestampShadow(accountShadow, startTime, endTime); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow"); assertEnableTimestampShadow(accountModel, startTime, endTime); - + // Check account in dummy resource assertDefaultDummyAccount("jack", "Jack Sparrow", true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -124,7 +124,7 @@ public void test131ModifyUserJackAssignAccountDefault() throws Exception { assertSteadyResources(); } - + @Test public void test132ModifyUserJackAssignAccountTest() throws Exception { final String TEST_NAME="test132ModifyUserJackAssignAccountTest"; @@ -134,57 +134,57 @@ public void test132ModifyUserJackAssignAccountTest() throws Exception { Task task = taskManager.createTaskInstance(TestIntent.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.RELATIVE); - + Collection> deltas = new ArrayList>(); - ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, + ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, ACCOUNT_INTENT_TEST, true); deltas.add(accountAssignmentUserDelta); - + XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); assertLinks(userJack, 2); String accountOidDefault = getLinkRefOid(userJack, RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, SchemaConstants.INTENT_DEFAULT); String accountOidTest = getLinkRefOid(userJack, RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, ACCOUNT_INTENT_TEST); - + // Check shadow: intent=default PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOidDefault, null, result); assertDummyAccountShadowRepo(accountShadow, accountOidDefault, ACCOUNT_JACK_DUMMY_USERNAME); - + // Check account: intent=default PrismObject accountModel = modelService.getObject(ShadowType.class, accountOidDefault, null, task, result); assertDummyAccountShadowModel(accountModel, accountOidDefault, ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow"); - + // Check account in dummy resource: intent=default assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); - + // Check shadow: intent=test PrismObject accountShadowTest = repositoryService.getObject(ShadowType.class, accountOidTest, null, result); assertDummyAccountShadowRepo(accountShadowTest, accountOidTest, "T"+ACCOUNT_JACK_DUMMY_USERNAME); assertEnableTimestampShadow(accountShadowTest, startTime, endTime); - + // Check account: intent=test PrismObject accountModelTest = modelService.getObject(ShadowType.class, accountOidTest, null, task, result); assertDummyAccountShadowModel(accountModelTest, accountOidTest, "T"+ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow (test)"); assertEnableTimestampShadow(accountModelTest, startTime, endTime); - + // Check account in dummy resource: intent=test assertDefaultDummyAccount("T"+ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow (test)", true); assertDefaultDummyGroupMember(GROUP_DUMMY_TESTERS_NAME, "T"+ACCOUNT_JACK_DUMMY_USERNAME); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -198,7 +198,7 @@ public void test132ModifyUserJackAssignAccountTest() throws Exception { assertSteadyResources(); } - + @Test public void test135ModifyUserJackFullName() throws Exception { final String TEST_NAME="test135ModifyUserJackFullName"; @@ -208,46 +208,46 @@ public void test135ModifyUserJackFullName() throws Exception { Task task = taskManager.createTaskInstance(TestIntent.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.RELATIVE); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, UserType.F_FULL_NAME, task, result, PrismTestUtil.createPolyString("cpt. Jack Sparrow")); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 2); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "cpt. Jack Sparrow", "Jack", "Sparrow"); assertLinks(userJack, 2); String accountOidDefault = getLinkRefOid(userJack, RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, SchemaConstants.INTENT_DEFAULT); String accountOidTest = getLinkRefOid(userJack, RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, ACCOUNT_INTENT_TEST); - + // Check shadow: intent=default PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOidDefault, null, result); assertDummyAccountShadowRepo(accountShadow, accountOidDefault, ACCOUNT_JACK_DUMMY_USERNAME); - + // Check account: intent=default PrismObject accountModel = modelService.getObject(ShadowType.class, accountOidDefault, null, task, result); assertDummyAccountShadowModel(accountModel, accountOidDefault, ACCOUNT_JACK_DUMMY_USERNAME, "cpt. Jack Sparrow"); - + // Check account in dummy resource: intent=default assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, "cpt. Jack Sparrow", true); - + // Check shadow: intent=test PrismObject accountShadowTest = repositoryService.getObject(ShadowType.class, accountOidTest, null, result); assertDummyAccountShadowRepo(accountShadowTest, accountOidTest, "T"+ACCOUNT_JACK_DUMMY_USERNAME); - + // Check account: intent=test PrismObject accountModelTest = modelService.getObject(ShadowType.class, accountOidTest, null, task, result); assertDummyAccountShadowModel(accountModelTest, accountOidTest, "T"+ACCOUNT_JACK_DUMMY_USERNAME, "cpt. Jack Sparrow (test)"); - + // Check account in dummy resource: intent=test assertDefaultDummyAccount("T"+ACCOUNT_JACK_DUMMY_USERNAME, "cpt. Jack Sparrow (test)", true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -261,7 +261,7 @@ public void test135ModifyUserJackFullName() throws Exception { assertSteadyResources(); } - + @Test public void test147ModifyUserJackUnAssignAccountDefault() throws Exception { final String TEST_NAME="test147ModifyUserJackUnAssignAccountDefault"; @@ -271,44 +271,44 @@ public void test147ModifyUserJackUnAssignAccountDefault() throws Exception { Task task = taskManager.createTaskInstance(TestIntent.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.RELATIVE); - + Collection> deltas = new ArrayList>(); - ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, + ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, null, false); deltas.add(accountAssignmentUserDelta); - + XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "cpt. Jack Sparrow", "Jack", "Sparrow"); assertLinks(userJack, 1); String accountOidTest = getLinkRefOid(userJack, RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, ACCOUNT_INTENT_TEST); - + // Check shadow: intent=test PrismObject accountShadowTest = repositoryService.getObject(ShadowType.class, accountOidTest, null, result); assertDummyAccountShadowRepo(accountShadowTest, accountOidTest, "T"+ACCOUNT_JACK_DUMMY_USERNAME); - + // Check account: intent=test PrismObject accountModelTest = modelService.getObject(ShadowType.class, accountOidTest, null, task, result); assertDummyAccountShadowModel(accountModelTest, accountOidTest, "T"+ACCOUNT_JACK_DUMMY_USERNAME, "cpt. Jack Sparrow (test)"); - + // Check account in dummy resource: intent=test assertDefaultDummyAccount("T"+ACCOUNT_JACK_DUMMY_USERNAME, "cpt. Jack Sparrow (test)", true); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); @@ -322,7 +322,7 @@ public void test147ModifyUserJackUnAssignAccountDefault() throws Exception { assertSteadyResources(); } - + @Test public void test149ModifyUserJackUnassignAccountTest() throws Exception { final String TEST_NAME = "test149ModifyUserJackUnassignAccountTest"; @@ -332,31 +332,31 @@ public void test149ModifyUserJackUnassignAccountTest() throws Exception { Task task = taskManager.createTaskInstance(TestIntent.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.RELATIVE); - + Collection> deltas = new ArrayList>(); - ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, + ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, ACCOUNT_INTENT_TEST, false); deltas.add(accountAssignmentUserDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userJack = getUser(USER_JACK_OID); assertUserJack(userJack, "cpt. Jack Sparrow", "Jack", "Sparrow"); assertLinks(userJack, 0); - + // Check is shadow is gone assertNoShadow(accountOid); - + // Check if dummy resource account is gone assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount("T"+ACCOUNT_JACK_DUMMY_USERNAME); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); 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 dfeb544ea00..436f8ac40a6 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 @@ -84,30 +84,30 @@ @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"; @@ -122,7 +122,7 @@ public class TestIteration extends AbstractInitializedModelIntegrationTest { protected static final File TASK_LIVE_SYNC_DUMMY_DARK_VIOLET_FILE = new File(TEST_DIR, "task-dumy-dark-violet-livesync.xml"); protected static final String TASK_LIVE_SYNC_DUMMY_DARK_VIOLET_OID = "10000000-0000-0000-5555-555500da0204"; - + // Iteration with token expression and pre- and post-condition. Sequential suffix. protected static final File USER_TEMPLATE_ITERATION_FILE = new File(TEST_DIR, "user-template-iteration.xml"); protected static final String USER_TEMPLATE_ITERATION_OID = "10000000-0000-0000-0000-0000000d0002"; @@ -130,14 +130,14 @@ 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"); protected static final String USER_TEMPLATE_ITERATION_UNIQUE_EMAIL_OID = "10000000-0000-0000-0000-0000000d0004"; - + private static final String USER_ANGELICA_NAME = "angelica"; private static final String ACCOUNT_SPARROW_NAME = "sparrow"; - + private static final String USER_DEWATT_NAME = "dewatt"; private static final String ACCOUNT_DEWATT_NAME = "DeWatt"; @@ -154,7 +154,7 @@ public class TestIteration extends AbstractInitializedModelIntegrationTest { private static final String ACCOUNT_CHARLES_USERNAME = "charles"; private static final String ACCOUNT_SHINETOP_USERNAME = "shinetop"; private static final String CHUCKIE_FULLNAME = "Chuckie"; - + private static final String ACCOUNT_MATUSALEM_USERNAME = "matusalem"; private static final String ACCOUNT_DIPLOMATICO_USERNAME = "diplomatico"; private static final String ACCOUNT_MILLONARIO_USERNAME = "millonario"; @@ -188,17 +188,17 @@ public class TestIteration extends AbstractInitializedModelIntegrationTest { protected static DummyResourceContoller dummyResourceCtlPink; protected ResourceType resourceDummyPinkType; protected PrismObject resourceDummyPink; - + protected static DummyResource dummyResourceViolet; protected static DummyResourceContoller dummyResourceCtlViolet; protected ResourceType resourceDummyVioletType; protected PrismObject resourceDummyViolet; - + protected static DummyResource dummyResourceDarkViolet; protected static DummyResourceContoller dummyResourceCtlDarkViolet; protected ResourceType resourceDummyDarkVioletType; protected PrismObject resourceDummyDarkViolet; - + protected static DummyResource dummyResourceMagenta; protected static DummyResourceContoller dummyResourceCtlMagenta; protected ResourceType resourceDummyMagentaType; @@ -211,37 +211,37 @@ public class TestIteration extends AbstractInitializedModelIntegrationTest { String iterationTokenDiplomatico; String iterationTokenMillonario; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + dummyResourceCtlPink = DummyResourceContoller.create(RESOURCE_DUMMY_PINK_NAME, resourceDummyPink); dummyResourceCtlPink.extendSchemaPirate(); dummyResourcePink = dummyResourceCtlPink.getDummyResource(); - resourceDummyPink = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_PINK_FILE, RESOURCE_DUMMY_PINK_OID, initTask, initResult); + resourceDummyPink = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_PINK_FILE, RESOURCE_DUMMY_PINK_OID, initTask, initResult); resourceDummyPinkType = resourceDummyPink.asObjectable(); dummyResourceCtlPink.setResource(resourceDummyPink); - + dummyResourceCtlViolet = DummyResourceContoller.create(RESOURCE_DUMMY_VIOLET_NAME, resourceDummyViolet); dummyResourceCtlViolet.extendSchemaPirate(); dummyResourceViolet = dummyResourceCtlViolet.getDummyResource(); - resourceDummyViolet = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_VIOLET_FILE, RESOURCE_DUMMY_VIOLET_OID, initTask, initResult); + resourceDummyViolet = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_VIOLET_FILE, RESOURCE_DUMMY_VIOLET_OID, initTask, initResult); resourceDummyVioletType = resourceDummyViolet.asObjectable(); dummyResourceCtlViolet.setResource(resourceDummyViolet); - + dummyResourceCtlDarkViolet = DummyResourceContoller.create(RESOURCE_DUMMY_DARK_VIOLET_NAME, resourceDummyViolet); dummyResourceCtlDarkViolet.extendSchemaPirate(); dummyResourceDarkViolet = dummyResourceCtlDarkViolet.getDummyResource(); - resourceDummyDarkViolet = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_DARK_VIOLET_FILE, RESOURCE_DUMMY_DARK_VIOLET_OID, initTask, initResult); + resourceDummyDarkViolet = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_DARK_VIOLET_FILE, RESOURCE_DUMMY_DARK_VIOLET_OID, initTask, initResult); resourceDummyDarkVioletType = resourceDummyDarkViolet.asObjectable(); dummyResourceCtlDarkViolet.setResource(resourceDummyDarkViolet); dummyResourceDarkViolet.setSyncStyle(DummySyncStyle.SMART); - + dummyResourceCtlMagenta = DummyResourceContoller.create(RESOURCE_DUMMY_MAGENTA_NAME, resourceDummyMagenta); dummyResourceCtlMagenta.extendSchemaPirate(); dummyResourceMagenta = dummyResourceCtlMagenta.getDummyResource(); - resourceDummyMagenta = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_MAGENTA_FILE, RESOURCE_DUMMY_MAGENTA_OID, initTask, initResult); + resourceDummyMagenta = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_MAGENTA_FILE, RESOURCE_DUMMY_MAGENTA_OID, initTask, initResult); resourceDummyMagentaType = resourceDummyMagenta.asObjectable(); dummyResourceCtlMagenta.setResource(resourceDummyMagenta); @@ -272,7 +272,7 @@ public void test100JackAssignAccountDummyConflicting() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // Make sure there is a conflicting account and also a shadow for it DummyAccount account = new DummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); account.setEnabled(true); @@ -280,36 +280,36 @@ public void test100JackAssignAccountDummyConflicting() throws Exception { account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Tortuga"); getDummyResource().addAccount(account); repoAddObject(createShadow(getDummyResourceObject(), ACCOUNT_JACK_DUMMY_USERNAME), result); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, null, true); deltas.add(accountAssignmentUserDelta); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); String accountOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountOid, ACCOUNT_JACK_DUMMY_USERNAME); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow"); - + // Check account in dummy resource assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -320,7 +320,7 @@ public void test100JackAssignAccountDummyConflicting() throws Exception { dummyAuditService.assertHasDelta(ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test200JackAssignAccountDummyPinkConflicting() throws Exception { final String TEST_NAME = "test200JackAssignAccountDummyPinkConflicting"; @@ -330,7 +330,7 @@ public void test200JackAssignAccountDummyPinkConflicting() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // Make sure there is a conflicting account and also a shadow for it DummyAccount account = new DummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); account.setEnabled(true); @@ -338,7 +338,7 @@ public void test200JackAssignAccountDummyPinkConflicting() throws Exception { account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Red Sea"); dummyResourcePink.addAccount(account); repoAddObject(createShadow(resourceDummyPink, ACCOUNT_JACK_DUMMY_USERNAME), result); - + Collection> deltas = new ArrayList>(); // assignment with weapon := 'pistol' (test for @@ -358,29 +358,29 @@ public void test200JackAssignAccountDummyPinkConflicting() throws Exception { ObjectDelta accountAssignmentUserDelta = ObjectDelta.createModifyDelta(USER_JACK_OID, modifications, UserType.class, prismContext); deltas.add(accountAssignmentUserDelta); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); assertLinks(userJack, 2); assertAccount(userJack, RESOURCE_DUMMY_OID); assertAccount(userJack, RESOURCE_DUMMY_PINK_OID); - + String accountPinkOid = getLinkRefOid(userJack, RESOURCE_DUMMY_PINK_OID); - + // Check shadow PrismObject accountPinkShadow = repositoryService.getObject(ShadowType.class, accountPinkOid, null, result); assertAccountShadowRepo(accountPinkShadow, accountPinkOid, "jack1", resourceDummyPinkType); - + // Check account PrismObject accountPinkModel = modelService.getObject(ShadowType.class, accountPinkOid, null, task, result); assertAccountShadowModel(accountPinkModel, accountPinkOid, "jack1", resourceDummyPinkType); @@ -394,7 +394,7 @@ public void test200JackAssignAccountDummyPinkConflicting() throws Exception { assertDummyAccount(RESOURCE_DUMMY_PINK_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Jack Pinky", true); // The new account assertDummyAccount(RESOURCE_DUMMY_PINK_NAME, "jack1", "Jack Sparrow", true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -405,7 +405,7 @@ public void test200JackAssignAccountDummyPinkConflicting() throws Exception { dummyAuditService.assertHasDelta(ChangeType.ADD, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + /** * Test the normal case. Just to be sure the default iteration algorithm works well. */ @@ -418,20 +418,20 @@ public void test210GuybrushAssignAccountDummyPink() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_GUYBRUSH_OID, RESOURCE_DUMMY_PINK_OID, null, true); deltas.add(accountAssignmentUserDelta); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userGuybrush = getUser(USER_GUYBRUSH_OID); display("User after change execution", userGuybrush); assertUser(userGuybrush, USER_GUYBRUSH_OID, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood", "Guybrush", "Threepwood"); @@ -439,20 +439,20 @@ public void test210GuybrushAssignAccountDummyPink() throws Exception { // Guybrush had dummy account before assertAccount(userGuybrush, RESOURCE_DUMMY_OID); assertAccount(userGuybrush, RESOURCE_DUMMY_PINK_OID); - + String accountPinkOid = getLinkRefOid(userGuybrush, RESOURCE_DUMMY_PINK_OID); - + // Check shadow PrismObject accountPinkShadow = repositoryService.getObject(ShadowType.class, accountPinkOid, null, result); assertAccountShadowRepo(accountPinkShadow, accountPinkOid, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, resourceDummyPinkType); - + // Check account PrismObject accountPinkModel = modelService.getObject(ShadowType.class, accountPinkOid, null, task, result); assertAccountShadowModel(accountPinkModel, accountPinkOid, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, resourceDummyPinkType); - + // The new account assertDummyAccount(RESOURCE_DUMMY_PINK_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood", true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -473,56 +473,56 @@ public void test220DeWattAssignAccountDummyPinkCaseIgnore() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userDeWatt = createUser(USER_DEWATT_NAME, "Augustus DeWatt", true); addObject(userDeWatt); String userDeWattkOid = userDeWatt.getOid(); - + PrismObject accountDeWatt = createAccount(resourceDummyPink, ACCOUNT_DEWATT_NAME, true); - addAttributeToShadow(accountDeWatt, resourceDummyPink, + addAttributeToShadow(accountDeWatt, resourceDummyPink, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Augustus DeWatt"); addObject(accountDeWatt); // precondition assertDummyAccount(RESOURCE_DUMMY_PINK_NAME, ACCOUNT_DEWATT_NAME, "Augustus DeWatt", true); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(userDeWattkOid, RESOURCE_DUMMY_PINK_OID, null, true); deltas.add(accountAssignmentUserDelta); - + dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userDeWattAfter = getUser(userDeWattkOid); display("User after change execution", userDeWattAfter); assertUser(userDeWattAfter, userDeWattkOid, USER_DEWATT_NAME, "Augustus DeWatt", null, null); assertLinks(userDeWattAfter, 1); assertAccount(userDeWattAfter, RESOURCE_DUMMY_PINK_OID); - + String accountPinkOid = getLinkRefOid(userDeWattAfter, RESOURCE_DUMMY_PINK_OID); - + // Check shadow PrismObject accountPinkShadow = repositoryService.getObject(ShadowType.class, accountPinkOid, null, result); assertAccountShadowRepo(accountPinkShadow, accountPinkOid, USER_DEWATT_NAME+"1", resourceDummyPinkType); - + // Check account PrismObject accountPinkModel = modelService.getObject(ShadowType.class, accountPinkOid, null, task, result); assertAccountShadowModel(accountPinkModel, accountPinkOid, USER_DEWATT_NAME + "1", resourceDummyPinkType); - + // 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); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -1156,7 +1156,7 @@ public void test300JackAssignAccountDummyVioletConflicting() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // Make sure there is a conflicting account and also a shadow for it DummyAccount account = new DummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); account.setEnabled(true); @@ -1164,20 +1164,20 @@ public void test300JackAssignAccountDummyVioletConflicting() throws Exception { account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Sea of Lavender"); dummyResourceViolet.addAccount(account); repoAddObject(createShadow(resourceDummyViolet, ACCOUNT_JACK_DUMMY_USERNAME), result); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_VIOLET_OID, null, true); deltas.add(accountAssignmentUserDelta); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); @@ -1185,24 +1185,24 @@ public void test300JackAssignAccountDummyVioletConflicting() throws Exception { assertAccount(userJack, RESOURCE_DUMMY_OID); assertAccount(userJack, RESOURCE_DUMMY_PINK_OID); assertAccount(userJack, RESOURCE_DUMMY_VIOLET_OID); - + String accountVioletOid = getLinkRefOid(userJack, RESOURCE_DUMMY_VIOLET_OID); - + // Check shadow PrismObject accountVioletShadow = repositoryService.getObject(ShadowType.class, accountVioletOid, null, result); assertAccountShadowRepo(accountVioletShadow, accountVioletOid, "jack.1", resourceDummyVioletType); - + // Check account PrismObject accountVioletModel = modelService.getObject(ShadowType.class, accountVioletOid, null, task, result); assertAccountShadowModel(accountVioletModel, accountVioletOid, "jack.1", resourceDummyVioletType); - + // Check account in dummy resource assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); // The original conflicting account should still remain assertDummyAccount(RESOURCE_DUMMY_VIOLET_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Jack Violet", true); // The new account assertDummyAccount(RESOURCE_DUMMY_VIOLET_NAME, "jack.1", "Jack Sparrow", true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -1213,7 +1213,7 @@ public void test300JackAssignAccountDummyVioletConflicting() throws Exception { dummyAuditService.assertHasDelta(ChangeType.ADD, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test350GuybrushAssignAccountDummyViolet() throws Exception { final String TEST_NAME = "test350GuybrushAssignAccountDummyViolet"; @@ -1223,20 +1223,20 @@ public void test350GuybrushAssignAccountDummyViolet() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_GUYBRUSH_OID, RESOURCE_DUMMY_VIOLET_OID, null, true); deltas.add(accountAssignmentUserDelta); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userGuybrush = getUser(USER_GUYBRUSH_OID); display("User after change execution", userGuybrush); assertUser(userGuybrush, USER_GUYBRUSH_OID, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood", "Guybrush", "Threepwood"); @@ -1244,22 +1244,22 @@ public void test350GuybrushAssignAccountDummyViolet() throws Exception { assertAccount(userGuybrush, RESOURCE_DUMMY_OID); assertAccount(userGuybrush, RESOURCE_DUMMY_PINK_OID); assertAccount(userGuybrush, RESOURCE_DUMMY_VIOLET_OID); - + String accountVioletOid = getLinkRefOid(userGuybrush, RESOURCE_DUMMY_VIOLET_OID); - + // Check shadow PrismObject accountVioletShadow = repositoryService.getObject(ShadowType.class, accountVioletOid, null, result); assertAccountShadowRepo(accountVioletShadow, accountVioletOid, "guybrush.3", resourceDummyVioletType); - + // Check account PrismObject accountVioletModel = modelService.getObject(ShadowType.class, accountVioletOid, null, task, result); assertAccountShadowModel(accountVioletModel, accountVioletOid, "guybrush.3", resourceDummyVioletType); - + // There should be no account with the "straight" name assertNoDummyAccount(RESOURCE_DUMMY_VIOLET_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); // The new account assertDummyAccount(RESOURCE_DUMMY_VIOLET_NAME, "guybrush.3", "Guybrush Threepwood", true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -1270,7 +1270,7 @@ public void test350GuybrushAssignAccountDummyViolet() throws Exception { dummyAuditService.assertHasDelta(ChangeType.ADD, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test360HermanAssignAccountDummyViolet() throws Exception { final String TEST_NAME = "test360HermanAssignAccountDummyViolet"; @@ -1279,47 +1279,47 @@ public void test360HermanAssignAccountDummyViolet() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + addObject(USER_HERMAN_FILE); - + dummyAuditService.clear(); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_HERMAN_OID, RESOURCE_DUMMY_VIOLET_OID, null, true); deltas.add(accountAssignmentUserDelta); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userHerman = getUser(USER_HERMAN_OID); display("User after change execution", userHerman); assertUser(userHerman, USER_HERMAN_OID, "herman", "Herman Toothrot", "Herman", "Toothrot"); assertLinks(userHerman, 1); assertAccount(userHerman, RESOURCE_DUMMY_VIOLET_OID); - + String accountVioletOid = getLinkRefOid(userHerman, RESOURCE_DUMMY_VIOLET_OID); - + // Check shadow PrismObject accountVioletShadow = repositoryService.getObject(ShadowType.class, accountVioletOid, null, result); assertAccountShadowRepo(accountVioletShadow, accountVioletOid, "herman.1", resourceDummyVioletType); - + assertIteration(accountVioletShadow, 1, ".1"); - + // Check account PrismObject accountVioletModel = modelService.getObject(ShadowType.class, accountVioletOid, null, task, result); assertAccountShadowModel(accountVioletModel, accountVioletOid, "herman.1", resourceDummyVioletType); - + // There should be no account with the "straight" name assertNoDummyAccount(RESOURCE_DUMMY_VIOLET_NAME, "herman"); // The new account assertDummyAccount(RESOURCE_DUMMY_VIOLET_NAME, "herman.1", "Herman Toothrot", true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -1330,7 +1330,7 @@ public void test360HermanAssignAccountDummyViolet() throws Exception { dummyAuditService.assertHasDelta(ChangeType.ADD, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test400RenameAngelicaConflicting() throws Exception { final String TEST_NAME = "test400RenameAngelicaConflicting"; @@ -1339,29 +1339,29 @@ public void test400RenameAngelicaConflicting() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userLechuck = createUser(USER_ANGELICA_NAME, "Angelica", true); userLechuck.asObjectable().getAssignment().add(createAccountAssignment(RESOURCE_DUMMY_PINK_OID, null)); addObject(userLechuck); String userLechuckOid = userLechuck.getOid(); - + PrismObject accountCharles = createAccount(resourceDummyPink, ACCOUNT_SPARROW_NAME, true); addObject(accountCharles); - + // preconditions assertDummyAccount(RESOURCE_DUMMY_PINK_NAME, USER_ANGELICA_NAME, "Angelica", true); assertDummyAccount(RESOURCE_DUMMY_PINK_NAME, ACCOUNT_SPARROW_NAME, null, true); - + // WHEN modifyUserReplace(userLechuckOid, UserType.F_NAME, task, result, PrismTestUtil.createPolyString(ACCOUNT_SPARROW_NAME)); - + // THEN assertDummyAccount(RESOURCE_DUMMY_PINK_NAME, ACCOUNT_SPARROW_NAME, null, true); assertDummyAccount(RESOURCE_DUMMY_PINK_NAME, ACCOUNT_SPARROW_NAME+"1", "Angelica", true); assertNoDummyAccount(RESOURCE_DUMMY_PINK_NAME, USER_ANGELICA_NAME); } - + /** * No conflict. Just make sure the iteration condition is not triggered. */ @@ -1374,20 +1374,20 @@ public void test500JackAssignAccountDummyMagenta() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_MAGENTA_OID, null, true); deltas.add(accountAssignmentUserDelta); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); @@ -1396,19 +1396,19 @@ public void test500JackAssignAccountDummyMagenta() throws Exception { assertAccount(userJack, RESOURCE_DUMMY_PINK_OID); assertAccount(userJack, RESOURCE_DUMMY_VIOLET_OID); assertAccount(userJack, RESOURCE_DUMMY_MAGENTA_OID); - + String accountMagentaOid = getLinkRefOid(userJack, RESOURCE_DUMMY_MAGENTA_OID); - + // Check shadow PrismObject accountMagentaShadow = repositoryService.getObject(ShadowType.class, accountMagentaOid, null, result); assertAccountShadowRepo(accountMagentaShadow, accountMagentaOid, "jack", resourceDummyMagentaType); - + // Check account PrismObject accountMagentaModel = modelService.getObject(ShadowType.class, accountMagentaOid, null, task, result); assertAccountShadowModel(accountMagentaModel, accountMagentaOid, "jack", resourceDummyMagentaType); - + assertIteration(accountMagentaShadow, 0, ""); - + // Check account in dummy resource assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); // The original conflicting account should still remain @@ -1416,10 +1416,10 @@ public void test500JackAssignAccountDummyMagenta() throws Exception { assertDummyAccount(RESOURCE_DUMMY_VIOLET_NAME, "jack.1", "Jack Sparrow", true); // The new account assertDummyAccount(RESOURCE_DUMMY_MAGENTA_NAME, "jack", "Jack Sparrow", true); - - PrismAsserts.assertPropertyValue(userJack, UserType.F_ORGANIZATION, + + PrismAsserts.assertPropertyValue(userJack, UserType.F_ORGANIZATION, PrismTestUtil.createPolyString(DESCRIPTION_RUM)); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(3); @@ -1430,7 +1430,7 @@ public void test500JackAssignAccountDummyMagenta() throws Exception { dummyAuditService.assertHasDelta(ChangeType.ADD, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + /** * Conflict on quote attribute */ @@ -1442,64 +1442,64 @@ public void test510DrakeAssignAccountDummyMagenta() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userDrake = PrismTestUtil.parseObject(USER_DRAKE_FILE); userDrake.asObjectable().setDescription(DESCRIPTION_RUM); userDrake.asObjectable().setLocality(PrismTestUtil.createPolyStringType("Jamaica")); addObject(userDrake); - + dummyAuditService.clear(); - + // Make sure there are some dummy accounts without quote. So if the code tries to search for null // it will get something and the test fails dummyResourceCtlMagenta.addAccount("afettucini", "Alfredo Fettucini"); dummyResourceCtlMagenta.addAccount("bfettucini", "Bill Fettucini"); - + Collection> deltas = new ArrayList>(); - ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_DRAKE_OID, + ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_DRAKE_OID, RESOURCE_DUMMY_MAGENTA_OID, null, true); deltas.add(accountAssignmentUserDelta); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userDrakeAfter = getUser(USER_DRAKE_OID); display("User after change execution", userDrakeAfter); assertUser(userDrakeAfter, USER_DRAKE_OID, "drake", "Francis Drake", "Fancis", "Drake"); assertLinks(userDrakeAfter, 1); assertAccount(userDrakeAfter, RESOURCE_DUMMY_MAGENTA_OID); - + String accountMagentaOid = getLinkRefOid(userDrakeAfter, RESOURCE_DUMMY_MAGENTA_OID); - + // Check shadow PrismObject accountMagentaShadow = repositoryService.getObject(ShadowType.class, accountMagentaOid, null, result); assertAccountShadowRepo(accountMagentaShadow, accountMagentaOid, "drake001", resourceDummyMagentaType); - + assertIteration(accountMagentaShadow, 1, "001"); - + // Check account PrismObject accountMagentaModel = modelService.getObject(ShadowType.class, accountMagentaOid, null, task, result); assertAccountShadowModel(accountMagentaModel, accountMagentaOid, "drake001", resourceDummyMagentaType); - + // There should be no account with the "straight" name assertNoDummyAccount(RESOURCE_DUMMY_MAGENTA_NAME, "drake"); // The new account assertDummyAccount(RESOURCE_DUMMY_MAGENTA_NAME, "drake001", "Francis Drake", true); - - assertDummyAccountAttribute(RESOURCE_DUMMY_MAGENTA_NAME, "drake001", + + assertDummyAccountAttribute(RESOURCE_DUMMY_MAGENTA_NAME, "drake001", DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, DESCRIPTION_RUM + " -- Francis Drake"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAGENTA_NAME, "drake001", + assertDummyAccountAttribute(RESOURCE_DUMMY_MAGENTA_NAME, "drake001", DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Jamaica"); - - PrismAsserts.assertPropertyValue(userDrakeAfter, UserType.F_ORGANIZATION, + + PrismAsserts.assertPropertyValue(userDrakeAfter, UserType.F_ORGANIZATION, PrismTestUtil.createPolyString(DESCRIPTION_RUM + " -- Francis Drake")); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(3); @@ -1510,7 +1510,7 @@ public void test510DrakeAssignAccountDummyMagenta() throws Exception { dummyAuditService.assertHasDelta(ChangeType.ADD, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + /* * Modify a property that has nothing to do with iteration */ @@ -1521,49 +1521,49 @@ public void test520DrakeModifyLocality() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); - OperationResult result = task.getResult(); + OperationResult result = task.getResult(); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserReplace(USER_DRAKE_OID, UserType.F_LOCALITY, task, result, PrismTestUtil.createPolyString("London")); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userDrakeAfter = getUser(USER_DRAKE_OID); display("User after change execution", userDrakeAfter); assertUser(userDrakeAfter, USER_DRAKE_OID, "drake", "Francis Drake", "Fancis", "Drake"); assertLinks(userDrakeAfter, 1); assertAccount(userDrakeAfter, RESOURCE_DUMMY_MAGENTA_OID); - + String accountMagentaOid = getLinkRefOid(userDrakeAfter, RESOURCE_DUMMY_MAGENTA_OID); - + // Check shadow PrismObject accountMagentaShadow = repositoryService.getObject(ShadowType.class, accountMagentaOid, null, result); assertAccountShadowRepo(accountMagentaShadow, accountMagentaOid, "drake001", resourceDummyMagentaType); - + assertIteration(accountMagentaShadow, 1, "001"); - + // Check account PrismObject accountMagentaModel = modelService.getObject(ShadowType.class, accountMagentaOid, null, task, result); assertAccountShadowModel(accountMagentaModel, accountMagentaOid, "drake001", resourceDummyMagentaType); - + // There should be no account with the "straight" name assertNoDummyAccount(RESOURCE_DUMMY_MAGENTA_NAME, "drake"); // The new account assertDummyAccount(RESOURCE_DUMMY_MAGENTA_NAME, "drake001", "Francis Drake", true); - - assertDummyAccountAttribute(RESOURCE_DUMMY_MAGENTA_NAME, "drake001", + + assertDummyAccountAttribute(RESOURCE_DUMMY_MAGENTA_NAME, "drake001", DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "London"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAGENTA_NAME, "drake001", + assertDummyAccountAttribute(RESOURCE_DUMMY_MAGENTA_NAME, "drake001", DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, DESCRIPTION_RUM + " -- Francis Drake"); - - PrismAsserts.assertPropertyValue(userDrakeAfter, UserType.F_ORGANIZATION, + + PrismAsserts.assertPropertyValue(userDrakeAfter, UserType.F_ORGANIZATION, PrismTestUtil.createPolyString(DESCRIPTION_RUM + " -- Francis Drake")); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -1574,7 +1574,7 @@ public void test520DrakeModifyLocality() throws Exception { dummyAuditService.assertHasDelta(ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + /** * Nothing special in this test. Just plain assignment. No conflicts. It just prepares the ground for the next * test and also tests the normal case. @@ -1588,20 +1588,20 @@ public void test530GuybrushAssignAccountDummyMagenta() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_GUYBRUSH_OID, RESOURCE_DUMMY_MAGENTA_OID, null, true); deltas.add(accountAssignmentUserDelta); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userGuybrush = getUser(USER_GUYBRUSH_OID); display("User after change execution", userGuybrush); assertUser(userGuybrush, USER_GUYBRUSH_OID, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood", "Guybrush", "Threepwood"); @@ -1610,26 +1610,26 @@ public void test530GuybrushAssignAccountDummyMagenta() throws Exception { assertAccount(userGuybrush, RESOURCE_DUMMY_PINK_OID); assertAccount(userGuybrush, RESOURCE_DUMMY_VIOLET_OID); assertAccount(userGuybrush, RESOURCE_DUMMY_MAGENTA_OID); - + String accountMagentaOid = getLinkRefOid(userGuybrush, RESOURCE_DUMMY_MAGENTA_OID); - + // Check shadow PrismObject accountMagentaShadow = repositoryService.getObject(ShadowType.class, accountMagentaOid, null, result); assertAccountShadowRepo(accountMagentaShadow, accountMagentaOid, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, resourceDummyMagentaType); - + assertIteration(accountMagentaShadow, 0, ""); - + // Check account PrismObject accountMagentaModel = modelService.getObject(ShadowType.class, accountMagentaOid, null, task, result); assertAccountShadowModel(accountMagentaModel, accountMagentaOid, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, resourceDummyMagentaType); - + // There should be no account with the "straight" name assertNoDummyAccount(RESOURCE_DUMMY_VIOLET_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); // old account assertDummyAccount(RESOURCE_DUMMY_VIOLET_NAME, "guybrush.3", "Guybrush Threepwood", true); // The new account assertDummyAccount(RESOURCE_DUMMY_MAGENTA_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood", true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -1640,7 +1640,7 @@ public void test530GuybrushAssignAccountDummyMagenta() throws Exception { dummyAuditService.assertHasDelta(ChangeType.ADD, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + /** * Change Guybrushe's description so it conflicts with Jack's description in magenta resource. * As the iterator is also bound to the account identifier (ICF NAME) the guybrushe's account will @@ -1659,12 +1659,12 @@ public void test532GuybrushModifyDescription() throws Exception { // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_DESCRIPTION, task, result, DESCRIPTION_RUM); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userGuybrush = getUser(USER_GUYBRUSH_OID); display("User after change execution", userGuybrush); assertUser(userGuybrush, USER_GUYBRUSH_OID, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood", "Guybrush", "Threepwood"); @@ -1673,32 +1673,32 @@ public void test532GuybrushModifyDescription() throws Exception { assertAccount(userGuybrush, RESOURCE_DUMMY_PINK_OID); assertAccount(userGuybrush, RESOURCE_DUMMY_VIOLET_OID); assertAccount(userGuybrush, RESOURCE_DUMMY_MAGENTA_OID); - + String accountMagentaOid = getLinkRefOid(userGuybrush, RESOURCE_DUMMY_MAGENTA_OID); - + // Check shadow PrismObject accountMagentaShadow = repositoryService.getObject(ShadowType.class, accountMagentaOid, null, result); assertAccountShadowRepo(accountMagentaShadow, accountMagentaOid, ACCOUNT_GUYBRUSH_DUMMY_USERNAME + "001", resourceDummyMagentaType); - + // Check account PrismObject accountMagentaModel = modelService.getObject(ShadowType.class, accountMagentaOid, null, task, result); assertAccountShadowModel(accountMagentaModel, accountMagentaOid, ACCOUNT_GUYBRUSH_DUMMY_USERNAME + "001", resourceDummyMagentaType); - + // There should be no account with the "straight" name assertNoDummyAccount(RESOURCE_DUMMY_VIOLET_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); assertDummyAccount(RESOURCE_DUMMY_VIOLET_NAME, "guybrush.3", "Guybrush Threepwood", true); - + // 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); - - 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, + + PrismAsserts.assertPropertyValue(userGuybrush, UserType.F_ORGANIZATION, PrismTestUtil.createPolyString(DESCRIPTION_RUM + " -- Guybrush Threepwood")); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(3); @@ -1709,7 +1709,7 @@ public void test532GuybrushModifyDescription() throws Exception { dummyAuditService.assertHasDelta(ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test600JackRename() throws Exception { final String TEST_NAME = "test600JackRename"; @@ -1719,17 +1719,17 @@ public void test600JackRename() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyUserReplace(USER_JACK_OID, UserType.F_NAME, task, result, + modifyUserReplace(USER_JACK_OID, UserType.F_NAME, task, result, PrismTestUtil.createPolyString(USER_JACK_RENAMED_NAME)); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, USER_JACK_RENAMED_NAME, "Jack Sparrow", "Jack", "Sparrow", "Caribbean"); @@ -1738,29 +1738,29 @@ public void test600JackRename() throws Exception { assertAccount(userJack, RESOURCE_DUMMY_PINK_OID); assertAccount(userJack, RESOURCE_DUMMY_VIOLET_OID); assertAccount(userJack, RESOURCE_DUMMY_MAGENTA_OID); - + String accountMagentaOid = getLinkRefOid(userJack, RESOURCE_DUMMY_MAGENTA_OID); - + // Check shadow PrismObject accountMagentaShadow = repositoryService.getObject(ShadowType.class, accountMagentaOid, null, result); assertAccountShadowRepo(accountMagentaShadow, accountMagentaOid, USER_JACK_RENAMED_NAME, resourceDummyMagentaType); - + // Check account PrismObject accountMagentaModel = modelService.getObject(ShadowType.class, accountMagentaOid, null, task, result); assertAccountShadowModel(accountMagentaModel, accountMagentaOid, USER_JACK_RENAMED_NAME, resourceDummyMagentaType); - + assertIteration(accountMagentaShadow, 0, ""); - + assertDefaultDummyAccount(USER_JACK_RENAMED_NAME, "Jack Sparrow", true); assertDummyAccount(RESOURCE_DUMMY_PINK_NAME, USER_JACK_RENAMED_NAME, "Jack Sparrow", true); // The original conflicting account should still remain assertDummyAccount(RESOURCE_DUMMY_VIOLET_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Jack Violet", true); assertDummyAccount(RESOURCE_DUMMY_VIOLET_NAME, USER_JACK_RENAMED_NAME, "Jack Sparrow", true); assertDummyAccount(RESOURCE_DUMMY_MAGENTA_NAME, USER_JACK_RENAMED_NAME, "Jack Sparrow", true); - - PrismAsserts.assertPropertyValue(userJack, UserType.F_ORGANIZATION, + + PrismAsserts.assertPropertyValue(userJack, UserType.F_ORGANIZATION, PrismTestUtil.createPolyString(DESCRIPTION_RUM)); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -1771,7 +1771,7 @@ public void test600JackRename() throws Exception { dummyAuditService.assertHasDelta(ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test700DarkVioletSyncTask() throws Exception { final String TEST_NAME = "test700DarkVioletSyncTask"; @@ -1779,7 +1779,7 @@ public void test700DarkVioletSyncTask() throws Exception { // WHEN importObjectFromFile(TASK_LIVE_SYNC_DUMMY_DARK_VIOLET_FILE); - + // THEN waitForTaskStart(TASK_LIVE_SYNC_DUMMY_DARK_VIOLET_OID, false); } @@ -1796,24 +1796,24 @@ public void test710DarkVioletAddLeChuck() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + DummyAccount account = new DummyAccount(ACCOUNT_LECHUCK_USERNAME); account.setEnabled(true); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, LECHUCK_FULLNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + display("Adding dummy account", account.debugDump()); dummyResourceDarkViolet.addAccount(account); - + waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_DARK_VIOLET_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertUserNick(ACCOUNT_LECHUCK_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME); } - + /* * Create account with fullname LeChuck. User with name LeChuck.1 should be created (conflict). */ @@ -1826,25 +1826,25 @@ public void test712DarkVioletAddCharles() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + DummyAccount account = new DummyAccount(ACCOUNT_CHARLES_USERNAME); account.setEnabled(true); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, LECHUCK_FULLNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + display("Adding dummy account", account.debugDump()); dummyResourceDarkViolet.addAccount(account); - + waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_DARK_VIOLET_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertUserNick(ACCOUNT_LECHUCK_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME); assertUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".1"); } - + /* * Create account with fullname LeChuck. User with name LeChuck.2 should be created (second conflict). */ @@ -1857,20 +1857,20 @@ public void test714DarkVioletAddShinetop() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + DummyAccount account = new DummyAccount(ACCOUNT_SHINETOP_USERNAME); account.setEnabled(true); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, LECHUCK_FULLNAME); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Melee Island"); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + display("Adding dummy account", account.debugDump()); dummyResourceDarkViolet.addAccount(account); - + waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_DARK_VIOLET_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertUserNick(ACCOUNT_LECHUCK_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME); @@ -1887,21 +1887,21 @@ public void test716DarkVioletDeleteCharles() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + dummyResourceDarkViolet.deleteAccountByName(ACCOUNT_CHARLES_USERNAME); - + waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_DARK_VIOLET_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); 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"); } - + @Test public void test720DarkVioletModifyShinetopLocation() throws Exception { final String TEST_NAME = "test720DarkVioletModifyShinetopLocation"; @@ -1911,16 +1911,16 @@ public void test720DarkVioletModifyShinetopLocation() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + DummyAccount account = dummyResourceDarkViolet.getAccountByUsername(ACCOUNT_SHINETOP_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + account.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Monkey Island"); - + waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_DARK_VIOLET_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); displayAllUsers(); @@ -1928,7 +1928,7 @@ public void test720DarkVioletModifyShinetopLocation() throws Exception { assertNoUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME, 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"; @@ -1938,16 +1938,16 @@ public void test722DarkVioletModifyShinetopFullName() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + DummyAccount account = dummyResourceDarkViolet.getAccountByUsername(ACCOUNT_SHINETOP_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + account.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, CHUCKIE_FULLNAME); - + waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_DARK_VIOLET_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); displayAllUsers(); @@ -1956,7 +1956,7 @@ public void test722DarkVioletModifyShinetopFullName() throws Exception { assertUserNick(ACCOUNT_SHINETOP_USERNAME, CHUCKIE_FULLNAME, CHUCKIE_FULLNAME, "Monkey Island"); assertNoUserNick(ACCOUNT_SHINETOP_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".2"); } - + /* * Create account with fullname barbossa. But user barbossa already exists. * User with name barbossa.1 should be created (conflict). @@ -1970,24 +1970,24 @@ public void test730DarkVioletAddBarbossa() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + DummyAccount account = new DummyAccount(USER_BARBOSSA_USERNAME); account.setEnabled(true); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, USER_BARBOSSA_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + display("Adding dummy account", account.debugDump()); dummyResourceDarkViolet.addAccount(account); - + waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_DARK_VIOLET_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertUserNick(USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME+".1"); } - + /* * Create yet another account with fullname barbossa. We already have two barbossa users, * so the next one is barbossa.2. But there is a post-iteration condition that refuses that @@ -2003,25 +2003,25 @@ public void test732DarkVioletAddBarbossa() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + DummyAccount account = new DummyAccount("YA" + USER_BARBOSSA_USERNAME); account.setEnabled(true); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, USER_BARBOSSA_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + display("Adding dummy account", account.debugDump()); dummyResourceDarkViolet.addAccount(account); - + waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_DARK_VIOLET_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); 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"; @@ -2031,28 +2031,28 @@ public void test750DarkVioletAddMatusalem() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // IMPORTANT! Change of user template! deleteObject(ObjectTemplateType.class, USER_TEMPLATE_ITERATION_OID, task, result); addObject(USER_TEMPLATE_ITERATION_RANDOM_FILE); - + DummyAccount account = new DummyAccount(ACCOUNT_MATUSALEM_USERNAME); account.setEnabled(true); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, RUM_FULLNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + display("Adding dummy account", account.debugDump()); dummyResourceDarkViolet.addAccount(account); - + waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_DARK_VIOLET_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertUserNick(ACCOUNT_MATUSALEM_USERNAME, RUM_FULLNAME, RUM_FULLNAME); } - + /* * Create account with fullname Rum. User with name Rum.xxx should be created (conflict). */ @@ -2065,25 +2065,25 @@ public void test752DarkVioletAddDiplomatico() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + DummyAccount account = new DummyAccount(ACCOUNT_DIPLOMATICO_USERNAME); account.setEnabled(true); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, RUM_FULLNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + display("Adding dummy account", account.debugDump()); dummyResourceDarkViolet.addAccount(account); - + waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_DARK_VIOLET_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); displayAllUsers(); - + assertUserNick(ACCOUNT_MATUSALEM_USERNAME, RUM_FULLNAME, RUM_FULLNAME); - + iterationTokenDiplomatico = lookupIterationTokenByAdditionalName(ACCOUNT_DIPLOMATICO_USERNAME); assertUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenDiplomatico); } @@ -2100,29 +2100,29 @@ public void test754DarkVioletAddMilionario() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + DummyAccount account = new DummyAccount(ACCOUNT_MILLONARIO_USERNAME); account.setEnabled(true); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, RUM_FULLNAME); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Peru"); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + display("Adding dummy account", account.debugDump()); dummyResourceDarkViolet.addAccount(account); - + waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_DARK_VIOLET_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertUserNick(ACCOUNT_MATUSALEM_USERNAME, RUM_FULLNAME, RUM_FULLNAME); assertUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenDiplomatico); - + iterationTokenMillonario = lookupIterationTokenByAdditionalName(ACCOUNT_MILLONARIO_USERNAME); assertUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenMillonario, "Peru"); } - + @Test public void test756DarkVioletDeleteDiplomatico() throws Exception { final String TEST_NAME = "test756DarkVioletDeleteDiplomatico"; @@ -2132,21 +2132,21 @@ public void test756DarkVioletDeleteDiplomatico() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + dummyResourceDarkViolet.deleteAccountByName(ACCOUNT_DIPLOMATICO_USERNAME); - + waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_DARK_VIOLET_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); 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"); } - + @Test public void test760DarkVioletModifyMillonarioLocation() throws Exception { final String TEST_NAME = "test760DarkVioletModifyMillonarioLocation"; @@ -2156,16 +2156,16 @@ public void test760DarkVioletModifyMillonarioLocation() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + DummyAccount account = dummyResourceDarkViolet.getAccountByUsername(ACCOUNT_MILLONARIO_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + account.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Northern Peru"); - + waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_DARK_VIOLET_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); displayAllUsers(); @@ -2173,7 +2173,7 @@ public void test760DarkVioletModifyMillonarioLocation() throws Exception { assertNoUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenDiplomatico); assertUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenMillonario, "Northern Peru"); } - + /** * Rename to an identifier that is free. Empty iterationToken is expected. */ @@ -2186,16 +2186,16 @@ public void test762DarkVioletModifyMillonarioFullName() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + DummyAccount account = dummyResourceDarkViolet.getAccountByUsername(ACCOUNT_MILLONARIO_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + account.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, RON_FULLNAME); - + waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_DARK_VIOLET_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); displayAllUsers(); @@ -2204,10 +2204,10 @@ public void test762DarkVioletModifyMillonarioFullName() throws Exception { assertUserNick(ACCOUNT_MILLONARIO_USERNAME, RON_FULLNAME, RON_FULLNAME, "Northern Peru"); assertNoUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenMillonario); } - + /** * Rename to an identifier that is taken. New random iterationToken is expected. - */ + */ @Test public void test764DarkVioletModifyMatusalemFullName() throws Exception { final String TEST_NAME = "test764DarkVioletModifyMatusalemFullName"; @@ -2217,16 +2217,16 @@ public void test764DarkVioletModifyMatusalemFullName() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + DummyAccount account = dummyResourceDarkViolet.getAccountByUsername(ACCOUNT_MATUSALEM_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + account.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, RON_FULLNAME); - + waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_DARK_VIOLET_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); displayAllUsers(); @@ -2237,8 +2237,8 @@ public void test764DarkVioletModifyMatusalemFullName() throws Exception { assertUserNick(ACCOUNT_MILLONARIO_USERNAME, RON_FULLNAME, RON_FULLNAME, "Northern Peru"); assertNoUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenMillonario); } - - + + /** * MID-2887 */ @@ -2251,32 +2251,32 @@ public void test800UniqeEmailAddUserAlfredoFettucini() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + 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); - + // WHEN TestUtil.displayWhen(TEST_NAME); addObject(user, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(user.getOid()); display("User after change execution", userAfter); - assertUser(userAfter, user.getOid(), USER_ALFREDO_FETTUCINI_USERNAME, + assertUser(userAfter, user.getOid(), USER_ALFREDO_FETTUCINI_USERNAME, 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()); - + assertEquals("Wrong "+user+" emailAddress", USER_FETTUCINI_NICKNAME + EMAIL_SUFFIX, userAfter.asObjectable().getEmailAddress()); } - + /** * MID-2887 */ @@ -2289,32 +2289,32 @@ public void test802UniqeEmailAddUserBillFettucini() throws Exception { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + setDefaultObjectTemplate(UserType.COMPLEX_TYPE, USER_TEMPLATE_ITERATION_UNIQUE_EMAIL_OID); - - PrismObject user = createUser(USER_BILL_FETTUCINI_USERNAME, USER_BILL_FETTUCINI_GIVEN_NAME, + + PrismObject user = createUser(USER_BILL_FETTUCINI_USERNAME, USER_BILL_FETTUCINI_GIVEN_NAME, USER_BILL_FETTUCINI_FAMILY_NAME, USER_FETTUCINI_NICKNAME, true); - + // WHEN TestUtil.displayWhen(TEST_NAME); addObject(user, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(user.getOid()); display("User after change execution", userAfter); - assertUser(userAfter, user.getOid(), USER_BILL_FETTUCINI_USERNAME, + assertUser(userAfter, user.getOid(), USER_BILL_FETTUCINI_USERNAME, 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()); - + assertEquals("Wrong "+user+" emailAddress", USER_FETTUCINI_NICKNAME + ".1" + EMAIL_SUFFIX, userAfter.asObjectable().getEmailAddress()); } - + private PrismObject createUser(String username, String givenName, String familyName, String nickname, boolean enabled) throws SchemaException { @@ -2330,7 +2330,7 @@ private void assertUserLargo(PrismObject userLargo) { private void assertUserNick(String accountName, String accountFullName, String expectedUserName) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { assertUserNick(accountName, accountFullName, expectedUserName, null); } - + 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); @@ -2344,13 +2344,13 @@ private void assertUserNick(String accountName, String accountFullName, String e 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 { PrismObject user = findUserByUsername(expectedUserName); 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 { Task task = taskManager.createTaskInstance(TestIteration.class.getName() + ".lookupIterationTokenByAdditionalName"); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestLoggingConfiguration.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestLoggingConfiguration.java index 651c9cbe439..d6c8dc2c13c 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestLoggingConfiguration.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestLoggingConfiguration.java @@ -61,9 +61,9 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestLoggingConfiguration extends AbstractConfiguredModelIntegrationTest { - - final String JUL_LOGGER_NAME = "com.exmple.jul.logger"; - + + final String JUL_LOGGER_NAME = "com.exmple.jul.logger"; + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { InternalsConfig.setAvoidLoggingChange(false); @@ -72,86 +72,86 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti repoAddObjectFromFile(ROLE_SUPERUSER_FILE, initResult); login(userAdministrator); } - + @Test public void test001CreateSystemConfiguration() throws Exception { final String TEST_NAME = "test001CreateSystemConfiguration"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN LogfileTestTailer tailer = new LogfileTestTailer(LoggingConfigurationManager.AUDIT_LOGGER_NAME); - + PrismObject systemConfiguration = PrismTestUtil.parseObject(SYSTEM_CONFIGURATION_FILE); Task task = taskManager.createTaskInstance(TestLoggingConfiguration.class.getName()+"."+TEST_NAME); OperationResult result = task.getResult(); - ObjectDelta systemConfigurationAddDelta = ObjectDelta.createAddDelta(systemConfiguration); + ObjectDelta systemConfigurationAddDelta = ObjectDelta.createAddDelta(systemConfiguration); Collection> deltas = MiscSchemaUtil.createCollection(systemConfigurationAddDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN tailer.logAndTail(); - + assertBasicLogging(tailer); // TODO: more asserts - + tailer.close(); - + } - + @Test public void test002InitialConfiguration() throws Exception { final String TEST_NAME = "test002InitialConfiguration"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN LogfileTestTailer tailer = new LogfileTestTailer(LoggingConfigurationManager.AUDIT_LOGGER_NAME); - + Task task = taskManager.createTaskInstance(TestLoggingConfiguration.class.getName()+"."+TEST_NAME); OperationResult result = task.getResult(); - + PrismObject systemConfiguration = PrismTestUtil.parseObject(SYSTEM_CONFIGURATION_FILE); LoggingConfigurationType logging = systemConfiguration.asObjectable().getLogging(); - + applyTestLoggingConfig(logging); - + SubSystemLoggerConfigurationType modelSubSystemLogger = new SubSystemLoggerConfigurationType(); modelSubSystemLogger.setComponent(LoggingComponentType.PROVISIONING); modelSubSystemLogger.setLevel(LoggingLevelType.TRACE); logging.getSubSystemLogger().add(modelSubSystemLogger); - + PrismObjectDefinition systemConfigurationTypeDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(SystemConfigurationType.class); - Collection modifications = - PropertyDelta.createModificationReplacePropertyCollection(SystemConfigurationType.F_LOGGING, + Collection modifications = + PropertyDelta.createModificationReplacePropertyCollection(SystemConfigurationType.F_LOGGING, systemConfigurationTypeDefinition, logging); - + // Modify directly in repository, so the logging code in model will not notice the change repositoryService.modifyObject(SystemConfigurationType.class, AbstractInitializedModelIntegrationTest.SYSTEM_CONFIGURATION_OID, modifications, result); - + // precondition - tailer.logAndTail(); + tailer.logAndTail(); assertBasicLogging(tailer); tailer.assertMarkerNotLogged(LogfileTestTailer.LEVEL_TRACE, ProfilingDataManager.Subsystem.PROVISIONING.name()); - + // WHEN repositoryService.postInit(result); modelService.postInit(result); // THEN tailer.logAndTail(); - + assertBasicLogging(tailer); tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_TRACE, ProfilingDataManager.Subsystem.PROVISIONING.name()); - + tailer.close(); - + } - + /** * Overwrite initial system configuration by itself. Check that everything * still works. @@ -160,107 +160,107 @@ public void test002InitialConfiguration() throws Exception { public void test004OverwriteInitialConfiguration() throws Exception { final String TEST_NAME = "test004OverwriteInitialConfiguration"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN LogfileTestTailer tailer = new LogfileTestTailer(LoggingConfigurationManager.AUDIT_LOGGER_NAME); - + Task task = taskManager.createTaskInstance(TestLoggingConfiguration.class.getName()+"."+TEST_NAME); OperationResult result = task.getResult(); - + PrismObject systemConfiguration = getObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value()); String previousVersion = systemConfiguration.getVersion(); systemConfiguration.setVersion(null); - + // precondition - tailer.logAndTail(); + tailer.logAndTail(); assertBasicLogging(tailer); tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_TRACE, ProfilingDataManager.Subsystem.PROVISIONING.name()); - + ObjectDelta delta = ObjectDelta.createAddDelta(systemConfiguration); ModelExecuteOptions options = ModelExecuteOptions.createOverwrite(); - + // WHEN modelService.executeChanges(MiscSchemaUtil.createCollection(delta), options, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + tailer.logAndTail(); - + assertBasicLogging(tailer); tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_TRACE, ProfilingDataManager.Subsystem.PROVISIONING.name()); - + tailer.close(); - + PrismObject systemConfigurationNew = getObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value()); String newVersion = systemConfigurationNew.getVersion(); assertTrue("Versions do not follow: "+previousVersion+" -> "+newVersion, Integer.parseInt(previousVersion) < Integer.parseInt(newVersion)); - + } - + @Test public void test010AddModelSubsystemLogger() throws Exception { final String TEST_NAME = "test010AddModelSubsystemLogger"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN LogfileTestTailer tailer = new LogfileTestTailer(LoggingConfigurationManager.AUDIT_LOGGER_NAME); - + Task task = taskManager.createTaskInstance(TestLoggingConfiguration.class.getName()+"."+TEST_NAME); OperationResult result = task.getResult(); - + // Precondition tailer.logAndTail(); - + assertBasicLogging(tailer); tailer.assertMarkerNotLogged(LogfileTestTailer.LEVEL_DEBUG, ProfilingDataManager.Subsystem.MODEL.name()); tailer.assertMarkerNotLogged(LogfileTestTailer.LEVEL_TRACE, ProfilingDataManager.Subsystem.MODEL.name()); // Setup - PrismObject systemConfiguration = + PrismObject systemConfiguration = PrismTestUtil.parseObject(AbstractInitializedModelIntegrationTest.SYSTEM_CONFIGURATION_FILE); LoggingConfigurationType logging = systemConfiguration.asObjectable().getLogging(); - + applyTestLoggingConfig(logging); - + SubSystemLoggerConfigurationType modelSubSystemLogger = new SubSystemLoggerConfigurationType(); modelSubSystemLogger.setComponent(LoggingComponentType.MODEL); modelSubSystemLogger.setLevel(LoggingLevelType.DEBUG); logging.getSubSystemLogger().add(modelSubSystemLogger); - - ObjectDelta systemConfigDelta = ObjectDelta.createModificationReplaceProperty(SystemConfigurationType.class, - AbstractInitializedModelIntegrationTest.SYSTEM_CONFIGURATION_OID, SystemConfigurationType.F_LOGGING, prismContext, + + ObjectDelta systemConfigDelta = ObjectDelta.createModificationReplaceProperty(SystemConfigurationType.class, + AbstractInitializedModelIntegrationTest.SYSTEM_CONFIGURATION_OID, SystemConfigurationType.F_LOGGING, prismContext, logging); Collection> deltas = MiscSchemaUtil.createCollection(systemConfigDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN tailer.logAndTail(); - + assertBasicLogging(tailer); tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_DEBUG, ProfilingDataManager.Subsystem.MODEL.name()); tailer.assertMarkerNotLogged(LogfileTestTailer.LEVEL_TRACE, ProfilingDataManager.Subsystem.MODEL.name()); - + // Test that the class logger for this test messages works // GIVEN tailer.setExpecteMessage("This is THE MESSage"); - + // WHEN display("This is THE MESSage"); - + // THEN tailer.tail(); tailer.assertExpectedMessage(); - + tailer.close(); - + } @@ -268,12 +268,12 @@ public void test010AddModelSubsystemLogger() throws Exception { public void test020JulLoggingDisabled() throws Exception { final String TEST_NAME = "test020JulLoggingDisabled"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN LogfileTestTailer tailer = new LogfileTestTailer(LoggingConfigurationManager.AUDIT_LOGGER_NAME); - + java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(JUL_LOGGER_NAME); - + // WHEN julLogger.severe(LogfileTestTailer.MARKER + " JULsevere"); julLogger.warning(LogfileTestTailer.MARKER + " JULwarning"); @@ -281,52 +281,52 @@ public void test020JulLoggingDisabled() throws Exception { julLogger.fine(LogfileTestTailer.MARKER + " JULfine"); julLogger.finer(LogfileTestTailer.MARKER + " JULfiner"); julLogger.finest(LogfileTestTailer.MARKER + " JULfinest"); - + tailer.tail(); - + tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_ERROR, "JULsevere"); tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_WARN, "JULwarning"); tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_INFO, "JULinfo"); tailer.assertMarkerNotLogged(LogfileTestTailer.LEVEL_DEBUG, "JULfine"); tailer.assertMarkerNotLogged(LogfileTestTailer.LEVEL_DEBUG, "JULfiner"); tailer.assertMarkerNotLogged(LogfileTestTailer.LEVEL_TRACE, "JULfinest"); - + tailer.close(); - + } @Test public void test021JulLoggingEnabled() throws Exception { final String TEST_NAME = "test021JulLoggingEnabled"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN LogfileTestTailer tailer = new LogfileTestTailer(LoggingConfigurationManager.AUDIT_LOGGER_NAME); - + java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(JUL_LOGGER_NAME); - + Task task = taskManager.createTaskInstance(TestLoggingConfiguration.class.getName()+"."+TEST_NAME); OperationResult result = task.getResult(); - + // Setup - PrismObject systemConfiguration = + PrismObject systemConfiguration = PrismTestUtil.parseObject(AbstractInitializedModelIntegrationTest.SYSTEM_CONFIGURATION_FILE); LoggingConfigurationType logging = systemConfiguration.asObjectable().getLogging(); - + applyTestLoggingConfig(logging); - + ClassLoggerConfigurationType classLogerCongif = new ClassLoggerConfigurationType(); classLogerCongif.setPackage(JUL_LOGGER_NAME); classLogerCongif.setLevel(LoggingLevelType.ALL); logging.getClassLogger().add(classLogerCongif ); - - ObjectDelta systemConfigDelta = ObjectDelta.createModificationReplaceProperty(SystemConfigurationType.class, - AbstractInitializedModelIntegrationTest.SYSTEM_CONFIGURATION_OID, SystemConfigurationType.F_LOGGING, prismContext, + + ObjectDelta systemConfigDelta = ObjectDelta.createModificationReplaceProperty(SystemConfigurationType.class, + AbstractInitializedModelIntegrationTest.SYSTEM_CONFIGURATION_OID, SystemConfigurationType.F_LOGGING, prismContext, logging); Collection> deltas = MiscSchemaUtil.createCollection(systemConfigDelta); - + modelService.executeChanges(deltas, null, task, result); - + // WHEN julLogger.severe(LogfileTestTailer.MARKER + " JULsevere"); julLogger.warning(LogfileTestTailer.MARKER + " JULwarning"); @@ -334,20 +334,20 @@ public void test021JulLoggingEnabled() throws Exception { julLogger.fine(LogfileTestTailer.MARKER + " JULfine"); julLogger.finer(LogfileTestTailer.MARKER + " JULfiner"); julLogger.finest(LogfileTestTailer.MARKER + " JULfinest"); - + tailer.tail(); - + tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_ERROR, "JULsevere"); tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_WARN, "JULwarning"); tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_INFO, "JULinfo"); tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_DEBUG, "JULfine"); tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_DEBUG, "JULfiner"); tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_TRACE, "JULfinest"); - + tailer.close(); - + } - + /** * Test if connectors log properly. The dummy connector logs on all levels when the * "test" operation is invoked. So let's try it. @@ -356,86 +356,86 @@ public void test021JulLoggingEnabled() throws Exception { public void test030ConnectorLogging() throws Exception { final String TEST_NAME = "test030ConnectorLogging"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN LogfileTestTailer tailer = new LogfileTestTailer(LoggingConfigurationManager.AUDIT_LOGGER_NAME); // ICF logging is prefixing the messages; tailer.setAllowPrefix(true); - + Task task = taskManager.createTaskInstance(TestLoggingConfiguration.class.getName()+"."+TEST_NAME); OperationResult result = task.getResult(); - + importObjectFromFile(RESOURCE_DUMMY_FILE, result); - + // Setup - PrismObject systemConfiguration = + PrismObject systemConfiguration = PrismTestUtil.parseObject(AbstractInitializedModelIntegrationTest.SYSTEM_CONFIGURATION_FILE); LoggingConfigurationType logging = systemConfiguration.asObjectable().getLogging(); - + applyTestLoggingConfig(logging); - + ClassLoggerConfigurationType classLogerCongif = new ClassLoggerConfigurationType(); classLogerCongif.setPackage(DummyConnector.class.getPackage().getName()); classLogerCongif.setLevel(LoggingLevelType.ALL); logging.getClassLogger().add(classLogerCongif ); - - ObjectDelta systemConfigDelta = ObjectDelta.createModificationReplaceProperty(SystemConfigurationType.class, - AbstractInitializedModelIntegrationTest.SYSTEM_CONFIGURATION_OID, SystemConfigurationType.F_LOGGING, prismContext, + + ObjectDelta systemConfigDelta = ObjectDelta.createModificationReplaceProperty(SystemConfigurationType.class, + AbstractInitializedModelIntegrationTest.SYSTEM_CONFIGURATION_OID, SystemConfigurationType.F_LOGGING, prismContext, logging); Collection> deltas = MiscSchemaUtil.createCollection(systemConfigDelta); - + modelService.executeChanges(deltas, null, task, result); - + // INFO part - + java.util.logging.Logger dummyConnctorJulLogger = java.util.logging.Logger.getLogger(DummyConnector.class.getName()); - LOGGER.info("Dummy connector JUL logger as seen by the test: {}; classloader {}", + LOGGER.info("Dummy connector JUL logger as seen by the test: {}; classloader {}", dummyConnctorJulLogger, dummyConnctorJulLogger.getClass().getClassLoader()); - + // WHEN modelService.testResource(RESOURCE_DUMMY_OID, task); - + // THEN tailer.tail(); - + tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_ERROR, "DummyConnectorIcfError"); tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_WARN, "DummyConnectorIcfWarn"); tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_DEBUG, "DummyConnectorIcfInfo"); tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_TRACE, "DummyConnectorIcfOk"); - + tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_ERROR, "DummyConnectorJULsevere"); tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_WARN, "DummyConnectorJULwarning"); tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_INFO, "DummyConnectorJULinfo"); tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_DEBUG, "DummyConnectorJULfine"); tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_DEBUG, "DummyConnectorJULfiner"); tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_TRACE, "DummyConnectorJULfinest"); - + tailer.close(); - + } - + @Test public void test101EnableBasicAudit() throws Exception { TestUtil.displayTestTitle("test101EnableBasicAudit"); - + // GIVEN LogfileTestTailer tailer = new LogfileTestTailer(LoggingConfigurationManager.AUDIT_LOGGER_NAME); - + Task task = taskManager.createTaskInstance(TestLoggingConfiguration.class.getName()+".test101EnableBasicAudit"); OperationResult result = task.getResult(); - + // Precondition tailer.tail(); tailer.assertNoAudit(); // Setup - PrismObject systemConfiguration = + PrismObject systemConfiguration = PrismTestUtil.parseObject(AbstractInitializedModelIntegrationTest.SYSTEM_CONFIGURATION_FILE); LoggingConfigurationType logging = systemConfiguration.asObjectable().getLogging(); - + applyTestLoggingConfig(logging); - + AuditingConfigurationType auditingConfigurationType = logging.getAuditing(); if (auditingConfigurationType == null) { auditingConfigurationType = new AuditingConfigurationType(); @@ -443,40 +443,40 @@ public void test101EnableBasicAudit() throws Exception { } auditingConfigurationType.setEnabled(true); auditingConfigurationType.setDetails(false); - - ObjectDelta systemConfigDelta = ObjectDelta.createModificationReplaceProperty(SystemConfigurationType.class, - AbstractInitializedModelIntegrationTest.SYSTEM_CONFIGURATION_OID, SystemConfigurationType.F_LOGGING, prismContext, + + ObjectDelta systemConfigDelta = ObjectDelta.createModificationReplaceProperty(SystemConfigurationType.class, + AbstractInitializedModelIntegrationTest.SYSTEM_CONFIGURATION_OID, SystemConfigurationType.F_LOGGING, prismContext, logging); Collection> deltas = MiscSchemaUtil.createCollection(systemConfigDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // Make sure that the (optional) audit message from the above change will not get into the way tailer.tail(); tailer.reset(); - + // This message will appear in the log and will help diagnose problems display("TEST: Applied audit config, going to execute test change"); - + // try do execute some change (add user object), it should be audited PrismObject user = PrismTestUtil.parseObject(AbstractInitializedModelIntegrationTest.USER_JACK_FILE); deltas = MiscSchemaUtil.createCollection(ObjectDelta.createAddDelta(user)); - + modelService.executeChanges(deltas, null, task, result); // This message will appear in the log and will help diagnose problems display("TEST: Executed test change"); - + // THEN - + tailer.tail(); tailer.assertAudit(2); tailer.assertAuditRequest(); tailer.assertAuditExecution(); - + tailer.close(); - + } private void applyTestLoggingConfig(LoggingConfigurationType logging) { @@ -485,13 +485,13 @@ private void applyTestLoggingConfig(LoggingConfigurationType logging) { testClassLogger.setPackage(TestLoggingConfiguration.class.getName()); testClassLogger.setLevel(LoggingLevelType.TRACE); logging.getClassLogger().add(testClassLogger); - + ClassLoggerConfigurationType integrationTestToolsLogger = new ClassLoggerConfigurationType(); integrationTestToolsLogger.setPackage(IntegrationTestTools.class.getName()); integrationTestToolsLogger.setLevel(LoggingLevelType.TRACE); logging.getClassLogger().add(integrationTestToolsLogger); } - + private void assertBasicLogging(LogfileTestTailer tailer) { tailer.assertMarkerLogged(LogfileTestTailer.LEVEL_ERROR, ProfilingDataManager.Subsystem.MODEL.name()); tailer.assertMarkerNotLogged(LogfileTestTailer.LEVEL_TRACE, ProfilingDataManager.Subsystem.REPOSITORY.name()); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMapping.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMapping.java index 22c5d70dacb..0565e5318de 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMapping.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMapping.java @@ -71,9 +71,9 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestMapping extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/mapping"); - + // CRIMSON resource has STRONG mappings, non-tolerant attributes, absolute-like mappings protected static final File RESOURCE_DUMMY_CRIMSON_FILE = new File(TEST_DIR, "resource-dummy-crimson.xml"); protected static final String RESOURCE_DUMMY_CRIMSON_OID = "10000000-0000-0000-0000-0000000001c4"; @@ -85,10 +85,10 @@ public class TestMapping extends AbstractInitializedModelIntegrationTest { protected static final String RESOURCE_DUMMY_LIGHT_CRIMSON_OID = "aa5d09b4-54d9-11e7-8ece-576137828ab7"; protected static final String RESOURCE_DUMMY_LIGHT_CRIMSON_NAME = "lightCrimson"; protected static final String RESOURCE_DUMMY_LIGHT_CRIMSON_NAMESPACE = MidPointConstants.NS_RI; - + protected static final String USER_GUYBRUSH_PASSWORD_1_CLEAR = "1wannaBEaP1rat3"; protected static final String USER_GUYBRUSH_PASSWORD_2_CLEAR = "1wannaBEtheP1rat3"; - + protected static final String LOCALITY_BLOOD_ISLAND = "Blood Island"; protected static final String LOCALITY_BOOTY_ISLAND = "Booty Island"; protected static final String LOCALITY_SCABB_ISLAND = "Scabb Island"; @@ -104,12 +104,12 @@ public class TestMapping extends AbstractInitializedModelIntegrationTest { @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - - initDummyResourcePirate(RESOURCE_DUMMY_CRIMSON_NAME, + + initDummyResourcePirate(RESOURCE_DUMMY_CRIMSON_NAME, RESOURCE_DUMMY_CRIMSON_FILE, RESOURCE_DUMMY_CRIMSON_OID, initTask, initResult); - initDummyResourcePirate(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, + initDummyResourcePirate(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, RESOURCE_DUMMY_LIGHT_CRIMSON_FILE, RESOURCE_DUMMY_LIGHT_CRIMSON_OID, initTask, initResult); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); } @@ -125,28 +125,28 @@ public void test100ModifyUserAssignAccountDummyBlue() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // WHEN displayWhen(TEST_NAME); assignAccount(USER_JACK_OID, RESOURCE_DUMMY_BLUE_OID, null, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); String accountOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertAccountShadowRepo(accountShadow, accountOid, ACCOUNT_JACK_DUMMY_USERNAME, getDummyResourceType(RESOURCE_DUMMY_BLUE_NAME)); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertAccountShadowModel(accountModel, accountOid, ACCOUNT_JACK_DUMMY_USERNAME, getDummyResourceType(RESOURCE_DUMMY_BLUE_NAME)); - + // Check account in dummy resource assertDummyAccount(RESOURCE_DUMMY_BLUE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyAccountAttribute(RESOURCE_DUMMY_BLUE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, @@ -157,11 +157,11 @@ public void test100ModifyUserAssignAccountDummyBlue() throws Exception { UUID drinkUuidBlue = UUID.fromString(drinkBlue); assertNotNull("No drink UUID", drinkUuidBlue); display("Drink UUID", drinkUuidBlue.toString()); - + assertAccountShip(userJack, ACCOUNT_JACK_DUMMY_FULLNAME, null, getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME), task); - assertDummyAccountAttribute(RESOURCE_DUMMY_BLUE_NAME, USER_JACK_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_BLUE_NAME, USER_JACK_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "Where's the rum? -- Jack Sparrow"); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -172,7 +172,7 @@ public void test100ModifyUserAssignAccountDummyBlue() throws Exception { dummyAuditService.assertHasDelta(ChangeType.ADD, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test101ModifyUserFullName() throws Exception { final String TEST_NAME = "test101ModifyUserFullName"; @@ -187,20 +187,20 @@ public void test101ModifyUserFullName() throws Exception { displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, UserType.F_FULL_NAME, task, result, PrismTestUtil.createPolyString("Cpt. Jack Sparrow")); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Cpt. Jack Sparrow", "Jack", "Sparrow"); - + assertAccountShip(userJack, "Jack Sparrow", null, getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME), task); - + // 'quote' is non-tolerant attribute. As the source of the mapping is changed, the current // value is no longer legal and the reconciliation has to remove it. - assertNoDummyAccountAttribute(RESOURCE_DUMMY_BLUE_NAME, USER_JACK_USERNAME, + assertNoDummyAccountAttribute(RESOURCE_DUMMY_BLUE_NAME, USER_JACK_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME); // Check audit @@ -212,7 +212,7 @@ public void test101ModifyUserFullName() throws Exception { dummyAuditService.assertHasDelta(ChangeType.MODIFY, UserType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test102ModifyUserFullNameRecon() throws Exception { final String TEST_NAME = "test102ModifyUserFullNameRecon"; @@ -225,24 +225,24 @@ public void test102ModifyUserFullNameRecon() throws Exception { // WHEN displayWhen(TEST_NAME); - ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_JACK_OID, UserType.F_FULL_NAME, + ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_JACK_OID, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Captain Jack Sparrow")); Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); modelService.executeChanges(deltas, ModelExecuteOptions.createReconcile(), task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Captain Jack Sparrow", "Jack", "Sparrow"); - + assertAccountShip(userJack, "Jack Sparrow", null, getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME), task); - + // The quote attribute was empty before this operation. So the weak mapping kicks in // and sets a new value. - assertDummyAccountAttribute(RESOURCE_DUMMY_BLUE_NAME, USER_JACK_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_BLUE_NAME, USER_JACK_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "Where's the rum? -- Captain Jack Sparrow"); @@ -269,14 +269,14 @@ public void test104ModifyUserOrganizationalUnit() throws Exception { // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, task, result, PrismTestUtil.createPolyString("Black Pearl")); - + // THEN assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Captain Jack Sparrow", "Jack", "Sparrow"); - + assertAccountShip(userJack, "Jack Sparrow", "Black Pearl", getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME), task); // Check audit @@ -289,7 +289,7 @@ public void test104ModifyUserOrganizationalUnit() throws Exception { dummyAuditService.assertHasDelta(ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test105ModifyAccountShip() throws Exception { final String TEST_NAME = "test105ModifyAccountShip"; @@ -299,10 +299,10 @@ public void test105ModifyAccountShip() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + PrismObject userJack = getUser(USER_JACK_OID); String accountOid = getSingleLinkOid(userJack); - + Collection> deltas = new ArrayList>(); ObjectDelta accountDelta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, accountOid, getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME), @@ -311,14 +311,14 @@ accountOid, getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).getAttributePat // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN assertSuccess(result); - + userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Captain Jack Sparrow", "Jack", "Sparrow"); - + assertAccountShip(userJack, "Jack Sparrow", "Flying Dutchman", getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME), task); // Check audit @@ -332,7 +332,7 @@ accountOid, getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).getAttributePat } /** - * There is a weak mapping for ship attribute. + * There is a weak mapping for ship attribute. * Therefore try to remove the value. The weak mapping should be applied. */ @Test @@ -344,10 +344,10 @@ public void test106ModifyAccountShipReplaceEmpty() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + PrismObject userJack = getUser(USER_JACK_OID); String accountOid = getSingleLinkOid(userJack); - + Collection> deltas = new ArrayList>(); ObjectDelta accountDelta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, accountOid, getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME), @@ -356,14 +356,14 @@ accountOid, getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).getAttributePat // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN assertSuccess(result); - + userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Captain Jack Sparrow", "Jack", "Sparrow"); - + assertAccountShip(userJack, "Jack Sparrow", "Black Pearl", getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME), task); // Check audit @@ -375,7 +375,7 @@ accountOid, getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).getAttributePat dummyAuditService.assertHasDelta(ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test107ModifyAccountShipAgain() throws Exception { final String TEST_NAME = "test107ModifyAccountShipAgain"; @@ -385,10 +385,10 @@ public void test107ModifyAccountShipAgain() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + PrismObject userJack = getUser(USER_JACK_OID); String accountOid = getSingleLinkOid(userJack); - + Collection> deltas = new ArrayList>(); ObjectDelta accountDelta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, accountOid, getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME), @@ -397,14 +397,14 @@ accountOid, getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).getAttributePat // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN assertSuccess(result); - + userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Captain Jack Sparrow", "Jack", "Sparrow"); - + assertAccountShip(userJack, "Jack Sparrow", "HMS Dauntless", getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME), task); // Check audit @@ -416,9 +416,9 @@ accountOid, getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).getAttributePat dummyAuditService.assertHasDelta(ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + /** - * There is a weak mapping for ship attribute. + * There is a weak mapping for ship attribute. * Therefore try to remove the value. The weak mapping should be applied. */ @Test @@ -430,10 +430,10 @@ public void test108ModifyAccountShipDelete() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + PrismObject userJack = getUser(USER_JACK_OID); String accountOid = getSingleLinkOid(userJack); - + Collection> deltas = new ArrayList>(); ObjectDelta accountDelta = ObjectDelta.createModificationDeleteProperty(ShadowType.class, accountOid, getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME), @@ -442,14 +442,14 @@ accountOid, getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).getAttributePat // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN assertSuccess(result); - + userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Captain Jack Sparrow", "Jack", "Sparrow"); - + assertAccountShip(userJack, "Jack Sparrow", "Black Pearl", getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME), task); // Check audit @@ -461,7 +461,7 @@ accountOid, getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).getAttributePat dummyAuditService.assertHasDelta(ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test109ModifyUserUnassignAccountBlue() throws Exception { final String TEST_NAME = "test109ModifyUserUnassignAccountBlue"; @@ -471,27 +471,27 @@ public void test109ModifyUserUnassignAccountBlue() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + Collection> deltas = new ArrayList>(); ObjectDelta userDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_BLUE_OID, null, false); userDelta.addModificationReplaceProperty(UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Jack Sparrow")); userDelta.addModificationReplaceProperty(UserType.F_ORGANIZATIONAL_UNIT); deltas.add(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); assertUserJack(userJack, "Jack Sparrow", "Jack", "Sparrow"); // Check accountRef assertUserNoAccountRefs(userJack); - + // Check if dummy resource account is gone assertNoDummyAccount("jack"); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); @@ -502,8 +502,8 @@ public void test109ModifyUserUnassignAccountBlue() throws Exception { dummyAuditService.assertHasDelta(ChangeType.DELETE, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - - + + /** * Red dummy has STRONG mappings. */ @@ -516,39 +516,39 @@ public void test120ModifyUserAssignAccountDummyRed() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + Collection> deltas = new ArrayList>(); - ObjectDelta userDelta = createAccountAssignmentUserDelta(USER_JACK_OID, + ObjectDelta userDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_RED_OID, null, true); deltas.add(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); String accountOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertAccountShadowRepo(accountShadow, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_RED_NAME)); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertAccountShadowModel(accountModel, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_RED_NAME)); - + // Check account in dummy resource assertDummyAccount(RESOURCE_DUMMY_RED_NAME, "jack", "Jack Sparrow", true); - - assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, + + assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, "mouth", "pistol"); - assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "Where's the rum? -- red resource"); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -559,7 +559,7 @@ public void test120ModifyUserAssignAccountDummyRed() throws Exception { dummyAuditService.assertHasDelta(ChangeType.ADD, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test121ModifyUserFullName() throws Exception { final String TEST_NAME = "test121ModifyUserFullName"; @@ -573,14 +573,14 @@ public void test121ModifyUserFullName() throws Exception { // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_FULL_NAME, task, result, PrismTestUtil.createPolyString("Captain Jack Sparrow")); - + // THEN assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Captain Jack Sparrow", "Jack", "Sparrow"); - + assertAccountShip(userJack, "Captain Jack Sparrow", null, getDummyResourceController(RESOURCE_DUMMY_RED_NAME), task); // Check audit @@ -607,14 +607,14 @@ public void test122ModifyUserOrganizationalUnit() throws Exception { // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, task, result, PrismTestUtil.createPolyString("Black Pearl")); - + // THEN assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Captain Jack Sparrow", "Jack", "Sparrow"); - + assertAccountShip(userJack, "Captain Jack Sparrow", "Black Pearl", getDummyResourceController(RESOURCE_DUMMY_RED_NAME), task); // Check audit @@ -627,7 +627,7 @@ public void test122ModifyUserOrganizationalUnit() throws Exception { dummyAuditService.assertHasDelta(ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test123ModifyAccountShip() throws Exception { final String TEST_NAME = "test123ModifyAccountShip"; @@ -637,10 +637,10 @@ public void test123ModifyAccountShip() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + PrismObject userJack = getUser(USER_JACK_OID); String accountOid = getSingleLinkOid(userJack); - + Collection> deltas = new ArrayList>(); ObjectDelta accountDelta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, accountOid, getDummyResourceController(RESOURCE_DUMMY_RED_NAME).getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME), @@ -650,21 +650,21 @@ accountOid, getDummyResourceController(RESOURCE_DUMMY_RED_NAME).getAttributePath // WHEN try { modelService.executeChanges(deltas, null, task, result); - + AssertJUnit.fail("Unexpected success"); } catch (SchemaException e) { // This is expected display("Expected exception", e); } - + // THEN result.computeStatus(); TestUtil.assertFailure(result); - + userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Captain Jack Sparrow", "Jack", "Sparrow"); - + assertAccountShip(userJack, "Captain Jack Sparrow", "Black Pearl", getDummyResourceController(RESOURCE_DUMMY_RED_NAME), task); // Check audit @@ -690,28 +690,28 @@ public void test124ModifyAccountShipReplaceEmpty() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + PrismObject userJack = getUser(USER_JACK_OID); String accountOid = getSingleLinkOid(userJack); - + Collection> deltas = new ArrayList>(); ObjectDelta accountDelta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, accountOid, getDummyResourceController(RESOURCE_DUMMY_RED_NAME).getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME), prismContext); deltas.add(accountDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN assertSuccess(result); - + userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Captain Jack Sparrow", "Jack", "Sparrow"); - + assertAccountShip(userJack, "Captain Jack Sparrow", "Black Pearl", getDummyResourceController(RESOURCE_DUMMY_RED_NAME), task); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); @@ -731,10 +731,10 @@ public void test126ModifyAccountShipDelete() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + PrismObject userJack = getUser(USER_JACK_OID); String accountOid = getSingleLinkOid(userJack); - + Collection> deltas = new ArrayList>(); ObjectDelta accountDelta = ObjectDelta.createModificationDeleteProperty(ShadowType.class, accountOid, getDummyResourceController(RESOURCE_DUMMY_RED_NAME).getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME), @@ -744,21 +744,21 @@ accountOid, getDummyResourceController(RESOURCE_DUMMY_RED_NAME).getAttributePath // WHEN try { modelService.executeChanges(deltas, null, task, result); - + AssertJUnit.fail("Unexpected success"); } catch (PolicyViolationException e) { // This is expected display("Expected exception", e); } - + // THEN result.computeStatus(); TestUtil.assertFailure(result); - + userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Captain Jack Sparrow", "Jack", "Sparrow"); - + assertAccountShip(userJack, "Captain Jack Sparrow", "Black Pearl", getDummyResourceController(RESOURCE_DUMMY_RED_NAME), task); // Check audit @@ -769,10 +769,10 @@ accountOid, getDummyResourceController(RESOURCE_DUMMY_RED_NAME).getAttributePath dummyAuditService.assertExecutionDeltas(0); dummyAuditService.assertExecutionOutcome(OperationResultStatus.FATAL_ERROR); } - + /** * Organization is used in the expression for "ship" attribute. But it is not specified as a source. - * Nevertheless the mapping is strong, therefore the result should be applied anyway. + * Nevertheless the mapping is strong, therefore the result should be applied anyway. * Reconciliation should be triggered. */ @Test @@ -788,14 +788,14 @@ public void test128ModifyUserOrganization() throws Exception { // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_ORGANIZATION, task, result, PrismTestUtil.createPolyString("Brethren of the Coast")); - + // THEN assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Captain Jack Sparrow", "Jack", "Sparrow"); - + assertAccountShip(userJack, "Captain Jack Sparrow", "Brethren of the Coast / Black Pearl", getDummyResourceController(RESOURCE_DUMMY_RED_NAME), task); // Check audit @@ -808,7 +808,7 @@ public void test128ModifyUserOrganization() throws Exception { dummyAuditService.assertHasDelta(ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + /** * Note: red resource disables account on unsassign, does NOT delete it */ @@ -821,41 +821,41 @@ public void test138ModifyUserUnassignAccountRed() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_RED_OID, null, false); deltas.add(accountAssignmentUserDelta); - + XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN assertSuccess(result); - + XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userJack = getUser(USER_JACK_OID); assertUserJack(userJack, "Captain Jack Sparrow", "Jack", "Sparrow"); - + String accountRedOid = getLinkRefOid(userJack, RESOURCE_DUMMY_RED_OID); PrismObject accountRed = getShadowModel(accountRedOid); - + XMLGregorianCalendar trigStart = clock.currentTimeXMLGregorianCalendar(); trigStart.add(XmlTypeConverter.createDuration(true, 0, 0, 25, 0, 0, 0)); XMLGregorianCalendar trigEnd = clock.currentTimeXMLGregorianCalendar(); trigEnd.add(XmlTypeConverter.createDuration(true, 0, 0, 35, 0, 0, 0)); assertTrigger(accountRed, RecomputeTriggerHandler.HANDLER_URI, trigStart, trigEnd); - + XMLGregorianCalendar disableTimestamp = accountRed.asObjectable().getActivation().getDisableTimestamp(); TestUtil.assertBetween("Wrong disableTimestamp", start, end, disableTimestamp); assertAccountShip(userJack, "Captain Jack Sparrow", "Brethren of the Coast / Black Pearl", false, getDummyResourceController(RESOURCE_DUMMY_RED_NAME), task); - + // Check if dummy resource account is gone assertNoDummyAccount("jack"); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); @@ -866,7 +866,7 @@ public void test138ModifyUserUnassignAccountRed() throws Exception { dummyAuditService.assertHasDelta(ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + /** * Note: red resource disables account on unsassign, does NOT delete it * So let's delete the account explicitly to make room for the following tests @@ -880,28 +880,28 @@ public void test139DeleteAccountRed() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + PrismObject userJack = getUser(USER_JACK_OID); String acccountRedOid = getLinkRefOid(userJack, RESOURCE_DUMMY_RED_OID); - + Collection> deltas = new ArrayList>(); ObjectDelta shadowDelta = ObjectDelta.createDeleteDelta(ShadowType.class, acccountRedOid, prismContext); deltas.add(shadowDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN assertSuccess(result); - + userJack = getUser(USER_JACK_OID); assertUserJack(userJack, "Captain Jack Sparrow", "Jack", "Sparrow"); assertNoLinkedAccount(userJack); - + // Check if dummy resource accounts are gone assertNoDummyAccount("jack"); assertNoDummyAccount(RESOURCE_DUMMY_RED_NAME, "jack"); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); @@ -913,7 +913,7 @@ public void test139DeleteAccountRed() throws Exception { dummyAuditService.assertExecutionSuccess(); } - + /** * Default dummy has combination of NORMAL, WEAK and STRONG mappings. */ @@ -926,36 +926,36 @@ public void test140ModifyUserAssignAccountDummyDefault() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + Collection> deltas = new ArrayList>(); - ObjectDelta userDelta = createAccountAssignmentUserDelta(USER_JACK_OID, + ObjectDelta userDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, null, true); userDelta.addModificationReplaceProperty(UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Jack Sparrow")); userDelta.addModificationReplaceProperty(UserType.F_ORGANIZATIONAL_UNIT); deltas.add(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); String accountOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertAccountShadowRepo(accountShadow, accountOid, "jack", getDummyResourceType()); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertAccountShadowModel(accountModel, accountOid, "jack", getDummyResourceType()); - + // Check account in dummy resource assertDummyAccount(null, "jack", "Jack Sparrow", true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -966,7 +966,7 @@ public void test140ModifyUserAssignAccountDummyDefault() throws Exception { dummyAuditService.assertHasDelta(ChangeType.ADD, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + /** * fullName mapping is NORMAL, the change should go through */ @@ -983,14 +983,14 @@ public void test141ModifyUserFullName() throws Exception { // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_FULL_NAME, task, result, PrismTestUtil.createPolyString("Captain Jack Sparrow")); - + // THEN assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Captain Jack Sparrow", "Jack", "Sparrow"); - + assertAccountShip(userJack, "Captain Jack Sparrow", null, dummyResourceCtl, task); // Check audit @@ -1020,14 +1020,14 @@ public void test142ModifyUserLocality() throws Exception { // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_LOCALITY, task, result, PrismTestUtil.createPolyString("Fountain of Youth")); - + // THEN assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Captain Jack Sparrow", "Jack", "Sparrow", "Fountain of Youth"); - + assertAccountLocation(userJack, "Captain Jack Sparrow", "Fountain of Youth", dummyResourceCtl, task); // Check audit @@ -1040,7 +1040,7 @@ public void test142ModifyUserLocality() throws Exception { dummyAuditService.assertHasDelta(ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test143ModifyAccountLocation() throws Exception { final String TEST_NAME = "test143ModifyAccountLocation"; @@ -1050,10 +1050,10 @@ public void test143ModifyAccountLocation() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + PrismObject userJack = getUser(USER_JACK_OID); String accountOid = getSingleLinkOid(userJack); - + Collection> deltas = new ArrayList>(); ObjectDelta accountDelta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, accountOid, dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME), @@ -1063,21 +1063,21 @@ public void test143ModifyAccountLocation() throws Exception { // WHEN try { modelService.executeChanges(deltas, null, task, result); - + AssertJUnit.fail("Unexpected success"); } catch (SchemaException e) { // This is expected display("Expected exception", e); } - + // THEN result.computeStatus(); TestUtil.assertFailure(result); - + userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Captain Jack Sparrow", "Jack", "Sparrow", "Fountain of Youth"); - + assertAccountLocation(userJack, "Captain Jack Sparrow", "Fountain of Youth", dummyResourceCtl, task); // Check audit @@ -1103,26 +1103,26 @@ public void test144ModifyAccountLocationReplaceEmpty() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + PrismObject userJack = getUser(USER_JACK_OID); String accountOid = getSingleLinkOid(userJack); - + Collection> deltas = new ArrayList>(); ObjectDelta accountDelta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, accountOid, dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME), prismContext); deltas.add(accountDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN assertSuccess(result); - + userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Captain Jack Sparrow", "Jack", "Sparrow", "Fountain of Youth"); - + assertAccountLocation(userJack, "Captain Jack Sparrow", "Fountain of Youth", dummyResourceCtl, task); // Check audit @@ -1144,10 +1144,10 @@ public void test145ModifyAccountLocationDelete() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + PrismObject userJack = getUser(USER_JACK_OID); String accountOid = getSingleLinkOid(userJack); - + Collection> deltas = new ArrayList>(); ObjectDelta accountDelta = ObjectDelta.createModificationDeleteProperty(ShadowType.class, accountOid, dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME), @@ -1157,21 +1157,21 @@ public void test145ModifyAccountLocationDelete() throws Exception { // WHEN try { modelService.executeChanges(deltas, null, task, result); - + AssertJUnit.fail("Unexpected success"); } catch (PolicyViolationException e) { // This is expected display("Expected exception", e); } - + // THEN result.computeStatus(); TestUtil.assertFailure(result); - + userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Captain Jack Sparrow", "Jack", "Sparrow", "Fountain of Youth"); - + assertAccountLocation(userJack, "Captain Jack Sparrow", "Fountain of Youth", dummyResourceCtl, task); // Check audit @@ -1182,7 +1182,7 @@ public void test145ModifyAccountLocationDelete() throws Exception { dummyAuditService.assertExecutionDeltas(0); dummyAuditService.assertExecutionOutcome(OperationResultStatus.FATAL_ERROR); } - + @Test public void test148ModifyUserRename() throws Exception { final String TEST_NAME = "test148ModifyUserRename"; @@ -1196,14 +1196,14 @@ public void test148ModifyUserRename() throws Exception { // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_NAME, task, result, PrismTestUtil.createPolyString("renamedJack")); - + // THEN assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "renamedJack", "Captain Jack Sparrow", "Jack", "Sparrow", "Fountain of Youth"); - + assertAccountRename(userJack, "renamedJack", "Captain Jack Sparrow", dummyResourceCtl, task); // Check audit @@ -1216,8 +1216,8 @@ public void test148ModifyUserRename() throws Exception { dummyAuditService.assertHasDelta(ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - - + + @Test public void test149ModifyUserUnassignAccountDummy() throws Exception { final String TEST_NAME = "test149ModifyUserUnassignAccountDummy"; @@ -1227,25 +1227,25 @@ public void test149ModifyUserUnassignAccountDummy() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, null, false); deltas.add(accountAssignmentUserDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); assertUserJack(userJack, "renamedJack", "Captain Jack Sparrow", "Jack", "Sparrow", "Fountain of Youth"); // Check accountRef assertUserNoAccountRefs(userJack); - + // Check if dummy resource account is gone assertNoDummyAccount("renamedJack"); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); @@ -1257,65 +1257,65 @@ public void test149ModifyUserUnassignAccountDummy() throws Exception { dummyAuditService.assertExecutionSuccess(); } - + private void assertAccountShip(PrismObject userJack, String expectedFullName, String expectedShip, DummyResourceContoller resourceCtl, Task task) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, SchemaViolationException, ConflictException, ExpressionEvaluationException { assertAccount(userJack, expectedFullName, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, expectedShip, true, resourceCtl, task); } - + private void assertAccountShip(PrismObject userJack, String expectedFullName, String expectedShip, boolean expectedEnabled, DummyResourceContoller resourceCtl, Task task) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, SchemaViolationException, ConflictException, ExpressionEvaluationException { assertAccount(userJack, expectedFullName, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, expectedShip, expectedEnabled, resourceCtl, task); } - + private void assertAccountLocation(PrismObject userJack, String expectedFullName, String expectedShip, DummyResourceContoller resourceCtl, Task task) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, SchemaViolationException, ConflictException, ExpressionEvaluationException { assertAccount(userJack, expectedFullName, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, expectedShip, true, resourceCtl, task); } - + private void assertAccountRename(PrismObject userJack, String name, String expectedFullName, DummyResourceContoller resourceCtl, Task task) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, SchemaViolationException, ConflictException, ExpressionEvaluationException { assertAccount(userJack, name, expectedFullName, null, null, true, resourceCtl, task); } - + private void assertAccount(PrismObject userJack, String name, String expectedFullName, String shipAttributeName, String expectedShip, boolean expectedEnabled, DummyResourceContoller resourceCtl, Task task) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, SchemaViolationException, ConflictException, ExpressionEvaluationException { - // ship inbound mapping is used, it is strong + // ship inbound mapping is used, it is strong String accountOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, task.getResult()); display("Repo shadow", accountShadow); assertAccountShadowRepo(accountShadow, accountOid, name, resourceCtl.getResource().asObjectable()); - + // Check account // All the changes should be reflected to the account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, task.getResult()); display("Model shadow", accountModel); assertAccountShadowModel(accountModel, accountOid, name, resourceCtl.getResource().asObjectable()); - PrismAsserts.assertPropertyValue(accountModel, + PrismAsserts.assertPropertyValue(accountModel, resourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME), expectedFullName); if (shipAttributeName != null) { if (expectedShip == null) { - PrismAsserts.assertNoItem(accountModel, - resourceCtl.getAttributePath(shipAttributeName)); + PrismAsserts.assertNoItem(accountModel, + resourceCtl.getAttributePath(shipAttributeName)); } else { - PrismAsserts.assertPropertyValue(accountModel, + PrismAsserts.assertPropertyValue(accountModel, resourceCtl.getAttributePath(shipAttributeName), expectedShip); } } - + // Check account in dummy resource assertDummyAccount(resourceCtl.getName(), name, expectedFullName, expectedEnabled); } - + private void assertAccount(PrismObject userJack, String expectedFullName, String attributeName, String expectedShip, boolean expectedEnabled, DummyResourceContoller resourceCtl, Task task) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, SchemaViolationException, ConflictException, ExpressionEvaluationException { assertAccount(userJack, "jack", expectedFullName, attributeName, expectedShip, expectedEnabled, resourceCtl, task); } - + @Test public void test200ModifyUserAssignAccountDummyCrimson() throws Exception { @@ -1325,29 +1325,29 @@ public void test200ModifyUserAssignAccountDummyCrimson() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); assignAccount(USER_GUYBRUSH_OID, RESOURCE_DUMMY_CRIMSON_OID, null, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + // Check account in dummy resource - DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); display("Dummy account", dummyAccount); - assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, ACCOUNT_GUYBRUSH_DUMMY_LOCATION); - + } - + /** * MID-3661 */ @@ -1359,38 +1359,38 @@ public void test202NativeModifyDummyCrimsonThenReconcile() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - dummyAccountBefore.replaceAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + dummyAccountBefore.replaceAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, DRINK_VODKA, DRINK_WHISKY); - + display("Dummy account before", dummyAccountBefore); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_GUYBRUSH_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + // Check account in dummy resource - DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); display("Dummy account after", dummyAccountAfter); - assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, ACCOUNT_GUYBRUSH_DUMMY_LOCATION); - assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, DRINK_VODKA, DRINK_WHISKY, rumFrom(ACCOUNT_GUYBRUSH_DUMMY_LOCATION)); - + } - + /** * Just make sure that plain recon does not destroy anything. * MID-3661 @@ -1403,36 +1403,36 @@ public void test204DummyCrimsonReconcile() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); display("Dummy account before", dummyAccountBefore); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_GUYBRUSH_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + String accountOid = getSingleLinkOid(userAfter); PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Repo shadow after", repoShadow); assertNoPostponedOperation(repoShadow); - + // Check account in dummy resource - DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); display("Dummy account after", dummyAccountAfter); - assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, ACCOUNT_GUYBRUSH_DUMMY_LOCATION); - assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, DRINK_VODKA, DRINK_WHISKY, rumFrom(ACCOUNT_GUYBRUSH_DUMMY_LOCATION)); } @@ -1449,46 +1449,46 @@ public void test206DummyCrimsonReconcileIOError() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); display("Dummy account before", dummyAccountBefore); - + // Make sure that only get is broken and not modify. We want to give the test // a chance to destroy data. getDummyResource(RESOURCE_DUMMY_CRIMSON_NAME).setGetBreakMode(BreakMode.IO); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_GUYBRUSH_OID, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertPartialError(result); - + getDummyResource(RESOURCE_DUMMY_CRIMSON_NAME).resetBreakMode(); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + String accountOid = getSingleLinkOid(userAfter); PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Repo shadow after", repoShadow); assertNoPostponedOperation(repoShadow); - + // Check account in dummy resource - DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); display("Dummy account after", dummyAccountAfter); - assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, ACCOUNT_GUYBRUSH_DUMMY_LOCATION); - assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, - DRINK_VODKA, DRINK_WHISKY, rumFrom(ACCOUNT_GUYBRUSH_DUMMY_LOCATION)); + assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + DRINK_VODKA, DRINK_WHISKY, rumFrom(ACCOUNT_GUYBRUSH_DUMMY_LOCATION)); } - + /** * Just make sure that second recon run does not destroy anything. * MID-3661 @@ -1501,38 +1501,38 @@ public void test208DummyCrimsonReconcileAgain() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + getDummyResource(RESOURCE_DUMMY_CRIMSON_NAME).resetBreakMode(); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); display("Dummy account before", dummyAccountBefore); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_GUYBRUSH_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + String accountOid = getSingleLinkOid(userAfter); PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Repo shadow after", repoShadow); assertNoPostponedOperation(repoShadow); - + // Check account in dummy resource - DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); display("Dummy account after", dummyAccountAfter); - assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, ACCOUNT_GUYBRUSH_DUMMY_LOCATION); - assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, DRINK_VODKA, DRINK_WHISKY, rumFrom(ACCOUNT_GUYBRUSH_DUMMY_LOCATION)); } @@ -1547,41 +1547,41 @@ public void test210ModifyUserLocality() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + getDummyResource(RESOURCE_DUMMY_CRIMSON_NAME).resetBreakMode(); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); display("Dummy account before", dummyAccountBefore); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_LOCALITY, task, result, createPolyString(LOCALITY_BLOOD_ISLAND)); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + String accountOid = getSingleLinkOid(userAfter); PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Repo shadow after", repoShadow); assertNoPostponedOperation(repoShadow); - + // Check account in dummy resource - DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); display("Dummy account after", dummyAccountAfter); - assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, LOCALITY_BLOOD_ISLAND); - assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, DRINK_VODKA, DRINK_WHISKY, rumFrom(LOCALITY_BLOOD_ISLAND)); } - + /** * MID-3661 */ @@ -1593,45 +1593,45 @@ public void test212ModifyUserLocalityRecon() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + getDummyResource(RESOURCE_DUMMY_CRIMSON_NAME).resetBreakMode(); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); display("Dummy account before", dummyAccountBefore); - + // WHEN displayWhen(TEST_NAME); - ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_GUYBRUSH_OID, new ItemPath(UserType.F_LOCALITY), + ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_GUYBRUSH_OID, new ItemPath(UserType.F_LOCALITY), PrismTestUtil.createPolyString(LOCALITY_SCABB_ISLAND)); Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); ModelExecuteOptions options = ModelExecuteOptions.createReconcile(); modelService.executeChanges(deltas, options, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + String accountOid = getSingleLinkOid(userAfter); PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Repo shadow after", repoShadow); assertNoPostponedOperation(repoShadow); - + // Check account in dummy resource - DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); display("Dummy account after", dummyAccountAfter); - assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, LOCALITY_SCABB_ISLAND); - assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, DRINK_VODKA, DRINK_WHISKY, "rum from Scabb Island"); } - + /** * MID-3661 */ @@ -1643,48 +1643,48 @@ public void test214ModifyUserLocalityIOError() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + getDummyResource(RESOURCE_DUMMY_CRIMSON_NAME).resetBreakMode(); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); display("Dummy account before", dummyAccountBefore); - + // Make sure that only get is broken and not modify. We want to give the test // a chance to destroy data. getDummyResource(RESOURCE_DUMMY_CRIMSON_NAME).setGetBreakMode(BreakMode.IO); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_LOCALITY, task, result, createPolyString(LOCALITY_BOOTY_ISLAND)); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + getDummyResource(RESOURCE_DUMMY_CRIMSON_NAME).resetBreakMode(); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + String accountOid = getSingleLinkOid(userAfter); PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Repo shadow after", repoShadow); assertNoPostponedOperation(repoShadow); - + // Check account in dummy resource - DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); display("Dummy account after", dummyAccountAfter); // TODO: How? Why? - assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, LOCALITY_BOOTY_ISLAND); - assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, DRINK_VODKA, DRINK_WHISKY, "rum from Scabb Island"); } - + /** * MID-3661 */ @@ -1692,56 +1692,56 @@ public void test214ModifyUserLocalityIOError() throws Exception { public void test220NativeModifyDummyCrimsonThenChangePassword() throws Exception { final String TEST_NAME = "test220NativeModifyDummyCrimsonThenChangePassword"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + getDummyResource(RESOURCE_DUMMY_CRIMSON_NAME).resetBreakMode(); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - dummyAccountBefore.replaceAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + dummyAccountBefore.replaceAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, DRINK_BRANDY, DRINK_GRAPPA); display("Dummy account before", dummyAccountBefore); - + // Make sure that only get is broken and not modify. We want to give the test // a chance to destroy data. getDummyResource(RESOURCE_DUMMY_CRIMSON_NAME).setGetBreakMode(BreakMode.IO); - + // WHEN displayWhen(TEST_NAME); modifyUserChangePassword(USER_GUYBRUSH_OID, USER_GUYBRUSH_PASSWORD_1_CLEAR, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + getDummyResource(RESOURCE_DUMMY_CRIMSON_NAME).resetBreakMode(); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + String accountOid = getSingleLinkOid(userAfter); PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Repo shadow after", repoShadow); assertNoPostponedOperation(repoShadow); - + assertEncryptedUserPassword(userAfter, USER_GUYBRUSH_PASSWORD_1_CLEAR); - + // Check account in dummy resource - DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); display("Dummy account after", dummyAccountAfter); - assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, LOCALITY_BOOTY_ISLAND); // location haven't changed and recon was not requested. The mapping was not evaluated. - assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, DRINK_BRANDY, DRINK_GRAPPA); } - + @Test public void test229ModifyUserUnassignAccountDummyCrimson() throws Exception { final String TEST_NAME = "test229ModifyUserUnassignAccountDummyCrimson"; @@ -1750,27 +1750,27 @@ public void test229ModifyUserUnassignAccountDummyCrimson() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); unassignAccount(USER_GUYBRUSH_OID, RESOURCE_DUMMY_CRIMSON_OID, null, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); assertNoAssignments(userAfter); assertLinks(userAfter, 0); - + // Check account in dummy resource assertNoDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - + } - + @Test public void test250ModifyUserAssignAccountDummyLightCrimson() throws Exception { final String TEST_NAME = "test250ModifyUserAssignAccountDummyLightCrimson"; @@ -1779,35 +1779,35 @@ public void test250ModifyUserAssignAccountDummyLightCrimson() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // preconditions PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); PrismAsserts.assertPropertyValue(userBefore, UserType.F_LOCALITY, createPolyString(LOCALITY_BOOTY_ISLAND)); assertNoDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - + // WHEN displayWhen(TEST_NAME); assignAccount(USER_GUYBRUSH_OID, RESOURCE_DUMMY_LIGHT_CRIMSON_OID, null, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + // Check account in dummy resource - DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); display("Dummy account", dummyAccount); - assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, LOCALITY_BOOTY_ISLAND); - + } - + /** * MID-3661, MID-3674 */ @@ -1819,38 +1819,38 @@ public void test252NativeModifyDummyLightCrimsonThenReconcile() throws Exception // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - dummyAccountBefore.replaceAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + dummyAccountBefore.replaceAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, DRINK_GIN, DRINK_MEZCAL); - + display("Dummy account before", dummyAccountBefore); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_GUYBRUSH_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + // Check account in dummy resource - DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); display("Dummy account after", dummyAccountAfter); - assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, LOCALITY_BOOTY_ISLAND); - assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, DRINK_GIN, DRINK_MEZCAL, rumFrom(LOCALITY_BOOTY_ISLAND)); - + } - + /** * Just make sure that plain recon does not destroy anything. * MID-3661, MID-3674 @@ -1863,40 +1863,40 @@ public void test254DummyLightCrimsonReconcile() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); display("Dummy account before", dummyAccountBefore); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_GUYBRUSH_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + String accountOid = getSingleLinkOid(userAfter); PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Repo shadow after", repoShadow); assertNoPostponedOperation(repoShadow); - + // Check account in dummy resource - DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); display("Dummy account after", dummyAccountAfter); - assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, LOCALITY_BOOTY_ISLAND); - assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, DRINK_GIN, DRINK_MEZCAL, rumFrom(LOCALITY_BOOTY_ISLAND)); - + } - + /** * IO Error on the resource. The account is not fetched. The operation should fail * and nothing should be destroyed. @@ -1910,46 +1910,46 @@ public void test256DummyLightCrimsonReconcileIOError() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); display("Dummy account before", dummyAccountBefore); - + // Make sure that only get is broken and not modify. We want to give the test // a chance to destroy data. getDummyResource(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME).setGetBreakMode(BreakMode.IO); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_GUYBRUSH_OID, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertPartialError(result); - + getDummyResource(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME).resetBreakMode(); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + String accountOid = getSingleLinkOid(userAfter); PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Repo shadow after", repoShadow); assertNoPostponedOperation(repoShadow); - + // Check account in dummy resource - DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); display("Dummy account after", dummyAccountAfter); - assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, LOCALITY_BOOTY_ISLAND); - assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, DRINK_GIN, DRINK_MEZCAL, rumFrom(LOCALITY_BOOTY_ISLAND)); } - + /** * Just make sure that second recon run does not destroy anything. * MID-3661, MID-3674 @@ -1962,41 +1962,41 @@ public void test258DummyLightCrimsonReconcileAgain() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + getDummyResource(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME).resetBreakMode(); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); display("Dummy account before", dummyAccountBefore); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_GUYBRUSH_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + String accountOid = getSingleLinkOid(userAfter); PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Repo shadow after", repoShadow); assertNoPostponedOperation(repoShadow); - + // Check account in dummy resource - DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); display("Dummy account after", dummyAccountAfter); - assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, LOCALITY_BOOTY_ISLAND); - assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, DRINK_GIN, DRINK_MEZCAL, rumFrom(LOCALITY_BOOTY_ISLAND)); } - + /** * MID-3661, MID-3674 */ @@ -2008,41 +2008,41 @@ public void test260ModifyUserLocality() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + getDummyResource(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME).resetBreakMode(); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); display("Dummy account before", dummyAccountBefore); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_LOCALITY, task, result, createPolyString(LOCALITY_BLOOD_ISLAND)); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + String accountOid = getSingleLinkOid(userAfter); PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Repo shadow after", repoShadow); assertNoPostponedOperation(repoShadow); - + // Check account in dummy resource - DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); display("Dummy account after", dummyAccountAfter); - assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, LOCALITY_BLOOD_ISLAND); - assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, DRINK_GIN, DRINK_MEZCAL, rumFrom(LOCALITY_BLOOD_ISLAND)); } - + /** * MID-3661, MID-3674 */ @@ -2054,45 +2054,45 @@ public void test262ModifyUserLocalityRecon() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + getDummyResource(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME).resetBreakMode(); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); display("Dummy account before", dummyAccountBefore); - + // WHEN displayWhen(TEST_NAME); - ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_GUYBRUSH_OID, new ItemPath(UserType.F_LOCALITY), + ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_GUYBRUSH_OID, new ItemPath(UserType.F_LOCALITY), PrismTestUtil.createPolyString(LOCALITY_SCABB_ISLAND)); Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); ModelExecuteOptions options = ModelExecuteOptions.createReconcile(); modelService.executeChanges(deltas, options, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + String accountOid = getSingleLinkOid(userAfter); PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Repo shadow after", repoShadow); assertNoPostponedOperation(repoShadow); - + // Check account in dummy resource - DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); display("Dummy account after", dummyAccountAfter); - assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, LOCALITY_SCABB_ISLAND); - assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, DRINK_GIN, DRINK_MEZCAL, rumFrom(LOCALITY_SCABB_ISLAND)); } - + /** * MID-3661, MID-3674 */ @@ -2104,48 +2104,48 @@ public void test264ModifyUserLocalityIOError() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + getDummyResource(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME).resetBreakMode(); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); display("Dummy account before", dummyAccountBefore); - + // Make sure that only get is broken and not modify. We want to give the test // a chance to destroy data. getDummyResource(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME).setGetBreakMode(BreakMode.IO); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_LOCALITY, task, result, createPolyString(LOCALITY_BOOTY_ISLAND)); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + getDummyResource(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME).resetBreakMode(); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + String accountOid = getSingleLinkOid(userAfter); PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Repo shadow after", repoShadow); assertNoPostponedOperation(repoShadow); - + // Check account in dummy resource - DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); display("Dummy account after", dummyAccountAfter); // TODO: How? Why? - assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, LOCALITY_BOOTY_ISLAND); - assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, DRINK_GIN, DRINK_MEZCAL, rumFrom(LOCALITY_SCABB_ISLAND)); } - + /** * MID-3661, MID-3674 */ @@ -2153,56 +2153,56 @@ public void test264ModifyUserLocalityIOError() throws Exception { public void test270NativeModifyDummyLightCrimsonThenChangePassword() throws Exception { final String TEST_NAME = "test270NativeModifyDummyLightCrimsonThenChangePassword"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + getDummyResource(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME).resetBreakMode(); - + DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - dummyAccountBefore.replaceAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + dummyAccountBefore.replaceAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, DRINK_BRANDY, DRINK_GRAPPA); display("Dummy account before", dummyAccountBefore); - + // Make sure that only get is broken and not modify. We want to give the test // a chance to destroy data. getDummyResource(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME).setGetBreakMode(BreakMode.IO); - + // WHEN displayWhen(TEST_NAME); modifyUserChangePassword(USER_GUYBRUSH_OID, USER_GUYBRUSH_PASSWORD_2_CLEAR, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + getDummyResource(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME).resetBreakMode(); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + String accountOid = getSingleLinkOid(userAfter); PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Repo shadow after", repoShadow); assertNoPostponedOperation(repoShadow); - + assertEncryptedUserPassword(userAfter, USER_GUYBRUSH_PASSWORD_2_CLEAR); - + // Check account in dummy resource - DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyAccount dummyAccountAfter = assertDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); display("Dummy account after", dummyAccountAfter); - assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, LOCALITY_BOOTY_ISLAND); // location haven't changed and recon was not requested. The mapping was not evaluated. - assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, DRINK_BRANDY, DRINK_GRAPPA); } - + @Test public void test279ModifyUserUnassignAccountDummyLightCrimson() throws Exception { final String TEST_NAME = "test279ModifyUserUnassignAccountDummyLightCrimson"; @@ -2211,28 +2211,28 @@ public void test279ModifyUserUnassignAccountDummyLightCrimson() throws Exception // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); unassignAccount(USER_GUYBRUSH_OID, RESOURCE_DUMMY_LIGHT_CRIMSON_OID, null, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); assertNoAssignments(userAfter); assertLinks(userAfter, 0); - + // Check account in dummy resource assertNoDummyAccount(RESOURCE_DUMMY_LIGHT_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_CRIMSON_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - + } - + /** * MID-3816, MID-4008 */ @@ -2244,36 +2244,36 @@ public void test300AssignGuybrushDummyYellow() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); assignAccount(USER_GUYBRUSH_OID, RESOURCE_DUMMY_YELLOW_OID, null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - + // Check account in dummy resource - DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); display("Dummy account", dummyAccount); - assertDummyAccountAttribute(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, IntegrationTestTools.CONST_DRINK); - assertDummyAccountAttribute(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, IntegrationTestTools.CONST_BLABLA + " administrator -- administrator"); - assertDummyAccountAttribute(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Some say elaine -- administrator"); } - + @Test public void test309UnassignGuybrushDummyYellow() throws Exception { final String TEST_NAME = "test309UnassignGuybrushDummyYellow"; @@ -2282,26 +2282,26 @@ public void test309UnassignGuybrushDummyYellow() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); unassignAccount(USER_GUYBRUSH_OID, RESOURCE_DUMMY_YELLOW_OID, null, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, + assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); assertNoAssignments(userAfter); assertLinks(userAfter, 0); - + // Check account in dummy resource assertNoDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); } - + private String rumFrom(String locality) { return "rum from " + locality; } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMappingInbound.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMappingInbound.java index 6f339f69a77..b104bd7895b 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMappingInbound.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMappingInbound.java @@ -50,7 +50,7 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestMappingInbound extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/mapping-inbound"); protected static final File RESOURCE_DUMMY_TEA_GREEN_FILE = new File(TEST_DIR, "resource-dummy-tea-green.xml"); @@ -242,5 +242,5 @@ protected void waitForSyncTaskStart() throws Exception { protected void waitForSyncTaskNextRun() throws Exception { waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_TEA_GREEN_OID, false, 10000); } - + } 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 2fd01ff0f99..d3a13482687 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 @@ -44,13 +44,13 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestMerge extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/merge"); - + public static final String MERGE_CONFIG_DEFAULT_NAME = "default"; public static final String MERGE_CONFIG_DEFAULT_SPECIFIC_NAME = "default-specific"; public static final String MERGE_CONFIG_EXPRESSION_NAME = "expression"; - + private String jackDummyAccountOid; private String jackDummyAccountRedOid; private String guybrushDummyAccountOid; @@ -59,17 +59,17 @@ public class TestMerge extends AbstractInitializedModelIntegrationTest { @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - - modifyUserAdd(USER_GUYBRUSH_OID, UserType.F_EMPLOYEE_TYPE, initTask, initResult, + + modifyUserAdd(USER_GUYBRUSH_OID, UserType.F_EMPLOYEE_TYPE, initTask, initResult, "SAILOR", "PIRATE WANNABE"); - modifyUserAdd(USER_GUYBRUSH_OID, UserType.F_ORGANIZATION, initTask, initResult, + modifyUserAdd(USER_GUYBRUSH_OID, UserType.F_ORGANIZATION, initTask, initResult, createPolyString("Pirate Wannabes"), createPolyString("Sailors"), createPolyString("Rum Club"), createPolyString("Lovers")); assignRole(USER_GUYBRUSH_OID, ROLE_SAILOR_OID, initTask, initResult); assignRole(USER_GUYBRUSH_OID, ROLE_CYAN_SAILOR_OID, initTask, initResult); assignRole(USER_GUYBRUSH_OID, ROLE_EMPTY_OID, initTask, initResult); assignRole(USER_GUYBRUSH_OID, ROLE_THIEF_OID, initTask, initResult); - - modifyUserAdd(USER_JACK_OID, UserType.F_ORGANIZATION, initTask, initResult, + + modifyUserAdd(USER_JACK_OID, UserType.F_ORGANIZATION, initTask, initResult, createPolyString("Pirate Brethren"), createPolyString("Sailors"), createPolyString("Rum Club"), createPolyString("Drinkers")); assignRole(USER_JACK_OID, ROLE_SAILOR_OID, initTask, initResult); assignRole(USER_JACK_OID, ROLE_RED_SAILOR_OID, initTask, initResult); @@ -77,26 +77,26 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti assignRole(USER_JACK_OID, ROLE_PIRATE_OID, initTask, initResult); assignRole(USER_JACK_OID, ROLE_NICE_PIRATE_OID, initTask, initResult); } - + @Test public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; TestUtil.displayTestTitle(this, TEST_NAME); - + PrismObject userJackBefore = getUser(USER_JACK_OID); display("Jack before", userJackBefore); - + jackDummyAccountOid = assertAccount(userJackBefore, RESOURCE_DUMMY_OID); jackDummyAccountRedOid = assertAccount(userJackBefore, RESOURCE_DUMMY_RED_OID); assertLinks(userJackBefore, 2); - + PrismObject userGuybrushBefore = getUser(USER_GUYBRUSH_OID); display("Guybrush before", userGuybrushBefore); - + guybrushDummyAccountOid = assertAccount(userGuybrushBefore, RESOURCE_DUMMY_OID); guybrushDummyAccountCyanOid = assertAccount(userGuybrushBefore, RESOURCE_DUMMY_CYAN_OID); assertLinks(userGuybrushBefore, 2); - + display("Jack DUMMY account", jackDummyAccountOid); display("Jack RED account", jackDummyAccountRedOid); display("Guybrush DUMMY account", guybrushDummyAccountOid); @@ -110,63 +110,63 @@ public void test000Sanity() throws Exception { public void test100MergeJackGuybrushPreviewDelta() throws Exception { final String TEST_NAME = "test100MergeJackGuybrushPreviewDelta"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userJackBefore = getUser(USER_JACK_OID); display("Jack before", userJackBefore); - + PrismObject userGuybrushBefore = getUser(USER_GUYBRUSH_OID); display("Guybrush before", userGuybrushBefore); - + // WHEN TestUtil.displayWhen(TEST_NAME); - MergeDeltas deltas = - modelInteractionService.mergeObjectsPreviewDeltas(UserType.class, + MergeDeltas deltas = + modelInteractionService.mergeObjectsPreviewDeltas(UserType.class, USER_JACK_OID, USER_GUYBRUSH_OID, MERGE_CONFIG_DEFAULT_NAME, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + display("Deltas", deltas); - + ObjectDelta leftObjectdelta = deltas.getLeftObjectDelta(); PrismAsserts.assertIsModify(leftObjectdelta); assertEquals("Wrong delta OID", USER_JACK_OID, leftObjectdelta.getOid()); PrismAsserts.assertNoItemDelta(leftObjectdelta, UserType.F_NAME); PrismAsserts.assertNoItemDelta(leftObjectdelta, UserType.F_GIVEN_NAME); PrismAsserts.assertPropertyReplace(leftObjectdelta, UserType.F_FAMILY_NAME); - PrismAsserts.assertPropertyReplace(leftObjectdelta, UserType.F_FULL_NAME, + PrismAsserts.assertPropertyReplace(leftObjectdelta, UserType.F_FULL_NAME, createPolyString(USER_GUYBRUSH_FULL_NAME)); PrismAsserts.assertPropertyReplace(leftObjectdelta, UserType.F_ADDITIONAL_NAME); - PrismAsserts.assertPropertyReplace(leftObjectdelta, UserType.F_LOCALITY, + PrismAsserts.assertPropertyReplace(leftObjectdelta, UserType.F_LOCALITY, createPolyString(USER_GUYBRUSH_LOCALITY)); - PrismAsserts.assertPropertyAdd(leftObjectdelta, UserType.F_EMPLOYEE_TYPE, + PrismAsserts.assertPropertyAdd(leftObjectdelta, UserType.F_EMPLOYEE_TYPE, "SAILOR", "PIRATE WANNABE"); - PrismAsserts.assertPropertyAdd(leftObjectdelta, UserType.F_ORGANIZATION, + PrismAsserts.assertPropertyAdd(leftObjectdelta, UserType.F_ORGANIZATION, createPolyString("Pirate Wannabes"), createPolyString("Lovers")); PrismAsserts.assertNoItemDelta(leftObjectdelta, UserType.F_ACTIVATION); - PrismAsserts.assertNoItemDelta(leftObjectdelta, + PrismAsserts.assertNoItemDelta(leftObjectdelta, new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS)); PrismAsserts.assertNoItemDelta(leftObjectdelta, UserType.F_ROLE_MEMBERSHIP_REF); PrismAsserts.assertNoItemDelta(leftObjectdelta, UserType.F_DELEGATED_REF); - PrismAsserts.assertContainerAdd(leftObjectdelta, UserType.F_ASSIGNMENT, + PrismAsserts.assertContainerAdd(leftObjectdelta, UserType.F_ASSIGNMENT, FocusTypeUtil.createRoleAssignment(ROLE_THIEF_OID)); - + PrismAsserts.assertNoItemDelta(leftObjectdelta, UserType.F_LINK_REF); - + ObjectDelta leftLinkDelta = deltas.getLeftLinkDelta(); PrismAsserts.assertReferenceAdd(leftLinkDelta, UserType.F_LINK_REF, guybrushDummyAccountCyanOid); - + ObjectDelta rightLinkDelta = deltas.getRightLinkDelta(); PrismAsserts.assertReferenceDelete(rightLinkDelta, UserType.F_LINK_REF, guybrushDummyAccountCyanOid); - + } - + /** * MID-3460 */ @@ -174,50 +174,50 @@ public void test100MergeJackGuybrushPreviewDelta() throws Exception { public void test102MergeJackGuybrushPreviewObject() throws Exception { final String TEST_NAME = "test102MergeJackGuybrushPreviewObject"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - PrismObject object = - modelInteractionService.mergeObjectsPreviewObject(UserType.class, + PrismObject object = + modelInteractionService.mergeObjectsPreviewObject(UserType.class, USER_JACK_OID, USER_GUYBRUSH_OID, MERGE_CONFIG_DEFAULT_NAME, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + display("Object", object); - + assertEquals("Wrong object OID", USER_JACK_OID, object.getOid()); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_NAME, createPolyString(USER_JACK_USERNAME)); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_GIVEN_NAME, createPolyString(USER_JACK_GIVEN_NAME)); PrismAsserts.assertNoItem(object, UserType.F_FAMILY_NAME); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_FULL_NAME, createPolyString(USER_GUYBRUSH_FULL_NAME)); PrismAsserts.assertNoItem(object, UserType.F_ADDITIONAL_NAME); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_LOCALITY, createPolyString(USER_GUYBRUSH_LOCALITY)); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_EMPLOYEE_TYPE, USER_JACK_EMPLOYEE_TYPE, "SAILOR", "PIRATE WANNABE"); - PrismAsserts.assertPropertyValue(object, - UserType.F_ORGANIZATION, + PrismAsserts.assertPropertyValue(object, + UserType.F_ORGANIZATION, createPolyString("Pirate Brethren"), createPolyString("Sailors"), createPolyString("Rum Club"), createPolyString("Pirate Wannabes"), createPolyString("Lovers"), createPolyString("Drinkers")); - - assertAssignedRoles(object, ROLE_SAILOR_OID, ROLE_RED_SAILOR_OID, ROLE_CYAN_SAILOR_OID, + + assertAssignedRoles(object, ROLE_SAILOR_OID, ROLE_RED_SAILOR_OID, ROLE_CYAN_SAILOR_OID, ROLE_EMPTY_OID, ROLE_THIEF_OID, ROLE_PIRATE_OID, ROLE_NICE_PIRATE_OID); - + assertLinked(object, jackDummyAccountOid); assertLinked(object, jackDummyAccountRedOid); assertLinked(object, guybrushDummyAccountCyanOid); assertLinks(object, 3); } - + /** * MID-3460 */ @@ -225,64 +225,64 @@ public void test102MergeJackGuybrushPreviewObject() throws Exception { public void test110MergeGuybrushJackPreviewDelta() throws Exception { final String TEST_NAME = "test110MergeGuybrushJackPreviewDelta"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userGuybrushBefore = getUser(USER_GUYBRUSH_OID); display("Guybrush before", userGuybrushBefore); - + PrismObject userJackBefore = getUser(USER_JACK_OID); display("Jack before", userJackBefore); - + // WHEN TestUtil.displayWhen(TEST_NAME); - MergeDeltas deltas = - modelInteractionService.mergeObjectsPreviewDeltas(UserType.class, + MergeDeltas deltas = + modelInteractionService.mergeObjectsPreviewDeltas(UserType.class, USER_GUYBRUSH_OID, USER_JACK_OID, MERGE_CONFIG_DEFAULT_NAME, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + display("Deltas", deltas); - + ObjectDelta delta = deltas.getLeftObjectDelta(); PrismAsserts.assertIsModify(delta); assertEquals("Wrong delta OID", USER_GUYBRUSH_OID, delta.getOid()); PrismAsserts.assertNoItemDelta(delta, UserType.F_NAME); PrismAsserts.assertNoItemDelta(delta, UserType.F_GIVEN_NAME); PrismAsserts.assertPropertyReplace(delta, UserType.F_FAMILY_NAME); - PrismAsserts.assertPropertyReplace(delta, UserType.F_FULL_NAME, + PrismAsserts.assertPropertyReplace(delta, UserType.F_FULL_NAME, createPolyString(USER_JACK_FULL_NAME)); PrismAsserts.assertPropertyReplace(delta, UserType.F_ADDITIONAL_NAME, createPolyString(USER_JACK_ADDITIONAL_NAME)); - PrismAsserts.assertPropertyReplace(delta, UserType.F_LOCALITY, + PrismAsserts.assertPropertyReplace(delta, UserType.F_LOCALITY, createPolyString(USER_JACK_LOCALITY)); - PrismAsserts.assertPropertyAdd(delta, UserType.F_EMPLOYEE_TYPE, + PrismAsserts.assertPropertyAdd(delta, UserType.F_EMPLOYEE_TYPE, USER_JACK_EMPLOYEE_TYPE); - PrismAsserts.assertPropertyAdd(delta, UserType.F_ORGANIZATION, + PrismAsserts.assertPropertyAdd(delta, UserType.F_ORGANIZATION, createPolyString("Pirate Brethren"), createPolyString("Drinkers")); PrismAsserts.assertNoItemDelta(delta, UserType.F_ACTIVATION); - PrismAsserts.assertNoItemDelta(delta, + PrismAsserts.assertNoItemDelta(delta, new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS)); PrismAsserts.assertNoItemDelta(delta, UserType.F_ROLE_MEMBERSHIP_REF); PrismAsserts.assertNoItemDelta(delta, UserType.F_DELEGATED_REF); - PrismAsserts.assertContainerAdd(delta, UserType.F_ASSIGNMENT, + PrismAsserts.assertContainerAdd(delta, UserType.F_ASSIGNMENT, FocusTypeUtil.createRoleAssignment(ROLE_PIRATE_OID), FocusTypeUtil.createRoleAssignment(ROLE_NICE_PIRATE_OID)); - + PrismAsserts.assertNoItemDelta(delta, UserType.F_LINK_REF); ObjectDelta leftLinkDelta = deltas.getLeftLinkDelta(); PrismAsserts.assertReferenceAdd(leftLinkDelta, UserType.F_LINK_REF, jackDummyAccountRedOid); - + ObjectDelta rightLinkDelta = deltas.getRightLinkDelta(); PrismAsserts.assertReferenceDelete(rightLinkDelta, UserType.F_LINK_REF, jackDummyAccountRedOid); } - + /** * MID-3460 */ @@ -290,45 +290,45 @@ public void test110MergeGuybrushJackPreviewDelta() throws Exception { public void test112MergeGuybrushJackPreviewObject() throws Exception { final String TEST_NAME = "test112MergeGuybrushJackPreviewObject"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - PrismObject object = - modelInteractionService.mergeObjectsPreviewObject(UserType.class, + PrismObject object = + modelInteractionService.mergeObjectsPreviewObject(UserType.class, USER_GUYBRUSH_OID, USER_JACK_OID, MERGE_CONFIG_DEFAULT_NAME, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + display("Object", object); - + assertEquals("Wrong object OID", USER_GUYBRUSH_OID, object.getOid()); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_NAME, createPolyString(USER_GUYBRUSH_USERNAME)); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_GIVEN_NAME, createPolyString(USER_GUYBRUSH_GIVEN_NAME)); PrismAsserts.assertNoItem(object, UserType.F_FAMILY_NAME); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_FULL_NAME, createPolyString(USER_JACK_FULL_NAME)); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_ADDITIONAL_NAME, createPolyString(USER_JACK_ADDITIONAL_NAME)); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_LOCALITY, createPolyString(USER_JACK_LOCALITY)); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_EMPLOYEE_TYPE, USER_JACK_EMPLOYEE_TYPE, "SAILOR", "PIRATE WANNABE"); - PrismAsserts.assertPropertyValue(object, - UserType.F_ORGANIZATION, + PrismAsserts.assertPropertyValue(object, + UserType.F_ORGANIZATION, createPolyString("Pirate Brethren"), createPolyString("Sailors"), createPolyString("Rum Club"), createPolyString("Pirate Wannabes"), createPolyString("Lovers"), createPolyString("Drinkers")); assertAssignedRoles(object, ROLE_SAILOR_OID, ROLE_RED_SAILOR_OID, ROLE_CYAN_SAILOR_OID, ROLE_EMPTY_OID, ROLE_THIEF_OID, ROLE_PIRATE_OID, ROLE_NICE_PIRATE_OID); - + } /** @@ -338,29 +338,29 @@ public void test112MergeGuybrushJackPreviewObject() throws Exception { public void test200MergeJackGuybrushExpressionPreviewDelta() throws Exception { final String TEST_NAME = "test200MergeJackGuybrushExpressionPreviewDelta"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userJackBefore = getUser(USER_JACK_OID); display("Jack before", userJackBefore); - + PrismObject userGuybrushBefore = getUser(USER_GUYBRUSH_OID); display("Guybrush before", userGuybrushBefore); - + // WHEN TestUtil.displayWhen(TEST_NAME); - MergeDeltas deltas = - modelInteractionService.mergeObjectsPreviewDeltas(UserType.class, + MergeDeltas deltas = + modelInteractionService.mergeObjectsPreviewDeltas(UserType.class, USER_JACK_OID, USER_GUYBRUSH_OID, MERGE_CONFIG_EXPRESSION_NAME, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + display("Deltas", deltas); - + ObjectDelta delta = deltas.getLeftObjectDelta(); PrismAsserts.assertIsModify(delta); assertEquals("Wrong delta OID", USER_JACK_OID, delta.getOid()); @@ -369,22 +369,22 @@ public void test200MergeJackGuybrushExpressionPreviewDelta() throws Exception { PrismAsserts.assertNoItemDelta(delta, UserType.F_FAMILY_NAME); PrismAsserts.assertNoItemDelta(delta, UserType.F_FULL_NAME); PrismAsserts.assertNoItemDelta(delta, UserType.F_ADDITIONAL_NAME); - PrismAsserts.assertPropertyAdd(delta, UserType.F_EMPLOYEE_TYPE, + PrismAsserts.assertPropertyAdd(delta, UserType.F_EMPLOYEE_TYPE, "SAILOR"); - PrismAsserts.assertPropertyAdd(delta, UserType.F_ORGANIZATION, + PrismAsserts.assertPropertyAdd(delta, UserType.F_ORGANIZATION, createPolyString("Pirate Wannabes")); - PrismAsserts.assertPropertyDelete(delta, UserType.F_ORGANIZATION, + PrismAsserts.assertPropertyDelete(delta, UserType.F_ORGANIZATION, createPolyString("Sailors"), createPolyString("Drinkers")); PrismAsserts.assertNoItemDelta(delta, UserType.F_ACTIVATION); - PrismAsserts.assertNoItemDelta(delta, + PrismAsserts.assertNoItemDelta(delta, new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS)); PrismAsserts.assertNoItemDelta(delta, UserType.F_ROLE_MEMBERSHIP_REF); PrismAsserts.assertNoItemDelta(delta, UserType.F_DELEGATED_REF); - PrismAsserts.assertContainerAdd(delta, UserType.F_ASSIGNMENT, - FocusTypeUtil.createRoleAssignment(ROLE_THIEF_OID)); + PrismAsserts.assertContainerAdd(delta, UserType.F_ASSIGNMENT, + FocusTypeUtil.createRoleAssignment(ROLE_THIEF_OID)); } - + /** * MID-3460 */ @@ -392,45 +392,45 @@ public void test200MergeJackGuybrushExpressionPreviewDelta() throws Exception { public void test202MergeJackGuybrushExpressionPreviewObject() throws Exception { final String TEST_NAME = "test202MergeJackGuybrushExpressionPreviewObject"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - PrismObject object = - modelInteractionService.mergeObjectsPreviewObject(UserType.class, + PrismObject object = + modelInteractionService.mergeObjectsPreviewObject(UserType.class, USER_JACK_OID, USER_GUYBRUSH_OID, MERGE_CONFIG_EXPRESSION_NAME, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + display("Object", object); - + assertEquals("Wrong object OID", USER_JACK_OID, object.getOid()); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_NAME, createPolyString(USER_JACK_USERNAME)); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_GIVEN_NAME, createPolyString(USER_JACK_GIVEN_NAME)); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_FAMILY_NAME, createPolyString(USER_JACK_FAMILY_NAME)); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_FULL_NAME, createPolyString(USER_JACK_FULL_NAME)); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_ADDITIONAL_NAME, createPolyString(USER_JACK_ADDITIONAL_NAME)); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_LOCALITY, createPolyString(USER_JACK_LOCALITY)); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_EMPLOYEE_TYPE, USER_JACK_EMPLOYEE_TYPE, "SAILOR"); - PrismAsserts.assertPropertyValue(object, - UserType.F_ORGANIZATION, + PrismAsserts.assertPropertyValue(object, + UserType.F_ORGANIZATION, createPolyString("Pirate Brethren"), createPolyString("Rum Club"), createPolyString("Pirate Wannabes")); - + assertAssignedRoles(object, ROLE_SAILOR_OID, ROLE_RED_SAILOR_OID, ROLE_CYAN_SAILOR_OID, - ROLE_EMPTY_OID, ROLE_THIEF_OID, ROLE_PIRATE_OID, ROLE_NICE_PIRATE_OID); + ROLE_EMPTY_OID, ROLE_THIEF_OID, ROLE_PIRATE_OID, ROLE_NICE_PIRATE_OID); } @@ -443,63 +443,63 @@ public void test202MergeJackGuybrushExpressionPreviewObject() throws Exception { public void test300MergeJackGuybrushPreviewDeltaDefaultSpecific() throws Exception { final String TEST_NAME = "test300MergeJackGuybrushPreviewDeltaDefaultSpecific"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userJackBefore = getUser(USER_JACK_OID); display("Jack before", userJackBefore); - + PrismObject userGuybrushBefore = getUser(USER_GUYBRUSH_OID); display("Guybrush before", userGuybrushBefore); - + // WHEN TestUtil.displayWhen(TEST_NAME); - MergeDeltas deltas = - modelInteractionService.mergeObjectsPreviewDeltas(UserType.class, + MergeDeltas deltas = + modelInteractionService.mergeObjectsPreviewDeltas(UserType.class, USER_JACK_OID, USER_GUYBRUSH_OID, MERGE_CONFIG_DEFAULT_SPECIFIC_NAME, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + display("Deltas", deltas); - + ObjectDelta leftObjectdelta = deltas.getLeftObjectDelta(); PrismAsserts.assertIsModify(leftObjectdelta); assertEquals("Wrong delta OID", USER_JACK_OID, leftObjectdelta.getOid()); PrismAsserts.assertNoItemDelta(leftObjectdelta, UserType.F_NAME); PrismAsserts.assertNoItemDelta(leftObjectdelta, UserType.F_GIVEN_NAME); PrismAsserts.assertPropertyReplace(leftObjectdelta, UserType.F_FAMILY_NAME); - PrismAsserts.assertPropertyReplace(leftObjectdelta, UserType.F_FULL_NAME, + PrismAsserts.assertPropertyReplace(leftObjectdelta, UserType.F_FULL_NAME, createPolyString(USER_GUYBRUSH_FULL_NAME)); PrismAsserts.assertPropertyReplace(leftObjectdelta, UserType.F_ADDITIONAL_NAME); - PrismAsserts.assertPropertyReplace(leftObjectdelta, UserType.F_LOCALITY, + PrismAsserts.assertPropertyReplace(leftObjectdelta, UserType.F_LOCALITY, createPolyString(USER_GUYBRUSH_LOCALITY)); - PrismAsserts.assertPropertyAdd(leftObjectdelta, UserType.F_EMPLOYEE_TYPE, + PrismAsserts.assertPropertyAdd(leftObjectdelta, UserType.F_EMPLOYEE_TYPE, "SAILOR", "PIRATE WANNABE"); - PrismAsserts.assertPropertyAdd(leftObjectdelta, UserType.F_ORGANIZATION, + PrismAsserts.assertPropertyAdd(leftObjectdelta, UserType.F_ORGANIZATION, createPolyString("Pirate Wannabes"), createPolyString("Lovers")); PrismAsserts.assertNoItemDelta(leftObjectdelta, UserType.F_ACTIVATION); - PrismAsserts.assertNoItemDelta(leftObjectdelta, + PrismAsserts.assertNoItemDelta(leftObjectdelta, new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS)); PrismAsserts.assertNoItemDelta(leftObjectdelta, UserType.F_ROLE_MEMBERSHIP_REF); PrismAsserts.assertNoItemDelta(leftObjectdelta, UserType.F_DELEGATED_REF); - PrismAsserts.assertContainerAdd(leftObjectdelta, UserType.F_ASSIGNMENT, + PrismAsserts.assertContainerAdd(leftObjectdelta, UserType.F_ASSIGNMENT, FocusTypeUtil.createRoleAssignment(ROLE_THIEF_OID)); - + PrismAsserts.assertNoItemDelta(leftObjectdelta, UserType.F_LINK_REF); - + ObjectDelta leftLinkDelta = deltas.getLeftLinkDelta(); PrismAsserts.assertReferenceAdd(leftLinkDelta, UserType.F_LINK_REF, guybrushDummyAccountCyanOid); - + ObjectDelta rightLinkDelta = deltas.getRightLinkDelta(); PrismAsserts.assertReferenceDelete(rightLinkDelta, UserType.F_LINK_REF, guybrushDummyAccountCyanOid); - + } - + /** * MID-3460 */ @@ -507,41 +507,41 @@ public void test300MergeJackGuybrushPreviewDeltaDefaultSpecific() throws Excepti public void test500MergeJackGuybrush() throws Exception { final String TEST_NAME = "test500MergeJackGuybrush"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modelService.mergeObjects(UserType.class, + modelService.mergeObjects(UserType.class, USER_JACK_OID, USER_GUYBRUSH_OID, MERGE_CONFIG_DEFAULT_NAME, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject object = getObject(UserType.class, USER_JACK_OID); display("Object", object); - + assertEquals("Wrong object OID", USER_JACK_OID, object.getOid()); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_NAME, createPolyString(USER_JACK_USERNAME)); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_GIVEN_NAME, createPolyString(USER_JACK_GIVEN_NAME)); PrismAsserts.assertNoItem(object, UserType.F_FAMILY_NAME); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_FULL_NAME, createPolyString(USER_GUYBRUSH_FULL_NAME)); PrismAsserts.assertNoItem(object, UserType.F_ADDITIONAL_NAME); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_LOCALITY, createPolyString(USER_GUYBRUSH_LOCALITY)); - PrismAsserts.assertPropertyValue(object, + PrismAsserts.assertPropertyValue(object, UserType.F_EMPLOYEE_TYPE, USER_JACK_EMPLOYEE_TYPE, "SAILOR", "PIRATE WANNABE"); - + assertAssignedRoles(object, ROLE_SAILOR_OID, ROLE_RED_SAILOR_OID, ROLE_CYAN_SAILOR_OID, ROLE_EMPTY_OID, ROLE_THIEF_OID, ROLE_PIRATE_OID, ROLE_NICE_PIRATE_OID); - + assertNoObject(UserType.class, USER_GUYBRUSH_OID); - + } } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMisc.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMisc.java index 0d6284ce4dd..ec83337cdbd 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMisc.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMisc.java @@ -57,19 +57,19 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestMisc extends AbstractInitializedModelIntegrationTest { - + public static final byte[] KEY = { 0x01, 0x02, 0x03, 0x04, 0x05 }; - + private static final String USER_CLEAN_NAME = "clean"; private static final String USER_CLEAN_GIVEN_NAME = "John"; private static final String USER_CLEAN_FAMILY_NAME = "Clean"; - + private String userCleanOid; - + public TestMisc() throws JAXBException { super(); } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { @@ -84,11 +84,11 @@ public void test100GetRepositoryDiag() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); RepositoryDiag diag = modelDiagnosticService.getRepositoryDiag(task, result); - + // THEN displayThen(TEST_NAME); display("Diag", diag); @@ -98,7 +98,7 @@ public void test100GetRepositoryDiag() throws Exception { assertNotNull("Missing implementationDescription", diag.getImplementationDescription()); // TODO } - + @Test public void test110RepositorySelfTest() throws Exception { final String TEST_NAME = "test110RepositorySelfTest"; @@ -106,11 +106,11 @@ public void test110RepositorySelfTest() throws Exception { // GIVEN Task task = createTask(TEST_NAME); - + // WHEN displayWhen(TEST_NAME); OperationResult testResult = modelDiagnosticService.repositorySelfTest(task); - + // THEN displayThen(TEST_NAME); display("Repository self-test result", testResult); @@ -118,7 +118,7 @@ public void test110RepositorySelfTest() throws Exception { // TODO: check the number of tests, etc. } - + @Test public void test200ExportUsers() throws Exception { final String TEST_NAME = "test200ExportUsers"; @@ -127,12 +127,12 @@ public void test200ExportUsers() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); - List> users = modelService.searchObjects(UserType.class, null, + List> users = modelService.searchObjects(UserType.class, null, SelectorOptions.createCollection(ItemPath.EMPTY_PATH, GetOperationOptions.createRaw()), task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); @@ -144,18 +144,18 @@ public void test200ExportUsers() throws Exception { display("Definition", user.getDefinition()); String xmlString = prismContext.serializerFor(PrismContext.LANG_XML).serialize(user); display("Exported user", xmlString); - + Document xmlDocument = DOMUtil.parseDocument(xmlString); Schema javaxSchema = prismContext.getSchemaRegistry().getJavaxSchema(); Validator validator = javaxSchema.newValidator(); validator.setResourceResolver(prismContext.getEntityResolver()); validator.validate(new DOMSource(xmlDocument)); - + PrismObject parsedUser = prismContext.parseObject(xmlString); assertTrue("Re-parsed user is not equal to original: "+user, user.equals(parsedUser)); - + } - + } /** @@ -170,11 +170,11 @@ public void test300RecomputeJack() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); @@ -182,7 +182,7 @@ public void test300RecomputeJack() throws Exception { PrismObject userAfter = getUser(USER_JACK_OID); display("User after", userAfter); } - + /** * Modify custom binary property. * MID-3999 @@ -195,11 +195,11 @@ public void test302UpdateKeyJack() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, getExtensionPath(PIRACY_KEY), task, result, KEY); - + // THEN displayThen(TEST_NAME); assertSuccess(result); @@ -208,7 +208,7 @@ public void test302UpdateKeyJack() throws Exception { display("User after", userAfter); PrismAsserts.assertPropertyValue(userAfter, getExtensionPath(PIRACY_KEY), KEY); } - + @Test public void test310AddUserClean() throws Exception { final String TEST_NAME = "test310AddUserClean"; @@ -217,23 +217,23 @@ public void test310AddUserClean() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = createUser(USER_CLEAN_NAME, USER_CLEAN_GIVEN_NAME, USER_CLEAN_FAMILY_NAME, true); - + // WHEN displayWhen(TEST_NAME); addObject(userBefore, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + userCleanOid = userBefore.getOid(); PrismObject userAfter = getUser(userCleanOid); display("User after", userAfter); } - + /** * Modify custom binary property. * MID-3999 @@ -246,11 +246,11 @@ public void test312UpdateBinaryIdClean() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(userCleanOid, getExtensionPath(PIRACY_BINARY_ID), task, result, KEY); - + // THEN displayThen(TEST_NAME); assertSuccess(result); 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 16428925ee1..e56fadd4608 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 @@ -44,28 +44,28 @@ /** * 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"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestModelCrudService 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; - + @Autowired(required = true) protected ModelCrudService modelCrudService; - + @Test public void test050AddResource() throws Exception { final String TEST_NAME = "test050AddResource"; @@ -75,24 +75,24 @@ public void test050AddResource() throws Exception { Task task = taskManager.createTaskInstance(TestModelCrudService.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + ResourceType resourceType = (ResourceType) PrismTestUtil.parseObject(RESOURCE_MAROON_FILE).asObjectable(); - + // WHEN PrismObject object = resourceType.asPrismObject(); prismContext.adopt(resourceType); modelCrudService.addObject(object, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + // Make sure the resource has t:norm part of polystring name PrismObject resourceAfter = modelService.getObject(ResourceType.class, RESOURCE_MAROON_OID, null, task, result); assertEquals("Wrong orig in resource name", "Dummy Resource Maroon", resourceAfter.asObjectable().getName().getOrig()); assertEquals("Wrong norm in resource name", "dummy resource maroon", resourceAfter.asObjectable().getName().getNorm()); } - + @Test public void test100ModifyUserAddAccount() throws Exception { final String TEST_NAME = "test100ModifyUserAddAccount"; @@ -102,18 +102,18 @@ public void test100ModifyUserAddAccount() throws Exception { Task task = taskManager.createTaskInstance(TestModelCrudService.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); - + Collection> modifications = new ArrayList<>(); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account); ReferenceDelta accountDelta = ReferenceDelta.createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); modifications.add(accountDelta); - + // WHEN modelCrudService.modifyObject(UserType.class, USER_JACK_OID, modifications , null, task, result); - + // THEN // Check accountRef PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); @@ -126,19 +126,19 @@ public void test100ModifyUserAddAccount() throws Exception { 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); assertDummyAccountShadowRepo(accountShadow, accountOid, "jack"); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, "jack", "Jack Sparrow"); - + // Check account in dummy resource assertDefaultDummyAccount("jack", "Jack Sparrow", true); } - + @Test public void test119ModifyUserDeleteAccount() throws Exception { TestUtil.displayTestTitle(this, "test119ModifyUserDeleteAccount"); @@ -150,23 +150,23 @@ public void test119ModifyUserDeleteAccount() throws Exception { PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); account.setOid(accountOid); - + Collection> modifications = new ArrayList<>(); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account); ReferenceDelta accountDelta = ReferenceDelta.createModificationDelete(UserType.F_LINK_REF, getUserDefinition(), account); modifications.add(accountDelta); - + // WHEN modelCrudService.modifyObject(UserType.class, USER_JACK_OID, modifications , null, task, result); - + // THEN // Check accountRef 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 is shadow is gone try { PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); @@ -174,11 +174,11 @@ public void test119ModifyUserDeleteAccount() throws Exception { } catch (ObjectNotFoundException e) { // This is OK } - + // Check if dummy resource account is gone assertNoDummyAccount("jack"); } - + @Test public void test120AddAccount() throws Exception { TestUtil.displayTestTitle(this, "test120AddAccount"); @@ -187,31 +187,31 @@ public void test120AddAccount() throws Exception { Task task = taskManager.createTaskInstance(TestModelCrudService.class.getName() + ".test120AddAccount"); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); - + // WHEN accountOid = modelCrudService.addObject(account, null, task, result); - + // THEN // Check accountRef (should be none) 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, accountOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountOid, "jack"); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, "jack", "Jack Sparrow"); - + // Check account in dummy resource assertDefaultDummyAccount("jack", "Jack Sparrow", true); } - + @Test public void test121ModifyUserAddAccountRef() throws Exception { TestUtil.displayTestTitle(this, "test121ModifyUserAddAccountRef"); @@ -220,34 +220,34 @@ public void test121ModifyUserAddAccountRef() throws Exception { Task task = taskManager.createTaskInstance(TestModelCrudService.class.getName() + ".test121ModifyUserAddAccountRef"); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + Collection> modifications = new ArrayList<>(); ReferenceDelta accountDelta = ReferenceDelta.createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountOid); modifications.add(accountDelta); - + // WHEN modelCrudService.modifyObject(UserType.class, USER_JACK_OID, modifications , null, task, result); - + // THEN // Check accountRef PrismObject userJack = getUser(USER_JACK_OID); assertUserJack(userJack); accountOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountOid, "jack"); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, "jack", "Jack Sparrow"); - + // Check account in dummy resource assertDefaultDummyAccount("jack", "Jack Sparrow", true); } - + @Test public void test128ModifyUserDeleteAccountRef() throws Exception { TestUtil.displayTestTitle(this, "test128ModifyUserDeleteAccountRef"); @@ -258,34 +258,34 @@ public void test128ModifyUserDeleteAccountRef() throws Exception { assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); - + Collection> modifications = new ArrayList<>(); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account); ReferenceDelta accountDelta = ReferenceDelta.createModificationDelete(UserType.F_LINK_REF, getUserDefinition(), accountOid); modifications.add(accountDelta); - + // WHEN modelCrudService.modifyObject(UserType.class, USER_JACK_OID, modifications , null, task, result); - + // THEN PrismObject userJack = getUser(USER_JACK_OID); assertUserJack(userJack); // Check accountRef assertUserNoAccountRefs(userJack); - + // Check shadow (if it is unchanged) PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountOid, "jack"); - + // Check account (if it is unchanged) PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, "jack", "Jack Sparrow"); - + // Check account in dummy resource (if it is unchanged) assertDefaultDummyAccount("jack", "Jack Sparrow", true); } - + @Test public void test129DeleteAccount() throws Exception { TestUtil.displayTestTitle(this, "test129DeleteAccount"); @@ -294,23 +294,23 @@ public void test129DeleteAccount() throws Exception { Task task = taskManager.createTaskInstance(TestModelCrudService.class.getName() + ".test129DeleteAccount"); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + // WHEN modelCrudService.deleteObject(ShadowType.class, accountOid, null, task, result); - + // THEN PrismObject userJack = getUser(USER_JACK_OID); assertUserJack(userJack); // Check accountRef assertUserNoAccountRefs(userJack); - + // Check is shadow is gone assertNoShadow(accountOid); - + // Check if dummy resource account is gone assertNoDummyAccount("jack"); } - + @Test public void test150AddUserBlackbeardWithAccount() throws Exception { TestUtil.displayTestTitle(this, "test150AddUserBlackbeardWithAccount"); @@ -319,12 +319,12 @@ public void test150AddUserBlackbeardWithAccount() throws Exception { Task task = taskManager.createTaskInstance(TestModelCrudService.class.getName() + ".test150AddUserBlackbeardWithAccount"); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - + PrismObject user = PrismTestUtil.parseObject(new File(TEST_CONTRACT_DIR, "user-blackbeard-account-dummy.xml")); - + // WHEN modelCrudService.addObject(user , null, task, result); - + // THEN // Check accountRef PrismObject userMorgan = modelService.getObject(UserType.class, USER_BLACKBEARD_OID, null, task, result); @@ -333,20 +333,20 @@ public void test150AddUserBlackbeardWithAccount() throws Exception { ObjectReferenceType accountRefType = userMorganType.getLinkRef().get(0); String accountOid = accountRefType.getOid(); assertFalse("No accountRef oid", StringUtils.isBlank(accountOid)); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountOid, "blackbeard"); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, "blackbeard", "Edward Teach"); - + // Check account in dummy resource assertDefaultDummyAccount("blackbeard", "Edward Teach", true); } - + @Test public void test210AddUserMorganWithAssignment() throws Exception { TestUtil.displayTestTitle(this, "test210AddUserMorganWithAssignment"); @@ -355,12 +355,12 @@ public void test210AddUserMorganWithAssignment() throws Exception { Task task = taskManager.createTaskInstance(TestModelCrudService.class.getName() + ".test210AddUserMorganWithAssignment"); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + PrismObject user = PrismTestUtil.parseObject(new File(TEST_CONTRACT_DIR, "user-morgan-assignment-dummy.xml")); - + // WHEN modelCrudService.addObject(user , null, task, result); - + // THEN // Check accountRef PrismObject userMorgan = modelService.getObject(UserType.class, USER_MORGAN_OID, null, task, result); @@ -369,15 +369,15 @@ public void test210AddUserMorganWithAssignment() throws Exception { ObjectReferenceType accountRefType = userMorganType.getLinkRef().get(0); String accountOid = accountRefType.getOid(); assertFalse("No accountRef oid", StringUtils.isBlank(accountOid)); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountOid, "morgan"); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, "morgan", "Sir Henry Morgan"); - + // Check account in dummy resource assertDefaultDummyAccount("morgan", "Sir Henry Morgan", true); } 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 4fb19d7bc56..ac0d2bf9980 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 @@ -107,16 +107,16 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestModelServiceContract extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/contract"); 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 accountJackOid; private static String accountJackBlueOid; private static String userCharlesOid; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { @@ -126,7 +126,7 @@ public void initSystem(Task initTask, OperationResult initResult) // InternalMonitor.setTraceResourceSchemaOperations(true); InternalMonitor.setTrace(InternalOperationClasses.PRISM_OBJECT_CLONES, true); } - + @Test public void test050GetUserJack() throws Exception { final String TEST_NAME = "test050GetUserJack"; @@ -138,18 +138,18 @@ public void test050GetUserJack() throws Exception { // WHEN PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); - + // THEN display("User jack", userJack); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); assertUserJack(userJack); - + result.computeStatus(); TestUtil.assertSuccess("getObject result", result); - + assertSteadyResources(); } - + @Test public void test051GetUserBarbossa() throws Exception { final String TEST_NAME = "test051GetUserBarbossa"; @@ -161,17 +161,17 @@ public void test051GetUserBarbossa() throws Exception { // WHEN PrismObject userBarbossa = modelService.getObject(UserType.class, USER_BARBOSSA_OID, null, task, result); - + // THEN display("User barbossa", userBarbossa); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); assertUser(userBarbossa, USER_BARBOSSA_OID, "barbossa", "Hector Barbossa", "Hector", "Barbossa"); - + result.computeStatus(); TestUtil.assertSuccess("getObject result", result); - + userBarbossa.checkConsistence(true, true, ConsistencyCheckScope.THOROUGH); - + assertSteadyResources(); } @@ -249,20 +249,20 @@ public void test100ModifyUserAddAccount() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserAddAccount(USER_JACK_OID, ACCOUNT_JACK_DUMMY_FILE, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + // Check accountRef PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); display("User jack after", userJack); @@ -275,21 +275,21 @@ public void test100ModifyUserAddAccount() throws Exception { PrismReferenceValue accountRefValue = accountRefType.asReferenceValue(); assertEquals("OID mismatch in accountRefValue", accountJackOid, accountRefValue.getOid()); assertNull("Unexpected object in accountRefValue", accountRefValue.getObject()); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); assertEnableTimestampShadow(accountShadow, startTime, endTime); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, "jack", "Jack Sparrow"); - + // Check account in dummy resource assertDefaultDummyAccount("jack", "Jack Sparrow", true); - + assertDummyScriptsAdd(userJack, accountModel, getDummyResourceType()); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -337,7 +337,7 @@ public void test101GetAccount() throws Exception { Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + // Let's do some evil things. Like changing some of the attribute on a resource and see if they will be // fetched after get. // Also set a value for ignored "water" attribute. The system should cope with that. @@ -345,10 +345,10 @@ public void test101GetAccount() throws Exception { jackDummyAccount.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "The best pirate captain ever"); jackDummyAccount.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WATER_NAME, "cold"); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN PrismObject account = modelService.getObject(ShadowType.class, accountJackOid, null , task, result); - + // THEN display("Account", account); display("Account def", account.getDefinition()); @@ -357,26 +357,26 @@ public void test101GetAccount() throws Exception { display("Account attributes def", accountContainer.getDefinition()); display("Account attributes def complex type def", accountContainer.getDefinition().getComplexTypeDefinition()); assertDummyAccountShadowModel(account, accountJackOid, "jack", "Jack Sparrow"); - + result.computeStatus(); TestUtil.assertSuccess("getObject result", result); - + account.checkConsistence(true, true, ConsistencyCheckScope.THOROUGH); - + IntegrationTestTools.assertAttribute(account, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME), "The best pirate captain ever"); // This one should still be here, even if ignored - IntegrationTestTools.assertAttribute(account, - getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WATER_NAME), + IntegrationTestTools.assertAttribute(account, + getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WATER_NAME), "cold"); - + ResourceAttributeContainer attributesContainer = ShadowUtil.getAttributesContainer(account); 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()); - + ResourceAttribute fullNameAttr = attributesContainer.findAttribute(dummyResourceCtl.getAttributeFullnameQName()); PrismAsserts.assertPropertyValue(fullNameAttr, ACCOUNT_JACK_DUMMY_FULLNAME); ResourceAttributeDefinition fullNameAttrDef = fullNameAttr.getDefinition(); @@ -388,7 +388,7 @@ public void test101GetAccount() throws Exception { AssertJUnit.fail("Wrong fullname displayOrder: " + fullNameAttrDef.getDisplayOrder()); } assertEquals("Wrong fullname displayName", "Full Name", fullNameAttrDef.getDisplayName()); - + assertSteadyResources(); } @@ -400,12 +400,12 @@ public void test102GetAccountNoFetch() throws Exception { Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test102GetAccountNoFetch"); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createNoFetch()); - + // WHEN PrismObject account = modelService.getObject(ShadowType.class, accountJackOid, options , task, result); - + display("Account", account); display("Account def", account.getDefinition()); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); @@ -413,13 +413,13 @@ public void test102GetAccountNoFetch() throws Exception { display("Account attributes def", accountContainer.getDefinition()); display("Account attributes def complex type def", accountContainer.getDefinition().getComplexTypeDefinition()); assertDummyAccountShadowRepo(account, accountJackOid, "jack"); - + result.computeStatus(); TestUtil.assertSuccess("getObject result", result); - + assertSteadyResources(); } - + @Test public void test103GetAccountRaw() throws Exception { TestUtil.displayTestTitle(this, "test103GetAccountRaw"); @@ -428,12 +428,12 @@ public void test103GetAccountRaw() throws Exception { Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test103GetAccountRaw"); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createRaw()); - + // WHEN PrismObject account = modelService.getObject(ShadowType.class, accountJackOid, options , task, result); - + display("Account", account); display("Account def", account.getDefinition()); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); @@ -441,10 +441,10 @@ public void test103GetAccountRaw() throws Exception { display("Account attributes def", accountContainer.getDefinition()); display("Account attributes def complex type def", accountContainer.getDefinition().getComplexTypeDefinition()); assertDummyAccountShadowRepo(account, accountJackOid, "jack"); - + result.computeStatus(); TestUtil.assertSuccess("getObject result", result); - + assertSteadyResources(); } @@ -515,9 +515,9 @@ public void test108ModifyUserAddAccountAgain() throws Exception { Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test108ModifyUserAddAccountAgain"); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_JACK_OID, prismContext); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account); @@ -526,10 +526,10 @@ public void test108ModifyUserAddAccountAgain() throws Exception { Collection> deltas = MiscSchemaUtil.createCollection(userDelta); try { - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN assert false : "Expected executeChanges operation to fail but it has obviously succeeded"; } catch (SchemaException e) { @@ -540,9 +540,9 @@ public void test108ModifyUserAddAccountAgain() throws Exception { assertMessageContains(message, "already contains account"); assertMessageContains(message, "default"); } - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); @@ -550,10 +550,10 @@ public void test108ModifyUserAddAccountAgain() throws Exception { dummyAuditService.assertAnyRequestDeltas(); dummyAuditService.assertTarget(USER_JACK_OID); dummyAuditService.assertExecutionOutcome(OperationResultStatus.FATAL_ERROR); - + assertSteadyResources(); } - + @Test public void test109ModifyUserAddAccountAgain() throws Exception { final String TEST_NAME = "test109ModifyUserAddAccountAgain"; @@ -563,22 +563,22 @@ public void test109ModifyUserAddAccountAgain() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); account.setOid(null); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_JACK_OID, prismContext); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account); ReferenceDelta accountDelta = ReferenceDelta.createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); userDelta.addModification(accountDelta); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + try { - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN assert false : "Expected executeChanges operation to fail but it has obviously succeeded"; } catch (SchemaException e) { @@ -588,11 +588,11 @@ public void test109ModifyUserAddAccountAgain() throws Exception { assertMessageContains(message, "already contains account"); assertMessageContains(message, "default"); } - + assertNoProvisioningScripts(); - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -600,7 +600,7 @@ public void test109ModifyUserAddAccountAgain() throws Exception { dummyAuditService.assertAnyRequestDeltas(); dummyAuditService.assertTarget(USER_JACK_OID); dummyAuditService.assertExecutionOutcome(OperationResultStatus.FATAL_ERROR); - + assertSteadyResources(); } @@ -614,12 +614,12 @@ public void test110GetUserResolveAccount() throws Exception { OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - Collection> options = + Collection> options = SelectorOptions.createCollection(UserType.F_LINK, GetOperationOptions.createResolve()); - + // WHEN PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, options , task, result); - + // THEN assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); assertUserJack(userJack); @@ -628,7 +628,7 @@ public void test110GetUserResolveAccount() throws Exception { ObjectReferenceType accountRefType = userJackType.getLinkRef().get(0); String accountOid = accountRefType.getOid(); assertFalse("No accountRef oid", StringUtils.isBlank(accountOid)); - + PrismReferenceValue accountRefValue = accountRefType.asReferenceValue(); assertEquals("OID mismatch in accountRefValue", accountOid, accountRefValue.getOid()); assertNotNull("Missing account object in accountRefValue", accountRefValue.getObject()); @@ -636,10 +636,10 @@ public void test110GetUserResolveAccount() throws Exception { assertEquals("Unexpected number of accounts", 1, userJackType.getLink().size()); ShadowType shadow = userJackType.getLink().get(0); assertDummyAccountShadowModel(shadow.asPrismObject(), accountOid, "jack", "Jack Sparrow"); - + result.computeStatus(); TestUtil.assertSuccess("getObject result", result); - + assertSteadyResources(); } @@ -654,15 +654,15 @@ public void test111GetUserResolveAccountResource() throws Exception { OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - Collection> options = + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createResolve(), new ItemPath(UserType.F_LINK), new ItemPath(UserType.F_LINK, ShadowType.F_RESOURCE) ); - + // WHEN PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, options , task, result); - + // THEN assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); assertUserJack(userJack); @@ -671,7 +671,7 @@ public void test111GetUserResolveAccountResource() throws Exception { ObjectReferenceType accountRefType = userJackType.getLinkRef().get(0); String accountOid = accountRefType.getOid(); assertFalse("No accountRef oid", StringUtils.isBlank(accountOid)); - + PrismReferenceValue accountRefValue = accountRefType.asReferenceValue(); assertEquals("OID mismatch in accountRefValue", accountOid, accountRefValue.getOid()); assertNotNull("Missing account object in accountRefValue", accountRefValue.getObject()); @@ -679,13 +679,13 @@ public void test111GetUserResolveAccountResource() throws Exception { assertEquals("Unexpected number of accounts", 1, userJackType.getLink().size()); ShadowType shadow = userJackType.getLink().get(0); assertDummyAccountShadowModel(shadow.asPrismObject(), accountOid, "jack", "Jack Sparrow"); - + assertNotNull("Resource in account was not resolved", shadow.getResource()); - + assertSuccess("getObject result", result); - + userJack.checkConsistence(true, true); - + assertSteadyResources(); } @@ -702,12 +702,12 @@ public void test112GetUserResolveAccountNoFetch() throws Exception { GetOperationOptions getOpts = new GetOperationOptions(); getOpts.setResolve(true); getOpts.setNoFetch(true); - Collection> options = + Collection> options = SelectorOptions.createCollection(UserType.F_LINK, getOpts); - + // WHEN PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, options , task, result); - + // THEN assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); assertUserJack(userJack); @@ -716,7 +716,7 @@ public void test112GetUserResolveAccountNoFetch() throws Exception { ObjectReferenceType accountRefType = userJackType.getLinkRef().get(0); String accountOid = accountRefType.getOid(); assertFalse("No accountRef oid", StringUtils.isBlank(accountOid)); - + PrismReferenceValue accountRefValue = accountRefType.asReferenceValue(); assertEquals("OID mismatch in accountRefValue", accountOid, accountRefValue.getOid()); assertNotNull("Missing account object in accountRefValue", accountRefValue.getObject()); @@ -724,15 +724,15 @@ public void test112GetUserResolveAccountNoFetch() throws Exception { assertEquals("Unexpected number of accounts", 1, userJackType.getLink().size()); ShadowType shadow = userJackType.getLink().get(0); assertDummyAccountShadowRepo(shadow.asPrismObject(), accountOid, "jack"); - + result.computeStatus(); TestUtil.assertSuccess("getObject result", result); - + userJack.checkConsistence(true, true); - + assertSteadyResources(); } - + @Test public void test119ModifyUserDeleteAccount() throws Exception { final String TEST_NAME = "test119ModifyUserDeleteAccount"; @@ -745,7 +745,7 @@ public void test119ModifyUserDeleteAccount() throws Exception { PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); account.setOid(accountJackOid); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_JACK_OID, prismContext); ReferenceDelta accountDelta = ReferenceDelta.createModificationDelete(UserType.F_LINK_REF, getUserDefinition(), account); userDelta.addModification(accountDelta); @@ -754,19 +754,19 @@ public void test119ModifyUserDeleteAccount() throws Exception { // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result, 2); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + // Check accountRef 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); @@ -774,12 +774,12 @@ public void test119ModifyUserDeleteAccount() throws Exception { } catch (ObjectNotFoundException e) { // This is OK } - + // Check if dummy resource account is gone assertNoDummyAccount("jack"); - + assertDummyScriptsDelete(); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -801,7 +801,7 @@ public void test119ModifyUserDeleteAccount() throws Exception { checkDummyTransportMessages("simpleAccountNotifier-DELETE-SUCCESS", 1); checkDummyTransportMessages("simpleUserNotifier", 0); checkDummyTransportMessages("simpleUserNotifier-ADD", 0); - + assertSteadyResources(); } @@ -813,22 +813,22 @@ public void test120AddAccount() throws Exception { Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test120AddAccount"); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); ObjectDelta accountDelta = ObjectDelta.createAddDelta(account); Collection> deltas = MiscSchemaUtil.createCollection(accountDelta); - + XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + accountJackOid = accountDelta.getOid(); assertNotNull("No account OID in resulting delta", accountJackOid); // Check accountRef (should be none) @@ -836,23 +836,23 @@ public void test120AddAccount() throws Exception { assertUserJack(userJack); UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 0, userJackType.getLinkRef().size()); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); assertEnableTimestampShadow(accountShadow, startTime, endTime); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, "jack", "Jack Sparrow"); assertEnableTimestampShadow(accountModel, startTime, endTime); - + // Check account in dummy resource assertDefaultDummyAccount("jack", "Jack Sparrow", true); - + // The user is not associated with the account assertDummyScriptsAdd(null, accountModel, getDummyResourceType()); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -873,10 +873,10 @@ public void test120AddAccount() throws Exception { checkDummyTransportMessages("simpleAccountNotifier-ADD-SUCCESS", 1); checkDummyTransportMessages("simpleUserNotifier", 0); // account has no owner checkDummyTransportMessages("simpleUserNotifier-ADD", 0); - + assertSteadyResources(); } - + /** * Linking existing account. */ @@ -893,32 +893,32 @@ public void test121ModifyUserAddAccountRef() throws Exception { ReferenceDelta accountDelta = ReferenceDelta.createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountJackOid); userDelta.addModification(accountDelta); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - + // There is strong mapping. Complete account is fetched. assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); - + PrismObject userJack = getUser(USER_JACK_OID); assertUserJack(userJack); accountJackOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, "jack", "Jack Sparrow"); - + // Check account in dummy resource assertDefaultDummyAccount("jack", "Jack Sparrow", true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -944,7 +944,7 @@ public void test121ModifyUserAddAccountRef() throws Exception { } - + @Test public void test128ModifyUserDeleteAccountRef() throws Exception { TestUtil.displayTestTitle(this, "test128ModifyUserDeleteAccountRef"); @@ -955,38 +955,38 @@ public void test128ModifyUserDeleteAccountRef() throws Exception { preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_JACK_OID, prismContext); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account); ReferenceDelta accountDelta = ReferenceDelta.createModificationDelete(UserType.F_LINK_REF, getUserDefinition(), accountJackOid); userDelta.addModification(accountDelta); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userJack = getUser(USER_JACK_OID); assertUserJack(userJack); // Check accountRef assertUserNoAccountRefs(userJack); - + // Check shadow (if it is unchanged) PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); - + // Check account (if it is unchanged) PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, "jack", "Jack Sparrow"); - + // Check account in dummy resource (if it is unchanged) assertDefaultDummyAccount("jack", "Jack Sparrow", true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -1010,7 +1010,7 @@ public void test128ModifyUserDeleteAccountRef() throws Exception { assertSteadyResources(); } - + @Test public void test129DeleteAccount() throws Exception { TestUtil.displayTestTitle(this, "test129DeleteAccount"); @@ -1019,31 +1019,31 @@ public void test129DeleteAccount() throws Exception { Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test129DeleteAccount"); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + ObjectDelta accountDelta = ObjectDelta.createDeleteDelta(ShadowType.class, accountJackOid, prismContext); Collection> deltas = MiscSchemaUtil.createCollection(accountDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userJack = getUser(USER_JACK_OID); assertUserJack(userJack); // Check accountRef assertUserNoAccountRefs(userJack); - + // Check is shadow is gone assertNoShadow(accountJackOid); - + // Check if dummy resource account is gone assertNoDummyAccount("jack"); - + assertDummyScriptsDelete(); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -1064,11 +1064,11 @@ public void test129DeleteAccount() throws Exception { checkDummyTransportMessages("simpleAccountNotifier-DELETE-SUCCESS", 1); checkDummyTransportMessages("simpleUserNotifier", 0); // there's no link user->account (removed in test128) checkDummyTransportMessages("simpleUserNotifier-ADD", 0); - + assertSteadyResources(); } - + @Test public void test130PreviewModifyUserJackAssignAccount() throws Exception { TestUtil.displayTestTitle(this, "test130PreviewModifyUserJackAssignAccount"); @@ -1078,19 +1078,19 @@ public void test130PreviewModifyUserJackAssignAccount() throws Exception { Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test130PreviewModifyUserJackAssignAccount"); 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); - + // WHEN ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); - + // 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); @@ -1100,20 +1100,20 @@ public void test130PreviewModifyUserJackAssignAccount() throws Exception { // TODO: assert context // TODO: assert context // TODO: assert context - + assertResolvedResourceRefs(modelContext); - + // Check account in dummy resource assertNoDummyAccount("jack"); - + dummyAuditService.assertNoRecord(); }catch(Exception ex){ LOGGER.info("Exception {}", ex.getMessage(), ex); } - + assertSteadyResources(); } - + @Test public void test131ModifyUserJackAssignAccount() throws Exception { final String TEST_NAME="test131ModifyUserJackAssignAccount"; @@ -1123,23 +1123,23 @@ public void test131ModifyUserJackAssignAccount() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.FULL); - + rememberCounter(InternalCounters.PRISM_OBJECT_CLONE_COUNT); - + XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignAccount(USER_JACK_OID, RESOURCE_DUMMY_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - assertCounterIncrement(InternalCounters.PRISM_OBJECT_CLONE_COUNT, 66); - + assertCounterIncrement(InternalCounters.PRISM_OBJECT_CLONE_COUNT, 66); + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); @@ -1147,24 +1147,24 @@ public void test131ModifyUserJackAssignAccount() throws Exception { assertAssignments(userJack, 1); assertModifyMetadata(userJack, startTime, endTime); assertCreateMetadata(assignmentType, startTime, endTime); - + accountJackOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); assertEnableTimestampShadow(accountShadow, startTime, endTime); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, "jack", "Jack Sparrow"); assertEnableTimestampShadow(accountModel, startTime, endTime); - + // Check account in dummy resource assertDefaultDummyAccount("jack", "Jack Sparrow", true); - + assertDummyScriptsAdd(userJack, accountModel, getDummyResourceType()); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -1186,10 +1186,10 @@ public void test131ModifyUserJackAssignAccount() throws Exception { checkDummyTransportMessages("simpleAccountNotifier-DELETE-SUCCESS", 0); checkDummyTransportMessages("simpleUserNotifier", 1); checkDummyTransportMessages("simpleUserNotifier-ADD", 0); - + assertSteadyResources(); } - + /** * Modify the account. Some of the changes should be reflected back to the user by inbound mapping. */ @@ -1202,7 +1202,7 @@ public void test132ModifyAccountJackDummy() throws Exception { Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.FULL); - + Collection> deltas = new ArrayList>(); ObjectDelta accountDelta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, accountJackOid, dummyResourceCtl.getAttributeFullnamePath(), prismContext, "Cpt. Jack Sparrow"); @@ -1210,62 +1210,62 @@ public void test132ModifyAccountJackDummy() throws Exception { dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME), "Queen Anne's Revenge"); deltas.add(accountDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); // There is strong mapping. Complete account is fetched. assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); // Fullname inbound mapping is not used because it is weak assertUserJack(userJack, "Jack Sparrow", "Jack", "Sparrow"); - // ship inbound mapping is used, it is strong - assertEquals("Wrong user locality (orig)", "The crew of Queen Anne's Revenge", + // ship inbound mapping is used, it is strong + assertEquals("Wrong user locality (orig)", "The crew of Queen Anne's Revenge", userJack.asObjectable().getOrganizationalUnit().iterator().next().getOrig()); - assertEquals("Wrong user locality (norm)", "the crew of queen annes revenge", + assertEquals("Wrong user locality (norm)", "the crew of queen annes revenge", userJack.asObjectable().getOrganizationalUnit().iterator().next().getNorm()); accountJackOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); - + // Check account // All the changes should be reflected to the account PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, "jack", "Cpt. Jack Sparrow"); - PrismAsserts.assertPropertyValue(accountModel, + PrismAsserts.assertPropertyValue(accountModel, dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME), "Queen Anne's Revenge"); - + // Check account in dummy resource assertDefaultDummyAccount(USER_JACK_USERNAME, "Cpt. Jack Sparrow", true); - assertDummyAccountAttribute(null, USER_JACK_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, + assertDummyAccountAttribute(null, USER_JACK_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "Queen Anne's Revenge"); - + assertDummyScriptsModify(userJack); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); dummyAuditService.assertRecords(3); dummyAuditService.assertAnyRequestDeltas(); - + dummyAuditService.assertExecutionDeltas(0, 1); dummyAuditService.assertHasDelta(0, ChangeType.MODIFY, ShadowType.class); - dummyAuditService.assertOldValue(0, ChangeType.MODIFY, ShadowType.class, + dummyAuditService.assertOldValue(0, ChangeType.MODIFY, ShadowType.class, dummyResourceCtl.getAttributeFullnamePath(), "Jack Sparrow"); -// dummyAuditService.assertOldValue(0, ChangeType.MODIFY, ShadowType.class, +// dummyAuditService.assertOldValue(0, ChangeType.MODIFY, ShadowType.class, // dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME)); - + dummyAuditService.assertExecutionDeltas(1, 1); dummyAuditService.assertHasDelta(1, ChangeType.MODIFY, UserType.class); - + dummyAuditService.assertTarget(USER_JACK_OID); dummyAuditService.assertExecutionSuccess(); @@ -1282,7 +1282,7 @@ public void test132ModifyAccountJackDummy() throws Exception { assertSteadyResources(); } - + /** * MID-3080 */ @@ -1295,16 +1295,16 @@ public void test135ModifyUserJackAssignAccountAgain() throws Exception { Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.FULL); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignAccount(USER_JACK_OID, RESOURCE_DUMMY_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); @@ -1312,19 +1312,19 @@ public void test135ModifyUserJackAssignAccountAgain() throws Exception { assertAssignments(userJack, 1); accountJackOid = getSingleLinkOid(userJack); - - + + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, "jack", "Cpt. Jack Sparrow"); - + // Check account in dummy resource assertDefaultDummyAccount("jack", "Cpt. Jack Sparrow", true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -1345,10 +1345,10 @@ public void test135ModifyUserJackAssignAccountAgain() throws Exception { checkDummyTransportMessages("simpleAccountNotifier-DELETE-SUCCESS", 0); checkDummyTransportMessages("simpleUserNotifier", 1); checkDummyTransportMessages("simpleUserNotifier-ADD", 0); - + assertSteadyResources(); } - + @Test public void test139ModifyUserJackUnassignAccount() throws Exception { final String TEST_NAME = "test139ModifyUserJackUnassignAccount"; @@ -1358,32 +1358,32 @@ public void test139ModifyUserJackUnassignAccount() throws Exception { Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.FULL); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, null, false); deltas.add(accountAssignmentUserDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userJack = getUser(USER_JACK_OID); assertUserJack(userJack, "Jack Sparrow", "Jack", "Sparrow"); // Check accountRef assertUserNoAccountRefs(userJack); - + // Check is shadow is gone assertNoShadow(accountJackOid); - + // Check if dummy resource account is gone assertNoDummyAccount("jack"); - + assertDummyScriptsDelete(); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); @@ -1408,7 +1408,7 @@ public void test139ModifyUserJackUnassignAccount() throws Exception { assertSteadyResources(); } - + /** * Assignment enforcement is set to POSITIVE for this test. The account should be added. */ @@ -1421,49 +1421,49 @@ public void test141ModifyUserJackAssignAccountPositiveEnforcement() throws Excep Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, null, true); deltas.add(accountAssignmentUserDelta); - + // Let's break the delta a bit. Projector should handle this anyway breakAssignmentDelta(deltas); - + // This is a second time we assigned this account. Therefore all the scripts in mapping should already // be compiled ... check this. rememberCounter(InternalCounters.SCRIPT_COMPILE_COUNT); - + XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); accountJackOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); assertEnableTimestampShadow(accountShadow, startTime, endTime); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, "jack", "Jack Sparrow"); assertEnableTimestampShadow(accountModel, startTime, endTime); - + // Check account in dummy resource assertDefaultDummyAccount("jack", "Jack Sparrow", true); - + assertDummyScriptsAdd(userJack, accountModel, getDummyResourceType()); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -1485,14 +1485,14 @@ public void test141ModifyUserJackAssignAccountPositiveEnforcement() throws Excep checkDummyTransportMessages("simpleAccountNotifier-DELETE-SUCCESS", 0); checkDummyTransportMessages("simpleUserNotifier", 1); checkDummyTransportMessages("simpleUserNotifier-ADD", 0); - + // This is a second time we assigned this account. Therefore all the scripts in mapping should already // be compiled ... check this. assertCounterIncrement(InternalCounters.SCRIPT_COMPILE_COUNT, 0); - + assertSteadyResources(); } - + /** * Assignment enforcement is set to POSITIVE for this test. The account should remain as it is. */ @@ -1502,7 +1502,7 @@ public void test148ModifyUserJackUnassignAccountPositiveEnforcement() throws Exc displayTestTitle(TEST_NAME); // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.FULL); @@ -1510,46 +1510,46 @@ public void test148ModifyUserJackUnassignAccountPositiveEnforcement() throws Exc Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, null, false); deltas.add(accountAssignmentUserDelta); - + // Let's break the delta a bit. Projector should handle this anyway breakAssignmentDelta(deltas); - + //change resource assigment policy to be positive..if they are not applied by projector, the test will fail assumeResourceAssigmentPolicy(RESOURCE_DUMMY_OID, AssignmentPolicyEnforcementType.POSITIVE, false); // the previous command changes resource, therefore let's explicitly re-read it before test // to refresh the cache and not affect the performance results (monitor). modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, task, result); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 1); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); // There is strong mapping. Complete account is fetched. assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); assertLinked(userJack, accountJackOid); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, "jack", "Jack Sparrow"); - + // Check account in dummy resource assertDefaultDummyAccount("jack", "Jack Sparrow", true); - + assertNoProvisioningScripts(); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -1570,10 +1570,10 @@ public void test148ModifyUserJackUnassignAccountPositiveEnforcement() throws Exc checkDummyTransportMessages("simpleAccountNotifier-DELETE-SUCCESS", 0); checkDummyTransportMessages("simpleUserNotifier", 1); checkDummyTransportMessages("simpleUserNotifier-ADD", 0); - + assertCounterIncrement(InternalCounters.SCRIPT_COMPILE_COUNT, 0); assertSteadyResources(); - + // return resource to the previous state..delete assignment enforcement to prevent next test to fail.. deleteResourceAssigmentPolicy(RESOURCE_DUMMY_OID, AssignmentPolicyEnforcementType.POSITIVE, false); // the previous command changes resource, therefore let's explicitly re-read it before test @@ -1595,38 +1595,38 @@ public void test149ModifyUserJackDeleteAccount() throws Exception { Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_JACK_OID, prismContext); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setOid(accountJackOid); ReferenceDelta accountRefDelta = ReferenceDelta.createModificationDelete(UserType.F_LINK_REF, getUserDefinition(), accountJackOid); userDelta.addModification(accountRefDelta); - + ObjectDelta accountDelta = ObjectDelta.createDeleteDelta(ShadowType.class, accountJackOid, prismContext); - + Collection> deltas = MiscSchemaUtil.createCollection(userDelta, accountDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userJack = getUser(USER_JACK_OID); assertUserJack(userJack, "Jack Sparrow", "Jack", "Sparrow"); // Check accountRef assertUserNoAccountRefs(userJack); - + // Check is shadow is gone assertNoShadow(accountJackOid); - + // Check if dummy resource account is gone assertNoDummyAccount("jack"); - + assertDummyScriptsDelete(); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); @@ -1648,11 +1648,11 @@ public void test149ModifyUserJackDeleteAccount() throws Exception { checkDummyTransportMessages("simpleAccountNotifier-DELETE-SUCCESS", 1); checkDummyTransportMessages("simpleUserNotifier", 0); checkDummyTransportMessages("simpleUserNotifier-ADD", 0); - + assertCounterIncrement(InternalCounters.SCRIPT_COMPILE_COUNT, 0); assertSteadyResources(); } - + /** * Assignment enforcement is set to RELATTIVE for this test. The account should be added. */ @@ -1665,45 +1665,45 @@ public void test151ModifyUserJackAssignAccountRelativeEnforcement() throws Excep Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.RELATIVE); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, null, true); deltas.add(accountAssignmentUserDelta); - + // Let's break the delta a bit. Projector should handle this anyway breakAssignmentDelta(deltas); - + XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN assertSuccess(result); assertResultSerialization(result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); accountJackOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); assertEnableTimestampShadow(accountShadow, startTime, endTime); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, "jack", "Jack Sparrow"); assertEnableTimestampShadow(accountModel, startTime, endTime); - + // Check account in dummy resource assertDefaultDummyAccount("jack", "Jack Sparrow", true); - + assertDummyScriptsAdd(userJack, accountModel, getDummyResourceType()); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -1725,7 +1725,7 @@ public void test151ModifyUserJackAssignAccountRelativeEnforcement() throws Excep checkDummyTransportMessages("simpleAccountNotifier-DELETE-SUCCESS", 0); checkDummyTransportMessages("simpleUserNotifier", 1); checkDummyTransportMessages("simpleUserNotifier-ADD", 0); - + assertCounterIncrement(InternalCounters.SCRIPT_COMPILE_COUNT, 0); assertSteadyResources(); } @@ -1739,7 +1739,7 @@ public void test158ModifyUserJackUnassignAccountRelativeEnforcement() throws Exc displayTestTitle(TEST_NAME); // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.RELATIVE); @@ -1747,28 +1747,28 @@ public void test158ModifyUserJackUnassignAccountRelativeEnforcement() throws Exc Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, null, false); deltas.add(accountAssignmentUserDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userJack = getUser(USER_JACK_OID); assertUserJack(userJack, "Jack Sparrow", "Jack", "Sparrow"); // Check accountRef assertUserNoAccountRefs(userJack); - + // Check is shadow is gone assertNoShadow(accountJackOid); - + // Check if dummy resource account is gone assertNoDummyAccount("jack"); - + assertDummyScriptsDelete(); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); @@ -1794,7 +1794,7 @@ public void test158ModifyUserJackUnassignAccountRelativeEnforcement() throws Exc assertCounterIncrement(InternalCounters.SCRIPT_COMPILE_COUNT, 0); assertSteadyResources(); } - + /** * Assignment enforcement is set to NONE for this test. */ @@ -1807,35 +1807,35 @@ public void test161ModifyUserJackAssignAccountNoneEnforcement() throws Exception Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.NONE); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, null, true); deltas.add(accountAssignmentUserDelta); - + // Let's break the delta a bit. Projector should handle this anyway breakAssignmentDelta(deltas); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userJack = getUser(USER_JACK_OID); assertUserJack(userJack, "Jack Sparrow", "Jack", "Sparrow"); // Check accountRef assertUserNoAccountRefs(userJack); - + // Check is shadow is gone assertNoShadow(accountJackOid); - + // Check if dummy resource account is gone assertNoDummyAccount("jack"); - + assertDummyProvisioningScriptsNone(); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); @@ -1856,11 +1856,11 @@ public void test161ModifyUserJackAssignAccountNoneEnforcement() throws Exception checkDummyTransportMessages("simpleAccountNotifier-DELETE-SUCCESS", 0); checkDummyTransportMessages("simpleUserNotifier", 1); checkDummyTransportMessages("simpleUserNotifier-ADD", 0); - + assertCounterIncrement(InternalCounters.SCRIPT_COMPILE_COUNT, 0); assertSteadyResources(); } - + @Test public void test163ModifyUserJackAddAccountNoneEnforcement() throws Exception { final String TEST_NAME = "test163ModifyUserJackAddAccountNoneEnforcement"; @@ -1870,51 +1870,51 @@ public void test163ModifyUserJackAddAccountNoneEnforcement() throws Exception { Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.NONE); - + PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_JACK_OID, prismContext); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account); ReferenceDelta accountDelta = ReferenceDelta.createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); userDelta.addModification(accountDelta); Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); - + dummyAuditService.clear(); dummyTransport.clearMessages(); notificationManager.setDisabled(false); - + XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); accountJackOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); assertEnableTimestampShadow(accountShadow, startTime, endTime); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, "jack", "Jack Sparrow"); assertEnableTimestampShadow(accountModel, startTime, endTime); - + // Check account in dummy resource assertDefaultDummyAccount("jack", "Jack Sparrow", true); - + assertDummyScriptsAdd(userJack, accountModel, getDummyResourceType()); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -1936,18 +1936,18 @@ public void test163ModifyUserJackAddAccountNoneEnforcement() throws Exception { checkDummyTransportMessages("simpleAccountNotifier-ADD-SUCCESS", 1); checkDummyTransportMessages("simpleUserNotifier", 0); checkDummyTransportMessages("simpleUserNotifier-ADD", 0); - + assertCounterIncrement(InternalCounters.SCRIPT_COMPILE_COUNT, 0); assertSteadyResources(); } - + @Test public void test164ModifyUserJackUnassignAccountNoneEnforcement() throws Exception { final String TEST_NAME = "test164ModifyUserJackUnassignAccountNoneEnforcement"; displayTestTitle(TEST_NAME); // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.NONE); @@ -1955,34 +1955,34 @@ public void test164ModifyUserJackUnassignAccountNoneEnforcement() throws Excepti Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, null, false); deltas.add(accountAssignmentUserDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); // Strong mappings assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); accountJackOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, "jack", "Jack Sparrow"); - + // Check account in dummy resource assertDefaultDummyAccount("jack", "Jack Sparrow", true); - + assertDummyProvisioningScriptsNone(); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -2003,11 +2003,11 @@ public void test164ModifyUserJackUnassignAccountNoneEnforcement() throws Excepti checkDummyTransportMessages("simpleAccountNotifier-ADD-SUCCESS", 0); checkDummyTransportMessages("simpleUserNotifier", 1); checkDummyTransportMessages("simpleUserNotifier-ADD", 0); - + assertCounterIncrement(InternalCounters.SCRIPT_COMPILE_COUNT, 0); assertSteadyResources(); } - + @Test public void test169ModifyUserJackDeleteAccountNoneEnforcement() throws Exception { final String TEST_NAME = "test169ModifyUserJackDeleteAccountNoneEnforcement"; @@ -2017,38 +2017,38 @@ public void test169ModifyUserJackDeleteAccountNoneEnforcement() throws Exception Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.NONE); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_JACK_OID, prismContext); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setOid(accountJackOid); ReferenceDelta accountRefDelta = ReferenceDelta.createModificationDelete(UserType.F_LINK_REF, getUserDefinition(), accountJackOid); userDelta.addModification(accountRefDelta); - + ObjectDelta accountDelta = ObjectDelta.createDeleteDelta(ShadowType.class, accountJackOid, prismContext); - + Collection> deltas = MiscSchemaUtil.createCollection(userDelta, accountDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userJack = getUser(USER_JACK_OID); assertUserJack(userJack, "Jack Sparrow", "Jack", "Sparrow"); // Check accountRef assertUserNoAccountRefs(userJack); - + // Check is shadow is gone assertNoShadow(accountJackOid); - + // Check if dummy resource account is gone assertNoDummyAccount("jack"); - + assertDummyScriptsDelete(); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); @@ -2084,45 +2084,45 @@ public void test180ModifyUserAddAccountFullEnforcement() throws Exception { Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.FULL); - + PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_JACK_OID, prismContext); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account); ReferenceDelta accountDelta = ReferenceDelta.createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); userDelta.addModification(accountDelta); Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); - + try { - + // WHEN modelService.executeChanges(deltas, null, task, result); - + AssertJUnit.fail("Unexpected executeChanges success"); } catch (PolicyViolationException e) { // This is expected display("Expected exception", e); } - + // THEN result.computeStatus(); TestUtil.assertFailure("executeChanges result", result); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userJack = getUser(USER_JACK_OID); assertUserJack(userJack, "Jack Sparrow", "Jack", "Sparrow"); // Check accountRef assertUserNoAccountRefs(userJack); - + // Check that shadow was not created assertNoShadow(accountJackOid); - + // Check that dummy resource account was not created assertNoDummyAccount("jack"); - + assertNoProvisioningScripts(); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -2131,11 +2131,11 @@ public void test180ModifyUserAddAccountFullEnforcement() throws Exception { dummyAuditService.assertExecutionDeltas(0, 0); dummyAuditService.assertExecutionOutcome(OperationResultStatus.FATAL_ERROR); dummyAuditService.assertTarget(USER_JACK_OID); - + assertCounterIncrement(InternalCounters.SCRIPT_COMPILE_COUNT, 0); assertSteadyResources(); } - + @Test public void test182ModifyUserAddAndAssignAccountPositiveEnforcement() throws Exception { final String TEST_NAME = "test182ModifyUserAddAndAssignAccountPositiveEnforcement"; @@ -2145,21 +2145,21 @@ public void test182ModifyUserAddAndAssignAccountPositiveEnforcement() throws Exc Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); - + ObjectDelta userDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, null, true); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account); ReferenceDelta accountDelta = ReferenceDelta.createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); userDelta.addModification(accountDelta); Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); - + XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); @@ -2174,25 +2174,25 @@ public void test182ModifyUserAddAndAssignAccountPositiveEnforcement() throws Exc PrismReferenceValue accountRefValue = accountRefType.asReferenceValue(); assertEquals("OID mismatch in accountRefValue", accountJackOid, accountRefValue.getOid()); assertNull("Unexpected object in accountRefValue", accountRefValue.getObject()); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); assertEnableTimestampShadow(accountShadow, startTime, endTime); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, "jack", "Jack Sparrow"); assertEnableTimestampShadow(accountModel, startTime, endTime); - + // Check account in dummy resource assertDefaultDummyAccount("jack", "Jack Sparrow", true); - + result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - + assertDummyScriptsAdd(userJack, accountModel, getDummyResourceType()); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -2203,11 +2203,11 @@ public void test182ModifyUserAddAndAssignAccountPositiveEnforcement() throws Exc dummyAuditService.assertHasDelta(ChangeType.ADD, ShadowType.class); dummyAuditService.assertTarget(USER_JACK_OID); dummyAuditService.assertExecutionSuccess(); - + assertCounterIncrement(InternalCounters.SCRIPT_COMPILE_COUNT, 0); assertSteadyResources(); } - + /** * Assignment enforcement is set to POSITIVE for this test as it was for the previous test. * Now we will explicitly delete the account. @@ -2220,35 +2220,35 @@ public void test189ModifyUserJackUnassignAndDeleteAccount() throws Exception { Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test149ModifyUserJackUnassignAccount"); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + ObjectDelta userDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, null, false); // Explicit unlink is not needed here, it should work without it - + ObjectDelta accountDelta = ObjectDelta.createDeleteDelta(ShadowType.class, accountJackOid, prismContext); - + Collection> deltas = MiscSchemaUtil.createCollection(userDelta, accountDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userJack = getUser(USER_JACK_OID); assertUserJack(userJack, "Jack Sparrow", "Jack", "Sparrow"); // Check accountRef assertUserNoAccountRefs(userJack); - + // Check is shadow is gone assertNoShadow(accountJackOid); - + // Check if dummy resource account is gone assertNoDummyAccount("jack"); - + assertDummyScriptsDelete(); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); @@ -2259,11 +2259,11 @@ public void test189ModifyUserJackUnassignAndDeleteAccount() throws Exception { dummyAuditService.assertHasDelta(ChangeType.DELETE, ShadowType.class); dummyAuditService.assertTarget(USER_JACK_OID); dummyAuditService.assertExecutionSuccess(); - + assertCounterIncrement(InternalCounters.SCRIPT_COMPILE_COUNT, 0); assertSteadyResources(); } - + /** * 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 @@ -2277,51 +2277,51 @@ public void test190ModifyUserJackAssignAccountAndModify() throws Exception { Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test190ModifyUserJackAssignAccountAndModify"); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.FULL); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, null, true); ShadowDiscriminatorObjectDelta accountDelta = ShadowDiscriminatorObjectDelta.createModificationReplaceProperty(ShadowType.class, RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, null, dummyResourceCtl.getAttributeFullnamePath(), prismContext, "Cpt. Jack Sparrow"); accountDelta.addModificationAddProperty( - dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME), + dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME), "smell"); deltas.add(accountDelta); deltas.add(accountAssignmentUserDelta); - + XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); accountJackOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountJackOid, USER_JACK_USERNAME); assertEnableTimestampShadow(accountShadow, startTime, endTime); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, USER_JACK_USERNAME, "Cpt. Jack Sparrow"); assertEnableTimestampShadow(accountModel, startTime, endTime); - + // Check account in dummy resource assertDefaultDummyAccount(USER_JACK_USERNAME, "Cpt. Jack Sparrow", true); DummyAccount dummyAccount = getDummyAccount(null, USER_JACK_USERNAME); assertDummyAccountAttribute(null, USER_JACK_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, "smell"); assertNull("Unexpected loot", dummyAccount.getAttributeValue("loot", Integer.class)); - + assertDummyScriptsAdd(userJack, accountModel, getDummyResourceType()); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -2366,11 +2366,11 @@ public void test191ModifyUserJackModifyAssignment() throws Exception { //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); // This explicitly parses the schema, therefore ... assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 1); - + RefinedObjectClassDefinition accountDefinition = refinedSchema.getRefinedDefinition(ShadowKindType.ACCOUNT, (String) null); PrismPropertyDefinition gossipDefinition = accountDefinition.findPropertyDefinition(new QName( "http://midpoint.evolveum.com/xml/ns/public/resource/instance/10000000-0000-0000-0000-000000000004", @@ -2408,7 +2408,7 @@ public void test191ModifyUserJackModifyAssignment() throws Exception { ObjectDelta accountAssignmentUserDelta = createReplaceAccountConstructionUserDelta(USER_JACK_OID, assignmentId, accountConstruction); deltas.add(accountAssignmentUserDelta); - + preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); PrismObject userJackOld = getUser(USER_JACK_OID); @@ -2449,7 +2449,7 @@ public void test191ModifyUserJackModifyAssignment() throws Exception { //assertEquals("Missing or incorrect attribute value", "soda", dummyAccount.getAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, String.class)); assertDummyScriptsModify(userJack, true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -2461,7 +2461,7 @@ public void test191ModifyUserJackModifyAssignment() throws Exception { dummyAuditService.assertHasDelta(ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertTarget(USER_JACK_OID); dummyAuditService.assertExecutionSuccess(); - + assertCounterIncrement(InternalCounters.SCRIPT_COMPILE_COUNT, 0); assertSteadyResources(); } @@ -2478,34 +2478,34 @@ public void test195ModifyUserJack() throws Exception { // WHEN TestUtil.displayWhen(TEST_NAME); - modifyUserReplace(USER_JACK_OID, UserType.F_FULL_NAME, task, result, + modifyUserReplace(USER_JACK_OID, UserType.F_FULL_NAME, task, result, PrismTestUtil.createPolyString("Magnificent Captain Jack Sparrow")); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); // Strong mappings assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Magnificent Captain Jack Sparrow"); accountJackOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, "jack", "Magnificent Captain Jack Sparrow"); - + // Check account in dummy resource assertDefaultDummyAccount("jack", "Magnificent Captain Jack Sparrow", true); - + assertDummyScriptsModify(userJack); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -2514,13 +2514,13 @@ public void test195ModifyUserJack() throws Exception { dummyAuditService.assertExecutionDeltas(2); dummyAuditService.assertHasDelta(ChangeType.MODIFY, UserType.class); dummyAuditService.assertHasDelta(ChangeType.MODIFY, ShadowType.class); - + dummyAuditService.assertOldValue(ChangeType.MODIFY, UserType.class, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Jack Sparrow")); // We have full account here. It is loaded because of strong mapping. - dummyAuditService.assertOldValue(ChangeType.MODIFY, ShadowType.class, + dummyAuditService.assertOldValue(ChangeType.MODIFY, ShadowType.class, dummyResourceCtl.getAttributeFullnamePath(), "Cpt. Jack Sparrow"); - + dummyAuditService.assertTarget(USER_JACK_OID); dummyAuditService.assertExecutionSuccess(); @@ -2534,11 +2534,11 @@ public void test195ModifyUserJack() throws Exception { checkDummyTransportMessages("simpleAccountNotifier-DELETE-SUCCESS", 0); checkDummyTransportMessages("simpleUserNotifier", 1); checkDummyTransportMessages("simpleUserNotifier-ADD", 0); - + assertCounterIncrement(InternalCounters.SCRIPT_COMPILE_COUNT, 0); assertSteadyResources(); } - + @Test public void test196ModifyUserJackLocationEmpty() throws Exception { final String TEST_NAME = "test196ModifyUserJackLocationEmpty"; @@ -2551,32 +2551,32 @@ public void test196ModifyUserJackLocationEmpty() throws Exception { // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_LOCALITY, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); // Strong mappings assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Magnificent Captain Jack Sparrow", "Jack", "Sparrow", null); accountJackOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, "jack", "Magnificent Captain Jack Sparrow"); IntegrationTestTools.assertNoAttribute(accountModel, dummyResourceCtl.getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME)); - + // Check account in dummy resource assertDefaultDummyAccount("jack", "Magnificent Captain Jack Sparrow", true); - + assertDummyScriptsModify(userJack); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -2612,11 +2612,11 @@ public void test197ModifyUserJackLocationNull() throws Exception { Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.FULL); - + try { // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_LOCALITY, task, result, (PolyString)null); - + AssertJUnit.fail("Unexpected success"); } catch (IllegalStateException e) { // This is expected @@ -2625,18 +2625,18 @@ public void test197ModifyUserJackLocationNull() throws Exception { result.computeStatus(); TestUtil.assertFailure(result); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + assertNoProvisioningScripts(); - + // Check audit display("Audit", dummyAuditService); // This should fail even before the request record is created dummyAuditService.assertRecords(0); - + assertCounterIncrement(InternalCounters.SCRIPT_COMPILE_COUNT, 0); assertSteadyResources(); } - + @Test public void test198ModifyUserJackRaw() throws Exception { TestUtil.displayTestTitle(this, "test198ModifyUserJackRaw"); @@ -2649,33 +2649,33 @@ public void test198ModifyUserJackRaw() throws Exception { ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_JACK_OID, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Marvelous Captain Jack Sparrow")); Collection> deltas = (Collection)MiscUtil.createCollection(objectDelta); - + // WHEN modelService.executeChanges(deltas, ModelExecuteOptions.createRaw(), task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Marvelous Captain Jack Sparrow", "Jack", "Sparrow", null); accountJackOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); - + // Check account - the original fullName should not be changed PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, "jack", "Magnificent Captain Jack Sparrow"); - + // Check account in dummy resource - the original fullName should not be changed assertDefaultDummyAccount("jack", "Magnificent Captain Jack Sparrow", true); - + assertNoProvisioningScripts(); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -2685,11 +2685,11 @@ public void test198ModifyUserJackRaw() throws Exception { dummyAuditService.assertHasDelta(ChangeType.MODIFY, UserType.class); dummyAuditService.assertTarget(USER_JACK_OID); // MID-2451 dummyAuditService.assertExecutionSuccess(); - + assertCounterIncrement(InternalCounters.SCRIPT_COMPILE_COUNT, 0); assertSteadyResources(); } - + @Test public void test199DeleteUserJack() throws Exception { TestUtil.displayTestTitle(this, "test199DeleteUserJack"); @@ -2698,33 +2698,33 @@ public void test199DeleteUserJack() throws Exception { Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test199DeleteUserJack"); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.FULL); - + ObjectDelta userDelta = ObjectDelta.createDeleteDelta(UserType.class, USER_JACK_OID, prismContext); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + try { PrismObject userJack = getUser(USER_JACK_OID); AssertJUnit.fail("Jack is still alive!"); } catch (ObjectNotFoundException ex) { // This is OK } - + // Check is shadow is gone assertNoShadow(accountJackOid); - + // Check if dummy resource account is gone assertNoDummyAccount("jack"); - + assertDummyScriptsDelete(); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -2747,11 +2747,11 @@ public void test199DeleteUserJack() throws Exception { checkDummyTransportMessages("simpleUserNotifier", 1); checkDummyTransportMessages("simpleUserNotifier-ADD", 0); checkDummyTransportMessages("simpleUserNotifier-DELETE", 1); - + assertCounterIncrement(InternalCounters.SCRIPT_COMPILE_COUNT, 0); assertSteadyResources(); } - + @Test public void test200AddUserBlackbeardWithAccount() throws Exception { final String TEST_NAME = "test200AddUserBlackbeardWithAccount"; @@ -2763,50 +2763,50 @@ public void test200AddUserBlackbeardWithAccount() throws Exception { task.setChannel("http://pirates.net/avast"); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + PrismObject user = PrismTestUtil.parseObject(new File(TEST_DIR, "user-blackbeard-account-dummy.xml")); ObjectDelta userDelta = ObjectDelta.createAddDelta(user); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userBlackbeard = modelService.getObject(UserType.class, USER_BLACKBEARD_OID, null, task, result); UserType userBlackbeardType = userBlackbeard.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userBlackbeardType.getLinkRef().size()); ObjectReferenceType accountRefType = userBlackbeardType.getLinkRef().get(0); String accountOid = accountRefType.getOid(); assertFalse("No accountRef oid", StringUtils.isBlank(accountOid)); - + assertEncryptedUserPassword(userBlackbeard, "QueenAnne"); assertPasswordMetadata(userBlackbeard, true, startTime, endTime, USER_ADMINISTRATOR_OID, "http://pirates.net/avast"); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountOid, "blackbeard"); assertEnableTimestampShadow(accountShadow, startTime, endTime); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, "blackbeard", "Edward Teach"); assertEnableTimestampShadow(accountModel, startTime, endTime); - + // 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)); - + assertDummyScriptsAdd(userBlackbeard, accountModel, getDummyResourceType()); - - // Check audit + + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); dummyAuditService.assertRecords(2); @@ -2833,11 +2833,11 @@ public void test200AddUserBlackbeardWithAccount() throws Exception { checkDummyTransportMessages("simpleUserNotifier", 1); checkDummyTransportMessages("simpleUserNotifier-ADD", 1); checkDummyTransportMessages("simpleUserNotifier-DELETE", 0); - + assertSteadyResources(); } - + @Test public void test210AddUserMorganWithAssignment() throws Exception { final String TEST_NAME = "test210AddUserMorganWithAssignment"; @@ -2847,24 +2847,24 @@ public void test210AddUserMorganWithAssignment() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.FULL); - + PrismObject user = PrismTestUtil.parseObject(new File(TEST_DIR, "user-morgan-assignment-dummy.xml")); ObjectDelta userDelta = ObjectDelta.createAddDelta(user); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userMorgan = modelService.getObject(UserType.class, USER_MORGAN_OID, null, task, result); display("User morgan after", userMorgan); UserType userMorganType = userMorgan.asObjectable(); @@ -2875,25 +2875,25 @@ public void test210AddUserMorganWithAssignment() throws Exception { assertFalse("No accountRef oid", StringUtils.isBlank(accountOid)); assertCreateMetadata(userMorgan, startTime, endTime); assertCreateMetadata(assignmentType, startTime, endTime); - + assertEncryptedUserPassword(userMorgan, "rum"); assertPasswordMetadata(userMorgan, true, startTime, endTime); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountOid, "morgan"); assertEnableTimestampShadow(accountShadow, startTime, endTime); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, "morgan", "Sir Henry Morgan"); assertEnableTimestampShadow(accountModel, startTime, endTime); - + // Check account in dummy resource assertDefaultDummyAccount("morgan", "Sir Henry Morgan", true); - + assertDummyScriptsAdd(userMorgan, accountModel, getDummyResourceType()); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -2920,7 +2920,7 @@ public void test210AddUserMorganWithAssignment() throws Exception { assertSteadyResources(); } - + @Test public void test212RenameUserMorgan() throws Exception { final String TEST_NAME = "test212RenameUserMorgan"; @@ -2930,40 +2930,40 @@ public void test212RenameUserMorgan() throws Exception { Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.FULL); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserReplace(USER_MORGAN_OID, UserType.F_NAME, task, result, PrismTestUtil.createPolyString("sirhenry")); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); // Strong mappings assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); - + PrismObject userMorgan = modelService.getObject(UserType.class, USER_MORGAN_OID, null, task, result); UserType userMorganType = userMorgan.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userMorganType.getLinkRef().size()); ObjectReferenceType accountRefType = userMorganType.getLinkRef().get(0); String accountOid = accountRefType.getOid(); assertFalse("No accountRef oid", StringUtils.isBlank(accountOid)); - + // Check shadow PrismObject accountShadowRepo = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Shadow repo", accountShadowRepo); assertDummyAccountShadowRepo(accountShadowRepo, accountOid, "sirhenry"); - + // Check account PrismObject accountShadowModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("Shadow model", accountShadowModel); assertDummyAccountShadowModel(accountShadowModel, accountOid, "sirhenry", "Sir Henry Morgan"); - + // Check account in dummy resource assertDefaultDummyAccount("sirhenry", "Sir Henry Morgan", true); - + assertDummyScriptsModify(userMorgan); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -2972,20 +2972,20 @@ public void test212RenameUserMorgan() throws Exception { dummyAuditService.assertExecutionDeltas(2); 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(), 3, auditShadowDelta.getObjectDelta().getModifications().size()); - + dummyAuditService.assertOldValue(ChangeType.MODIFY, UserType.class, UserType.F_NAME, PrismTestUtil.createPolyString("morgan")); - dummyAuditService.assertOldValue(ChangeType.MODIFY, ShadowType.class, + dummyAuditService.assertOldValue(ChangeType.MODIFY, ShadowType.class, new ItemPath(ShadowType.F_ATTRIBUTES, SchemaConstants.ICFS_NAME), "morgan"); - dummyAuditService.assertOldValue(ChangeType.MODIFY, ShadowType.class, + dummyAuditService.assertOldValue(ChangeType.MODIFY, ShadowType.class, new ItemPath(ShadowType.F_ATTRIBUTES, SchemaConstants.ICFS_UID), "morgan"); // This is a side-effect change. It is silently done by provisioning. It is not supposed to // appear in audit log. -// dummyAuditService.assertOldValue(ChangeType.MODIFY, ShadowType.class, +// dummyAuditService.assertOldValue(ChangeType.MODIFY, ShadowType.class, // new ItemPath(ShadowType.F_NAME), PrismTestUtil.createPolyString("morgan")); - + dummyAuditService.assertTarget(USER_MORGAN_OID); dummyAuditService.assertExecutionSuccess(); @@ -3003,7 +3003,7 @@ public void test212RenameUserMorgan() throws Exception { assertSteadyResources(); } - + /** * This basically tests for correct auditing. */ @@ -3019,22 +3019,22 @@ public void test240AddUserCharlesRaw() throws Exception { PrismObject user = createUser("charles", "Charles L. Charles"); ObjectDelta userDelta = ObjectDelta.createAddDelta(user); - Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + Collection> deltas = MiscSchemaUtil.createCollection(userDelta); + // WHEN modelService.executeChanges(deltas, ModelExecuteOptions.createRaw(), task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userAfter = findUserByUsername("charles"); assertNotNull("No charles", userAfter); userCharlesOid = userAfter.getOid(); - + assertNoProvisioningScripts(); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -3045,10 +3045,10 @@ public void test240AddUserCharlesRaw() throws Exception { // raw operation, no target // dummyAuditService.assertTarget(userAfter.getOid()); dummyAuditService.assertExecutionSuccess(); - + assertSteadyResources(); } - + /** * This basically tests for correct auditing. */ @@ -3063,21 +3063,21 @@ public void test241DeleteUserCharlesRaw() throws Exception { preTestCleanup(AssignmentPolicyEnforcementType.FULL); ObjectDelta userDelta = ObjectDelta.createDeleteDelta(UserType.class, userCharlesOid, prismContext); - Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + Collection> deltas = MiscSchemaUtil.createCollection(userDelta); + // WHEN modelService.executeChanges(deltas, ModelExecuteOptions.createRaw(), task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userAfter = findUserByUsername("charles"); assertNull("Charles is not gone", userAfter); - + assertNoProvisioningScripts(); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -3088,10 +3088,10 @@ public void test241DeleteUserCharlesRaw() throws Exception { // raw operation, no target // dummyAuditService.assertTarget(userCharlesOid); dummyAuditService.assertExecutionSuccess(); - + assertSteadyResources(); } - + @Test public void test300AddUserJackWithAssignmentBlue() throws Exception { final String TEST_NAME="test300AddUserJackWithAssignmentBlue"; @@ -3101,45 +3101,45 @@ public void test300AddUserJackWithAssignmentBlue() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.RELATIVE); - + PrismObject userJack = PrismTestUtil.parseObject(USER_JACK_FILE); AssignmentType assignmentBlue = createConstructionAssignment(RESOURCE_DUMMY_BLUE_OID, ShadowKindType.ACCOUNT, null); userJack.asObjectable().getAssignment().add(assignmentBlue); - + ObjectDelta delta = ObjectDelta.createAddDelta(userJack); - + XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject userJackAfter = getUser(USER_JACK_OID); display("User after change execution", userJackAfter); assertUserJack(userJackAfter); accountJackBlueOid = getSingleLinkOid(userJackAfter); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackBlueOid, null, result); assertAccountShadowRepo(accountShadow, accountJackBlueOid, USER_JACK_USERNAME, getDummyResourceType(RESOURCE_DUMMY_BLUE_NAME)); assertEnableTimestampShadow(accountShadow, startTime, endTime); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackBlueOid, null, task, result); - assertShadowModel(accountModel, accountJackBlueOid, USER_JACK_USERNAME, getDummyResourceType(RESOURCE_DUMMY_BLUE_NAME), + assertShadowModel(accountModel, accountJackBlueOid, USER_JACK_USERNAME, getDummyResourceType(RESOURCE_DUMMY_BLUE_NAME), getAccountObjectClass(getDummyResourceType(RESOURCE_DUMMY_BLUE_NAME))); assertEnableTimestampShadow(accountModel, startTime, endTime); - + // Check account in dummy resource assertDummyAccount(RESOURCE_DUMMY_BLUE_NAME, USER_JACK_USERNAME, USER_JACK_FULL_NAME, true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -3151,10 +3151,10 @@ public void test300AddUserJackWithAssignmentBlue() throws Exception { dummyAuditService.assertHasDelta(ChangeType.ADD, ShadowType.class); dummyAuditService.assertTarget(USER_JACK_OID); dummyAuditService.assertExecutionSuccess(); - + assertSteadyResources(); } - + /** * modify account blue directly + request reconcile. check old value in delta. */ @@ -3167,77 +3167,77 @@ public void test302ModifyAccountJackDummyBlue() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.FULL); - + Collection> deltas = new ArrayList>(); ObjectDelta accountDelta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, - accountJackBlueOid, getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).getAttributeFullnamePath(), prismContext, + accountJackBlueOid, getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).getAttributeFullnamePath(), prismContext, "Cpt. Jack Sparrow"); accountDelta.addModificationReplaceProperty( getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME), "Queen Anne's Revenge"); deltas.add(accountDelta); - + ModelExecuteOptions options = ModelExecuteOptions.createReconcile(); - + // WHEN modelService.executeChanges(deltas, options, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); // Not sure why 2 ... but this is not a big problem now assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 2); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); // Fullname inbound mapping is not used because it is weak assertUserJack(userJack, "Jack Sparrow", "Jack", "Sparrow"); String accountJackOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); assertAccountShadowRepo(accountShadow, accountJackBlueOid, USER_JACK_USERNAME, getDummyResourceType(RESOURCE_DUMMY_BLUE_NAME)); - + // Check account // All the changes should be reflected to the account PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); assertAccountShadowRepo(accountShadow, accountJackBlueOid, USER_JACK_USERNAME, getDummyResourceType(RESOURCE_DUMMY_BLUE_NAME)); - + // Check account in dummy resource assertDummyAccount(RESOURCE_DUMMY_BLUE_NAME, USER_JACK_USERNAME, "Cpt. Jack Sparrow", true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); dummyAuditService.assertRecords(2); dummyAuditService.assertAnyRequestDeltas(); - + dummyAuditService.assertExecutionDeltas(0, 1); dummyAuditService.assertHasDelta(0, ChangeType.MODIFY, ShadowType.class); - dummyAuditService.assertOldValue(0, ChangeType.MODIFY, ShadowType.class, + dummyAuditService.assertOldValue(0, ChangeType.MODIFY, ShadowType.class, getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).getAttributeFullnamePath(), "Jack Sparrow"); -// dummyAuditService.assertOldValue(0, ChangeType.MODIFY, ShadowType.class, +// dummyAuditService.assertOldValue(0, ChangeType.MODIFY, ShadowType.class, // dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME)); - + dummyAuditService.assertTarget(USER_JACK_OID); dummyAuditService.assertExecutionSuccess(); assertSteadyResources(); } - + private void assertDummyScriptsAdd(PrismObject user, PrismObject account, ResourceType resource) { ProvisioningScriptSpec script = new ProvisioningScriptSpec("\nto spiral :size\n" + " if :size > 30 [stop]\n fd :size rt 15\n spiral :size *1.02\nend\n "); - + String userName = null; if (user != null) { userName = user.asObjectable().getName().getOrig(); } script.addArgSingle("usr", "user: "+userName); - + // Note: We cannot test for account name as name is only assigned in provisioning String accountEnabled = null; - if (account != null && account.asObjectable().getActivation() != null + if (account != null && account.asObjectable().getActivation() != null && account.asObjectable().getActivation().getAdministrativeStatus() != null) { accountEnabled = account.asObjectable().getActivation().getAdministrativeStatus().toString(); } @@ -3257,7 +3257,7 @@ private void assertDummyScriptsAdd(PrismObject user, PrismObject user) { assertDummyScriptsModify(user, false); } - + private void assertDummyScriptsModify(PrismObject user, boolean recon) { ProvisioningScriptSpec modScript = new ProvisioningScriptSpec("Beware the Jabberwock, my son!"); String name = null; @@ -3287,7 +3287,7 @@ private void assertDummyScriptsDelete() { ProvisioningScriptSpec script = new ProvisioningScriptSpec("The Jabberwock, with eyes of flame"); IntegrationTestTools.assertScripts(getDummyResource().getScriptHistory(), script); } - + private void preTestCleanup(AssignmentPolicyEnforcementType enforcementPolicy) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { assumeAssignmentPolicy(enforcementPolicy); dummyAuditService.clear(); @@ -3295,7 +3295,7 @@ private void preTestCleanup(AssignmentPolicyEnforcementType enforcementPolicy) t purgeProvisioningScriptHistory(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); } - + private void assertResultSerialization(OperationResult result) throws SchemaException { OperationResultType resultType = result.createOperationResultType(); String serialized = prismContext.serializerFor(PrismContext.LANG_XML).serializeAnyData(resultType, SchemaConstants.C_RESULT); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelServiceContractCaching.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelServiceContractCaching.java index 9c23e125ae1..ef0a0afb163 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelServiceContractCaching.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelServiceContractCaching.java @@ -57,7 +57,7 @@ protected File getResourceDummyBlueFile() { protected File getResourceDummyGreenFile() { return RESOURCE_DUMMY_GREEN_CACHING_FILE; } - + @Override protected void assertShadowRepo(PrismObject shadow, String oid, String username, ResourceType resourceType, QName objectClass, MatchingRule nameMatchingRule) throws SchemaException { @@ -65,7 +65,7 @@ protected void assertShadowRepo(PrismObject shadow, String oid, Stri CachingMetadataType cachingMetadata = shadow.asObjectable().getCachingMetadata(); assertNotNull("Missing caching metadata in repo shadow"+shadow, cachingMetadata); } - + @Override protected void assertRepoShadowAttributes(List> 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 diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelVisualization.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelVisualization.java index 8f3ab806291..e370c9a70f7 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelVisualization.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelVisualization.java @@ -37,7 +37,7 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestModelVisualization extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/modelVisualization"); @Override diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMultiResource.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMultiResource.java index 992b91fa171..687578046c2 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMultiResource.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMultiResource.java @@ -78,43 +78,43 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestMultiResource extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/multi"); - + // LAVENDER dummy resource has a STRICT dependency on default dummy resource protected static final File RESOURCE_DUMMY_LAVENDER_FILE = new File(TEST_DIR, "resource-dummy-lavender.xml"); protected static final String RESOURCE_DUMMY_LAVENDER_OID = "10000000-0000-0000-0000-000000000504"; protected static final String RESOURCE_DUMMY_LAVENDER_NAME = "lavender"; protected static final String RESOURCE_DUMMY_LAVENDER_NAMESPACE = MidPointConstants.NS_RI; - + // IVORY dummy resource has a LAX dependency on default dummy resource protected static final File RESOURCE_DUMMY_IVORY_FILE = new File(TEST_DIR, "resource-dummy-ivory.xml"); protected static final String RESOURCE_DUMMY_IVORY_OID = "10000000-0000-0000-0000-000000011504"; protected static final String RESOURCE_DUMMY_IVORY_NAME = "ivory"; protected static final String RESOURCE_DUMMY_IVORY_NAMESPACE = MidPointConstants.NS_RI; - + // IVORY dummy resource has a RELAXED dependency on default dummy resource protected static final File RESOURCE_DUMMY_BEIGE_FILE = new File(TEST_DIR, "resource-dummy-beige.xml"); protected static final String RESOURCE_DUMMY_BEIGE_OID = "10000000-0000-0000-0000-00000001b504"; protected static final String RESOURCE_DUMMY_BEIGE_NAME = "beige"; protected static final String RESOURCE_DUMMY_BEIGE_NAMESPACE = MidPointConstants.NS_RI; - + // PERU dummy resource has a RELAXED dependency on YELLOW dummy resource protected static final File RESOURCE_DUMMY_PERU_FILE = new File(TEST_DIR, "resource-dummy-peru.xml"); protected static final String RESOURCE_DUMMY_PERU_OID = "10000000-0000-0000-0000-00000001c504"; protected static final String RESOURCE_DUMMY_PERU_NAME = "peru"; protected static final String RESOURCE_DUMMY_PERU_NAMESPACE = MidPointConstants.NS_RI; - + protected static final File RESOURCE_DUMMY_DAVID_FILE = new File(TEST_DIR, "resource-dummy-david.xml"); protected static final String RESOURCE_DUMMY_DAVID_OID = "10000000-0000-0000-0000-000000300001"; protected static final String RESOURCE_DUMMY_DAVID_NAME = "david"; protected static final String RESOURCE_DUMMY_DAVID_NAMESPACE = MidPointConstants.NS_RI; - + protected static final File RESOURCE_DUMMY_GOLIATH_FILE = new File(TEST_DIR, "resource-dummy-goliath.xml"); protected static final String RESOURCE_DUMMY_GOLIATH_OID = "10000000-0000-0000-0000-000000300001"; protected static final String RESOURCE_DUMMY_GOLIATH_NAME = "goliath"; protected static final String RESOURCE_DUMMY_GOLIATH_NAMESPACE = MidPointConstants.NS_RI; - + // Assigns default dummy resource and red dummy resource protected static final File ROLE_DUMMIES_FILE = new File(TEST_DIR, "role-dummies.xml"); protected static final String ROLE_DUMMIES_OID = "12345678-d34d-b33f-f00d-55555555dddd"; @@ -129,29 +129,29 @@ public class TestMultiResource extends AbstractInitializedModelIntegrationTest { protected static final String USER_WORLD_FULL_NAME = "The World"; private static final String USER_FIELD_NAME = "field"; - + private static final String USER_PASSWORD_A_CLEAR = "A"; // too short - + protected static DummyResource dummyResourceLavender; protected static DummyResourceContoller dummyResourceCtlLavender; protected ResourceType resourceDummyLavenderType; protected PrismObject resourceDummyLavender; - + protected static DummyResource dummyResourceIvory; protected static DummyResourceContoller dummyResourceCtlIvory; protected ResourceType resourceDummyIvoryType; protected PrismObject resourceDummyIvory; - + protected static DummyResource dummyResourceBeige; protected static DummyResourceContoller dummyResourceCtlBeige; protected ResourceType resourceDummyBeigeType; protected PrismObject resourceDummyBeige; - + protected static DummyResource dummyResourcePeru; protected static DummyResourceContoller dummyResourceCtlPeru; protected ResourceType resourceDummyPeruType; protected PrismObject resourceDummyPeru; - + protected static DummyResource dummyResourceDavid; protected static DummyResourceContoller dummyResourceCtlDavid; protected PrismObject resourceDummyDavid; @@ -163,28 +163,28 @@ public class TestMultiResource extends AbstractInitializedModelIntegrationTest { @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + dummyResourceCtlLavender = DummyResourceContoller.create(RESOURCE_DUMMY_LAVENDER_NAME, resourceDummyLavender); dummyResourceCtlLavender.extendSchemaPirate(); dummyResourceLavender = dummyResourceCtlLavender.getDummyResource(); resourceDummyLavender = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_LAVENDER_FILE, RESOURCE_DUMMY_LAVENDER_OID, initTask, initResult); resourceDummyLavenderType = resourceDummyLavender.asObjectable(); dummyResourceCtlLavender.setResource(resourceDummyLavender); - + dummyResourceCtlIvory = DummyResourceContoller.create(RESOURCE_DUMMY_IVORY_NAME, resourceDummyIvory); dummyResourceCtlIvory.extendSchemaPirate(); dummyResourceIvory = dummyResourceCtlIvory.getDummyResource(); resourceDummyIvory = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_IVORY_FILE, RESOURCE_DUMMY_IVORY_OID, initTask, initResult); resourceDummyIvoryType = resourceDummyIvory.asObjectable(); dummyResourceCtlIvory.setResource(resourceDummyIvory); - + dummyResourceCtlBeige = DummyResourceContoller.create(RESOURCE_DUMMY_BEIGE_NAME, resourceDummyBeige); dummyResourceCtlBeige.extendSchemaPirate(); dummyResourceBeige = dummyResourceCtlBeige.getDummyResource(); resourceDummyBeige = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_BEIGE_FILE, RESOURCE_DUMMY_BEIGE_OID, initTask, initResult); resourceDummyBeigeType = resourceDummyBeige.asObjectable(); dummyResourceCtlBeige.setResource(resourceDummyBeige); - + dummyResourceCtlPeru = DummyResourceContoller.create(RESOURCE_DUMMY_PERU_NAME, resourceDummyPeru); dummyResourceCtlPeru.extendSchemaPirate(); dummyResourcePeru = dummyResourceCtlPeru.getDummyResource(); @@ -208,7 +208,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti repoAddObjectFromFile(ROLE_DUMMIES_IVORY_FILE, initResult); repoAddObjectFromFile(ROLE_DUMMIES_BEIGE_FILE, initResult); repoAddObjectFromFile(ROLE_FIGHT_FILE, initResult); - + getDummyResource().resetBreakMode(); } @@ -218,23 +218,23 @@ public void test110JackAssignRoleDummiesFull() throws Exception { assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); jackAssignRoleDummies(TEST_NAME); } - + @Test public void test113JackRenameFull() throws Exception { final String TEST_NAME = "test113JackRenameFull"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); jackRename(TEST_NAME); } - + @Test public void test114JackUnAssignRoleDummiesFull() throws Exception { final String TEST_NAME = "test114JackUnAssignRoleDummiesFull"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); jackUnAssignRoleDummies(TEST_NAME); } - + // TODO: lavender resource with failure - + @Test public void test115JackAssignRoleDummiesFullErrorIvory() throws Exception { final String TEST_NAME = "test115JackAssignRoleDummiesFullErrorIvory"; @@ -250,7 +250,7 @@ public void test116JackUnAssignRoleDummiesFullErrorIvory() throws Exception { getDummyResource().setAddBreakMode(BreakMode.NETWORK); jackUnAssignRoleDummiesError(TEST_NAME, ROLE_DUMMIES_IVORY_OID); } - + @Test public void test117JackAssignRoleDummiesFullErrorBeige() throws Exception { final String TEST_NAME = "test117JackAssignRoleDummiesFullErrorBeige"; @@ -266,21 +266,21 @@ public void test118JackUnAssignRoleDummiesFullErrorBeige() throws Exception { getDummyResource().setAddBreakMode(BreakMode.NETWORK); jackUnAssignRoleDummiesError(TEST_NAME, ROLE_DUMMIES_BEIGE_OID); } - + @Test public void test120JackAssignRoleDummiesRelative() throws Exception { final String TEST_NAME = "test120JackAssignRoleDummiesRelative"; - + getDummyResource().resetBreakMode(); // Clean up user Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); modifyUserReplace(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, task, result); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); jackAssignRoleDummies(TEST_NAME); } - + /** * Try to delete Jack's default dummy account. As other provisioned accounts depends on it the * operation should fail. @@ -289,107 +289,107 @@ public void test120JackAssignRoleDummiesRelative() throws Exception { public void test121JackTryDeleteAccount() throws Exception { final String TEST_NAME = "test121JackTryDeleteAccount"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + getDummyResource().resetBreakMode(); // Clean up user Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); PrismObject userJack = getUser(USER_JACK_OID); String accountJackDummyOid = getLinkRefOid(userJack, RESOURCE_DUMMY_OID); - + ObjectDelta accountDelta = ObjectDelta.createDeleteDelta(ShadowType.class, accountJackDummyOid, prismContext); Collection> deltas = MiscSchemaUtil.createCollection(accountDelta); - + try { // WHEN modelService.executeChanges(deltas, null, task, result); - + AssertJUnit.fail("Unexpected success"); } catch (PolicyViolationException e) { // This is expected display("Expected exception", e); } } - + @Test public void test123JackRenameRelative() throws Exception { final String TEST_NAME = "test123JackRenameRelative"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); jackRename(TEST_NAME); } - + @Test public void test129JackUnAssignRoleDummiesRelative() throws Exception { final String TEST_NAME = "test129JackUnAssignRoleDummiesRelative"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); jackUnAssignRoleDummies(TEST_NAME); } - + /** * Ivory resource has a lax dependency. The provisioning should go OK. */ @Test public void test200JackAssignDummyIvory() throws Exception { final String TEST_NAME = "test200JackAssignDummyIvory"; - + // GIVEN Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + // Clean up user modifyUserReplace(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, task, result); - + // WHEN assignAccount(USER_JACK_OID, RESOURCE_DUMMY_IVORY_OID, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); assertLinks(userJack, 1); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME); - + assertDummyAccount(RESOURCE_DUMMY_IVORY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); // No value for ship ... no place to get it from assertDummyAccountAttribute(RESOURCE_DUMMY_IVORY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME); } - + /** * Ivory resource has a lax dependency. The provisioning should go OK. */ @Test public void test209JackUnAssignDummyIvory() throws Exception { final String TEST_NAME = "test209JackUnAssignDummyIvory"; - + // GIVEN Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + // Clean up user modifyUserReplace(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, task, result); - + // WHEN unassignAccount(USER_JACK_OID, RESOURCE_DUMMY_IVORY_OID, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); assertLinks(userJack, 0); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_IVORY_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * Beige resource has a relaxed dependency. The provisioning should go OK * even if there is no default dummy account. @@ -398,36 +398,36 @@ public void test209JackUnAssignDummyIvory() throws Exception { public void test210JackAssignDummyBeige() throws Exception { final String TEST_NAME = "test210JackAssignDummyBeige"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + // Clean up user modifyUserReplace(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, task, result); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignAccount(USER_JACK_OID, RESOURCE_DUMMY_BEIGE_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); assertLinks(userJack, 1); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_IVORY_NAME, ACCOUNT_JACK_DUMMY_USERNAME); - + assertDummyAccount(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); // No value for ship ... no place to get it from assertDummyAccountAttribute(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME); } - + /** * Beige resource has a relaxed dependency. The deprovisioning should go OK * even if there is not default dummy account. @@ -436,33 +436,33 @@ public void test210JackAssignDummyBeige() throws Exception { public void test219JackUnAssignDummyBeige() throws Exception { final String TEST_NAME = "test219JackUnAssignDummyBeige"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + // Clean up user modifyUserReplace(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, task, result); - + // WHEN TestUtil.displayWhen(TEST_NAME); unassignAccount(USER_JACK_OID, RESOURCE_DUMMY_BEIGE_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); assertLinks(userJack, 0); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_IVORY_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * Beige resource has a relaxed dependency. Try provisioning of both * beige and default dummy accounts. @@ -471,72 +471,72 @@ public void test219JackUnAssignDummyBeige() throws Exception { public void test220JackAssignDummyBeigeAndDefault() throws Exception { final String TEST_NAME = "test220JackAssignDummyBeigeAndDefault"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + // Clean up user modifyUserReplace(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, task, result); - + ObjectDelta userDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_BEIGE_OID, null, true); userDelta.addModification(createAssignmentModification(RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, null, true)); - + // WHEN TestUtil.displayWhen(TEST_NAME); executeChanges(userDelta, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); assertLinks(userJack, 2); - + assertDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyAccount(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); // No value for ship ... no place to get it from assertDummyAccountAttribute(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME); - + assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_IVORY_NAME, ACCOUNT_JACK_DUMMY_USERNAME); } - + /** - * Recompute to check that recompute will not ruin anything. + * Recompute to check that recompute will not ruin anything. */ @Test public void test221JackRecompute() throws Exception { final String TEST_NAME = "test221JackRecompute"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); assertLinks(userJack, 2); - + assertDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyAccount(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); // No value for ship ... no place to get it from assertDummyAccountAttribute(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME); - + assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_IVORY_NAME, ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * Delete account on default dummy resource (but keep it assigned and keep the shadow). * The recompute the user. The account should be re-created. @@ -546,34 +546,34 @@ public void test221JackRecompute() throws Exception { public void test223JackKillDefaultDummyAccounAndRecompute() throws Exception { final String TEST_NAME = "test223JackKillDefaultDummyAccounAndRecompute"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + getDummyResource().deleteAccountByName(ACCOUNT_JACK_DUMMY_USERNAME); display("dummy resource before", getDummyResource()); - + // WHEN TestUtil.displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("user after", userJack); assertLinks(userJack, 2); - + display("dummy resource after", getDummyResource()); - + assertDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyAccount(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); // No value for ship ... no place to get it from assertDummyAccountAttribute(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME); - + assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_IVORY_NAME, ACCOUNT_JACK_DUMMY_USERNAME); } @@ -587,37 +587,37 @@ public void test223JackKillDefaultDummyAccounAndRecompute() throws Exception { public void test224JackKillBeigeAccounAndRecompute() throws Exception { final String TEST_NAME = "test224JackKillBeigeAccounAndRecompute"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + dummyResourceBeige.deleteAccountByName(ACCOUNT_JACK_DUMMY_USERNAME); display("beige dummy resource before", dummyResourceBeige); - + // WHEN TestUtil.displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, ModelExecuteOptions.createReconcile(), task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); assertLinks(userJack, 2); - + display("beige dummy resource after", dummyResourceBeige); - + assertDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyAccount(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); // No value for ship ... no place to get it from assertDummyAccountAttribute(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME); - + assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_IVORY_NAME, ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * Delete both accounts on beige and default dummy resource (but keep it assigned and keep the shadows). * The recompute the user. The accounts should be re-created. @@ -627,41 +627,41 @@ public void test224JackKillBeigeAccounAndRecompute() throws Exception { public void test225JackKillBothAccounsAndRecompute() throws Exception { final String TEST_NAME = "test225JackKillBothAccounsAndRecompute"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + getDummyResource().deleteAccountByName(ACCOUNT_JACK_DUMMY_USERNAME); display("dummy resource before", getDummyResource()); - + dummyResourceBeige.deleteAccountByName(ACCOUNT_JACK_DUMMY_USERNAME); display("beige dummy resource before", dummyResourceBeige); - + // WHEN TestUtil.displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, ModelExecuteOptions.createReconcile(), task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); assertLinks(userJack, 2); - + display("dummy resource after", getDummyResource()); display("beige dummy resource after", dummyResourceBeige); - + assertDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyAccount(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); // No value for ship ... no place to get it from assertDummyAccountAttribute(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME); - + assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_IVORY_NAME, ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * Cause schema violation on the account during a provisioning operation. This should fail * the operation, but other operations should proceed and the account should definitelly NOT @@ -677,37 +677,37 @@ public void test227ModifyUserJackDefaultDummyBrokenSchemaViolation() throws Exce Task task = taskManager.createTaskInstance(TestMultiResource.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + getDummyResource().setModifyBreakMode(BreakMode.SCHEMA); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyUserReplace(USER_JACK_OID, UserType.F_FULL_NAME, task, result, + modifyUserReplace(USER_JACK_OID, UserType.F_FULL_NAME, task, result, new PolyString("Cpt. Jack Sparrow", null)); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); display("Result", result); TestUtil.assertPartialError(result); - + PrismObject userJack = getUser(USER_JACK_OID); assertLinks(userJack, 2); - + display("dummy resource after", getDummyResource()); display("beige dummy resource after", dummyResourceBeige); - + assertDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyAccount(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Cpt. Jack Sparrow", true); // No value for ship ... no place to get it from assertDummyAccountAttribute(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME); - + assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_IVORY_NAME, ACCOUNT_JACK_DUMMY_USERNAME); - + getDummyResource().resetBreakMode(); } - + /** * Reset break mode, make sure that everything is back to normal. * MID-2134 @@ -722,29 +722,29 @@ public void test228ModifyUserJackDefaultDummyNoError() throws Exception { OperationResult result = task.getResult(); dummyAuditService.clear(); getDummyResource().resetBreakMode(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyUserReplace(USER_JACK_OID, UserType.F_FULL_NAME, task, result, + modifyUserReplace(USER_JACK_OID, UserType.F_FULL_NAME, task, result, new PolyString(USER_JACK_FULL_NAME, null)); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); display("Result", result); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); assertLinks(userJack, 2); - + display("dummy resource after", getDummyResource()); display("beige dummy resource after", dummyResourceBeige); - + assertDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyAccount(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); // No value for ship ... no place to get it from assertDummyAccountAttribute(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME); - + assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_IVORY_NAME, ACCOUNT_JACK_DUMMY_USERNAME); } @@ -757,35 +757,35 @@ public void test228ModifyUserJackDefaultDummyNoError() throws Exception { public void test229JackUnassignDummyBeigeAndDefault() throws Exception { final String TEST_NAME = "test229JackUnassignDummyBeigeAndDefault"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); getDummyResource().resetBreakMode(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + ObjectDelta userDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_BEIGE_OID, null, false); userDelta.addModification(createAssignmentModification(RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, null, false)); - + // WHEN TestUtil.displayWhen(TEST_NAME); executeChanges(userDelta, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); assertLinks(userJack, 0); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_IVORY_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * Lavender resource has a strict dependency. The provisioning should fail. */ @@ -793,37 +793,37 @@ public void test229JackUnassignDummyBeigeAndDefault() throws Exception { public void test250JackAssignDummyLavender() throws Exception { final String TEST_NAME = "test250JackAssignDummyLavender"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + // Clean up user modifyUserReplace(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, task, result); - + try { // WHEN assignAccount(USER_JACK_OID, RESOURCE_DUMMY_LAVENDER_OID, null, task, result); - + AssertJUnit.fail("Unexpected success"); } catch (PolicyViolationException e) { // this is expected } - + // THEN result.computeStatus(); TestUtil.assertFailure(result); - + PrismObject userJack = getUser(USER_JACK_OID); assertLinks(userJack, 0); assertAssignments(userJack, 0); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); - assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); + assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_IVORY_NAME, ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * The "dummies" role assigns two dummy resources that are in a dependency. The value of DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME is propagated from one * resource through the user to the other resource. If dependency does not work then no value is propagated. @@ -834,14 +834,14 @@ public void jackAssignRoleDummies(final String TEST_NAME) throws Exception { Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); clearJackOrganizationalUnit(task, result); - + // WHEN assignRole(USER_JACK_OID, ROLE_DUMMIES_OID, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); assertAssignedRole(USER_JACK_OID, ROLE_DUMMIES_OID, task, result); assertLinks(userJack, 4); @@ -849,7 +849,7 @@ public void jackAssignRoleDummies(final String TEST_NAME) throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", "The Great Voodoo Master"); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "The Lost Souls"); - + // This is set up by "feedback" using an inbound expression. It has nothing with dependencies yet. assertUserProperty(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of The Lost Souls")); @@ -857,11 +857,11 @@ public void jackAssignRoleDummies(final String TEST_NAME) throws Exception { assertDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); // This is set by red's outbound from user's organizationalUnit. If dependencies work this outbound is processed // after user's organizationUnit is set and it will have the same value as above. - assertDummyAccountAttribute(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "The crew of The Lost Souls"); - assertDummyAccountAttribute(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow must be the best CAPTAIN the Caribbean has ever seen"); - + assertDummyAccount(RESOURCE_DUMMY_IVORY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); // This is set by red's outbound from user's organizationalUnit. If dependencies work this outbound is processed // after user's organizationUnit is set and it will have the same value as above. @@ -882,23 +882,23 @@ public void jackRename(final String TEST_NAME) throws Exception { jackRename(TEST_NAME, "jackie", "Jackie Sparrow", task, result); jackRename(TEST_NAME, USER_JACK_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, task, result); } - + public void jackRename(final String TEST_NAME, String toName, String toFullName, Task task, OperationResult result) throws Exception { - ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_JACK_OID, UserType.F_NAME, + ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_JACK_OID, UserType.F_NAME, PrismTestUtil.createPolyString(toName)); objectDelta.addModificationReplaceProperty(UserType.F_FULL_NAME, PrismTestUtil.createPolyString(toFullName)); Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); PrismAsserts.assertPropertyValue(userJack, UserType.F_NAME, PrismTestUtil.createPolyString(toName)); PrismAsserts.assertPropertyValue(userJack, UserType.F_FULL_NAME, PrismTestUtil.createPolyString(toFullName)); @@ -908,18 +908,18 @@ public void jackRename(final String TEST_NAME, String toName, String toFullName, assertDefaultDummyAccount(toName, toFullName, true); assertDefaultDummyAccountAttribute(toName, "title", "The Great Voodoo Master"); assertDefaultDummyAccountAttribute(toName, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "The Lost Souls"); - + // This is set up by "feedback" using an inbound expression. It has nothing with dependencies yet. assertUserProperty(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of The Lost Souls")); - + assertDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, toName, toFullName, true); // This is set by red's outbound from user's organizationalUnit. If dependencies work this outbound is processed // after user's organizationUnit is set and it will have the same value as above. assertDummyAccountAttribute(RESOURCE_DUMMY_LAVENDER_NAME, toName, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "The crew of The Lost Souls"); - assertDummyAccountAttribute(RESOURCE_DUMMY_LAVENDER_NAME, toName, + assertDummyAccountAttribute(RESOURCE_DUMMY_LAVENDER_NAME, toName, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, toFullName +" must be the best CAPTAIN the Caribbean has ever seen"); - + assertDummyAccount(RESOURCE_DUMMY_IVORY_NAME, toName, toFullName, true); // This is set by red's outbound from user's organizationalUnit. If dependencies work this outbound is processed // after user's organizationUnit is set and it will have the same value as above. @@ -936,41 +936,41 @@ public void jackUnAssignRoleDummies(final String TEST_NAME) throws Exception { Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignRole(USER_JACK_OID, ROLE_DUMMIES_OID, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject user = getUser(USER_JACK_OID); assertAssignedNoRole(user); assertLinks(user, 0); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_IVORY_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME); - - assertUserProperty(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of The Lost Souls")); + + assertUserProperty(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of The Lost Souls")); } - + /** * The "dummies" role assigns two dummy resources that are in a dependency. The value of DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME is propagated from one * resource through the user to the other resource. If dependency does not work then no value is propagated. */ - public void jackAssignRoleDummiesError(final String TEST_NAME, String roleOid, String dummyResourceName, + public void jackAssignRoleDummiesError(final String TEST_NAME, String roleOid, String dummyResourceName, boolean expectAccount) throws Exception { TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); clearJackOrganizationalUnit(task, result); - + // WHEN assignRole(USER_JACK_OID, roleOid, task, result); - + // THEN result.computeStatus(); display(result); @@ -980,7 +980,7 @@ public void jackAssignRoleDummiesError(final String TEST_NAME, String roleOid, S TestUtil.assertStatus(result, OperationResultStatus.PARTIAL_ERROR); // TestUtil.assertPartialError(result); } - + PrismObject userJack = getUser(USER_JACK_OID); assertAssignedRole(USER_JACK_OID, roleOid, task, result); // One of the accountRefs is actually ref to an uncreated shadow @@ -997,7 +997,7 @@ public void jackAssignRoleDummiesError(final String TEST_NAME, String roleOid, S assertNoDummyAccount(dummyResourceName, ACCOUNT_JACK_DUMMY_USERNAME); } } - + private void clearJackOrganizationalUnit(Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyUserReplace(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, task, result); } @@ -1007,11 +1007,11 @@ public void jackUnAssignRoleDummiesError(final String TEST_NAME, String roleOid) Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, roleOid, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -1022,28 +1022,28 @@ public void jackUnAssignRoleDummiesError(final String TEST_NAME, String roleOid) if (status != OperationResultStatus.SUCCESS && status != OperationResultStatus.PARTIAL_ERROR) { AssertJUnit.fail("Expected result success or partial error status, but was "+status); } - + PrismObject user = getUser(USER_JACK_OID); assertAssignedNoRole(user); assertLinks(user, 0); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_IVORY_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME); - - assertUserProperty(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of The Lost Souls")); + + assertUserProperty(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of The Lost Souls")); } - + @Test public void test300AddAndAssignRelative() throws Exception { final String TEST_NAME = "test300AddAndAssignRelative"; TestUtil.displayTestTitle(TEST_NAME); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // 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 @@ -1062,16 +1062,16 @@ public void test300AddAndAssignRelative() throws Exception { assertUserJack(userJack); assertAccount(userJack, RESOURCE_DUMMY_OID); assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignAccount(USER_JACK_OID, RESOURCE_DUMMY_BLUE_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + userJack = getUser(USER_JACK_OID); display("User after red dummy assignment", userJack); assertUserJack(userJack); @@ -1079,58 +1079,58 @@ public void test300AddAndAssignRelative() throws Exception { assertAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertLinks(userJack, 2); String accountOid = getLinkRefOid(userJack, RESOURCE_DUMMY_BLUE_OID); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertAccountShadowRepo(accountShadow, accountOid, ACCOUNT_JACK_DUMMY_USERNAME, getDummyResourceType(RESOURCE_DUMMY_BLUE_NAME)); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertAccountShadowModel(accountModel, accountOid, ACCOUNT_JACK_DUMMY_USERNAME, getDummyResourceType(RESOURCE_DUMMY_BLUE_NAME)); - + assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyAccount(RESOURCE_DUMMY_BLUE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - + } - + @Test public void test310AddedAccountAndUnassignRelative() throws Exception { final String TEST_NAME = "test310AddedAccountAndUnassignRelative"; TestUtil.displayTestTitle(TEST_NAME); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); unassignAccount(USER_JACK_OID, RESOURCE_DUMMY_BLUE_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after red dummy unassignment", userJack); assertUserJack(userJack); assertAccount(userJack, RESOURCE_DUMMY_OID); assertLinks(userJack, 1); String accountOid = getLinkRefOid(userJack, RESOURCE_DUMMY_OID); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountOid, ACCOUNT_JACK_DUMMY_USERNAME); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME); - + assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertNoDummyAccount(RESOURCE_DUMMY_BLUE_NAME, ACCOUNT_JACK_DUMMY_USERNAME); - + } - + /** * This is mostly a cleanup. But it also tests some cases. */ @@ -1139,19 +1139,19 @@ public void test319UnassignDummyRelative() throws Exception { final String TEST_NAME = "test319UnassignDummyRelative"; TestUtil.displayTestTitle(TEST_NAME); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); unassignAccount(USER_JACK_OID, RESOURCE_DUMMY_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after red dummy unassignment", userJack); assertUserJack(userJack); @@ -1163,9 +1163,9 @@ public void test319UnassignDummyRelative() throws Exception { assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_OID, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_IVORY_OID, ACCOUNT_JACK_DUMMY_USERNAME); - + } - + /** * Attempt to add lavender account should fail. There is unsatisfied strict dependency on * default dummy resource. @@ -1175,104 +1175,104 @@ public void test350AddAccountLavender() throws Exception { final String TEST_NAME = "test350AddAccountLavender"; TestUtil.displayTestTitle(TEST_NAME); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta userDelta = createModifyUserAddAccount(USER_JACK_OID, resourceDummyLavender); - + // WHEN try { TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + AssertJUnit.fail("Unexpected success"); } catch (PolicyViolationException e) { // this is expected display("Expected exception", e); } - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertFailure(result); - + assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); - + } - + @Test public void test352AddAccountIvory() throws Exception { final String TEST_NAME = "test352AddAccountIvory"; TestUtil.displayTestTitle(TEST_NAME); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta userDelta = createModifyUserAddAccount(USER_JACK_OID, resourceDummyIvory); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertDummyAccount(RESOURCE_DUMMY_IVORY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - + } - + @Test public void test354AddAccountBeige() throws Exception { final String TEST_NAME = "test354AddAccountBeige"; TestUtil.displayTestTitle(TEST_NAME); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta userDelta = createModifyUserAddAccount(USER_JACK_OID, resourceDummyBeige); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertDummyAccount(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - + } - + @Test public void test360AddAccountDummy() throws Exception { final String TEST_NAME = "test360AddAccountDummy"; TestUtil.displayTestTitle(TEST_NAME); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta userDelta = createModifyUserAddAccount(USER_JACK_OID, getDummyResourceObject()); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - + } - + /** * This should work now as the dependency is satisfied. */ @@ -1281,25 +1281,25 @@ public void test362AddAccountLavender() throws Exception { final String TEST_NAME = "test362AddAccountLavender"; TestUtil.displayTestTitle(TEST_NAME); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta userDelta = createModifyUserAddAccount(USER_JACK_OID, resourceDummyLavender); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - + } - + /** * The account cannot be deleted because there is strict dependency on it (from lavender resource). */ @@ -1308,35 +1308,35 @@ public void test370DeleteAccountDummy() throws Exception { final String TEST_NAME = "test370DeleteAccountDummy"; TestUtil.displayTestTitle(TEST_NAME); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta userDelta = createModifyUserDeleteAccount(USER_JACK_OID, getDummyResourceObject()); - + // WHEN try { TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + AssertJUnit.fail("Unexpected success"); } catch (PolicyViolationException e) { // this is expected display("Expected exception", e); } - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertFailure(result); - + PrismObject user = getUser(USER_JACK_OID); assertAccount(user, RESOURCE_DUMMY_OID); - + assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - + } - + /** * The account cannot be unlinked because there is strict dependency on it (from lavender resource). */ @@ -1345,23 +1345,23 @@ public void test372UnlinkAccountDummy() throws Exception { final String TEST_NAME = "test372UnlinkAccountDummy"; TestUtil.displayTestTitle(TEST_NAME); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta userDelta = createModifyUserUnlinkAccount(USER_JACK_OID, getDummyResourceObject()); - + // WHEN try { TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + AssertJUnit.fail("Unexpected success"); } catch (PolicyViolationException e) { // this is expected display("Expected exception", e); } - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -1371,36 +1371,36 @@ public void test372UnlinkAccountDummy() throws Exception { assertAccount(user, RESOURCE_DUMMY_OID); assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - + } - + @Test public void test374DeleteAccountLavender() throws Exception { final String TEST_NAME = "test374DeleteAccountLavender"; TestUtil.displayTestTitle(TEST_NAME); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta userDelta = createModifyUserDeleteAccount(USER_JACK_OID, resourceDummyLavender); - + TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject user = getUser(USER_JACK_OID); assertAccount(user, RESOURCE_DUMMY_OID); - + assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - + } - + /** * This should go well now as the dependency is gone. */ @@ -1409,24 +1409,24 @@ public void test376DeleteAccountDummy() throws Exception { final String TEST_NAME = "test376DeleteAccountDummy"; TestUtil.displayTestTitle(TEST_NAME); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta userDelta = createModifyUserDeleteAccount(USER_JACK_OID, getDummyResourceObject()); - + TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME); } - + /** * Beige resource has relaxed dependency on default dummy. Even though the default dummy is no * longer there the delete should go smoothly. @@ -1436,25 +1436,25 @@ public void test378DeleteAccountBeige() throws Exception { final String TEST_NAME = "test378DeleteAccountBeige"; TestUtil.displayTestTitle(TEST_NAME); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta userDelta = createModifyUserDeleteAccount(USER_JACK_OID, resourceDummyBeige); - + TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME); } - + /** * Ivory resource has lax dependency on default dummy. Even though the default dummy is no * longer there the delete should go smoothly. @@ -1464,26 +1464,26 @@ public void test379DeleteAccountIvory() throws Exception { final String TEST_NAME = "test379DeleteAccountIvory"; TestUtil.displayTestTitle(TEST_NAME); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta userDelta = createModifyUserDeleteAccount(USER_JACK_OID, resourceDummyIvory); - + TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_IVORY_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME); } - + /** * Resource peru depends on resource yellow, but the dependency is relaxed. * The account should be created even if we do not have yellow account yet. @@ -1494,24 +1494,24 @@ public void test380AddAccountPeru() throws Exception { TestUtil.displayTestTitle(TEST_NAME); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); getDummyResource().resetBreakMode(); - + // precondition assertEncryptedUserPassword(USER_JACK_OID, USER_JACK_PASSWORD); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta userDelta = createModifyUserAddAccount(USER_JACK_OID, resourceDummyPeru); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertDummyAccount(RESOURCE_DUMMY_PERU_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyPassword(RESOURCE_DUMMY_PERU_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_PASSWORD); } @@ -1521,33 +1521,33 @@ public void test382AddAccountYellow() throws Exception { final String TEST_NAME = "test382AddAccountYellow"; TestUtil.displayTestTitle(TEST_NAME); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta userDelta = createModifyUserAddAccount(USER_JACK_OID, getDummyResourceObject(RESOURCE_DUMMY_YELLOW_NAME)); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); assertLinks(userJack, 2); - + assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyPassword(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_PASSWORD); - + assertDummyAccount(RESOURCE_DUMMY_PERU_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyPassword(RESOURCE_DUMMY_PERU_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_PASSWORD); } - + /** * Yellow resource has minimum password length constraint. Change password to something shorter. * There is dependency yellow<-peru. Make sure that the peru is not affected (the dependency is relaxed) @@ -1562,14 +1562,14 @@ public void test385ModifyUserJackPasswordA() throws Exception { Task task = taskManager.createTaskInstance(AbstractPasswordTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + // WHEN modifyUserChangePassword(USER_JACK_OID, USER_PASSWORD_A_CLEAR, task, result); - + // THEN result.computeStatus(); TestUtil.assertPartialError(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); @@ -1578,71 +1578,71 @@ public void test385ModifyUserJackPasswordA() throws Exception { // Check account in dummy resource (yellow): password is too short for this, original password should remain there assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyPassword(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_PASSWORD); - + // Check account in dummy resource (peru) assertDummyAccount(RESOURCE_DUMMY_PERU_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyPassword(RESOURCE_DUMMY_PERU_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_A_CLEAR); - + assertEncryptedUserPassword(userJack, USER_PASSWORD_A_CLEAR); } - + @Test public void test389DeleteAccountPeru() throws Exception { final String TEST_NAME = "test389DeleteAccountPeru"; TestUtil.displayTestTitle(TEST_NAME); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta userDelta = createModifyUserDeleteAccount(USER_JACK_OID, resourceDummyPeru); - + TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertNoDummyAccount(RESOURCE_DUMMY_PERU_NAME, ACCOUNT_JACK_DUMMY_USERNAME); - + // just to be sure assertNoDummyAccount(RESOURCE_DUMMY_LAVENDER_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_BEIGE_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_IVORY_NAME, ACCOUNT_JACK_DUMMY_USERNAME); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME); } - + @Test public void test400DavidAndGoliathAssignRole() throws Exception { final String TEST_NAME = "test400DavidAndGoliathAssignRole"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = createUser(USER_WORLD_NAME, USER_WORLD_FULL_NAME, true); userBefore.asObjectable().getOrganizationalUnit().add(PrismTestUtil.createPolyStringType("stone")); addObject(userBefore); - + dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(userBefore.getOid(), ROLE_FIGHT_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); assertDavidGoliath(userBefore.getOid(), "stone", USER_WORLD_NAME, true, true, true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(4); @@ -1658,18 +1658,18 @@ public void test400DavidAndGoliathAssignRole() throws Exception { dummyAuditService.assertHasDelta(2,ChangeType.MODIFY, UserType.class); dummyAuditService.assertHasDelta(2,ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); - + // Have a closer look at the last shadow modify delta. Make sure there are no phantom changes. ObjectDeltaOperation executionDeltaOp = dummyAuditService.getExecutionDelta(2, ChangeType.MODIFY, ShadowType.class); ObjectDelta executionDelta = executionDeltaOp.getObjectDelta(); display("Last execution delta", executionDelta); PrismAsserts.assertModifications("Phantom changes in last delta:", executionDelta, 2); } - + private void assertDavidGoliath(String userOid, String ou, String name, boolean userEnabled, boolean davidEnabled, boolean goliathEnabled) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, SchemaViolationException, ConflictException, ExpressionEvaluationException { PrismObject userAfter = getUser(userOid); display("User after", userAfter); - + assertUser(userAfter, userOid, name, USER_WORLD_FULL_NAME, null, null); assertAccount(userAfter, RESOURCE_DUMMY_GOLIATH_OID); assertAccount(userAfter, RESOURCE_DUMMY_DAVID_OID); @@ -1679,47 +1679,47 @@ private void assertDavidGoliath(String userOid, String ou, String name, boolean } else { assertAdministrativeStatusDisabled(userAfter); } - + assertDummyAccount(RESOURCE_DUMMY_DAVID_NAME, name, USER_WORLD_FULL_NAME, davidEnabled); - + assertDummyAccountAttribute(RESOURCE_DUMMY_DAVID_NAME, name, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, ou+ " ("+name+") take"); - + assertDummyAccountAttribute(RESOURCE_DUMMY_DAVID_NAME, name, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "the king"); - + assertUserProperty(userAfter, UserType.F_LOCALITY, PrismTestUtil.createPolyString(ou+" ("+name+") take throw")); - + assertDummyAccount(RESOURCE_DUMMY_GOLIATH_NAME, name, USER_WORLD_FULL_NAME, goliathEnabled); - + assertDummyAccountAttribute(RESOURCE_DUMMY_GOLIATH_NAME, name, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, ou+" ("+name+") take throw ("+name+") hit"); - + assertUserProperty(userAfter, UserType.F_TITLE, PrismTestUtil.createPolyString(ou+" ("+name+") take throw ("+name+") hit fall")); - + assertDummyAccountAttribute(RESOURCE_DUMMY_DAVID_NAME, name, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, ou+" ("+name+") take throw ("+name+") hit fall ("+name+") win"); - + } @Test public void test401DavidAndGoliathModifyOu() throws Exception { final String TEST_NAME = "test401DavidAndGoliathModifyOu"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = findUserByUsername(USER_WORLD_NAME); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserReplace(userBefore.getOid(), UserType.F_ORGANIZATIONAL_UNIT, task, result, PrismTestUtil.createPolyString("rock")); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -1742,40 +1742,40 @@ public void test401DavidAndGoliathModifyOu() throws Exception { dummyAuditService.assertHasDelta(2,ChangeType.MODIFY, UserType.class); dummyAuditService.assertHasDelta(2,ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); - + // Have a closer look at the last shadow modify delta. Make sure there are no phantom changes. ObjectDeltaOperation executionDeltaOp = dummyAuditService.getExecutionDelta(2, ChangeType.MODIFY, ShadowType.class); ObjectDelta executionDelta = executionDeltaOp.getObjectDelta(); display("Last execution delta", executionDelta); PrismAsserts.assertModifications("Phantom changes in last delta:", executionDelta, 2); } - + @Test public void test403DavidAndGoliathDisableUser() throws Exception { final String TEST_NAME = "test403DavidAndGoliathDisableUser"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = findUserByUsername(USER_WORLD_NAME); assertAdministrativeStatusEnabled(userBefore); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserReplace(userBefore.getOid(), ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.DISABLED); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertDavidGoliath(userBefore.getOid(), "rock", USER_WORLD_NAME, false, false, false); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(3); // last one is duplicate @@ -1788,32 +1788,32 @@ public void test403DavidAndGoliathDisableUser() throws Exception { dummyAuditService.assertHasDelta(1,ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test404DavidAndGoliathEnableUser() throws Exception { final String TEST_NAME = "test404DavidAndGoliathEnableUser"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = findUserByUsername(USER_WORLD_NAME); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserReplace(userBefore.getOid(), ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.ENABLED); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertDavidGoliath(userBefore.getOid(), "rock", USER_WORLD_NAME, true, true, true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(3); // last one is duplicate @@ -1826,7 +1826,7 @@ public void test404DavidAndGoliathEnableUser() throws Exception { dummyAuditService.assertHasDelta(1,ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test405DavidAndGoliathDisableAccountDavid() throws Exception { final String TEST_NAME = "test405DavidAndGoliathDisableAccountDavid"; @@ -1834,26 +1834,26 @@ public void test405DavidAndGoliathDisableAccountDavid() throws Exception { // GIVEN assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = findUserByUsername(USER_WORLD_NAME); assertAdministrativeStatusEnabled(userBefore); String accountDavidOid = getLinkRefOid(userBefore, RESOURCE_DUMMY_DAVID_OID); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyAccountShadowReplace(accountDavidOid, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.DISABLED); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertDavidGoliath(userBefore.getOid(), "rock", USER_WORLD_NAME, true, false, true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -1863,7 +1863,7 @@ public void test405DavidAndGoliathDisableAccountDavid() throws Exception { dummyAuditService.assertHasDelta(0,ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + /** * Try to recompute to make sure it does not destroy anything. The recompute should do nothing. */ @@ -1871,60 +1871,60 @@ public void test405DavidAndGoliathDisableAccountDavid() throws Exception { public void test406DavidAndGoliathRecompute() throws Exception { final String TEST_NAME = "test406DavidAndGoliathRecompute"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = findUserByUsername(USER_WORLD_NAME); assertAdministrativeStatusEnabled(userBefore); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); recomputeUser(userBefore.getOid(), task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertDavidGoliath(userBefore.getOid(), "rock", USER_WORLD_NAME, true, false, true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertNoRecord(); } - + @Test public void test408DavidAndGoliathEnableAccountDavid() throws Exception { final String TEST_NAME = "test408DavidAndGoliathEnableAccountDavid"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = findUserByUsername(USER_WORLD_NAME); assertAdministrativeStatusEnabled(userBefore); String accountDavidOid = getLinkRefOid(userBefore, RESOURCE_DUMMY_DAVID_OID); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyAccountShadowReplace(accountDavidOid, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.ENABLED); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertDavidGoliath(userBefore.getOid(), "rock", USER_WORLD_NAME, true, true, true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -1934,32 +1934,32 @@ public void test408DavidAndGoliathEnableAccountDavid() throws Exception { dummyAuditService.assertHasDelta(0,ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test410DavidAndGoliathRename() throws Exception { final String TEST_NAME = "test410DavidAndGoliathRename"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = findUserByUsername(USER_WORLD_NAME); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserReplace(userBefore.getOid(), UserType.F_NAME, task, result, PrismTestUtil.createPolyString(USER_FIELD_NAME)); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertDavidGoliath(userBefore.getOid(), "rock", USER_FIELD_NAME, true, true, true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(4); @@ -1975,45 +1975,45 @@ public void test410DavidAndGoliathRename() throws Exception { dummyAuditService.assertHasDelta(2,ChangeType.MODIFY, UserType.class); dummyAuditService.assertHasDelta(2,ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); - + // Have a closer look at the last shadow modify delta. Make sure there are no phantom changes. ObjectDeltaOperation executionDeltaOp = dummyAuditService.getExecutionDelta(2, ChangeType.MODIFY, ShadowType.class); ObjectDelta executionDelta = executionDeltaOp.getObjectDelta(); display("Last execution delta", executionDelta); PrismAsserts.assertModifications("Phantom changes in last delta:", executionDelta, 2); } - + @Test public void test419DavidAndGoliathUnassignRole() throws Exception { final String TEST_NAME = "test419DavidAndGoliathUnassignRole"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = findUserByUsername(USER_FIELD_NAME); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); unassignRole(userBefore.getOid(), ROLE_FIGHT_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result, 2); - + PrismObject userAfter = getUser(userBefore.getOid()); display("User after fight", userAfter); assertUser(userAfter, userBefore.getOid(), USER_FIELD_NAME, USER_WORLD_FULL_NAME, null, null); assertLinks(userAfter, 0); - + assertNoDummyAccount(RESOURCE_DUMMY_DAVID_NAME, USER_FIELD_NAME); assertNoDummyAccount(RESOURCE_DUMMY_GOLIATH_NAME, USER_FIELD_NAME); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(4); @@ -2026,20 +2026,20 @@ public void test419DavidAndGoliathUnassignRole() throws Exception { dummyAuditService.assertExecutionDeltas(2,2); dummyAuditService.assertHasDelta(1,ChangeType.MODIFY, UserType.class); dummyAuditService.assertHasDelta(1,ChangeType.DELETE, ShadowType.class); - dummyAuditService.assertExecutionSuccess(); + dummyAuditService.assertExecutionSuccess(); } - + @Test public void test420DavidAndGoliathAssignRoleGoliathDown() throws Exception { final String TEST_NAME = "test420DavidAndGoliathAssignRoleGoliathDown"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = findUserByUsername(USER_FIELD_NAME); ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, userBefore.getOid(), UserType.F_LOCALITY, prismContext); @@ -2047,40 +2047,40 @@ public void test420DavidAndGoliathAssignRoleGoliathDown() throws Exception { modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); result.computeStatus(); TestUtil.assertSuccess(result); - + userBefore = findUserByUsername(USER_FIELD_NAME); display("User before", userBefore); - + dummyResourceGoliath.setBreakMode(BreakMode.NETWORK); - + dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(userBefore.getOid(), ROLE_FIGHT_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); // Inner errors are expected TestUtil.assertPartialError(result); - + PrismObject userAfter = getUser(userBefore.getOid()); display("User after fight", userAfter); assertUser(userAfter, userBefore.getOid(), USER_FIELD_NAME, USER_WORLD_FULL_NAME, null, null); assertAccount(userAfter, RESOURCE_DUMMY_DAVID_OID); assertAccount(userAfter, RESOURCE_DUMMY_GOLIATH_OID); // This is unfinished shadow assertLinks(userAfter, 2); - + assertDummyAccount(RESOURCE_DUMMY_DAVID_NAME, USER_FIELD_NAME, USER_WORLD_FULL_NAME, true); - + assertDummyAccountAttribute(RESOURCE_DUMMY_DAVID_NAME, USER_FIELD_NAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, "rock (field) take"); - + assertUserProperty(userAfter, UserType.F_LOCALITY, PrismTestUtil.createPolyString("rock (field) take throw")); - + // Goliath is down. No account. - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(4); @@ -2093,33 +2093,33 @@ public void test420DavidAndGoliathAssignRoleGoliathDown() throws Exception { dummyAuditService.assertHasDelta(1,ChangeType.MODIFY, UserType.class); dummyAuditService.assertHasDelta(1,ChangeType.ADD, ShadowType.class); dummyAuditService.assertExecutionDeltas(2,1); - dummyAuditService.assertHasDelta(2,ChangeType.MODIFY, UserType.class); + dummyAuditService.assertHasDelta(2,ChangeType.MODIFY, UserType.class); } - + // MID-1566 @Test(enabled=false) public void test422DavidAndGoliathAssignRoleGoliathUpRecompute() throws Exception { final String TEST_NAME = "test422DavidAndGoliathAssignRoleGoliathUpRecompute"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = findUserByUsername(USER_FIELD_NAME); - + dummyResourceGoliath.setBreakMode(BreakMode.NONE); - + // WHEN recomputeUser(userBefore.getOid(), task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertDavidGoliath(userBefore.getOid(), "rock", USER_FIELD_NAME, true, true, true); // Check audit @@ -2137,42 +2137,42 @@ public void test422DavidAndGoliathAssignRoleGoliathUpRecompute() throws Exceptio dummyAuditService.assertHasDelta(2,ChangeType.MODIFY, UserType.class); dummyAuditService.assertHasDelta(2,ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); - + } - + @Test public void test429DavidAndGoliathUnassignRole() throws Exception { final String TEST_NAME = "test429DavidAndGoliathUnassignRole"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = findUserByUsername(USER_FIELD_NAME); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); unassignRole(userBefore.getOid(), ROLE_FIGHT_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); // TestUtil.assertSuccess(result, 2); - + dummyResourceGoliath.setBreakMode(BreakMode.NONE); - + PrismObject userAfter = getUser(userBefore.getOid()); display("User after fight", userAfter); assertUser(userAfter, userBefore.getOid(), USER_FIELD_NAME, USER_WORLD_FULL_NAME, null, null); assertLinks(userAfter, 0); - + assertNoDummyAccount(RESOURCE_DUMMY_DAVID_NAME, USER_FIELD_NAME); assertNoDummyAccount(RESOURCE_DUMMY_GOLIATH_NAME, USER_FIELD_NAME); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(4); @@ -2187,18 +2187,18 @@ public void test429DavidAndGoliathUnassignRole() throws Exception { dummyAuditService.assertHasDelta(1,ChangeType.DELETE, ShadowType.class); dummyAuditService.assertExecutionOutcome(OperationResultStatus.PARTIAL_ERROR); } - + @Test public void test430DavidAndGoliathAssignRoleDavidDown() throws Exception { final String TEST_NAME = "test430DavidAndGoliathAssignRoleDavidDown"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = findUserByUsername(USER_FIELD_NAME); ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, userBefore.getOid(), UserType.F_LOCALITY, prismContext); @@ -2206,38 +2206,38 @@ public void test430DavidAndGoliathAssignRoleDavidDown() throws Exception { modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); result.computeStatus(); TestUtil.assertSuccess(result); - + userBefore = findUserByUsername(USER_FIELD_NAME); display("User before", userBefore); - + dummyResourceGoliath.setBreakMode(BreakMode.NONE); dummyResourceDavid.setBreakMode(BreakMode.NETWORK); - + dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(userBefore.getOid(), ROLE_FIGHT_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); // Inner errors are expected TestUtil.assertPartialError(result); - + PrismObject userAfter = getUser(userBefore.getOid()); display("User after fight", userAfter); assertUser(userAfter, userBefore.getOid(), USER_FIELD_NAME, USER_WORLD_FULL_NAME, null, null); assertAccount(userAfter, RESOURCE_DUMMY_DAVID_OID); // This is unfinished shadow // No goliath account, not even tried, the dependency stopped it assertLinks(userAfter, 1); - + // David is down. No account. - + // Goliath depends on David, no account. - + assertNoDummyAccount(RESOURCE_DUMMY_GOLIATH_NAME, USER_FIELD_NAME); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(3); @@ -2250,72 +2250,72 @@ public void test430DavidAndGoliathAssignRoleDavidDown() throws Exception { dummyAuditService.assertHasDelta(1,ChangeType.MODIFY, UserType.class); // dummyAuditService.assertExecutionDeltas(2,1); // dummyAuditService.asserHasDelta(2,ChangeType.MODIFY, UserType.class); - + } - + @Test public void test440DavidAndGoliathAssignRoleAndCreateUserInOneStep() throws Exception { final String TEST_NAME = "test440DavidAndGoliathAssignRoleAndCreateUserInOneStep"; TestUtil.displayTestTitle(TEST_NAME); - + dummyResourceGoliath.setBreakMode(BreakMode.NONE); dummyResourceDavid.setBreakMode(BreakMode.NONE); try{ Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); // delete user and his roles which were added before - + PrismObject userWorld = findUserByUsername(USER_FIELD_NAME); - + AssertJUnit.assertNotNull("User must not be null.", userWorld); - + ObjectDelta delta = ObjectDelta.createDeleteDelta(UserType.class, userWorld.getOid(), prismContext); Collection> deltas = new ArrayList>(); deltas.add(delta); modelService.executeChanges(deltas, null, task, result); - + OperationResult deleteResult = new OperationResult("Check if user was deleted properly."); try { repositoryService.getObject(UserType.class, userWorld.getOid(), null, deleteResult); } catch (ObjectNotFoundException ex){ //this is OK, we deleted user before } - + // GIVEN assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - - - + + + PrismObject userBefore = createUser(USER_WORLD_NAME, USER_WORLD_FULL_NAME, true); userBefore.asObjectable().getOrganizationalUnit().add(PrismTestUtil.createPolyStringType("stone")); - + PrismContainerValue cval = new PrismContainerValue(prismContext); PrismReference targetRef = cval.findOrCreateReference(AssignmentType.F_TARGET_REF); targetRef.getValue().setOid(ROLE_FIGHT_OID); targetRef.getValue().setTargetType(RoleType.COMPLEX_TYPE); userBefore.findOrCreateContainer(UserType.F_ASSIGNMENT).add((PrismContainerValue) cval); - - - + + + // userBefore.asObjectable().getAssignmentNew().add(cval.asContainerable()); - + // this should add user and at the sate time assign the role fight..-> // the result of the operation have to be the same as in test 400 addObject(userBefore); - + dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); // assignRole(userBefore.getOid(), ROLE_FIGHT_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertDavidGoliath(userBefore.getOid(), "stone", USER_WORLD_NAME, true, true, true); - + // Check audit display("Audit", dummyAuditService); // dummyAuditService.assertRecords(4); @@ -2331,7 +2331,7 @@ public void test440DavidAndGoliathAssignRoleAndCreateUserInOneStep() throws Exce // dummyAuditService.asserHasDelta(2,ChangeType.MODIFY, UserType.class); // dummyAuditService.asserHasDelta(2,ChangeType.MODIFY, ShadowType.class); // dummyAuditService.assertExecutionSuccess(); -// +// // // Have a closer look at the last shadow modify delta. Make sure there are no phantom changes. // ObjectDeltaOperation executionDeltaOp = dummyAuditService.getExecutionDelta(2, ChangeType.MODIFY, ShadowType.class); // ObjectDelta executionDelta = executionDeltaOp.getObjectDelta(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestNotifications.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestNotifications.java index 5c6ed31800d..bd2a24beb44 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestNotifications.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestNotifications.java @@ -57,7 +57,7 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestNotifications extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/notifications"); public static final File SYSTEM_CONFIGURATION_FILE = new File(TEST_DIR, "system-configuration.xml"); @@ -318,20 +318,20 @@ public void test131ModifyUserJackAssignAccount() throws Exception { assertEquals("Wrong message body", expected, dummyTransport.getMessages("dummy:simpleUserNotifier").get(0).getBody()); } - + private void assertDummyScriptsAdd(PrismObject user, PrismObject account, ResourceType resource) { ProvisioningScriptSpec script = new ProvisioningScriptSpec("\nto spiral :size\n" + " if :size > 30 [stop]\n fd :size rt 15\n spiral :size *1.02\nend\n "); - + String userName = null; if (user != null) { userName = user.asObjectable().getName().getOrig(); } script.addArgSingle("usr", "user: "+userName); - + // Note: We cannot test for account name as name is only assigned in provisioning String accountEnabled = null; - if (account != null && account.asObjectable().getActivation() != null + if (account != null && account.asObjectable().getActivation() != null && account.asObjectable().getActivation().getAdministrativeStatus() != null) { accountEnabled = account.asObjectable().getActivation().getAdministrativeStatus().toString(); } @@ -351,7 +351,7 @@ private void assertDummyScriptsAdd(PrismObject user, PrismObject user) { assertDummyScriptsModify(user, false); } - + private void assertDummyScriptsModify(PrismObject user, boolean recon) { ProvisioningScriptSpec modScript = new ProvisioningScriptSpec("Beware the Jabberwock, my son!"); String name = null; @@ -381,7 +381,7 @@ private void assertDummyScriptsDelete() { ProvisioningScriptSpec script = new ProvisioningScriptSpec("The Jabberwock, with eyes of flame"); IntegrationTestTools.assertScripts(getDummyResource().getScriptHistory(), script); } - + private void preTestCleanup(AssignmentPolicyEnforcementType enforcementPolicy) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { assumeAssignmentPolicy(enforcementPolicy); dummyAuditService.clear(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestPersona.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestPersona.java index eabc3cebfc1..bbd06b350ec 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestPersona.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestPersona.java @@ -106,13 +106,13 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestPersona extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/persona"); private static final String USER_JACK_GIVEN_NAME_NEW = "Jackie"; String userJackAdminPersonaOid; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { @@ -121,10 +121,10 @@ public void initSystem(Task initTask, OperationResult initResult) // InternalMonitor.setTraceShadowFetchOperation(true); // InternalMonitor.setTraceResourceSchemaOperations(true); InternalMonitor.setTrace(InternalOperationClasses.PRISM_OBJECT_CLONES, true); - + addObject(OBJECT_TEMPLATE_PERSONA_ADMIN_FILE); addObject(ROLE_PERSONA_ADMIN_FILE); - + // Persona full name is computed by using this ordinary user template setDefaultObjectTemplate(UserType.COMPLEX_TYPE, USER_TEMPLATE_OID, initResult); } @@ -137,20 +137,20 @@ public void test100AssignRolePersonaAdminToJack() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_PERSONA_ADMIN_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", userAfter); assertUserJack(userAfter); assertUserPassword(userAfter, USER_JACK_PASSWORD); - + assertLinks(userAfter, 0); assertPersonaLinks(userAfter, 1); PrismObject persona = assertLinkedPersona(userAfter, UserType.class, "admin"); @@ -163,7 +163,7 @@ public void test100AssignRolePersonaAdminToJack() throws Exception { assertSteadyResources(); } - + @Test public void test102RecomputeUserJack() throws Exception { final String TEST_NAME = "test102RecomputeUserJack"; @@ -172,15 +172,15 @@ public void test102RecomputeUserJack() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + assertUserJack11x(); } @@ -192,15 +192,15 @@ public void test103ReconcileUserJack() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + assertUserJack11x(); } @@ -212,18 +212,18 @@ public void test104RecomputeJackAdminPersona() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); recomputeUser(userJackAdminPersonaOid, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + assertUserJack11x(); } - + @Test public void test105ReconcileJackAdminPersona() throws Exception { final String TEST_NAME = "test105ReconcileJackAdminPersona"; @@ -232,15 +232,15 @@ public void test105ReconcileJackAdminPersona() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); reconcileUser(userJackAdminPersonaOid, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + assertUserJack11x(); } @@ -249,7 +249,7 @@ private void assertUserJack11x() throws Exception { display("User after", userAfter); assertUserJack(userAfter); assertUserPassword(userAfter, USER_JACK_PASSWORD); - + assertLinks(userAfter, 0); assertPersonaLinks(userAfter, 1); PrismObject persona = assertLinkedPersona(userAfter, UserType.class, "admin"); @@ -260,7 +260,7 @@ private void assertUserJack11x() throws Exception { assertSteadyResources(); } - + @Test public void test120ModifyJackGivenName() throws Exception { final String TEST_NAME = "test120ModifyJackGivenName"; @@ -269,20 +269,20 @@ public void test120ModifyJackGivenName() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, UserType.F_GIVEN_NAME, task, result, createPolyString(USER_JACK_GIVEN_NAME_NEW)); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", userAfter); assertUser(userAfter, USER_JACK_OID, USER_JACK_USERNAME, USER_JACK_FULL_NAME, USER_JACK_GIVEN_NAME_NEW, USER_JACK_FAMILY_NAME); assertUserPassword(userAfter, USER_JACK_PASSWORD); - + assertLinks(userAfter, 0); assertPersonaLinks(userAfter, 1); PrismObject persona = assertLinkedPersona(userAfter, UserType.class, "admin"); @@ -294,15 +294,15 @@ public void test120ModifyJackGivenName() throws Exception { assertSteadyResources(); } - + // TODO: recompute, reconcile (both user and persona) - + // TODO: change password - + // TODO: assign some accouts/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"; @@ -311,28 +311,28 @@ public void test199UnassignRolePersonaAdminFromJack() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_PERSONA_ADMIN_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", userAfter); assertUser(userAfter, USER_JACK_OID, USER_JACK_USERNAME, USER_JACK_FULL_NAME, USER_JACK_GIVEN_NAME_NEW, USER_JACK_FAMILY_NAME); assertUserPassword(userAfter, USER_JACK_PASSWORD); - + assertLinks(userAfter, 0); assertPersonaLinks(userAfter, 0); - + assertNoObject(UserType.class, userJackAdminPersonaOid); assertSteadyResources(); } - + private String toAdminPersonaUsername(String username) { return "a-"+username; } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestPreviewChanges.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestPreviewChanges.java index efd94a1898c..14c865c5fde 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestPreviewChanges.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestPreviewChanges.java @@ -95,7 +95,7 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestPreviewChanges extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/preview"); // LEMON dummy resource has a STRICT dependency on default dummy resource @@ -108,16 +108,16 @@ public class TestPreviewChanges extends AbstractInitializedModelIntegrationTest private static final String USER_BLACKBEARD_OID = "c0c010c0-d34d-b33f-f00d-161161116666"; static final File USER_ROGERS_FILE = new File(TEST_DIR, "user-rogers.xml"); - + private static String accountOid; @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - initDummyResourcePirate(RESOURCE_DUMMY_LEMON_NAME, + initDummyResourcePirate(RESOURCE_DUMMY_LEMON_NAME, RESOURCE_DUMMY_LEMON_FILE, RESOURCE_DUMMY_LEMON_OID, initTask, initResult); - + // Elaine is in inconsistent state. Account attributes do not match the mappings. // We do not want that here, as it would add noise to preview operations. reconcileUser(USER_ELAINE_OID, initTask, initResult); @@ -126,9 +126,9 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test100ModifyUserAddAccountBundle() throws Exception { final String TEST_NAME = "test100ModifyUserAddAccountBundle"; - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + ObjectSource> accountSource = new ObjectSource>() { @Override public PrismObject get() { @@ -141,14 +141,14 @@ public PrismObject get() { } } }; - + ObjectChecker> checker = new ObjectChecker>() { @Override public void check(ModelContext modelContext) { - assertAddAccount(modelContext, false); + assertAddAccount(modelContext, false); } }; - + modifyUserAddAccountImplicit(TEST_NAME, accountSource, checker); modifyUserAddAccountExplicit(TEST_NAME, accountSource, checker); modifyUserAddAccountImplicitExplicitSame(TEST_NAME, accountSource, checker); @@ -158,13 +158,13 @@ public void check(ModelContext modelContext) { modifyUserAddAccountImplicitExplicitNotEqual(TEST_NAME, accountSource, checker); modifyUserAddAccountImplicitExplicitNotEqualReverse(TEST_NAME, accountSource, checker); } - + @Test public void test101ModifyUserAddAccountNoAttributesBundle() throws Exception { final String TEST_NAME = "test101ModifyUserAddAccountNoAttributesBundle"; - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + ObjectSource> accountSource = new ObjectSource>() { @Override public PrismObject get() { @@ -177,14 +177,14 @@ public PrismObject get() { } } }; - + ObjectChecker> checker = new ObjectChecker>() { @Override public void check(ModelContext modelContext) { - assertAddAccount(modelContext, true); + assertAddAccount(modelContext, true); } }; - + modifyUserAddAccountImplicit(TEST_NAME, accountSource, checker); modifyUserAddAccountExplicit(TEST_NAME, accountSource, checker); modifyUserAddAccountImplicitExplicitSame(TEST_NAME, accountSource, checker); @@ -194,8 +194,8 @@ public void check(ModelContext modelContext) { modifyUserAddAccountImplicitExplicitNotEqual(TEST_NAME, accountSource, checker); modifyUserAddAccountImplicitExplicitNotEqualReverse(TEST_NAME, accountSource, checker); } - - private void modifyUserAddAccountImplicit(String bundleName, ObjectSource> accountSource, + + private void modifyUserAddAccountImplicit(String bundleName, ObjectSource> accountSource, ObjectChecker> checker) throws Exception { final String TEST_NAME = bundleName + "Implicit"; displayTestTitle(TEST_NAME); @@ -203,20 +203,20 @@ private void modifyUserAddAccountImplicit(String bundleName, ObjectSource account = accountSource.get(); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_JACK_OID, prismContext); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account); ReferenceDelta accountRefDelta = ReferenceDelta.createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); userDelta.addModification(accountRefDelta); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + doPreview(deltas, checker, task, result); } - - private void modifyUserAddAccountExplicit(String bundleName, ObjectSource> accountSource, + + private void modifyUserAddAccountExplicit(String bundleName, ObjectSource> accountSource, ObjectChecker> checker) throws Exception { final String TEST_NAME = bundleName + "Explicit"; displayTestTitle(TEST_NAME); @@ -226,15 +226,15 @@ private void modifyUserAddAccountExplicit(String bundleName, ObjectSource account = accountSource.get(); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_JACK_OID, prismContext); ObjectDelta accountDelta = account.createAddDelta(); Collection> deltas = MiscSchemaUtil.createCollection(userDelta, accountDelta); - + doPreview(deltas, checker, task, result); } - - private void modifyUserAddAccountImplicitExplicitSame(String bundleName, + + private void modifyUserAddAccountImplicitExplicitSame(String bundleName, ObjectSource> accountSource, ObjectChecker> checker) throws Exception { final String TEST_NAME = bundleName + "ImplicitExplicitSame"; displayTestTitle(TEST_NAME); @@ -242,9 +242,9 @@ private void modifyUserAddAccountImplicitExplicitSame(String bundleName, // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject account = accountSource.get(); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_JACK_OID, prismContext); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account); @@ -252,11 +252,11 @@ private void modifyUserAddAccountImplicitExplicitSame(String bundleName, userDelta.addModification(accountRefDelta); ObjectDelta accountDelta = account.createAddDelta(); Collection> deltas = MiscSchemaUtil.createCollection(userDelta, accountDelta); - + doPreview(deltas, checker, task, result); } - - private void modifyUserAddAccountImplicitExplicitSameReverse(String bundleName, + + private void modifyUserAddAccountImplicitExplicitSameReverse(String bundleName, ObjectSource> accountSource, ObjectChecker> checker) throws Exception { final String TEST_NAME = bundleName + "ImplicitExplicitSameReverse"; displayTestTitle(TEST_NAME); @@ -264,9 +264,9 @@ private void modifyUserAddAccountImplicitExplicitSameReverse(String bundleName, // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject account = accountSource.get(); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_JACK_OID, prismContext); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account); @@ -274,11 +274,11 @@ private void modifyUserAddAccountImplicitExplicitSameReverse(String bundleName, userDelta.addModification(accountRefDelta); ObjectDelta accountDelta = account.createAddDelta(); Collection> deltas = MiscSchemaUtil.createCollection(accountDelta, userDelta); - + doPreview(deltas, checker, task, result); } - - private void modifyUserAddAccountImplicitExplicitEqual(String bundleName, + + private void modifyUserAddAccountImplicitExplicitEqual(String bundleName, ObjectSource> accountSource, ObjectChecker> checker) throws Exception { final String TEST_NAME = bundleName + "ImplicitExplicitEqual"; displayTestTitle(TEST_NAME); @@ -286,9 +286,9 @@ private void modifyUserAddAccountImplicitExplicitEqual(String bundleName, // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject account = accountSource.get(); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_JACK_OID, prismContext); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account.clone()); @@ -296,21 +296,21 @@ private void modifyUserAddAccountImplicitExplicitEqual(String bundleName, userDelta.addModification(accountRefDelta); ObjectDelta accountDelta = account.createAddDelta(); Collection> deltas = MiscSchemaUtil.createCollection(userDelta, accountDelta); - + doPreview(deltas, checker, task, result); } - - private void modifyUserAddAccountImplicitExplicitEqualReverse(String bundleName, + + private void modifyUserAddAccountImplicitExplicitEqualReverse(String bundleName, ObjectSource> accountSource, ObjectChecker> checker) throws Exception { final String TEST_NAME = bundleName + "ImplicitExplicitEqualReverse"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject account = accountSource.get(); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_JACK_OID, prismContext); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account.clone()); @@ -318,21 +318,21 @@ private void modifyUserAddAccountImplicitExplicitEqualReverse(String bundleName, userDelta.addModification(accountRefDelta); ObjectDelta accountDelta = account.createAddDelta(); Collection> deltas = MiscSchemaUtil.createCollection(accountDelta, userDelta); - + doPreview(deltas, checker, task, result); } - - private void modifyUserAddAccountImplicitExplicitNotEqual(String bundleName, + + private void modifyUserAddAccountImplicitExplicitNotEqual(String bundleName, ObjectSource> accountSource, ObjectChecker> checker) throws Exception { final String TEST_NAME = bundleName + "ImplicitExplicitNotEqual"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject account = accountSource.get(); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_JACK_OID, prismContext); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account.clone()); @@ -342,11 +342,11 @@ private void modifyUserAddAccountImplicitExplicitNotEqual(String bundleName, account.asObjectable().setDescription("aye!"); ObjectDelta accountDelta = account.createAddDelta(); Collection> deltas = MiscSchemaUtil.createCollection(userDelta, accountDelta); - + doPreviewFail(deltas, task, result); } - - private void modifyUserAddAccountImplicitExplicitNotEqualReverse(String bundleName, + + private void modifyUserAddAccountImplicitExplicitNotEqualReverse(String bundleName, ObjectSource> accountSource, ObjectChecker> checker) throws Exception { final String TEST_NAME = bundleName + "ImplicitExplicitNotEqualReverse"; displayTestTitle(TEST_NAME); @@ -354,9 +354,9 @@ private void modifyUserAddAccountImplicitExplicitNotEqualReverse(String bundleNa // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject account = accountSource.get(); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_JACK_OID, prismContext); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account.clone()); @@ -366,60 +366,60 @@ private void modifyUserAddAccountImplicitExplicitNotEqualReverse(String bundleNa account.asObjectable().setDescription("aye!"); ObjectDelta accountDelta = account.createAddDelta(); Collection> deltas = MiscSchemaUtil.createCollection(accountDelta, userDelta); - + doPreviewFail(deltas, task, result); } - - private void doPreview(Collection> deltas, - ObjectChecker> checker, Task task, OperationResult result) + + private void doPreview(Collection> deltas, + ObjectChecker> checker, Task task, OperationResult result) throws SchemaException, PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException, ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException { display("Input deltas: ", deltas); - + // WHEN ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); - + // THEN display("Preview context", modelContext); checker.check(modelContext); - + result.computeStatus(); TestUtil.assertSuccess(result); } - - private void doPreviewFail(Collection> deltas, Task task, OperationResult result) + + private void doPreviewFail(Collection> deltas, Task task, OperationResult result) throws SchemaException, PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException, ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException { display("Input deltas: ", deltas); - + try { // WHEN ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); - + AssertJUnit.fail("Expected exception, but it haven't come"); } catch (SchemaException e) { // This is expected display("Expected exception", e); } - + result.computeStatus(); TestUtil.assertFailure(result); } - + private void assertAddAccount(ModelContext modelContext, boolean expectFullNameDelta) { assertNotNull("Null model context", modelContext); - + ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); assertSideEffectiveDeltasOnly(focusContext.getSecondaryDelta(), "focus secondary delta", ActivationStatusType.ENABLED); - + Collection projectionContexts = modelContext.getProjectionContexts(); assertNotNull("Null model projection context list", projectionContexts); assertEquals("Unexpected number of projection contexts", 1, projectionContexts.size()); ModelProjectionContext accContext = projectionContexts.iterator().next(); assertNotNull("Null model projection context", accContext); - + assertEquals("Wrong policy decision", SynchronizationPolicyDecision.ADD, accContext.getSynchronizationPolicyDecision()); ObjectDelta accountPrimaryDelta = accContext.getPrimaryDelta(); assertEquals(ChangeType.ADD, accountPrimaryDelta.getChangeType()); @@ -437,16 +437,16 @@ private void assertAddAccount(ModelContext modelContext, boolean expec if (expectFullNameDelta) { assertNotNull("No full name delta in account secondary delta", fullNameDelta); PrismAsserts.assertReplace(fullNameDelta, "Jack Sparrow"); - PrismAsserts.assertOrigin(fullNameDelta, OriginType.OUTBOUND); + PrismAsserts.assertOrigin(fullNameDelta, OriginType.OUTBOUND); } else { assertNull("Unexpected full name delta in account secondary delta", fullNameDelta); } PrismObject accountNew = accContext.getObjectNew(); IntegrationTestTools.assertIcfsNameAttribute(accountNew, "jack"); - IntegrationTestTools.assertAttribute(accountNew, dummyResourceCtl.getAttributeFullnameQName(), "Jack Sparrow"); + IntegrationTestTools.assertAttribute(accountNew, dummyResourceCtl.getAttributeFullnameQName(), "Jack Sparrow"); } - + @Test public void test130GetAdminGuiConfig() throws Exception { final String TEST_NAME = "test130GetAdminGuiConfig"; @@ -462,16 +462,16 @@ public void test130GetAdminGuiConfig() throws Exception { // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + assertAdminGuiConfigurations(adminGuiConfiguration, 0, 1, 3, 1, 0); - + RichHyperlinkType link = adminGuiConfiguration.getUserDashboardLink().get(0); assertEquals("Bad link label", "Foo", link.getLabel()); assertEquals("Bad link targetUrl", "/foo", link.getTargetUrl()); - + assertEquals("Bad timezone targetUrl", "Jamaica", adminGuiConfiguration.getDefaultTimezone()); } - + @Test public void test150GetGuybrushRefinedObjectClassDef() throws Exception { final String TEST_NAME = "test150GetGuybrushRefinedObjectClassDef"; @@ -482,22 +482,22 @@ public void test150GetGuybrushRefinedObjectClassDef() throws Exception { OperationResult result = task.getResult(); PrismObject shadow = getShadowModel(ACCOUNT_SHADOW_GUYBRUSH_OID); - + // WHEN - RefinedObjectClassDefinition rOCDef = modelInteractionService.getEditObjectClassDefinition(shadow, + RefinedObjectClassDefinition rOCDef = modelInteractionService.getEditObjectClassDefinition(shadow, getDummyResourceObject(), AuthorizationPhaseType.REQUEST); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + display("Refined object class", rOCDef); assertNotNull("Null config", rOCDef); - + display("Password credentials outbound", rOCDef.getPasswordOutbound()); assertNotNull("Assert not null", rOCDef.getPasswordOutbound()); } - + @Test public void test200ModifyUserGuybrushDeleteAccount() throws Exception { final String TEST_NAME = "test200ModifyUserGuybrushDeleteAccount"; @@ -509,7 +509,7 @@ public void test200ModifyUserGuybrushDeleteAccount() throws Exception { assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); PrismObject account = PrismTestUtil.parseObject(ACCOUNT_GUYBRUSH_DUMMY_FILE); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_GUYBRUSH_OID, prismContext); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account); @@ -517,36 +517,36 @@ public void test200ModifyUserGuybrushDeleteAccount() throws Exception { userDelta.addModification(accountDelta); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); display("Input deltas: ", deltas); - + // WHEN displayWhen(TEST_NAME); ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); - + // THEN displayThen(TEST_NAME); display("Preview context", modelContext); assertNotNull("Null model context", modelContext); - + result.computeStatus(); TestUtil.assertSuccess(result); - + ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); assertSideEffectiveDeltasOnly("focus secondary delta", focusContext.getSecondaryDelta()); - + Collection projectionContexts = modelContext.getProjectionContexts(); assertNotNull("Null model projection context list", projectionContexts); assertEquals("Unexpected number of projection contexts", 1, projectionContexts.size()); ModelProjectionContext accContext = projectionContexts.iterator().next(); assertNotNull("Null model projection context", accContext); - + assertEquals("Wrong policy decision", SynchronizationPolicyDecision.DELETE, accContext.getSynchronizationPolicyDecision()); ObjectDelta accountPrimaryDelta = accContext.getPrimaryDelta(); assertEquals(ChangeType.DELETE, accountPrimaryDelta.getChangeType()); } - + @Test public void test210GuybrushAddAccount() throws Exception { final String TEST_NAME = "test210GuybrushAddAccount"; @@ -556,33 +556,33 @@ public void test210GuybrushAddAccount() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); ObjectDelta accountDelta = ObjectDelta.createAddDelta(account); Collection> deltas = MiscSchemaUtil.createCollection(accountDelta); display("Input deltas: ", deltas); - + // WHEN displayWhen(TEST_NAME); ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); - + // THEN displayThen(TEST_NAME); display("Preview context", modelContext); assertNotNull("Null model context", modelContext); - + result.computeStatus(); TestUtil.assertSuccess(result); - + ModelElementContext focusContext = modelContext.getFocusContext(); assertNull("Unexpected model focus context", focusContext); - + Collection projectionContexts = modelContext.getProjectionContexts(); assertNotNull("Null model projection context list", projectionContexts); assertEquals("Unexpected number of projection contexts", 1, projectionContexts.size()); ModelProjectionContext accContext = projectionContexts.iterator().next(); assertNotNull("Null model projection context", accContext); - + // Decision does not matter now // assertEquals("Wrong policy decision", SynchronizationPolicyDecision.ADD, accContext.getSynchronizationPolicyDecision()); ObjectDelta accountPrimaryDelta = accContext.getPrimaryDelta(); @@ -597,7 +597,7 @@ public void test210GuybrushAddAccount() throws Exception { ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); PrismAsserts.assertModifications(accountSecondaryDelta, 1); } - + @Test public void test212ModifyUserAddAccountRef() throws Exception { final String TEST_NAME = "test212ModifyUserAddAccountRef"; @@ -607,51 +607,51 @@ public void test212ModifyUserAddAccountRef() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_GUYBRUSH_OID, prismContext); - ReferenceDelta accountDelta = ReferenceDelta.createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), + ReferenceDelta accountDelta = ReferenceDelta.createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), ACCOUNT_SHADOW_GUYBRUSH_OID); userDelta.addModification(accountDelta); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); display("Input deltas: ", userDelta); - + // WHEN displayWhen(TEST_NAME); ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); - + // THEN displayThen(TEST_NAME); display("Preview context", modelContext); assertNotNull("Null model context", modelContext); - + result.computeStatus(); TestUtil.assertSuccess(result); - + ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); - + ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertSideEffectiveDeltasOnly("focus secondary delta", focusContext.getSecondaryDelta()); - + Collection projectionContexts = modelContext.getProjectionContexts(); assertNotNull("Null model projection context list", projectionContexts); assertEquals("Unexpected number of projection contexts", 1, projectionContexts.size()); ModelProjectionContext accContext = projectionContexts.iterator().next(); assertNotNull("Null model projection context", accContext); - + assertEquals("Wrong policy decision", SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); ObjectDelta accountPrimaryDelta = accContext.getPrimaryDelta(); assertNull("Unexpected account primary delta", accountPrimaryDelta); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertEquals("Unexpected size of account secondary delta: "+accountSecondaryDelta, 2, accountSecondaryDelta.getModifications().size()); - PrismAsserts.assertPropertyAdd(accountSecondaryDelta, + PrismAsserts.assertPropertyAdd(accountSecondaryDelta, dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME), "rum"); - PrismAsserts.assertPropertyAdd(accountSecondaryDelta, + PrismAsserts.assertPropertyAdd(accountSecondaryDelta, dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME), "Arr!"); } - + /** * MID-3079 */ @@ -664,90 +664,90 @@ public void test220PreviewJackAssignRolePirate() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - - ObjectDelta delta = createAssignmentFocusDelta(UserType.class, USER_JACK_OID, + + ObjectDelta delta = createAssignmentFocusDelta(UserType.class, USER_JACK_OID, ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, null, null, true); - + // WHEN displayWhen(TEST_NAME); ModelContext modelContext = modelInteractionService.previewChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN displayThen(TEST_NAME); display("Preview context", modelContext); assertNotNull("Null model context", modelContext); - + result.computeStatus(); TestUtil.assertSuccess(result); - + ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Model focus context missing", focusContext); - + Collection projectionContexts = modelContext.getProjectionContexts(); assertNotNull("Null model projection context list", projectionContexts); assertEquals("Unexpected number of projection contexts", 1, projectionContexts.size()); ModelProjectionContext accContext = projectionContexts.iterator().next(); assertNotNull("Null model projection context", accContext); - + ObjectDelta accountPrimaryDelta = accContext.getPrimaryDelta(); assertNull("Unexpected account primary delta", accountPrimaryDelta); - + ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertEquals(ChangeType.MODIFY, accountSecondaryDelta.getChangeType()); - + assertAccountItemModify(accountSecondaryDelta, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, null, // old null, // add null, // delete new ActivationStatusType[] { ActivationStatusType.ENABLED }); // replace - + assertAccountDefaultDummyAttributeModify(accountSecondaryDelta, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, null, // old new String[] { ROLE_PIRATE_WEAPON }, // add null, // delete null); // replace - + assertAccountDefaultDummyAttributeModify(accountSecondaryDelta, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, null, // old new String[] { ROLE_PIRATE_TITLE }, // add null, // delete null); // replace - + assertAccountDefaultDummyAttributeModify(accountSecondaryDelta, DUMMY_ACCOUNT_ATTRIBUTE_SEA_NAME, null, // old null, // add null, // delete new String[] { "jack sailed The Seven Seas, immediately , role , with this The Seven Seas while focused on (in Pirate)" }); // replace - + assertAccountDefaultDummyAttributeModify(accountSecondaryDelta, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, null, // old new String[] { "Jack Sparrow is the best pirate Caribbean has ever seen" }, // add null, // delete null); // replace - + assertAccountDefaultDummyAttributeModify(accountSecondaryDelta, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, null, // old new String[] { RESOURCE_DUMMY_QUOTE }, // add null, // delete null); // replace - + assertAccountDefaultDummyAttributeModify(accountSecondaryDelta, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, null, // old new String[] { RESOURCE_DUMMY_DRINK }, // add null, // delete null); // replace - + PrismAsserts.assertModifications(accountSecondaryDelta, 15); } - + /** * Make sure that Guybrush has an existing account and that it is properly populated. * We will use this setup in following tests. @@ -761,23 +761,23 @@ public void test230GuybrushAssignAccountDummy() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - - ObjectDelta delta = createAssignmentFocusDelta(UserType.class, USER_GUYBRUSH_OID, + + ObjectDelta delta = createAssignmentFocusDelta(UserType.class, USER_GUYBRUSH_OID, ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, null, null, true); - + ModelExecuteOptions options = ModelExecuteOptions.createReconcile(); - + // WHEN displayWhen(TEST_NAME); - modifyUserReplace(USER_GUYBRUSH_OID, new ItemPath(UserType.F_EXTENSION, PIRACY_WEAPON), task, result, + modifyUserReplace(USER_GUYBRUSH_OID, new ItemPath(UserType.F_EXTENSION, PIRACY_WEAPON), task, result, "tongue"); assignAccount(USER_GUYBRUSH_OID, RESOURCE_DUMMY_OID, null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + DummyAccount dummyAccount = assertDummyAccount(null, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true); display("Dummy account after", dummyAccount); dummyAccount.addAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Great Pirate"); @@ -795,59 +795,59 @@ public void test232PreviewGuybrushAddRolePirate() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - - ObjectDelta delta = createAssignmentFocusDelta(UserType.class, USER_GUYBRUSH_OID, + + ObjectDelta delta = createAssignmentFocusDelta(UserType.class, USER_GUYBRUSH_OID, ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, null, null, true); - + // WHEN displayWhen(TEST_NAME); ModelContext modelContext = modelInteractionService.previewChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN displayThen(TEST_NAME); display("Preview context", modelContext); assertNotNull("Null model context", modelContext); - + result.computeStatus(); TestUtil.assertSuccess(result); - + ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Model focus context missing", focusContext); - + Collection projectionContexts = modelContext.getProjectionContexts(); assertNotNull("Null model projection context list", projectionContexts); assertEquals("Unexpected number of projection contexts", 1, projectionContexts.size()); ModelProjectionContext accContext = projectionContexts.iterator().next(); assertNotNull("Null model projection context", accContext); - + ObjectDelta accountPrimaryDelta = accContext.getPrimaryDelta(); assertNull("Unexpected account primary delta", accountPrimaryDelta); - + ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertEquals(ChangeType.MODIFY, accountSecondaryDelta.getChangeType()); - + assertAccountDefaultDummyAttributeModify(accountSecondaryDelta, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, new String[] { "Great Pirate" }, // old new String[] { ROLE_PIRATE_TITLE }, // add null, // delete null); // replace - + assertAccountDefaultDummyAttributeModify(accountSecondaryDelta, DUMMY_ACCOUNT_ATTRIBUTE_SEA_NAME, null, // old null, // add null, // delete new String[] { "guybrush sailed The Seven Seas, immediately , role , with this The Seven Seas while focused on (in Pirate)" }); // replace - + assertAccountDefaultDummyAttributeModify(accountSecondaryDelta, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, null, // old new String[] { "Guybrush Threepwood is the best pirate Melee Island has ever seen" }, // add null, // delete null); // replace - + PrismAsserts.assertModifications(accountSecondaryDelta, 3); } @@ -863,61 +863,61 @@ public void test234PreviewGuybrushAddRolePirateRecon() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - - ObjectDelta delta = createAssignmentFocusDelta(UserType.class, USER_GUYBRUSH_OID, + + ObjectDelta delta = createAssignmentFocusDelta(UserType.class, USER_GUYBRUSH_OID, ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, null, null, true); - + ModelExecuteOptions options = ModelExecuteOptions.createReconcile(); - + // WHEN displayWhen(TEST_NAME); ModelContext modelContext = modelInteractionService.previewChanges(MiscSchemaUtil.createCollection(delta), options, task, result); - + // THEN displayThen(TEST_NAME); display("Preview context", modelContext); assertNotNull("Null model context", modelContext); - + result.computeStatus(); TestUtil.assertSuccess(result); - + ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Model focus context missing", focusContext); - + Collection projectionContexts = modelContext.getProjectionContexts(); assertNotNull("Null model projection context list", projectionContexts); assertEquals("Unexpected number of projection contexts", 1, projectionContexts.size()); ModelProjectionContext accContext = projectionContexts.iterator().next(); assertNotNull("Null model projection context", accContext); - + ObjectDelta accountPrimaryDelta = accContext.getPrimaryDelta(); assertNull("Unexpected account primary delta", accountPrimaryDelta); - + ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertEquals(ChangeType.MODIFY, accountSecondaryDelta.getChangeType()); - + assertAccountDefaultDummyAttributeModify(accountSecondaryDelta, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, new String[] { "Great Pirate" }, // old new String[] { ROLE_PIRATE_TITLE }, // add null, // delete null); // replace - + assertAccountDefaultDummyAttributeModify(accountSecondaryDelta, DUMMY_ACCOUNT_ATTRIBUTE_SEA_NAME, null, // old null, // add null, // delete new String[] { "guybrush sailed The Seven Seas, immediately , role , with this The Seven Seas while focused on (in Pirate)" }); // replace - + assertAccountDefaultDummyAttributeModify(accountSecondaryDelta, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, null, // old new String[] { "Guybrush Threepwood is the best pirate Melee Island has ever seen" }, // add null, // delete null); // replace - + PrismAsserts.assertModifications(accountSecondaryDelta, 3); } @@ -933,45 +933,45 @@ public void test236PreviewGuybrushAddRoleSailor() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - - ObjectDelta delta = createAssignmentFocusDelta(UserType.class, USER_GUYBRUSH_OID, + + ObjectDelta delta = createAssignmentFocusDelta(UserType.class, USER_GUYBRUSH_OID, ROLE_SAILOR_OID, RoleType.COMPLEX_TYPE, null, null, null, true); - + // WHEN displayWhen(TEST_NAME); ModelContext modelContext = modelInteractionService.previewChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN displayThen(TEST_NAME); display("Preview context", modelContext); assertNotNull("Null model context", modelContext); - + result.computeStatus(); TestUtil.assertSuccess(result); - + ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Model focus context missing", focusContext); - + Collection projectionContexts = modelContext.getProjectionContexts(); assertNotNull("Null model projection context list", projectionContexts); assertEquals("Unexpected number of projection contexts", 1, projectionContexts.size()); ModelProjectionContext accContext = projectionContexts.iterator().next(); assertNotNull("Null model projection context", accContext); - + ObjectDelta accountPrimaryDelta = accContext.getPrimaryDelta(); assertNull("Unexpected account primary delta", accountPrimaryDelta); - + ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertEquals(ChangeType.MODIFY, accountSecondaryDelta.getChangeType()); - + assertAccountDefaultDummyAttributeModify(accountSecondaryDelta, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, new String[] { RESOURCE_DUMMY_DRINK }, // old new String[] { ROLE_SAILOR_DRINK }, // add null, // delete null); // replace - + PrismAsserts.assertModifications(accountSecondaryDelta, 1); } @@ -984,19 +984,19 @@ public void test239GuybrushUnAssignAccountDummy() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + // WHEN displayWhen(TEST_NAME); unassignAccount(USER_GUYBRUSH_OID, RESOURCE_DUMMY_OID, null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertNoDummyAccount(null, USER_GUYBRUSH_USERNAME); } - + /** * Make sure that Guybrush has an existing account and that it is properly populated. * We will use this setup in following tests. @@ -1010,21 +1010,21 @@ public void test240GuybrushAssignAccountDummyRelative() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + // WHEN displayWhen(TEST_NAME); assignAccount(USER_GUYBRUSH_OID, RESOURCE_DUMMY_RELATIVE_OID, null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_RELATIVE_NAME, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true); display("Dummy account after", dummyAccount); dummyAccount.addAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Great Pirate"); } - + /** * MID-3079 * Relative operation on a relative resource. The account is not retrieved. @@ -1039,62 +1039,62 @@ public void test242PreviewGuybrushAddRolePirateRelative() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - - ObjectDelta delta = createAssignmentFocusDelta(UserType.class, USER_GUYBRUSH_OID, + + ObjectDelta delta = createAssignmentFocusDelta(UserType.class, USER_GUYBRUSH_OID, ROLE_PIRATE_RELATIVE_OID, RoleType.COMPLEX_TYPE, null, null, null, true); - + // WHEN displayWhen(TEST_NAME); ModelContext modelContext = modelInteractionService.previewChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN displayThen(TEST_NAME); display("Preview context", modelContext); assertNotNull("Null model context", modelContext); - + result.computeStatus(); TestUtil.assertSuccess(result); - + ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Model focus context missing", focusContext); - + Collection projectionContexts = modelContext.getProjectionContexts(); assertNotNull("Null model projection context list", projectionContexts); assertEquals("Unexpected number of projection contexts", 1, projectionContexts.size()); ModelProjectionContext accContext = projectionContexts.iterator().next(); assertNotNull("Null model projection context", accContext); - + ObjectDelta accountPrimaryDelta = accContext.getPrimaryDelta(); assertNull("Unexpected account primary delta", accountPrimaryDelta); - + ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertEquals(ChangeType.MODIFY, accountSecondaryDelta.getChangeType()); - + assertAccountDummyAttributeModify(accountSecondaryDelta, RESOURCE_DUMMY_RELATIVE_NAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, null, // old new String[] { ROLE_PIRATE_WEAPON }, // add null, // delete null); // replace - + assertAccountDummyAttributeModify(accountSecondaryDelta, RESOURCE_DUMMY_RELATIVE_NAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, null, // old new String[] { ROLE_PIRATE_TITLE }, // add null, // delete null); // replace - + assertAccountDummyAttributeModify(accountSecondaryDelta, RESOURCE_DUMMY_RELATIVE_NAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, null, // old new String[] { "Guybrush Threepwood is the best pirate Melee Island has ever seen" }, // add null, // delete null); // replace - + PrismAsserts.assertModifications(accountSecondaryDelta, 3); } - + /** * MID-3079 */ @@ -1107,59 +1107,59 @@ public void test244PreviewGuybrushAddRolePirateRelativeRecon() throws Exception Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - - ObjectDelta delta = createAssignmentFocusDelta(UserType.class, USER_GUYBRUSH_OID, + + ObjectDelta delta = createAssignmentFocusDelta(UserType.class, USER_GUYBRUSH_OID, ROLE_PIRATE_RELATIVE_OID, RoleType.COMPLEX_TYPE, null, null, null, true); - + // WHEN displayWhen(TEST_NAME); ModelContext modelContext = modelInteractionService.previewChanges(MiscSchemaUtil.createCollection(delta), ModelExecuteOptions.createReconcile(), task, result); - + // THEN displayThen(TEST_NAME); display("Preview context", modelContext); assertNotNull("Null model context", modelContext); - + result.computeStatus(); TestUtil.assertSuccess(result); - + ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Model focus context missing", focusContext); - + Collection projectionContexts = modelContext.getProjectionContexts(); assertNotNull("Null model projection context list", projectionContexts); assertEquals("Unexpected number of projection contexts", 1, projectionContexts.size()); ModelProjectionContext accContext = projectionContexts.iterator().next(); assertNotNull("Null model projection context", accContext); - + ObjectDelta accountPrimaryDelta = accContext.getPrimaryDelta(); assertNull("Unexpected account primary delta", accountPrimaryDelta); - + ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertEquals(ChangeType.MODIFY, accountSecondaryDelta.getChangeType()); - + assertAccountDummyAttributeModify(accountSecondaryDelta, RESOURCE_DUMMY_RELATIVE_NAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, new String[] { "tongue" }, // old new String[] { ROLE_PIRATE_WEAPON }, // add null, // delete null); // replace - + assertAccountDummyAttributeModify(accountSecondaryDelta, RESOURCE_DUMMY_RELATIVE_NAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, new String[] { "Great Pirate" }, // old new String[] { ROLE_PIRATE_TITLE }, // add null, // delete null); // replace - + assertAccountDummyAttributeModify(accountSecondaryDelta, RESOURCE_DUMMY_RELATIVE_NAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, null, // old new String[] { "Guybrush Threepwood is the best pirate Melee Island has ever seen" }, // add null, // delete null); // replace - + PrismAsserts.assertModifications(accountSecondaryDelta, 3); } @@ -1172,48 +1172,48 @@ public void test249GuybrushUnAssignAccountDummyRelative() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + // WHEN displayWhen(TEST_NAME); unassignAccount(USER_GUYBRUSH_OID, RESOURCE_DUMMY_RELATIVE_OID, null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertNoDummyAccount(RESOURCE_DUMMY_RELATIVE_NAME, USER_GUYBRUSH_USERNAME); } - + private void assertAccountDefaultDummyAttributeModify(ObjectDelta accountDelta, - String attrName, + String attrName, T[] expectedOldValues, T[] expectedAddValues, T[] expectedDeleteValues, T[] expectedReplaceValues) { ItemPath itemPath = getDummyResourceController().getAttributePath(attrName); assertAccountItemModify(accountDelta, itemPath, expectedOldValues, expectedAddValues, expectedDeleteValues, expectedReplaceValues); } - + private void assertAccountDummyAttributeModify(ObjectDelta accountDelta, - String dummyName, String attrName, + String dummyName, String attrName, T[] expectedOldValues, T[] expectedAddValues, T[] expectedDeleteValues, T[] expectedReplaceValues) { ItemPath itemPath = getDummyResourceController(dummyName).getAttributePath(attrName); assertAccountItemModify(accountDelta, itemPath, expectedOldValues, expectedAddValues, expectedDeleteValues, expectedReplaceValues); } - + private void assertAccountItemModify(ObjectDelta accountDelta, - ItemPath itemPath, + ItemPath itemPath, T[] expectedOldValues, T[] expectedAddValues, T[] expectedDeleteValues, T[] expectedReplaceValues) { PropertyDelta attrDelta = accountDelta.findPropertyDelta(itemPath); 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. - + /** * Changing ACCOUNT fullname (replace delta), no user changes. */ @@ -1226,50 +1226,50 @@ public void test300ModifyElaineAccountDummyReplace() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + ObjectDelta accountDelta = createModifyAccountShadowReplaceAttributeDelta( ACCOUNT_SHADOW_ELAINE_DUMMY_OID, getDummyResourceObject(), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Elaine Threepwood"); Collection> deltas = MiscSchemaUtil.createCollection(accountDelta); display("Input deltas: ", deltas); - + // WHEN ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); - + // THEN display("Preview context", modelContext); assertNotNull("Null model context", modelContext); - + result.computeStatus(); TestUtil.assertSuccess(result); - + ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); - + ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertSideEffectiveDeltasOnly("focus secondary delta", focusContext.getSecondaryDelta()); - + Collection projectionContexts = modelContext.getProjectionContexts(); assertNotNull("Null model projection context list", projectionContexts); assertEquals("Unexpected number of projection contexts", 3, projectionContexts.size()); - + ModelProjectionContext accContext = modelContext.findProjectionContext( new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, null)); assertNotNull("Null model projection context", accContext); - + assertEquals("Wrong policy decision", SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); ObjectDelta accountPrimaryDelta = accContext.getPrimaryDelta(); assertNotNull("No account primary delta", accountPrimaryDelta); PrismAsserts.assertModifications(accountPrimaryDelta, 1); - PrismAsserts.assertPropertyReplace(accountPrimaryDelta, + PrismAsserts.assertPropertyReplace(accountPrimaryDelta, getAttributePath(getDummyResourceObject(), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME), "Elaine Threepwood"); - + ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertNull("Unexpected account secondary delta: "+accountSecondaryDelta, accountSecondaryDelta); } - + /** * Changing ACCOUNT fullname (add/delete delta), no user changes. */ @@ -1282,53 +1282,53 @@ public void test301ModifyElaineAccountDummyDeleteAdd() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + ObjectDelta accountDelta = createModifyAccountShadowEmptyDelta(ACCOUNT_SHADOW_ELAINE_DUMMY_OID); - PropertyDelta fullnameDelta = createAttributeAddDelta(getDummyResourceObject(), + PropertyDelta fullnameDelta = createAttributeAddDelta(getDummyResourceObject(), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Elaine Threepwood"); fullnameDelta.addValueToDelete(new PrismPropertyValue("Elaine Marley")); accountDelta.addModification(fullnameDelta); Collection> deltas = MiscSchemaUtil.createCollection(accountDelta); display("Input deltas: ", deltas); - + // WHEN ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); - + // THEN display("Preview context", modelContext); assertNotNull("Null model context", modelContext); - + result.computeStatus(); TestUtil.assertSuccess(result); - + ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); - + ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertSideEffectiveDeltasOnly("focus secondary delta", focusContext.getSecondaryDelta()); - + Collection projectionContexts = modelContext.getProjectionContexts(); assertNotNull("Null model projection context list", projectionContexts); assertEquals("Unexpected number of projection contexts", 3, projectionContexts.size()); - + ModelProjectionContext accContext = modelContext.findProjectionContext( new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, null)); assertNotNull("Null model projection context", accContext); - + assertEquals("Wrong policy decision", SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); ObjectDelta accountPrimaryDelta = accContext.getPrimaryDelta(); assertNotNull("No account primary delta", accountPrimaryDelta); PrismAsserts.assertModifications(accountPrimaryDelta, 1); - PrismAsserts.assertPropertyAdd(accountPrimaryDelta, + PrismAsserts.assertPropertyAdd(accountPrimaryDelta, getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME), "Elaine Threepwood"); - PrismAsserts.assertPropertyDelete(accountPrimaryDelta, + PrismAsserts.assertPropertyDelete(accountPrimaryDelta, getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME), "Elaine Marley"); - + ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertNull("Unexpected account secondary delta: "+accountSecondaryDelta, accountSecondaryDelta); } - + /** * Changing ACCOUNT fullname (replace delta), no user changes. * Attempt to make a change to a single-valued attribute or which there is already a strong mapping. @@ -1343,28 +1343,28 @@ public void test400ModifyElaineAccountDummyRedReplace() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + ObjectDelta accountDelta = createModifyAccountShadowReplaceAttributeDelta( - ACCOUNT_SHADOW_ELAINE_DUMMY_RED_OID, getDummyResourceObject(RESOURCE_DUMMY_RED_NAME), + ACCOUNT_SHADOW_ELAINE_DUMMY_RED_OID, getDummyResourceObject(RESOURCE_DUMMY_RED_NAME), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Elaine Threepwood"); Collection> deltas = MiscSchemaUtil.createCollection(accountDelta); display("Input deltas: ", deltas); - + try { // WHEN ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); display("Preview context", modelContext); - + AssertJUnit.fail("Preview unexpectedly succeeded"); } catch (SchemaException e) { // This is expected display("Expected exception", e); } - + result.computeStatus(); TestUtil.assertFailure(result); } - + /** * Changing ACCOUNT fullname (add/delete delta), no user changes. * Attempt to make a change to a single-valued attribute or which there is already a strong mapping. @@ -1379,32 +1379,32 @@ public void test401ModifyElaineAccountDummyRedDeleteAdd() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + ObjectDelta accountDelta = createModifyAccountShadowEmptyDelta(ACCOUNT_SHADOW_ELAINE_DUMMY_RED_OID); - PropertyDelta fullnameDelta = createAttributeAddDelta(getDummyResourceObject(RESOURCE_DUMMY_RED_NAME), + PropertyDelta fullnameDelta = createAttributeAddDelta(getDummyResourceObject(RESOURCE_DUMMY_RED_NAME), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Elaine Threepwood"); fullnameDelta.addValueToDelete(new PrismPropertyValue("Elaine Marley")); accountDelta.addModification(fullnameDelta); Collection> deltas = MiscSchemaUtil.createCollection(accountDelta); display("Input deltas: ", deltas); - + try { // WHEN ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); display("Preview context", modelContext); - + AssertJUnit.fail("Preview unexpectedly succeeded"); } catch (PolicyViolationException e) { // This is expected display("Expected exception", e); } - + result.computeStatus(); TestUtil.assertFailure(result); } // the test5xx is testing mappings with blue dummy resource. It has WEAK mappings. - + /** * Changing ACCOUNT fullname (replace delta), no user changes. */ @@ -1417,50 +1417,50 @@ public void test500ModifyElaineAccountDummyBlueReplace() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + ObjectDelta accountDelta = createModifyAccountShadowReplaceAttributeDelta( - ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_OID, getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), + ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_OID, getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Elaine Threepwood"); Collection> deltas = MiscSchemaUtil.createCollection(accountDelta); display("Input deltas: ", deltas); - + // WHEN ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); - + // THEN display("Preview context", modelContext); assertNotNull("Null model context", modelContext); - + result.computeStatus(); TestUtil.assertSuccess(result); - + ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); - + ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertSideEffectiveDeltasOnly("focus secondary delta", userSecondaryDelta); - + Collection projectionContexts = modelContext.getProjectionContexts(); assertNotNull("Null model projection context list", projectionContexts); assertEquals("Unexpected number of projection contexts", 3, projectionContexts.size()); - + ModelProjectionContext accContext = modelContext.findProjectionContext( new ResourceShadowDiscriminator(RESOURCE_DUMMY_BLUE_OID, ShadowKindType.ACCOUNT, null)); assertNotNull("Null model projection context", accContext); - + assertEquals("Wrong policy decision", SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); ObjectDelta accountPrimaryDelta = accContext.getPrimaryDelta(); assertNotNull("No account primary delta", accountPrimaryDelta); PrismAsserts.assertModifications(accountPrimaryDelta, 1); - PrismAsserts.assertPropertyReplace(accountPrimaryDelta, + PrismAsserts.assertPropertyReplace(accountPrimaryDelta, getAttributePath(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME), "Elaine Threepwood"); - + ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertNull("Unexpected account secondary delta: "+accountSecondaryDelta, accountSecondaryDelta); } - + /** * Changing ACCOUNT fullname (add/delete delta), no user changes. */ @@ -1475,7 +1475,7 @@ public void test501ModifyElaineAccountDummyBlueDeleteAdd() throws Exception { assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); display("elaine blue account before", getDummyAccount(RESOURCE_DUMMY_BLUE_NAME, ACCOUNT_ELAINE_DUMMY_BLUE_USERNAME)); - + ObjectDelta accountDelta = createModifyAccountShadowEmptyDelta(ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_OID); PropertyDelta fullnameDelta = createAttributeAddDelta(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Elaine Threepwood"); @@ -1483,32 +1483,32 @@ public void test501ModifyElaineAccountDummyBlueDeleteAdd() throws Exception { accountDelta.addModification(fullnameDelta); Collection> deltas = MiscSchemaUtil.createCollection(accountDelta); display("Input deltas: ", deltas); - + // WHEN ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); - + // THEN display("Preview context", modelContext); assertNotNull("Null model context", modelContext); - + result.computeStatus(); TestUtil.assertSuccess(result); - + ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); - + ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertSideEffectiveDeltasOnly("focus secondary delta", userSecondaryDelta); - + Collection projectionContexts = modelContext.getProjectionContexts(); assertNotNull("Null model projection context list", projectionContexts); assertEquals("Unexpected number of projection contexts", 3, projectionContexts.size()); - + ModelProjectionContext accContext = modelContext.findProjectionContext( new ResourceShadowDiscriminator(RESOURCE_DUMMY_BLUE_OID, ShadowKindType.ACCOUNT, null)); assertNotNull("Null model projection context", accContext); - + assertEquals("Wrong policy decision", SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); ObjectDelta accountPrimaryDelta = accContext.getPrimaryDelta(); assertNotNull("No account primary delta", accountPrimaryDelta); @@ -1519,12 +1519,12 @@ public void test501ModifyElaineAccountDummyBlueDeleteAdd() throws Exception { PrismAsserts.assertPropertyDelete(accountPrimaryDelta, getAttributePath(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME), "Elaine Marley"); - + ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertNull("Unexpected account secondary delta: "+accountSecondaryDelta, accountSecondaryDelta); } - + /** * Changing USER fullName (replace delta), no account changes. */ @@ -1537,87 +1537,87 @@ public void test600ModifyElaineUserDummyReplace() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - - ObjectDelta userDelta = createModifyUserReplaceDelta(USER_ELAINE_OID, UserType.F_FULL_NAME, + + ObjectDelta userDelta = createModifyUserReplaceDelta(USER_ELAINE_OID, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Elaine Threepwood")); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); display("Input deltas: ", deltas); - + // WHEN displayWhen(TEST_NAME); ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); - + // THEN displayThen(TEST_NAME); - + display("Preview context", modelContext); assertNotNull("Null model context", modelContext); - + result.computeStatus(); TestUtil.assertSuccess(result); - + ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); ObjectDelta userPrimaryDelta = focusContext.getPrimaryDelta(); assertNotNull("No focus primary delta: "+userPrimaryDelta, userPrimaryDelta); PrismAsserts.assertModifications(userPrimaryDelta, 1); PrismAsserts.assertPropertyReplace(userPrimaryDelta, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Elaine Threepwood")); - + ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertSideEffectiveDeltasOnly("focus secondary delta", userSecondaryDelta); - + Collection projectionContexts = modelContext.getProjectionContexts(); assertNotNull("Null model projection context list", projectionContexts); assertEquals("Unexpected number of projection contexts", 3, projectionContexts.size()); - + // DEFAULT dummy resource: normal mappings ModelProjectionContext accContext = modelContext.findProjectionContext( new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, null)); assertNotNull("Null model projection context (default)", accContext); - + assertEquals("Wrong policy decision (default)", SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); ObjectDelta accountPrimaryDelta = accContext.getPrimaryDelta(); assertNull("Unexpected account primary delta (default)", accountPrimaryDelta); - + ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertNotNull("No account secondary delta (default)", accountSecondaryDelta); PrismAsserts.assertModifications(accountSecondaryDelta, 1); - PrismAsserts.assertPropertyReplace(accountSecondaryDelta, + PrismAsserts.assertPropertyReplace(accountSecondaryDelta, getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME), "Elaine Threepwood"); - + // RED dummy resource: strong mappings accContext = modelContext.findProjectionContext( new ResourceShadowDiscriminator(RESOURCE_DUMMY_RED_OID, ShadowKindType.ACCOUNT, null)); assertNotNull("Null model projection context (red)", accContext); - + assertEquals("Wrong policy decision", SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); accountPrimaryDelta = accContext.getPrimaryDelta(); assertNull("Unexpected account primary delta (red)", accountPrimaryDelta); - + accountSecondaryDelta = accContext.getSecondaryDelta(); assertNotNull("No account secondary delta (red)", accountSecondaryDelta); PrismAsserts.assertModifications(accountSecondaryDelta, 1); - PrismAsserts.assertPropertyReplace(accountSecondaryDelta, + PrismAsserts.assertPropertyReplace(accountSecondaryDelta, getAttributePath(getDummyResourceObject(RESOURCE_DUMMY_RED_NAME), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME), "Elaine Threepwood"); - + // BLUE dummy resource: weak mappings accContext = modelContext.findProjectionContext( new ResourceShadowDiscriminator(RESOURCE_DUMMY_BLUE_OID, ShadowKindType.ACCOUNT, null)); assertNotNull("Null model projection context (blue)", accContext); - + assertEquals("Wrong policy decision", SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); accountPrimaryDelta = accContext.getPrimaryDelta(); assertNull("Unexpected account primary delta (blue)", accountPrimaryDelta); - + accountSecondaryDelta = accContext.getSecondaryDelta(); PrismAsserts.assertModifications(accountSecondaryDelta, 1); - PrismAsserts.assertPropertyDelete(accountSecondaryDelta, + PrismAsserts.assertPropertyDelete(accountSecondaryDelta, getAttributePath(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME), "null -- Elaine Marley"); } - + /** * Changing USER fullName (replace delta), change account fullname (replace delta). */ @@ -1630,55 +1630,55 @@ public void test610ModifyElaineUserAccountDummyReplace() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - - ObjectDelta userDelta = createModifyUserReplaceDelta(USER_ELAINE_OID, UserType.F_FULL_NAME, + + ObjectDelta userDelta = createModifyUserReplaceDelta(USER_ELAINE_OID, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Elaine Threepwood")); ObjectDelta accountDelta = createModifyAccountShadowReplaceAttributeDelta( ACCOUNT_SHADOW_ELAINE_DUMMY_OID, getDummyResourceObject(), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Elaine LeChuck"); // Cannot change the attribute on RED resource. It would conflict with the strong mapping and therefore fail. // ObjectDelta accountDeltaRed = createModifyAccountShadowReplaceAttributeDelta( -// ACCOUNT_SHADOW_ELAINE_DUMMY_RED_OID, resourceDummyRed, +// ACCOUNT_SHADOW_ELAINE_DUMMY_RED_OID, resourceDummyRed, // DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Elaine LeChuck"); ObjectDelta accountDeltaBlue = createModifyAccountShadowReplaceAttributeDelta( - ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_OID, getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), + ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_OID, getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Elaine LeChuck"); Collection> deltas = MiscSchemaUtil.createCollection(userDelta, accountDelta, accountDeltaBlue); display("Input deltas: ", deltas); - + // WHEN displayWhen(TEST_NAME); ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); - + // THEN displayThen(TEST_NAME); display("Preview context", modelContext); assertNotNull("Null model context", modelContext); - + result.computeStatus(); TestUtil.assertSuccess(result); - + ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); ObjectDelta userPrimaryDelta = focusContext.getPrimaryDelta(); assertNotNull("No focus primary delta: "+userPrimaryDelta, userPrimaryDelta); PrismAsserts.assertModifications(userPrimaryDelta, 1); PrismAsserts.assertPropertyReplace(userPrimaryDelta, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Elaine Threepwood")); - + ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertSideEffectiveDeltasOnly("focus secondary delta", userSecondaryDelta); - + Collection projectionContexts = modelContext.getProjectionContexts(); assertNotNull("Null model projection context list", projectionContexts); assertEquals("Unexpected number of projection contexts", 3, projectionContexts.size()); - + // DEFAULT dummy resource: normal mappings ModelProjectionContext accContext = modelContext.findProjectionContext( new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, null)); assertNotNull("Null model projection context (default)", accContext); - + assertEquals("Wrong policy decision (default)", SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); ObjectDelta accountPrimaryDelta = accContext.getPrimaryDelta(); assertNotNull("No account primary delta (default)", accountPrimaryDelta); @@ -1686,45 +1686,45 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_OID, getDummyResourceObject(RESOURCE_DUMMY_BLUE PrismAsserts.assertPropertyReplace(accountPrimaryDelta, getAttributePath(getDummyResourceObject(), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME), "Elaine LeChuck"); - + ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertNull("Unexpected account secondary delta: "+accountSecondaryDelta, accountSecondaryDelta); - + // RED dummy resource: strong mappings accContext = modelContext.findProjectionContext( new ResourceShadowDiscriminator(RESOURCE_DUMMY_RED_OID, ShadowKindType.ACCOUNT, null)); assertNotNull("Null model projection context (red)", accContext); - + assertEquals("Wrong policy decision", SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); accountPrimaryDelta = accContext.getPrimaryDelta(); - assertNull("Unexpected account primary delta (red)", accountPrimaryDelta); + assertNull("Unexpected account primary delta (red)", accountPrimaryDelta); accountSecondaryDelta = accContext.getSecondaryDelta(); assertNotNull("No account secondary delta (red)", accountSecondaryDelta); PrismAsserts.assertModifications(accountSecondaryDelta, 1); - PrismAsserts.assertPropertyReplace(accountSecondaryDelta, + PrismAsserts.assertPropertyReplace(accountSecondaryDelta, getAttributePath(getDummyResourceObject(RESOURCE_DUMMY_RED_NAME), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME), "Elaine Threepwood"); - + // BLUE dummy resource: weak mappings accContext = modelContext.findProjectionContext( new ResourceShadowDiscriminator(RESOURCE_DUMMY_BLUE_OID, ShadowKindType.ACCOUNT, null)); assertNotNull("Null model projection context (blue)", accContext); - + assertEquals("Wrong policy decision", SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); accountPrimaryDelta = accContext.getPrimaryDelta(); assertNotNull("No account primary delta (blue)", accountPrimaryDelta); PrismAsserts.assertModifications(accountPrimaryDelta, 1); - PrismAsserts.assertPropertyReplace(accountPrimaryDelta, + PrismAsserts.assertPropertyReplace(accountPrimaryDelta, getAttributePath(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME), "Elaine LeChuck"); - + accountSecondaryDelta = accContext.getSecondaryDelta(); PrismAsserts.assertModifications("account secondary delta (blue)", accountSecondaryDelta, 1); - PrismAsserts.assertPropertyDelete(accountSecondaryDelta, + PrismAsserts.assertPropertyDelete(accountSecondaryDelta, getAttributePath(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME), "null -- Elaine Marley"); } - + @Test public void test620AddUserCapsize() throws Exception { final String TEST_NAME = "test620AddUserCapsize"; @@ -1734,72 +1734,72 @@ public void test620AddUserCapsize() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + PrismObject user = PrismTestUtil.parseObject(USER_CAPSIZE_FILE); ObjectDelta userDelta = ObjectDelta.createAddDelta(user); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + // WHEN ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); - + // THEN display("Preview context", modelContext); assertNotNull("Null model context", modelContext); - + result.computeStatus(); - TestUtil.assertSuccess(result); - + TestUtil.assertSuccess(result); + ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); ObjectDelta userPrimaryDelta = focusContext.getPrimaryDelta(); assertNotNull("No focus primary delta: " + userPrimaryDelta, userPrimaryDelta); PrismAsserts.assertIsAdd(userPrimaryDelta); - + ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertSideEffectiveDeltasOnly(userSecondaryDelta, "focus secondary delta", ActivationStatusType.ENABLED); - + Collection projectionContexts = modelContext.getProjectionContexts(); assertNotNull("Null model projection context list", projectionContexts); assertEquals("Unexpected number of projection contexts", 3, projectionContexts.size()); - + // DEFAULT dummy resource: normal mappings ModelProjectionContext accContext = modelContext.findProjectionContext( new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, null)); assertNotNull("Null model projection context (default)", accContext); - + assertEquals("Wrong policy decision (default)", SynchronizationPolicyDecision.ADD, accContext.getSynchronizationPolicyDecision()); ObjectDelta accountPrimaryDelta = accContext.getPrimaryDelta(); assertNotNull("No account primary delta (default)", accountPrimaryDelta); PrismAsserts.assertIsAdd(accountPrimaryDelta); - + ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertNotNull("No account secondary delta (default)", accountSecondaryDelta); PrismAsserts.assertModifications(accountSecondaryDelta, 9); PrismAsserts.assertNoItemDelta(accountSecondaryDelta, getAttributePath(getDummyResourceObject(), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME)); - + // RED dummy resource: strong mappings accContext = modelContext.findProjectionContext( new ResourceShadowDiscriminator(RESOURCE_DUMMY_RED_OID, ShadowKindType.ACCOUNT, null)); assertNotNull("Null model projection context (red)", accContext); - + assertEquals("Wrong policy decision", SynchronizationPolicyDecision.ADD, accContext.getSynchronizationPolicyDecision()); accountPrimaryDelta = accContext.getPrimaryDelta(); assertNotNull("No account primary delta (default)", accountPrimaryDelta); PrismAsserts.assertIsAdd(accountPrimaryDelta); - + accountSecondaryDelta = accContext.getSecondaryDelta(); assertNotNull("No account secondary delta (red)", accountSecondaryDelta); PrismAsserts.assertModifications(accountSecondaryDelta, 9); - PrismAsserts.assertPropertyReplace(accountSecondaryDelta, + PrismAsserts.assertPropertyReplace(accountSecondaryDelta, getAttributePath(getDummyResourceObject(RESOURCE_DUMMY_RED_NAME), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME), "Kate Capsize"); - + // BLUE dummy resource: weak mappings accContext = modelContext.findProjectionContext( new ResourceShadowDiscriminator(RESOURCE_DUMMY_BLUE_OID, ShadowKindType.ACCOUNT, null)); assertNotNull("Null model projection context (blue)", accContext); - + assertEquals("Wrong policy decision", SynchronizationPolicyDecision.ADD, accContext.getSynchronizationPolicyDecision()); accountPrimaryDelta = accContext.getPrimaryDelta(); assertNotNull("No account primary delta (default)", accountPrimaryDelta); @@ -1810,7 +1810,7 @@ public void test620AddUserCapsize() throws Exception { PrismAsserts.assertModifications(accountSecondaryDelta, 10); PrismAsserts.assertNoItemDelta(accountSecondaryDelta, getAttributePath(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME)); - assertPasswordDelta(accountSecondaryDelta); + assertPasswordDelta(accountSecondaryDelta); } // testing multiple resources with dependencies (dummy -> dummy lemon) @@ -1903,9 +1903,9 @@ public void test630AddUserRogers() throws Exception { getAttributePath(getDummyResourceObject(RESOURCE_DUMMY_LEMON_NAME), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WATER_NAME), "pirate Rum Rogers Sr. drinks only rum!"); } - + // The 7xx tests try to do various non-common cases - + /** * Enable two accounts at once. Both accounts belongs to the same user. But no user delta is here. * This may cause problems when constructing the lens context inside model implementation. @@ -1919,67 +1919,67 @@ public void test700DisableElaineAccountTwoResources() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - - ObjectDelta accountDeltaDefault = createModifyAccountShadowReplaceDelta(ACCOUNT_SHADOW_ELAINE_DUMMY_OID, + + ObjectDelta accountDeltaDefault = createModifyAccountShadowReplaceDelta(ACCOUNT_SHADOW_ELAINE_DUMMY_OID, getDummyResourceObject(), ACTIVATION_ADMINISTRATIVE_STATUS_PATH, ActivationStatusType.DISABLED); - ObjectDelta accountDeltaBlue = createModifyAccountShadowReplaceDelta(ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_OID, + ObjectDelta accountDeltaBlue = createModifyAccountShadowReplaceDelta(ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_OID, getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), ACTIVATION_ADMINISTRATIVE_STATUS_PATH, ActivationStatusType.DISABLED); Collection> deltas = MiscSchemaUtil.createCollection(accountDeltaDefault, accountDeltaBlue); display("Input deltas: ", deltas); - + // WHEN ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); - + // THEN display("Preview context", modelContext); assertNotNull("Null model context", modelContext); - + result.computeStatus(); TestUtil.assertSuccess(result); - + ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); - + ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertSideEffectiveDeltasOnly("focus secondary delta", userSecondaryDelta); - + Collection projectionContexts = modelContext.getProjectionContexts(); assertNotNull("Null model projection context list", projectionContexts); assertEquals("Unexpected number of projection contexts", 3, projectionContexts.size()); - + ModelProjectionContext accContextDefault = modelContext.findProjectionContext( new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, null)); assertNotNull("Null model projection context (default)", accContextDefault); - + assertEquals("Wrong policy decision (default)", SynchronizationPolicyDecision.KEEP, accContextDefault.getSynchronizationPolicyDecision()); ObjectDelta accountPrimaryDelta = accContextDefault.getPrimaryDelta(); assertNotNull("No account primary delta (default)", accountPrimaryDelta); PrismAsserts.assertModifications(accountPrimaryDelta, 1); PrismAsserts.assertPropertyReplace(accountPrimaryDelta, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, ActivationStatusType.DISABLED); - + ObjectDelta accountSecondaryDelta = accContextDefault.getSecondaryDelta(); PrismAsserts.assertModifications(accountSecondaryDelta, 2); - assertNotNull("No disableTimestamp delta in account secodary delta (default)", + assertNotNull("No disableTimestamp delta in account secodary delta (default)", accountSecondaryDelta.findPropertyDelta( new ItemPath(ShadowType.F_ACTIVATION, ActivationType.F_DISABLE_TIMESTAMP))); PrismAsserts.assertPropertyReplace(accountSecondaryDelta, SchemaConstants.PATH_ACTIVATION_DISABLE_REASON, SchemaConstants.MODEL_DISABLE_REASON_EXPLICIT); // the other modification is disable timestamp - + ModelProjectionContext accContextBlue = modelContext.findProjectionContext( new ResourceShadowDiscriminator(RESOURCE_DUMMY_BLUE_OID, ShadowKindType.ACCOUNT, null)); assertNotNull("Null model projection context (blue)", accContextBlue); - + assertEquals("Wrong policy decision (blue)", SynchronizationPolicyDecision.KEEP, accContextBlue.getSynchronizationPolicyDecision()); ObjectDelta accountPrimaryDeltaBlue = accContextBlue.getPrimaryDelta(); assertNotNull("No account primary delta (blue)", accountPrimaryDeltaBlue); PrismAsserts.assertModifications(accountPrimaryDeltaBlue, 1); PrismAsserts.assertPropertyReplace(accountPrimaryDeltaBlue, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, ActivationStatusType.DISABLED); - + ObjectDelta accountSecondaryDeltaBlue = accContextBlue.getSecondaryDelta(); PrismAsserts.assertModifications(accountSecondaryDeltaBlue, 2); - assertNotNull("No disableTimestamp delta in account secodary delta (blue)", + assertNotNull("No disableTimestamp delta in account secodary delta (blue)", accountSecondaryDeltaBlue.findPropertyDelta( new ItemPath(ShadowType.F_ACTIVATION, ActivationType.F_DISABLE_TIMESTAMP))); PrismAsserts.assertPropertyReplace(accountSecondaryDeltaBlue, SchemaConstants.PATH_ACTIVATION_DISABLE_REASON, 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 e627581a1c9..c5415170e82 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 @@ -42,7 +42,7 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestRaceConditions extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/contract"); @Override @@ -83,7 +83,7 @@ public void test100AssignRoles() throws Exception { assertUserJack(userJack); String accountJackOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); @@ -95,7 +95,7 @@ public void test100AssignRoles() throws Exception { // Check account in dummy resource assertDefaultDummyAccount("jack", "Jack Sparrow", true); } - + /** * Remove both roles at once, in different threads. */ @@ -139,5 +139,5 @@ private void deleteAssignment(PrismObject user, int index, Task task, throw new SystemException(t); } } - + } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestResources.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestResources.java index 63f6146d2af..d502dd69d25 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestResources.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestResources.java @@ -91,64 +91,64 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestResources extends AbstractConfiguredModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/contract"); private static final int MAX_RANDOM_SEQUENCE_ITERATIONS = 15; - + private static List> ants = new ArrayList>(); private static CarefulAnt descriptionAnt; private static String lastVersion; private static Random rnd = new Random(); - + protected DummyResource dummyResource; protected DummyResourceContoller dummyResourceCtl; protected PrismObject resourceDummy; - + protected DummyResource dummyResourceRed; protected DummyResourceContoller dummyResourceCtlRed; protected PrismObject resourceDummyRed; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + dummyResourceCtl = DummyResourceContoller.create(null); dummyResourceCtl.extendSchemaPirate(); dummyResource = dummyResourceCtl.getDummyResource(); dummyResourceCtl.addAttrDef(dummyResource.getAccountObjectClass(), DUMMY_ACCOUNT_ATTRIBUTE_SEA_NAME, String.class, false, false); - + // Add resource directly to repo to avoid any initialization resourceDummy = PrismTestUtil.parseObject(RESOURCE_DUMMY_FILE); PrismObject connectorDummy = findConnectorByTypeAndVersion(CONNECTOR_DUMMY_TYPE, CONNECTOR_DUMMY_VERSION, initResult); resourceDummy.asObjectable().getConnectorRef().setOid(connectorDummy.getOid()); repositoryService.addObject(resourceDummy, null, initResult); - + dummyResourceCtl.setResource(resourceDummy); - - + + dummyResourceCtlRed = DummyResourceContoller.create(RESOURCE_DUMMY_RED_NAME, resourceDummyRed); dummyResourceCtlRed.extendSchemaPirate(); dummyResourceRed = dummyResourceCtlRed.getDummyResource(); - + // Add resource directly to repo to avoid any initialization resourceDummyRed = PrismTestUtil.parseObject(RESOURCE_DUMMY_RED_FILE); resourceDummyRed.asObjectable().getConnectorRef().setOid(connectorDummy.getOid()); repositoryService.addObject(resourceDummyRed, null, initResult); - + dummyResourceCtlRed.setResource(resourceDummyRed); - + ResourceCarefulAntUtil.initAnts(ants, RESOURCE_DUMMY_FILE, prismContext); descriptionAnt = ants.get(0); InternalMonitor.reset(); InternalMonitor.setTrace(InternalOperationClasses.SHADOW_FETCH_OPERATIONS, true); InternalMonitor.setTrace(InternalOperationClasses.RESOURCE_SCHEMA_OPERATIONS, true); InternalsConfig.encryptionChecks = false; - + InternalMonitor.setTrace(InternalOperationClasses.PRISM_OBJECT_CLONES, true); } - + /** * MID-3424 */ @@ -161,7 +161,7 @@ public void test050GetResourceRaw() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + // precondition assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); @@ -169,33 +169,33 @@ public void test050GetResourceRaw() throws Exception { assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); rememberCounter(InternalCounters.PRISM_OBJECT_CLONE_COUNT); - + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createRaw()); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, options , task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("getObject result", result); - + display("Resource", resource); - + assertCounterIncrement(InternalCounters.PRISM_OBJECT_CLONE_COUNT, 1); - + assertResourceDummy(resource, false); - + assertNull("Schema sneaked in", ResourceTypeUtil.getResourceXsdSchema(resource)); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 1); } - + /** * MID-3424 */ @@ -208,7 +208,7 @@ public void test052GetResourceNoFetch() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + // precondition assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); @@ -216,35 +216,35 @@ public void test052GetResourceNoFetch() throws Exception { assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); rememberCounter(InternalCounters.PRISM_OBJECT_CLONE_COUNT); - + Collection> options = SelectorOptions.createCollection( GetOperationOptions.createNoFetch()); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, options, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("getObject result", result); - + display("Resource", resource); - + assertCounterIncrement(InternalCounters.PRISM_OBJECT_CLONE_COUNT, 1); - + assertResourceDummy(resource, false); - + assertNull("Schema sneaked in", ResourceTypeUtil.getResourceXsdSchema(resource)); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); } - + /** * MID-3424 */ @@ -257,7 +257,7 @@ public void test053GetResourceNoFetchReadOnly() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + // precondition assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); @@ -265,36 +265,36 @@ public void test053GetResourceNoFetchReadOnly() throws Exception { assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); rememberCounter(InternalCounters.PRISM_OBJECT_CLONE_COUNT); - + GetOperationOptions option = GetOperationOptions.createNoFetch(); option.setReadOnly(true); Collection> options = SelectorOptions.createCollection(option); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, options, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("getObject result", result); - + display("Resource", resource); - + assertCounterIncrement(InternalCounters.PRISM_OBJECT_CLONE_COUNT, 0); - + assertResourceDummy(resource, false); - + assertNull("Schema sneaked in", ResourceTypeUtil.getResourceXsdSchema(resource)); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); } - + /** * MID-3424 */ @@ -307,13 +307,13 @@ public void test100SearchResourcesNoFetch() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + // precondition assertSteadyResources(); rememberCounter(InternalCounters.PRISM_OBJECT_CLONE_COUNT); - + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createNoFetch()); - + // WHEN TestUtil.displayWhen(TEST_NAME); List> resources = modelService.searchObjects(ResourceType.class, null, options, task, result); @@ -323,25 +323,25 @@ public void test100SearchResourcesNoFetch() throws Exception { assertNotNull("null search return", resources); assertFalse("Empty search return", resources.isEmpty()); assertEquals("Unexpected number of resources found", 2, resources.size()); - + result.computeStatus(); TestUtil.assertSuccess("searchObjects result", result); - + assertCounterIncrement(InternalCounters.PRISM_OBJECT_CLONE_COUNT, 2); for (PrismObject resource: resources) { assertResource(resource, false); } - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); - + assertSteadyResources(); } - + /** * MID-3424 */ @@ -354,15 +354,15 @@ public void test102SearchResourcesNoFetchReadOnly() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + // precondition assertSteadyResources(); rememberCounter(InternalCounters.PRISM_OBJECT_CLONE_COUNT); - + GetOperationOptions option = GetOperationOptions.createNoFetch(); option.setReadOnly(true); Collection> options = SelectorOptions.createCollection(option); - + // WHEN TestUtil.displayWhen(TEST_NAME); List> resources = modelService.searchObjects(ResourceType.class, null, options, task, result); @@ -372,25 +372,25 @@ public void test102SearchResourcesNoFetchReadOnly() throws Exception { assertNotNull("null search return", resources); assertFalse("Empty search return", resources.isEmpty()); assertEquals("Unexpected number of resources found", 2, resources.size()); - + result.computeStatus(); TestUtil.assertSuccess("searchObjects result", result); - + assertCounterIncrement(InternalCounters.PRISM_OBJECT_CLONE_COUNT, 0); for (PrismObject resource: resources) { assertResource(resource, false); } - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); - + assertSteadyResources(); } - + /** * MID-3424 */ @@ -403,21 +403,21 @@ public void test105SearchResourcesIterativeNoFetch() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + // precondition assertSteadyResources(); rememberCounter(InternalCounters.PRISM_OBJECT_CLONE_COUNT); final List> resources = new ArrayList>(); - + ResultHandler handler = (resource, parentResult) -> { assertResource(resource, false); resources.add(resource); return true; }; - + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createNoFetch()); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.searchObjectsIterative(ResourceType.class, null, handler, options, task, result); @@ -429,18 +429,18 @@ public void test105SearchResourcesIterativeNoFetch() throws Exception { assertFalse("Empty search return", resources.isEmpty()); assertEquals("Unexpected number of resources found", 2, resources.size()); - + assertCounterIncrement(InternalCounters.PRISM_OBJECT_CLONE_COUNT, 2); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); - + assertSteadyResources(); } - + /** * MID-3424 */ @@ -453,23 +453,23 @@ public void test107SearchResourcesIterativeNoFetchReadOnly() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + // precondition assertSteadyResources(); rememberCounter(InternalCounters.PRISM_OBJECT_CLONE_COUNT); final List> resources = new ArrayList>(); - + ResultHandler handler = (resource, parentResult) -> { assertResource(resource, false); resources.add(resource); return true; }; - + GetOperationOptions option = GetOperationOptions.createNoFetch(); option.setReadOnly(true); Collection> options = SelectorOptions.createCollection(option); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.searchObjectsIterative(ResourceType.class, null, handler, options, task, result); @@ -481,18 +481,18 @@ public void test107SearchResourcesIterativeNoFetchReadOnly() throws Exception { assertFalse("Empty search return", resources.isEmpty()); assertEquals("Unexpected number of resources found", 2, resources.size()); - + assertCounterIncrement(InternalCounters.PRISM_OBJECT_CLONE_COUNT, 2); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); - + assertSteadyResources(); } - + @Test public void test110GetResourceDummy() throws Exception { final String TEST_NAME = "test110GetResourceDummy"; @@ -502,33 +502,33 @@ public void test110GetResourceDummy() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + rememberCounter(InternalCounters.PRISM_OBJECT_CLONE_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null , task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("getObject result", result); assertCounterIncrement(InternalCounters.PRISM_OBJECT_CLONE_COUNT, 4); - + assertResourceDummy(resource, true); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 1); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 1); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 1); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 1); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); - + IntegrationTestTools.displayXml("Initialized dummy resource", resource); - + assertEquals("Wrong dummy useless string", RESOURCE_DUMMY_USELESS_STRING, dummyResource.getUselessString()); } - + @Test public void test112GetResourceDummyReadOnly() throws Exception { final String TEST_NAME = "test112GetResourceDummyReadOnly"; @@ -538,36 +538,36 @@ public void test112GetResourceDummyReadOnly() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + rememberCounter(InternalCounters.PRISM_OBJECT_CLONE_COUNT); - + Collection> options = SelectorOptions.createCollection( GetOperationOptions.createReadOnly()); - + // WHEN TestUtil.displayWhen(TEST_NAME); - PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, + PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, options , task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("getObject result", result); assertCounterIncrement(InternalCounters.PRISM_OBJECT_CLONE_COUNT, 1); - + assertResourceDummy(resource, true); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); - + IntegrationTestTools.displayXml("Initialized dummy resource", resource); } - - + + @Test public void test120SearchResources() throws Exception { final String TEST_NAME = "test120SearchResources"; @@ -577,10 +577,10 @@ public void test120SearchResources() throws Exception { Task task = taskManager.createTaskInstance(TestResources.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + // precondition assertSteadyResources(); - + // WHEN TestUtil.displayWhen(TEST_NAME); List> resources = modelService.searchObjects(ResourceType.class, null, null, task, result); @@ -590,21 +590,21 @@ public void test120SearchResources() throws Exception { assertNotNull("null search return", resources); assertFalse("Empty search return", resources.isEmpty()); assertEquals("Unexpected number of resources found", 2, resources.size()); - + result.computeStatus(); TestUtil.assertSuccess("searchObjects result", result); for (PrismObject resource: resources) { assertResource(resource, true); } - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 1); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 1); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 1); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 1); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); } - + @Test public void test125SearchResourcesIterative() throws Exception { final String TEST_NAME = "test125SearchResourcesIterative"; @@ -614,18 +614,18 @@ public void test125SearchResourcesIterative() throws Exception { Task task = taskManager.createTaskInstance(TestResources.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + // precondition assertSteadyResources(); final List> resources = new ArrayList>(); - + ResultHandler handler = (resource, parentResult) -> { assertResource(resource, true); resources.add(resource); return true; }; - + // WHEN modelService.searchObjectsIterative(ResourceType.class, null, handler, null, task, result); @@ -635,47 +635,47 @@ public void test125SearchResourcesIterative() throws Exception { assertFalse("Empty search return", resources.isEmpty()); assertEquals("Unexpected number of resources found", 2, resources.size()); - + assertSteadyResources(); } - + private void assertResourceDummy(PrismObject resource, boolean expectSchema) { assertResource(resource, expectSchema); PrismContainer configurationContainer = resource.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); PrismContainerDefinition configurationContainerDefinition = configurationContainer.getDefinition(); assertDummyConfigurationContainerDefinition(configurationContainerDefinition, "from container"); - + PrismContainer configurationPropertiesContainer = configurationContainer.findContainer(SchemaConstants.CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_QNAME); assertNotNull("No container "+SchemaConstants.CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_QNAME, configurationPropertiesContainer); - - assertConfigurationPropertyDefinition(configurationPropertiesContainer, + + assertConfigurationPropertyDefinition(configurationPropertiesContainer, "uselessString", DOMUtil.XSD_STRING, 0, 1, "UI_INSTANCE_USELESS_STRING", "UI_INSTANCE_USELESS_STRING_HELP"); PrismContainerDefinition configurationPropertiesContainerDefinition = configurationContainerDefinition.findContainerDefinition(SchemaConstants.CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_QNAME); configurationPropertiesContainerDefinition = configurationPropertiesContainer.getDefinition(); assertNotNull("No container definition in "+configurationPropertiesContainer); - - assertConfigurationPropertyDefinition(configurationPropertiesContainerDefinition, + + assertConfigurationPropertyDefinition(configurationPropertiesContainerDefinition, "uselessString", DOMUtil.XSD_STRING, 0, 1, "UI_INSTANCE_USELESS_STRING", "UI_INSTANCE_USELESS_STRING_HELP"); - + PrismObjectDefinition objectDefinition = resource.getDefinition(); assertNotNull("No object definition in resource", objectDefinition); PrismContainerDefinition configurationContainerDefinitionFromObjectDefinition = objectDefinition.findContainerDefinition(ResourceType.F_CONNECTOR_CONFIGURATION); assertDummyConfigurationContainerDefinition(configurationContainerDefinitionFromObjectDefinition, "from object definition"); } - + private void assertDummyConfigurationContainerDefinition( PrismContainerDefinition configurationContainerDefinition, String desc) { display("Dummy configuration container definition "+desc, configurationContainerDefinition); PrismContainerDefinition configurationPropertiesContainerDefinition = configurationContainerDefinition.findContainerDefinition(SchemaConstants.CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_QNAME); assertNotNull("No container definition for "+SchemaConstants.CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_QNAME+" "+desc, configurationPropertiesContainerDefinition); - - assertConfigurationPropertyDefinition(configurationPropertiesContainerDefinition, + + assertConfigurationPropertyDefinition(configurationPropertiesContainerDefinition, "uselessString", DOMUtil.XSD_STRING, 0, 1, "UI_INSTANCE_USELESS_STRING", "UI_INSTANCE_USELESS_STRING_HELP"); - + } private void assertConfigurationPropertyDefinition(PrismContainerDefinition containerDefinition, @@ -711,12 +711,12 @@ private void assertResource(PrismObject resource, boolean expectSc display("Resource connector configuration def", configurationContainerDefinition); display("Resource connector configuration def complex type def", configurationContainerDefinition.getComplexTypeDefinition()); assertNotNull("Empty Resource connector configuration def", configurationContainer.isEmpty()); - assertEquals("Wrong compile-time class in Resource connector configuration in "+resource, ConnectorConfigurationType.class, + assertEquals("Wrong compile-time class in Resource connector configuration in "+resource, ConnectorConfigurationType.class, configurationContainer.getCompileTimeClass()); assertEquals("configurationContainer maxOccurs", 1, configurationContainerDefinition.getMaxOccurs()); - + resource.checkConsistence(true, true); - + Element schema = ResourceTypeUtil.getResourceXsdSchema(resource); if (expectSchema) { assertNotNull("no schema in "+resource, schema); @@ -734,25 +734,25 @@ public void test200GetResourceRawAfterSchema() throws Exception { Task task = taskManager.createTaskInstance(TestResources.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - + IntegrationTestTools.assertNoRepoCache(); - + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createRaw()); // WHEN PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, options , task, result); - + // THEN IntegrationTestTools.assertNoRepoCache(); SqlRepoTestUtil.assertVersionProgress(null, resource.getVersion()); lastVersion = resource.getVersion(); display("Initial version", lastVersion); - + result.computeStatus(); TestUtil.assertSuccess("getObject result", result); - + IntegrationTestTools.displayXml("Initialized dummy resource", resource); } - + /** * Red resource has an expression for uselessString configuration property. Check that. */ @@ -765,32 +765,32 @@ public void test210GetResourceDummyRed() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + rememberCounter(InternalCounters.PRISM_OBJECT_CLONE_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_RED_OID, null , task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertSuccess(result); assertCounterIncrement(InternalCounters.PRISM_OBJECT_CLONE_COUNT, 1); - + assertResourceDummy(resource, true); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); - + IntegrationTestTools.displayXml("Initialized dummy resource", resource); - + assertEquals("Wrong RED useless string", RESOURCE_DUMMY_RED_USELESS_STRING, dummyResourceRed.getUselessString()); } - + @Test public void test750GetResourceRaw() throws Exception { final String TEST_NAME = "test750GetResourceRaw"; @@ -800,7 +800,7 @@ public void test750GetResourceRaw() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + // precondition assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); @@ -808,32 +808,32 @@ public void test750GetResourceRaw() throws Exception { assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); rememberCounter(InternalCounters.PRISM_OBJECT_CLONE_COUNT); - + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createRaw()); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, options , task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("getObject result", result); - + display("Resource", resource); IntegrationTestTools.displayXml("Initialized dummy resource", resource); - + assertCounterIncrement(InternalCounters.PRISM_OBJECT_CLONE_COUNT, 1); - + assertResourceDummy(resource, true); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); } - + @Test public void test752GetResourceDummy() throws Exception { final String TEST_NAME = "test752GetResourceDummy"; @@ -843,98 +843,98 @@ public void test752GetResourceDummy() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + rememberCounter(InternalCounters.PRISM_OBJECT_CLONE_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null , task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); assertCounterIncrement(InternalCounters.PRISM_OBJECT_CLONE_COUNT, 1); - + assertResourceDummy(resource, true); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); - + IntegrationTestTools.displayXml("Initialized dummy resource", resource); } - + @Test public void test760ModifyConfigurationString() throws Exception { final String TEST_NAME = "test760ModifyConfigurationString"; displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta resourceDelta = createConfigurationPropertyDelta(IntegrationTestTools.RESOURCE_DUMMY_CONFIGURATION_USELESS_STRING_ELEMENT_NAME, "whatever wherever"); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(resourceDelta), null, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject resourceAfter = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, task, result); - PrismAsserts.assertPropertyValue(resourceAfter, + PrismAsserts.assertPropertyValue(resourceAfter, getConfigurationPropertyPath(IntegrationTestTools.RESOURCE_DUMMY_CONFIGURATION_USELESS_STRING_ELEMENT_NAME), "whatever wherever"); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 1); } - + @Test public void test761ModifyConfigurationStringRaw() throws Exception { final String TEST_NAME = "test761ModifyConfigurationStringRaw"; displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta resourceDelta = createConfigurationPropertyDelta(IntegrationTestTools.RESOURCE_DUMMY_CONFIGURATION_USELESS_STRING_ELEMENT_NAME, "whatever raw wherever"); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(resourceDelta), ModelExecuteOptions.createRaw(), task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject resourceAfter = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, task, result); - PrismAsserts.assertPropertyValue(resourceAfter, + PrismAsserts.assertPropertyValue(resourceAfter, getConfigurationPropertyPath(IntegrationTestTools.RESOURCE_DUMMY_CONFIGURATION_USELESS_STRING_ELEMENT_NAME), "whatever raw wherever"); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 1); } - + @Test public void test765ModifyConfigurationDiffExpressionRawPrismContextParse() throws Exception { - final String TEST_NAME = "test765ModifyConfigurationDiffExpressionRawPrismContextParse"; + final String TEST_NAME = "test765ModifyConfigurationDiffExpressionRawPrismContextParse"; modifyConfigurationDiffExpressionRaw(TEST_NAME, xml -> prismContext.parseObject(xml)); } - + /** * This is what GUI "Repository objects" page really does with XML. */ @Test public void test767ModifyConfigurationDiffExpressionRawValidatorParse() throws Exception { - final String TEST_NAME = "test767ModifyConfigurationDiffExpressionRawValidatorParse"; + final String TEST_NAME = "test767ModifyConfigurationDiffExpressionRawValidatorParse"; modifyConfigurationDiffExpressionRaw(TEST_NAME, xml -> { final Holder> objectHolder = new Holder<>(); EventHandler handler = new EventHandler() { @@ -964,58 +964,58 @@ public void handleGlobalError(OperationResult currentResult) { return objectHolder.getValue(); }); } - + public void modifyConfigurationDiffExpressionRaw(final String TEST_NAME, FailableFunction> parser) throws Exception { displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject resourceBefore = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, task, result); // just to improve readability resourceBefore.removeProperty(ObjectType.F_FETCH_RESULT); String serializedResource = prismContext.serializerFor(PrismContext.LANG_XML).serialize(resourceBefore); - String modifiedResourceXml = serializedResource.replace("whatever raw wherever", + String modifiedResourceXml = serializedResource.replace("whatever raw wherever", "useless"); display("New resource XML", modifiedResourceXml); - + PrismObject modifiedResource = parser.apply(modifiedResourceXml); display("New resource", modifiedResource); - + // just for fun String serializedModifiedResource = prismContext.serializerFor(PrismContext.LANG_XML).serialize(modifiedResource); assertNotNull(serializedModifiedResource); - + ObjectDelta diffDelta = resourceBefore.diff(modifiedResource, true, true); display("Diff delta", diffDelta); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(diffDelta), ModelExecuteOptions.createRaw(), task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + // Evaluate expression, re-apply configuration OperationResult testResult = modelService.testResource(RESOURCE_DUMMY_OID, task); TestUtil.assertSuccess("Dummy resource test", testResult); - + assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 1); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 1); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 1); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 1); - + PrismObject resourceAfter = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, task, result); display("Resource after", resourceAfter); - + assertEquals("Wrong default useless string", IntegrationTestTools.CONST_USELESS, dummyResource.getUselessString()); - - // TODO: strictly speaking, this should not be necessary. + + // TODO: strictly speaking, this should not be necessary. // But now the schema is re-parsed a bit more than is needed assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 1); } - + private ObjectDelta createConfigurationPropertyDelta(QName elementQName, String newValue) { ItemPath propPath = getConfigurationPropertyPath(elementQName); PrismPropertyDefinition propDef = new PrismPropertyDefinitionImpl<>(IntegrationTestTools.RESOURCE_DUMMY_CONFIGURATION_USELESS_STRING_ELEMENT_NAME, @@ -1025,12 +1025,12 @@ private ObjectDelta createConfigurationPropertyDelta(QName element display("Resource delta", resourceDelta); return resourceDelta; } - + private ItemPath getConfigurationPropertyPath(QName elementQName) { return new ItemPath(ResourceType.F_CONNECTOR_CONFIGURATION, SchemaConstants.ICF_CONFIGURATION_PROPERTIES, elementQName); } - + @Test public void test800GetResourceDummy() throws Exception { final String TEST_NAME = "test800GetResourceDummy"; @@ -1040,74 +1040,74 @@ public void test800GetResourceDummy() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); - + rememberCounter(InternalCounters.PRISM_OBJECT_CLONE_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null , task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); assertCounterIncrement(InternalCounters.PRISM_OBJECT_CLONE_COUNT, 1); - + assertResourceDummy(resource, true); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); - + IntegrationTestTools.displayXml("Initialized dummy resource", resource); } - + @Test public void test820SingleDescriptionModify() throws Exception { final String TEST_NAME = "test820SingleDescriptionModify"; displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + singleModify(descriptionAnt, -1, task, result); } - + @Test public void test840RadomModifySequence() throws Exception { final String TEST_NAME = "test840RadomModifySequence"; displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + for(int i=0; i <= MAX_RANDOM_SEQUENCE_ITERATIONS; i++) { singleRandomModify(i, task, result); } } - + private void singleRandomModify(int iteration, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { int i = rnd.nextInt(ants.size()); CarefulAnt ant = ants.get(i); singleModify(ant, iteration, task, result); } - + private void singleModify(CarefulAnt ant, int iteration, Task task, OperationResult result) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { // GIVEN ItemDelta itemDelta = ant.createDelta(iteration); ObjectDelta objectDelta = ObjectDelta.createModifyDelta(RESOURCE_DUMMY_OID, itemDelta, ResourceType.class, prismContext); Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); - + IntegrationTestTools.assertNoRepoCache(); - + ModelExecuteOptions options = ModelExecuteOptions.createRaw(); // WHEN modelService.executeChanges(deltas, options , task, result); - + // THEN IntegrationTestTools.assertNoRepoCache(); Collection> getOptions = SelectorOptions.createCollection(GetOperationOptions.createRaw()); @@ -1115,15 +1115,15 @@ private void singleModify(CarefulAnt ant, int iteration, Task task SqlRepoTestUtil.assertVersionProgress(lastVersion, resourceAfter.getVersion()); lastVersion = resourceAfter.getVersion(); display("Version", lastVersion); - + Element xsdSchema = ResourceTypeUtil.getResourceXsdSchema(resourceAfter); if (xsdSchema != null) { String targetNamespace = xsdSchema.getAttribute("targetNamespace"); assertNotNull("No targetNamespace in schema after application of "+objectDelta, targetNamespace); } - + IntegrationTestTools.assertNoRepoCache(); - + ant.assertModification(resourceAfter, iteration); } 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 d8ed5e905b5..e6e80300324 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 @@ -37,20 +37,20 @@ /** * 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"}) @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. */ @@ -61,24 +61,24 @@ public void test001GetObject() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_SCHEMALESS_OID, null, task, result); - + // THEN assertNotNull("Null resource returned", resource); } - + @Test public void test002TestConnection() throws Exception { final String TEST_NAME = "test002TestConnection"; TestUtil.displayTestTitle(this, TEST_NAME); Task task = createTask(TEST_NAME); - + // WHEN OperationResult testResult = modelService.testResource(RESOURCE_DUMMY_SCHEMALESS_OID, task); - + // THEN display("Test result", testResult); OperationResult connectorResult = assertSingleConnectorTestResult(testResult); @@ -90,5 +90,5 @@ public void test002TestConnection() throws Exception { 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 3d5c9fde0f7..3c467ee367e 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 @@ -50,7 +50,7 @@ public class TestScriptHooks extends AbstractInitializedModelIntegrationTest { private static final File TEST_DIR = new File("src/test/resources/scripthooks"); - + 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"; @@ -58,29 +58,29 @@ public class TestScriptHooks extends AbstractInitializedModelIntegrationTest { 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"); - + protected DummyResource dummyResourceHook; protected DummyResourceContoller dummyResourceCtlHook; protected ResourceType resourceDummyHookType; protected PrismObject resourceDummyHook; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + 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); - + importObjectFromFile(GENERIC_BLACK_PEARL_FILE); importObjectFromFile(ORG_TOP_FILE); } @@ -100,31 +100,31 @@ public void test100JackAssignHookAccount() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestScriptHooks.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); dummyAuditService.clear(); StaticHookRecorder.reset(); - + // WHEN assignAccount(USER_JACK_OID, RESOURCE_DUMMY_HOOK_OID, null, task, result); - + // THEN assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); String accountOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Shadow (repo)", accountShadow); assertAccountShadowRepo(accountShadow, accountOid, ACCOUNT_JACK_DUMMY_USERNAME, resourceDummyHookType); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("Shadow (model)", accountModel); assertAccountShadowModel(accountModel, accountOid, ACCOUNT_JACK_DUMMY_USERNAME, resourceDummyHookType); - + // Check account in dummy resource assertDummyAccount(RESOURCE_DUMMY_HOOK_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); @@ -133,7 +133,7 @@ public void test100JackAssignHookAccount() throws Exception { StaticHookRecorder.assertInvocationCount("foo", 5); StaticHookRecorder.assertInvocationCount("bar", 5); StaticHookRecorder.assertInvocationCount("bar-user", 1); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -145,7 +145,7 @@ public void test100JackAssignHookAccount() throws Exception { dummyAuditService.assertTarget(USER_JACK_OID); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test110JackAddOrganization() throws Exception { final String TEST_NAME = "test110JackAddOrganization"; @@ -154,38 +154,38 @@ public void test110JackAddOrganization() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestScriptHooks.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); dummyAuditService.clear(); StaticHookRecorder.reset(); - + // WHEN modifyUserAdd(USER_JACK_OID, UserType.F_ORGANIZATION, task, result, createPolyString("Pirate Brethren")); - + // THEN assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); String accountOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Shadow (repo)", accountShadow); assertAccountShadowRepo(accountShadow, accountOid, ACCOUNT_JACK_DUMMY_USERNAME, resourceDummyHookType); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("Shadow (model)", accountModel); assertAccountShadowModel(accountModel, accountOid, ACCOUNT_JACK_DUMMY_USERNAME, resourceDummyHookType); - + // Check account in dummy resource assertDummyAccount(RESOURCE_DUMMY_HOOK_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); - + PrismObject brethrenOrg = searchObjectByName(OrgType.class, "Pirate Brethren", task, result); assertNotNull("Brethren org was not created", brethrenOrg); display("Brethren org", brethrenOrg); - + assertAssignedOrg(userJack, brethrenOrg); display("StaticHookRecorder", StaticHookRecorder.dump()); @@ -206,5 +206,5 @@ public void test110JackAddOrganization() throws Exception { // dummyAuditService.asserHasDelta(3,ChangeType.MODIFY, UserType.class); // dummyAuditService.assertExecutionSuccess(); } - + } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestStrangeCases.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestStrangeCases.java index 43f9801a90d..a50d5a72026 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestStrangeCases.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestStrangeCases.java @@ -77,35 +77,35 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestStrangeCases extends AbstractInitializedModelIntegrationTest { - + private static final File TEST_DIR = new File("src/test/resources/strange"); - + private static final File USER_DEGHOULASH_FILE = new File(TEST_DIR, "user-deghoulash.xml"); private static final String USER_DEGHOULASH_OID = "c0c010c0-d34d-b33f-f00d-1d11dd11dd11"; private static final String USER_DEGHOULASH_NAME = "deghoulash"; protected static final File USER_TEMPLATE_STRANGE_FILE = new File(TEST_DIR, "user-template-strange.xml"); protected static final String USER_TEMPLATE_STRANGE_OID = "830060c0-87f4-11e7-9a48-57789b5d92c7"; - + private static final String RESOURCE_DUMMY_CIRCUS_NAME = "circus"; private static final File RESOURCE_DUMMY_CIRCUS_FILE = new File(TEST_DIR, "resource-dummy-circus.xml"); private static final String RESOURCE_DUMMY_CIRCUS_OID = "65d73d14-bafb-11e6-9de3-ff46daf6e769"; - + private static final File ROLE_IDIOT_FILE = new File(TEST_DIR, "role-idiot.xml"); private static final String ROLE_IDIOT_OID = "12345678-d34d-b33f-f00d-555555550001"; - + private static final File ROLE_IDIOT_ASSIGNMENT_FILE = new File(TEST_DIR, "role-idiot-assignment.xml"); private static final String ROLE_IDIOT_ASSIGNMENT_OID = "12345678-d34d-b33f-f00d-5a5555550001"; private static final File ROLE_STUPID_FILE = new File(TEST_DIR, "role-stupid.xml"); private static final String ROLE_STUPID_OID = "12345678-d34d-b33f-f00d-555555550002"; - + private static final File ROLE_STUPID_ASSIGNMENT_FILE = new File(TEST_DIR, "role-stupid-assignment.xml"); private static final String ROLE_STUPID_ASSIGNMENT_OID = "12345678-d34d-b33f-f00d-5a5555550002"; - + private static final File ROLE_BAD_CONSTRUCTION_RESOURCE_REF_FILE = new File(TEST_DIR, "role-bad-construction-resource-ref.xml"); private static final String ROLE_BAD_CONSTRUCTION_RESOURCE_REF_OID = "54084f2c-eba0-11e5-8278-03ea5d7058d9"; - + private static final File ROLE_META_BAD_CONSTRUCTION_RESOURCE_REF_FILE = new File(TEST_DIR, "role-meta-bad-construction-resource-ref.xml"); private static final String ROLE_META_BAD_CONSTRUCTION_RESOURCE_REF_OID = "90b931ae-eba8-11e5-977a-b73ba58cf18b"; @@ -114,52 +114,52 @@ public class TestStrangeCases extends AbstractInitializedModelIntegrationTest { private static final File ROLE_RECURSION_FILE = new File(TEST_DIR, "role-recursion.xml"); private static final String ROLE_RECURSION_OID = "12345678-d34d-b33f-f00d-555555550003"; - + private static final File ROLE_RECURSION_ASSIGNMENT_FILE = new File(TEST_DIR, "role-recursion-assignment.xml"); private static final String ROLE_RECURSION_ASSIGNMENT_OID = "12345678-d34d-b33f-f00d-5a5555550003"; private static final String NON_EXISTENT_ACCOUNT_OID = "f000f000-f000-f000-f000-f000f000f000"; - + private static final String RESOURCE_NONEXISTENT_OID = "00000000-f000-f000-f000-f000f000f000";; - private static final XMLGregorianCalendar USER_DEGHOULASH_FUNERAL_TIMESTAMP = + private static final XMLGregorianCalendar USER_DEGHOULASH_FUNERAL_TIMESTAMP = XmlTypeConverter.createXMLGregorianCalendar(1771, 1, 2, 11, 22, 33); - + private static final File TREASURE_ISLAND_FILE = new File(TEST_DIR, "treasure-island.txt"); private static String treasureIsland; - + private String accountGuybrushOid; private String accountJackOid; private String accountJackRedOid; - + public TestStrangeCases() throws JAXBException { super(); } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + initDummyResource(RESOURCE_DUMMY_CIRCUS_NAME, RESOURCE_DUMMY_CIRCUS_FILE, RESOURCE_DUMMY_CIRCUS_OID, initTask, initResult); - + getDummyResourceController(RESOURCE_DUMMY_RED_NAME).addAccount(ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood", "Monkey Island"); - + repoAddObjectFromFile(ACCOUNT_GUYBRUSH_DUMMY_RED_FILE, initResult); - + treasureIsland = IOUtils.toString(new FileInputStream(TREASURE_ISLAND_FILE)).replace("\r\n", "\n"); // for Windows compatibility - + addObject(ROLE_IDIOT_FILE, initTask, initResult); addObject(ROLE_STUPID_FILE, initTask, initResult); addObject(ROLE_IDIOT_ASSIGNMENT_FILE, initTask, initResult); addObject(ROLE_RECURSION_FILE, initTask, initResult); addObject(ROLE_BAD_CONSTRUCTION_RESOURCE_REF_FILE, initTask, initResult); addObject(ROLE_META_BAD_CONSTRUCTION_RESOURCE_REF_FILE, initTask, initResult); - + repoAddObjectFromFile(USER_TEMPLATE_STRANGE_FILE, initResult); - + setDefaultObjectTemplate(UserType.COMPLEX_TYPE, USER_TEMPLATE_STRANGE_OID, initResult); // DebugUtil.setDetailedDebugDump(true); @@ -179,29 +179,29 @@ public void test050AddRoleRecursionAssignment() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - + try { // WHEN addObject(ROLE_RECURSION_ASSIGNMENT_FILE, task, result); - + assertNotReached(); } catch (PolicyViolationException e) { // This is expected display("Expected exception", e); } - + // THEN assertFailure(result); - + assertNoObject(RoleType.class, ROLE_RECURSION_ASSIGNMENT_OID); } - + /** * Stupid: see Idiot * Idiot: see Stupid - * + * * In this case the assignment loop is broken after few attempts. - * + * * MID-3652 */ @Test @@ -214,17 +214,17 @@ public void test060AddRoleStupidAssignment() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - + // WHEN addObject(ROLE_STUPID_ASSIGNMENT_FILE, task, result); - + // THEN assertSuccess(result); - + PrismObject role = getObject(RoleType.class, ROLE_STUPID_ASSIGNMENT_OID); assertObject(role); } - + @Test public void test100ModifyUserGuybrushAddAccountDummyRedNoAttributesConflict() throws Exception { final String TEST_NAME = "test100ModifyUserGuybrushAddAccountDummyRedNoAttributesConflict"; @@ -234,31 +234,31 @@ public void test100ModifyUserGuybrushAddAccountDummyRedNoAttributesConflict() th Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + PrismObject account = PrismTestUtil.parseObject(ACCOUNT_GUYBRUSH_DUMMY_RED_FILE); // Remove the attributes. This will allow outbound mapping to take place instead. account.removeContainer(ShadowType.F_ATTRIBUTES); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_GUYBRUSH_OID, prismContext); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account); ReferenceDelta accountDelta = ReferenceDelta.createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); userDelta.addModification(accountDelta); Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); - + dummyAuditService.clear(); - + try { - + // WHEN modelService.executeChanges(deltas, null, task, getCheckingProgressListenerCollection(), result); - + AssertJUnit.fail("Unexpected executeChanges success"); } catch (ObjectAlreadyExistsException e) { // This is expected display("Expected exception", e); } - + // Check accountRef PrismObject userGuybrush = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); UserType userGuybrushType = userGuybrush.asObjectable(); @@ -269,22 +269,22 @@ public void test100ModifyUserGuybrushAddAccountDummyRedNoAttributesConflict() th 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); assertDummyAccountShadowRepo(accountShadow, accountOid, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood"); - + // Check account in dummy resource assertDefaultDummyAccount(ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood", true); - + result.computeStatus(); display("executeChanges result", result); TestUtil.assertFailure("executeChanges result", result); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -293,7 +293,7 @@ public void test100ModifyUserGuybrushAddAccountDummyRedNoAttributesConflict() th Collection> auditExecution0Deltas = dummyAuditService.getExecutionDeltas(0); assertEquals("Wrong number of execution deltas", 0, auditExecution0Deltas.size()); dummyAuditService.assertExecutionOutcome(OperationResultStatus.FATAL_ERROR); - + } @Test @@ -306,38 +306,38 @@ public void test180DeleteHalfAssignmentFromUser() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - + PrismObject userOtis = createUser("otis", "Otis"); fillinUserAssignmentAccountConstruction(userOtis, RESOURCE_DUMMY_OID); - + display("Half-assigned user", userOtis); - + // Remember the assignment so we know what to remove AssignmentType assignmentType = userOtis.asObjectable().getAssignment().iterator().next(); - + // Add to repo to avoid processing of the assignment String userOtisOid = repositoryService.addObject(userOtis, null, result); - - ObjectDelta userDelta = ObjectDelta.createModificationDeleteContainer(UserType.class, + + ObjectDelta userDelta = ObjectDelta.createModificationDeleteContainer(UserType.class, userOtisOid, UserType.F_ASSIGNMENT, prismContext, assignmentType.asPrismContainerValue().clone()); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, getCheckingProgressListenerCollection(), result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - + PrismObject userOtisAfter = getUser(userOtisOid); assertNotNull("Otis is gone!", userOtisAfter); // Check accountRef assertUserNoAccountRefs(userOtisAfter); - + // Check if dummy resource account is gone assertNoDummyAccount("otis"); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -347,7 +347,7 @@ public void test180DeleteHalfAssignmentFromUser() throws Exception { dummyAuditService.assertHasDelta(ChangeType.MODIFY, UserType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test190DeleteHalfAssignedUser() throws Exception { String TEST_NAME = "test190DeleteHalfAssignedUser"; @@ -358,37 +358,37 @@ public void test190DeleteHalfAssignedUser() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - + PrismObject userNavigator = createUser("navigator", "Head of the Navigator"); fillinUserAssignmentAccountConstruction(userNavigator, RESOURCE_DUMMY_OID); - + display("Half-assigned user", userNavigator); - + // Add to repo to avoid processing of the assignment String userNavigatorOid = repositoryService.addObject(userNavigator, null, result); - + ObjectDelta userDelta = ObjectDelta.createDeleteDelta(UserType.class, userNavigatorOid, prismContext); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, getCheckingProgressListenerCollection(), result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - + try { getUser(userNavigatorOid); AssertJUnit.fail("navigator is still alive!"); } catch (ObjectNotFoundException ex) { // This is OK } - + // Check if dummy resource account is gone assertNoDummyAccount("navigator"); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -398,7 +398,7 @@ public void test190DeleteHalfAssignedUser() throws Exception { dummyAuditService.assertHasDelta(ChangeType.DELETE, UserType.class); dummyAuditService.assertExecutionSuccess(); } - + /** * User with linkRef that points nowhere. * MID-2134 @@ -413,26 +413,26 @@ public void test200ModifyUserJackBrokenAccountRefAndPolyString() throws Exceptio OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - + addBrokenAccountRef(USER_JACK_OID); // Make sure that the polystring does not have correct norm value PolyString fullNamePolyString = new PolyString("Magnificent Captain Jack Sparrow", null); - + // WHEN displayWhen(TEST_NAME); - modifyUserReplace(USER_JACK_OID, UserType.F_FULL_NAME, task, result, + modifyUserReplace(USER_JACK_OID, UserType.F_FULL_NAME, task, result, fullNamePolyString); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result, 2); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Magnificent Captain Jack Sparrow"); assertAccounts(USER_JACK_OID, 0); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -442,7 +442,7 @@ public void test200ModifyUserJackBrokenAccountRefAndPolyString() throws Exceptio dummyAuditService.assertHasDelta(ChangeType.MODIFY, UserType.class); dummyAuditService.assertExecutionOutcome(OperationResultStatus.HANDLED_ERROR); } - + /** * Not much to see here. Just making sure that add account goes smoothly * after previous test. Also preparing setup for following tests. @@ -458,24 +458,24 @@ public void test210ModifyUserAddAccount() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + // WHEN displayWhen(TEST_NAME); modifyUserAddAccount(USER_JACK_OID, ACCOUNT_JACK_DUMMY_FILE, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + // Check accountRef PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); accountJackOid = getSingleLinkOid(userJack); - + // Check account in dummy resource assertDefaultDummyAccount("jack", "Jack Sparrow", true); } - + /** * Not much to see here. Just preparing setup for following tests. * The account is simply added, not assigned. This makes it quite fragile. @@ -490,26 +490,26 @@ public void test212ModifyUserAddAccountRed() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + // WHEN displayWhen(TEST_NAME); modifyUserAddAccount(USER_JACK_OID, ACCOUNT_JACK_DUMMY_RED_FILE, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + // Check accountRef PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); assertLinks(userJack, 2); accountJackRedOid = getLinkRefOid(userJack, RESOURCE_DUMMY_RED_OID); assertNotNull(accountJackRedOid); - + assertDefaultDummyAccount("jack", "Jack Sparrow", true); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, "jack", "Magnificent Captain Jack Sparrow", true); } - + /** * Cause schema violation on the account during a provisioning operation. This should fail * the operation, but other operations should proceed and the account should definitelly NOT @@ -525,31 +525,31 @@ public void test212ModifyUserJackBrokenSchemaViolationPolyString() throws Except Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + getDummyResource().setModifyBreakMode(BreakMode.SCHEMA); - + // WHEN displayWhen(TEST_NAME); - modifyUserReplace(USER_JACK_OID, UserType.F_FULL_NAME, task, result, + modifyUserReplace(USER_JACK_OID, UserType.F_FULL_NAME, task, result, new PolyString("Cpt. Jack Sparrow", null)); - + // THEN displayThen(TEST_NAME); result.computeStatus(); display("Result", result); TestUtil.assertPartialError(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Cpt. Jack Sparrow"); - + assertLinks(userJack, 2); String accountJackRedOidAfter = getLinkRefOid(userJack, RESOURCE_DUMMY_RED_OID); assertNotNull(accountJackRedOidAfter); - + // The change was not propagated here because of schema violation error assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); - + // The change should be propagated here normally assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Cpt. Jack Sparrow", true); } @@ -569,35 +569,35 @@ public void test214ModifyUserJackBrokenPassword() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + getDummyResource().setModifyBreakMode(BreakMode.SCHEMA); - + // WHEN displayWhen(TEST_NAME); modifyUserChangePassword(USER_JACK_OID, "whereStheRUM", task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); display("Result", result); TestUtil.assertPartialError(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Cpt. Jack Sparrow"); assertEncryptedUserPassword(userJack, "whereStheRUM"); - + assertLinks(userJack, 2); String accountJackRedOidAfter = getLinkRefOid(userJack, RESOURCE_DUMMY_RED_OID); assertNotNull(accountJackRedOidAfter); - + // The change was not propagated here because of schema violation error assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); - + // The change should be propagated here normally assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Cpt. Jack Sparrow", true); } - + /** * Cause modification that will be mapped to the account and that will cause * conflict (AlreadyExistsException). Make sure that midpoint does not end up @@ -613,40 +613,40 @@ public void test220ModifyUserJackBrokenConflict() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + getDummyResource().setModifyBreakMode(BreakMode.CONFLICT); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, UserType.F_LOCALITY, task, result, createPolyString("High seas")); - + // THEN displayThen(TEST_NAME); result.computeStatus(); display("Result", result); TestUtil.assertPartialError(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); PrismAsserts.assertPropertyValue(userJack, UserType.F_LOCALITY, createPolyString("High seas")); - + assertLinks(userJack, 2); String accountJackRedOidAfter = getLinkRefOid(userJack, RESOURCE_DUMMY_RED_OID); assertNotNull(accountJackRedOidAfter); - + // The change was not propagated here because of schema violation error assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Caribbean"); - + // The change should be propagated here normally assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Cpt. Jack Sparrow", true); - assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "High seas"); - + getDummyResource().setModifyBreakMode(BreakMode.NONE); } - + /** * User modification triggers PolicyViolationException being thrown from the * user template mapping. Make sure that there is a user friendly message. @@ -662,25 +662,25 @@ public void test230ModifyUserJackUserTemplatePolicyViolation() throws Exception OperationResult result = task.getResult(); getDummyResource().setModifyBreakMode(BreakMode.NONE); dummyAuditService.clear(); - + try { // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, UserType.F_COST_CENTER, task, result, "broke"); - + assertNotReached(); - + } catch (ExpressionEvaluationException e) { // THEN displayThen(TEST_NAME); - + display("Exception (expected)", e); assertExceptionUserFriendly(e, "We do not serve your kind here"); - + display("Result", result); assertFailure(result); } - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); @@ -688,12 +688,12 @@ public void test230ModifyUserJackUserTemplatePolicyViolation() throws Exception // Lets test various extension magic and border cases now. This is maybe quite hight in the architecture for // this test, but we want to make sure that none of the underlying components will screw the things up. - + @Test public void test300ExtensionSanity() throws Exception { final String TEST_NAME = "test300ExtensionSanity"; displayTestTitle(TEST_NAME); - + PrismObjectDefinition userDef = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); PrismContainerDefinition extensionContainerDef = userDef.findContainerDefinition(UserType.F_EXTENSION); PrismAsserts.assertPropertyDefinition(extensionContainerDef, PIRACY_SHIP, DOMUtil.XSD_STRING, 1, 1); @@ -709,7 +709,7 @@ public void test300ExtensionSanity() throws Exception { PrismAsserts.assertPropertyDefinition(extensionContainerDef, PIRACY_FUNERAL_TIMESTAMP, DOMUtil.XSD_DATETIME, 0, 1); PrismAsserts.assertIndexed(extensionContainerDef, PIRACY_FUNERAL_TIMESTAMP, true); } - + @Test public void test301AddUserDeGhoulash() throws Exception { final String TEST_NAME = "test301AddUserDeGhoulash"; @@ -720,23 +720,23 @@ public void test301AddUserDeGhoulash() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - + PrismObject user = PrismTestUtil.parseObject(USER_DEGHOULASH_FILE); ObjectDelta userAddDelta = ObjectDelta.createAddDelta(user); Collection> deltas = MiscSchemaUtil.createCollection(userAddDelta); - + // WHEN modelService.executeChanges(deltas, null, task, getCheckingProgressListenerCollection(), result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - + PrismObject userDeGhoulash = getUser(USER_DEGHOULASH_OID); display("User after change execution", userDeGhoulash); assertUser(userDeGhoulash, USER_DEGHOULASH_OID, "deghoulash", "Charles DeGhoulash", "Charles", "DeGhoulash"); assertAccounts(USER_DEGHOULASH_OID, 0); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -745,10 +745,10 @@ public void test301AddUserDeGhoulash() throws Exception { dummyAuditService.assertExecutionDeltas(1); dummyAuditService.assertHasDelta(ChangeType.ADD, UserType.class); dummyAuditService.assertExecutionSuccess(); - + assertBasicDeGhoulashExtension(userDeGhoulash); } - + @Test public void test310SearchDeGhoulashByShip() throws Exception { final String TEST_NAME = "test310SearchDeGhoulashByShip"; @@ -788,14 +788,14 @@ public void test316SearchDeGhoulashByBadLuck28561() throws Exception { final String TEST_NAME = "test316SearchDeGhoulashByBadLuck28561"; searchDeGhoulash(TEST_NAME, PIRACY_BAD_LUCK, 28561L); } - + @Test public void test317SearchDeGhoulashByFuneralTimestamp() throws Exception { final String TEST_NAME = "test317SearchDeGhoulashByFuneralTimestamp"; searchDeGhoulash(TEST_NAME, PIRACY_FUNERAL_TIMESTAMP, USER_DEGHOULASH_FUNERAL_TIMESTAMP); } - + private void searchDeGhoulash(String testName, QName propName, T propValue) throws Exception { TestUtil.displayTestTitle(this, testName); @@ -803,14 +803,14 @@ private void searchDeGhoulash(String testName, QName propName, T propValue) Task task = taskManager.createTaskInstance(TestStrangeCases.class.getName() + "." + testName); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + // Simple query ObjectQuery query = QueryBuilder.queryFor(UserType.class, prismContext) .item(UserType.F_EXTENSION, propName).eq(propValue) .build(); // WHEN, THEN searchDeGhoulash(testName, query, task, result); - + // Complex query, combine with a name. This results in join down in the database query = QueryBuilder.queryFor(UserType.class, prismContext) .item(UserType.F_NAME).eq(USER_DEGHOULASH_NAME) @@ -819,11 +819,11 @@ private void searchDeGhoulash(String testName, QName propName, T propValue) // WHEN, THEN searchDeGhoulash(testName, query, task, result); } - + private void searchDeGhoulash(String testName, ObjectQuery query, Task task, OperationResult result) throws Exception { // WHEN List> users = modelService.searchObjects(UserType.class, query, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); @@ -832,10 +832,10 @@ private void searchDeGhoulash(String testName, ObjectQuery query, Task task, PrismObject userDeGhoulash = users.iterator().next(); display("Found user", userDeGhoulash); assertUser(userDeGhoulash, USER_DEGHOULASH_OID, "deghoulash", "Charles DeGhoulash", "Charles", "DeGhoulash"); - + assertBasicDeGhoulashExtension(userDeGhoulash); } - + private void assertBasicDeGhoulashExtension(PrismObject userDeGhoulash) { assertExtension(userDeGhoulash, PIRACY_SHIP, "The Undead Pot"); assertExtension(userDeGhoulash, PIRACY_TALES, treasureIsland); @@ -844,7 +844,7 @@ private void assertBasicDeGhoulashExtension(PrismObject userDeGhoulash assertExtension(userDeGhoulash, PIRACY_BAD_LUCK, 13L, 169L, 2197L, 28561L, 371293L, 131313131313131313L); assertExtension(userDeGhoulash, PIRACY_FUNERAL_TIMESTAMP, USER_DEGHOULASH_FUNERAL_TIMESTAMP); } - + /** * Idiot and Stupid are cyclic roles. However, the assignment should proceed because now that's allowed. */ @@ -865,7 +865,7 @@ public void test330AssignDeGhoulashIdiot() throws Exception { // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userDeGhoulash = getUser(USER_DEGHOULASH_OID); display("User after change execution", userDeGhoulash); assertUser(userDeGhoulash, USER_DEGHOULASH_OID, "deghoulash", "Charles DeGhoulash", "Charles", "DeGhoulash"); @@ -886,32 +886,32 @@ public void test332AssignDeGhoulashRecursion() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - + try { // WHEN assignRole(USER_DEGHOULASH_OID, ROLE_RECURSION_OID, task, result); - + assertNotReached(); } catch (PolicyViolationException e) { // This is expected display("Expected exception", e); } - + // THEN assertFailure(result); - + PrismObject userDeGhoulash = getUser(USER_DEGHOULASH_OID); display("User after change execution", userDeGhoulash); assertUser(userDeGhoulash, USER_DEGHOULASH_OID, "deghoulash", "Charles DeGhoulash", "Charles", "DeGhoulash"); assertAssignedRoles(userDeGhoulash, ROLE_IDIOT_OID); } - + /** * Stupid: see Idiot * Idiot: see Stupid - * + * * In this case the assignment loop is broken after few attempts. - * + * * MID-3652 */ @Test @@ -924,25 +924,25 @@ public void test334AssignDeGhoulashStupidAssignment() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - + // WHEN assignRole(USER_DEGHOULASH_OID, ROLE_STUPID_ASSIGNMENT_OID, task, result); - + // THEN assertSuccess(result); - + PrismObject userDeGhoulash = getUser(USER_DEGHOULASH_OID); display("User after change execution", userDeGhoulash); assertUser(userDeGhoulash, USER_DEGHOULASH_OID, "deghoulash", "Charles DeGhoulash", "Charles", "DeGhoulash"); assertAssignedRoles(userDeGhoulash, ROLE_IDIOT_OID, ROLE_STUPID_ASSIGNMENT_OID); } - + /** * Stupid: see Idiot * Idiot: see Stupid - * + * * In this case the assignment loop is broken after few attempts. - * + * * MID-3652 */ @Test @@ -955,19 +955,19 @@ public void test336UnassignDeGhoulashStupidAssignment() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - + // WHEN unassignRole(USER_DEGHOULASH_OID, ROLE_STUPID_ASSIGNMENT_OID, task, result); - + // THEN assertSuccess(result); - + PrismObject userDeGhoulash = getUser(USER_DEGHOULASH_OID); display("User after change execution", userDeGhoulash); assertUser(userDeGhoulash, USER_DEGHOULASH_OID, "deghoulash", "Charles DeGhoulash", "Charles", "DeGhoulash"); assertAssignedRoles(userDeGhoulash, ROLE_IDIOT_OID); } - + @Test public void test340AssignDeGhoulashConstructionNonExistentResource() throws Exception { final String TEST_NAME = "test340AssignDeGhoulashConstructionNonExistentResource"; @@ -978,23 +978,23 @@ public void test340AssignDeGhoulashConstructionNonExistentResource() throws Exce OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - + // WHEN // We have loose referential consistency. Even if the target resource is not present // the assignment should be added. The error is indicated in the result. assignAccount(USER_DEGHOULASH_OID, RESOURCE_NONEXISTENT_OID, null, task, result); - + // THEN result.computeStatus(); display("Result", result); TestUtil.assertFailure(result); - + PrismObject userDeGhoulash = getUser(USER_DEGHOULASH_OID); display("User after change execution", userDeGhoulash); assertUser(userDeGhoulash, USER_DEGHOULASH_OID, "deghoulash", "Charles DeGhoulash", "Charles", "DeGhoulash"); assertAssignments(userDeGhoulash, 2); } - + @Test public void test349UnAssignDeGhoulashConstructionNonExistentResource() throws Exception { final String TEST_NAME = "test349UnAssignDeGhoulashConstructionNonExistentResource"; @@ -1005,22 +1005,22 @@ public void test349UnAssignDeGhoulashConstructionNonExistentResource() throws Ex OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - + // WHEN unassignAccount(USER_DEGHOULASH_OID, RESOURCE_NONEXISTENT_OID, null, task, result); - + // THEN result.computeStatus(); display("Result", result); TestUtil.assertFailure(result); - + PrismObject userDeGhoulash = getUser(USER_DEGHOULASH_OID); display("User after change execution", userDeGhoulash); assertUser(userDeGhoulash, USER_DEGHOULASH_OID, "deghoulash", "Charles DeGhoulash", "Charles", "DeGhoulash"); assertAssignments(userDeGhoulash, 1); assertAssignedRoles(userDeGhoulash, ROLE_IDIOT_OID); } - + @Test public void test350AssignDeGhoulashRoleBadConstructionResourceRef() throws Exception { final String TEST_NAME = "test350AssignDeGhoulashRoleBadConstructionResourceRef"; @@ -1031,10 +1031,10 @@ public void test350AssignDeGhoulashRoleBadConstructionResourceRef() throws Excep OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - + // WHEN assignRole(USER_DEGHOULASH_OID, ROLE_BAD_CONSTRUCTION_RESOURCE_REF_OID, task, result); - + // THEN result.computeStatus(); display("result", result); @@ -1043,13 +1043,13 @@ public void test350AssignDeGhoulashRoleBadConstructionResourceRef() throws Excep TestUtil.assertMessageContains(message, "role:"+ROLE_BAD_CONSTRUCTION_RESOURCE_REF_OID); TestUtil.assertMessageContains(message, "Bad resourceRef in construction"); TestUtil.assertMessageContains(message, "this-oid-does-not-exist"); - + PrismObject userDeGhoulash = getUser(USER_DEGHOULASH_OID); display("User after change execution", userDeGhoulash); assertUser(userDeGhoulash, USER_DEGHOULASH_OID, "deghoulash", "Charles DeGhoulash", "Charles", "DeGhoulash"); assertAssignedRoles(userDeGhoulash, ROLE_BAD_CONSTRUCTION_RESOURCE_REF_OID, ROLE_IDIOT_OID); } - + @Test public void test351UnAssignDeGhoulashRoleBadConstructionResourceRef() throws Exception { final String TEST_NAME = "test351UnAssignDeGhoulashRoleBadConstructionResourceRef"; @@ -1060,10 +1060,10 @@ public void test351UnAssignDeGhoulashRoleBadConstructionResourceRef() throws Exc OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - + // WHEN unassignRole(USER_DEGHOULASH_OID, ROLE_BAD_CONSTRUCTION_RESOURCE_REF_OID, task, result); - + // THEN result.computeStatus(); display("result", result); @@ -1072,7 +1072,7 @@ public void test351UnAssignDeGhoulashRoleBadConstructionResourceRef() throws Exc TestUtil.assertMessageContains(message, "role:"+ROLE_BAD_CONSTRUCTION_RESOURCE_REF_OID); TestUtil.assertMessageContains(message, "Bad resourceRef in construction"); TestUtil.assertMessageContains(message, "this-oid-does-not-exist"); - + PrismObject userDeGhoulash = getUser(USER_DEGHOULASH_OID); display("User after change execution", userDeGhoulash); assertUser(userDeGhoulash, USER_DEGHOULASH_OID, "deghoulash", "Charles DeGhoulash", "Charles", "DeGhoulash"); @@ -1092,7 +1092,7 @@ public void test360AddRoleTargetBadConstructionResourceRef() throws Exception { // WHEN addObject(ROLE_TARGET_BAD_CONSTRUCTION_RESOURCE_REF_FILE, task, result); - + // THEN result.computeStatus(); display("result", result); @@ -1100,7 +1100,7 @@ public void test360AddRoleTargetBadConstructionResourceRef() throws Exception { String message = result.getMessage(); TestUtil.assertMessageContains(message, "role:"+ROLE_META_BAD_CONSTRUCTION_RESOURCE_REF_OID); TestUtil.assertMessageContains(message, "Bad resourceRef in construction metarole"); - TestUtil.assertMessageContains(message, "this-oid-does-not-exist"); + TestUtil.assertMessageContains(message, "this-oid-does-not-exist"); } @Test @@ -1113,19 +1113,19 @@ public void test400ImportJackMockTask() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - + // WHEN displayWhen(TEST_NAME); importObjectFromFile(TASK_MOCK_JACK_FILE); - + // THEN displayThen(TEST_NAME); result.computeStatus(); assertSuccess(result); - + waitForTaskFinish(TASK_MOCK_JACK_OID, false); } - + @Test public void test401ListTasks() throws Exception { final String TEST_NAME = "test401ListTasks"; @@ -1136,15 +1136,15 @@ public void test401ListTasks() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - + // WHEN displayWhen(TEST_NAME); List> objects = modelService.searchObjects(TaskType.class, null, null, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + display("Tasks", objects); assertEquals("Unexpected number of tasks", 1, objects.size()); boolean found = false; @@ -1154,7 +1154,7 @@ public void test401ListTasks() throws Exception { } } assertTrue("Mock task not found (model)", found); - + // ClusterStatusInformation clusterStatusInformation = taskManager.getRunningTasksClusterwide(result); // display("Cluster status", clusterStatusInformation); // TaskInfo jackTaskInfo = null; @@ -1165,12 +1165,12 @@ public void test401ListTasks() throws Exception { // } // } // assertNotNull("Mock task not found (taskManager)", jackTaskInfo); - + // Make sure that the tasks still runs waitForTaskFinish(TASK_MOCK_JACK_OID, false); - + } - + /** * Delete user jack. See that Jack's tasks are still there (although they may be broken) */ @@ -1184,18 +1184,18 @@ public void test410DeleteJack() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - + // WHEN displayWhen(TEST_NAME); deleteObject(UserType.class, USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + // Make sure the user is gone assertNoObject(UserType.class, USER_JACK_OID, task, result); - + List> objects = modelService.searchObjects(TaskType.class, null, null, task, result); display("Tasks", objects); assertEquals("Unexpected number of tastsk", 1, objects.size()); @@ -1207,7 +1207,7 @@ public void test410DeleteJack() throws Exception { } assertNotNull("Mock task not found (model)", jackTask); display("Jack's task (model)", jackTask); - + // ClusterStatusInformation clusterStatusInformation = taskManager.getRunningTasksClusterwide(result); // display("Cluster status", clusterStatusInformation); // TaskInfo jackTaskInfo = null; @@ -1219,11 +1219,11 @@ public void test410DeleteJack() throws Exception { // } // assertNotNull("Mock task not found (taskManager)", jackTaskInfo); // display("Jack's task (taskManager)", jackTaskInfo); - + // TODO: check task status - + } - + @Test public void test500EnumerationExtension() throws Exception { final String TEST_NAME = "test500EnumerationExtension"; @@ -1231,45 +1231,45 @@ public void test500EnumerationExtension() throws Exception { PrismObjectDefinition userDef = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); PrismPropertyDefinition markDef = userDef.findPropertyDefinition(new ItemPath(UserType.F_EXTENSION, PIRACY_MARK)); - + // WHEN - TestUtil.assertSetEquals("Wrong allowedValues in mark", MiscUtil.getValuesFromDisplayableValues(markDef.getAllowedValues()), + TestUtil.assertSetEquals("Wrong allowedValues in mark", MiscUtil.getValuesFromDisplayableValues(markDef.getAllowedValues()), "pegLeg","noEye","hook","tatoo","scar","bravery"); - + for (DisplayableValue disp: markDef.getAllowedValues()) { if (disp.getValue().equals("pegLeg")) { assertEquals("Wrong pegLeg label", "Peg Leg", disp.getLabel()); } } } - + @Test public void test502EnumerationStoreGood() throws Exception { final String TEST_NAME = "test502EnumerationStoreGood"; displayTestTitle(TEST_NAME); // GIVEN - + PrismObjectDefinition userDef = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); PrismPropertyDefinition markDef = userDef.findPropertyDefinition(new ItemPath(UserType.F_EXTENSION, PIRACY_MARK)); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // WHEN - modifyObjectReplaceProperty(UserType.class, USER_GUYBRUSH_OID, new ItemPath(UserType.F_EXTENSION, PIRACY_MARK), + modifyObjectReplaceProperty(UserType.class, USER_GUYBRUSH_OID, new ItemPath(UserType.F_EXTENSION, PIRACY_MARK), task, result, "bravery"); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject user = getUser(USER_GUYBRUSH_OID); PrismProperty markProp = user.findProperty(new ItemPath(UserType.F_EXTENSION, PIRACY_MARK)); assertEquals("Bad mark", "bravery", markProp.getRealValue()); } - + /** * Guybrush has stored mark "bravery". Change schema so this value becomes illegal. * They try to read it. @@ -1295,20 +1295,20 @@ public void test510EnumerationGetBad() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // WHEN PrismObject user = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismProperty markProp = user.findProperty(new ItemPath(UserType.F_EXTENSION, PIRACY_MARK)); assertEquals("Bad mark", null, markProp.getRealValue()); ((Collection) markDef.getAllowedValues()).add(braveryValue); // because of the following test } - + /** * Store value in extension/ship. Then remove extension/ship definition from the schema. * The next read should NOT fail, because of the 'tolerate raw data' mode. @@ -1319,20 +1319,20 @@ public void test520ShipReadBadTolerateRawData() throws Exception { displayTestTitle(TEST_NAME); // GIVEN - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - - modifyObjectReplaceProperty(UserType.class, USER_GUYBRUSH_OID, new ItemPath(UserType.F_EXTENSION, PIRACY_SHIP), + + modifyObjectReplaceProperty(UserType.class, USER_GUYBRUSH_OID, new ItemPath(UserType.F_EXTENSION, PIRACY_SHIP), task, result, "The Pink Lady"); assertSuccess(result); changeDefinition(PIRACY_SHIP, PIRACY_SHIP_BROKEN); - + // WHEN modelService.getObject(UserType.class, USER_GUYBRUSH_OID, SelectorOptions.createCollection(createTolerateRawData()), task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); @@ -1422,14 +1422,14 @@ public void test550AssignCircus() throws Exception { displayTestTitle(TEST_NAME); // GIVEN - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + try { // WHEN assignAccount(USER_GUYBRUSH_OID, RESOURCE_DUMMY_CIRCUS_OID, null, task, result); - + assertNotReached(); } catch (PolicyViolationException e) { // THEN @@ -1437,9 +1437,9 @@ public void test550AssignCircus() throws Exception { result.computeStatus(); TestUtil.assertFailure(result); } - + } - + @Test public void test600AddUserGuybrushAssignAccount() throws Exception { final String TEST_NAME="test600AddUserGuybrushAssignAccount"; @@ -1448,38 +1448,38 @@ public void test600AddUserGuybrushAssignAccount() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_GUYBRUSH_OID, RESOURCE_DUMMY_OID, null, true); deltas.add(accountAssignmentUserDelta); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, getCheckingProgressListenerCollection(), result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after change execution", userAfter); accountGuybrushOid = getSingleLinkOid(userAfter); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountGuybrushOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountGuybrushOid, USER_GUYBRUSH_USERNAME); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountGuybrushOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountGuybrushOid, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); - + // Check account in dummy resource assertDefaultDummyAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true); } - + /** * Set attribute that is not in the schema directly into dummy resource. * Get that account. Make sure that the operations does not die. @@ -1492,27 +1492,27 @@ public void test610GetAccountGuybrushRogueAttribute() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + getDummyResource().setEnforceSchema(false); DummyAccount dummyAccount = getDummyAccount(null, USER_GUYBRUSH_USERNAME); dummyAccount.addAttributeValues("rogue", "habakuk"); getDummyResource().setEnforceSchema(true); - + // WHEN displayWhen(TEST_NAME); PrismObject shadow = modelService.getObject(ShadowType.class, accountGuybrushOid, null, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + display("Shadow after", shadow); assertDummyAccountShadowModel(shadow, accountGuybrushOid, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); - + assertDummyAccountAttribute(null, USER_GUYBRUSH_USERNAME, "rogue", "habakuk"); } - + private void assertExtension(PrismObject object, QName propName, T... expectedValues) { PrismContainer extensionContainer = object.findContainer(ObjectType.F_EXTENSION); assertNotNull("No extension container in "+object, extensionContainer); @@ -1521,16 +1521,16 @@ private void assertExtension(PrismObject object, QN PrismAsserts.assertPropertyValues("Values of extension property "+propName, extensionProperty.getValues(), expectedValues); } - /** - * Break the user in the repo by inserting accountRef that points nowhere. + /** + * Break the user in the repo by inserting accountRef that points nowhere. */ private void addBrokenAccountRef(String userOid) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { OperationResult result = new OperationResult(TestStrangeCases.class.getName() + ".addBrokenAccountRef"); - - Collection modifications = ReferenceDelta.createModificationAddCollection(UserType.class, + + Collection modifications = ReferenceDelta.createModificationAddCollection(UserType.class, UserType.F_LINK_REF, prismContext, NON_EXISTENT_ACCOUNT_OID); repositoryService.modifyObject(UserType.class, userOid, modifications , result); - + assertSuccess(result); } 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 932e32a11b3..bdcc17b244b 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 @@ -57,15 +57,15 @@ @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"; - + private static String accountOid; private static PrismObjectDefinition accountDefinition; - + @Test public void test100ModifyUserAddAccount() throws Exception { TestUtil.displayTestTitle(this, "test100ModifyUserAddAccount"); @@ -74,30 +74,30 @@ public void test100ModifyUserAddAccount() throws Exception { Task task = taskManager.createTaskInstance(TestTolerantAttributes.class.getName() + ".test100ModifyUserAddAccount"); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - + PrismObject account = PrismTestUtil.parseObject(new File(ACCOUNT_JACK_DUMMY_BLACK_FILENAME)); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_JACK_OID, prismContext); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account); ReferenceDelta accountDelta = ReferenceDelta.createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); userDelta.addModification(accountDelta); Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); - + getDummyResource().purgeScriptHistory(); dummyAuditService.clear(); dummyTransport.clearMessages(); notificationManager.setDisabled(false); XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); - + // Check accountRef PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); assertUserJack(userJack); @@ -109,23 +109,23 @@ public void test100ModifyUserAddAccount() throws Exception { 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)); assertEnableTimestampShadow(accountShadow, startTime, endTime); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertAccountShadowModel(accountModel, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); - + accountDefinition = accountModel.getDefinition(); - + // Check account in dummy resource assertAccount(userJack, RESOURCE_DUMMY_BLACK_OID); - + } - + @Test public void test101modifyAddAttributesIntolerantPattern() throws Exception{ TestUtil.displayTestTitle(this, "test101modifyAddAttributesIntolerantPattern"); @@ -134,17 +134,17 @@ public void test101modifyAddAttributesIntolerantPattern() throws Exception{ Task task = taskManager.createTaskInstance(TestTolerantAttributes.class.getName() + ".test101modifyAddAttributesIntolerantPattern"); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_JACK_OID, prismContext); PropertyDelta propertyDelta = PropertyDelta.createModificationAddProperty(new ItemPath(UserType.F_DESCRIPTION), getUserDefinition().findPropertyDefinition(UserType.F_DESCRIPTION), "This value will be not added"); 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); @@ -156,24 +156,24 @@ public void test101modifyAddAttributesIntolerantPattern() throws Exception{ 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", null); } - + @Test public void test102modifyAddAttributeTolerantPattern() throws Exception{ TestUtil.displayTestTitle(this, "test102modifyAddAttributeTolerantPattern"); @@ -182,17 +182,17 @@ public void test102modifyAddAttributeTolerantPattern() throws Exception{ Task task = taskManager.createTaskInstance(TestTolerantAttributes.class.getName() + ".test102modifyAddAttributeTolerantPattern"); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_JACK_OID, prismContext); PropertyDelta propertyDelta = PropertyDelta.createModificationAddProperty(new ItemPath(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); @@ -204,24 +204,24 @@ public void test102modifyAddAttributeTolerantPattern() throws Exception{ 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{ TestUtil.displayTestTitle(this, "test103modifyReplaceAttributeIntolerant"); @@ -230,17 +230,17 @@ public void test103modifyReplaceAttributeIntolerant() throws Exception{ Task task = taskManager.createTaskInstance(TestTolerantAttributes.class.getName() + ".test103modifyReplaceAttributeIntolerant"); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_JACK_OID, prismContext); PropertyDelta propertyDelta = PropertyDelta.createModificationReplaceProperty(new ItemPath(UserType.F_EMPLOYEE_NUMBER), getUserDefinition(), "gossip-thiIsNotOk"); 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); @@ -252,23 +252,23 @@ public void test103modifyReplaceAttributeIntolerant() throws Exception{ 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{ TestUtil.displayTestTitle(this, "test104modifyReplaceAttributeTolerantPattern"); @@ -277,18 +277,18 @@ public void test104modifyReplaceAttributeTolerantPattern() throws Exception{ Task task = taskManager.createTaskInstance(TestTolerantAttributes.class.getName() + ".test104modifyReplaceAttributeTolerantPattern"); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, USER_JACK_OID, prismContext); ItemPath drinkItemPath = new ItemPath(new QName(getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME).getNamespace(), "drink")); PropertyDelta propertyDelta = PropertyDelta.createModificationReplaceProperty(new ItemPath(UserType.F_EMPLOYEE_NUMBER), getUserDefinition(), "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); @@ -300,18 +300,18 @@ public void test104modifyReplaceAttributeTolerantPattern() throws Exception{ 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"); @@ -325,15 +325,15 @@ public void test105modifyAddNonTolerantAttribute() throws Exception{ Task task = taskManager.createTaskInstance(TestTolerantAttributes.class.getName() + ".test105modifyAddNonTolerantAttribute"); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(ShadowType.class, accountOid, prismContext); - + ItemPath drinkItemPath = new ItemPath(ShadowType.F_ATTRIBUTES, new QName(RESOURCE_DUMMY_BLACK_NAMESPACE, "drink")); assertNotNull("null definition for drink attribute ", accountDefinition.findPropertyDefinition(drinkItemPath)); PropertyDelta propertyDelta = PropertyDelta.createModificationAddProperty(drinkItemPath, accountDefinition.findPropertyDefinition(drinkItemPath), "This should be ignored"); userDelta.addModification(propertyDelta); Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); - + try{ modelService.executeChanges(deltas, ModelExecuteOptions.createReconcile(), task, result); fail("Expected Policy violation exception, because non-tolerant attribute is modified, but haven't got one."); @@ -342,6 +342,6 @@ public void test105modifyAddNonTolerantAttribute() throws Exception{ } } - - + + } 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 a4030cdba53..cfe1ad9d4c1 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 @@ -50,20 +50,20 @@ public class TestTriggerTask extends AbstractInitializedModelIntegrationTest { private static final XMLGregorianCalendar LONG_LONG_TIME_AGO = XmlTypeConverter.createXMLGregorianCalendar(1111, 1, 1, 12, 00, 00); private MockTriggerHandler testTriggerHandler; - + private XMLGregorianCalendar drakeValidFrom; private XMLGregorianCalendar drakeValidTo; - + @Autowired(required=true) private TriggerHandlerRegistry triggerHandlerRegistry; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { // TODO Auto-generated method stub super.initSystem(initTask, initResult); - + testTriggerHandler = new MockTriggerHandler(); - + triggerHandlerRegistry.register(MockTriggerHandler.HANDLER_URI, testTriggerHandler); } @@ -75,32 +75,32 @@ public void test100ImportScannerTask() throws Exception { // GIVEN Task task = createTask(TestTriggerTask.class.getName() + "." + TEST_NAME); 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); - + XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); - + /// WHEN TestUtil.displayWhen(TEST_NAME); importObjectFromFile(TASK_TRIGGER_SCANNER_FILE); - + waitForTaskStart(TASK_TRIGGER_SCANNER_OID, false); waitForTaskFinish(TASK_TRIGGER_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); XMLGregorianCalendar endCal = clock.currentTimeXMLGregorianCalendar(); assertLastRecomputeTimestamp(TASK_TRIGGER_SCANNER_OID, startCal, endCal); - + assertNotNull("Trigger was not called", testTriggerHandler.getLastObject()); assertEquals("Trigger was called incorrect number of times", 1, testTriggerHandler.getInvocationCount()); assertNoTrigger(UserType.class, USER_JACK_OID); - + assertLastRecomputeTimestamp(TASK_TRIGGER_SCANNER_OID, startCal, endCal); } - + @Test public void test105NoTrigger() throws Exception { final String TEST_NAME = "test105NoTrigger"; @@ -110,16 +110,16 @@ public void test105NoTrigger() throws Exception { Task task = createTask(TestTriggerTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); testTriggerHandler.reset(); - + XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); - + /// WHEN TestUtil.displayWhen(TEST_NAME); waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); - + // THEN XMLGregorianCalendar endCal = clock.currentTimeXMLGregorianCalendar(); @@ -128,7 +128,7 @@ public void test105NoTrigger() throws Exception { assertLastRecomputeTimestamp(TASK_TRIGGER_SCANNER_OID, startCal, endCal); } - + @Test public void test110TriggerCalledAgain() throws Exception { final String TEST_NAME = "test110TriggerCalledAgain"; @@ -138,18 +138,18 @@ public void test110TriggerCalledAgain() throws Exception { Task task = createTask(TestTriggerTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); testTriggerHandler.reset(); - + XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); - + addTrigger(USER_JACK_OID, startCal, MockTriggerHandler.HANDLER_URI); - + /// WHEN TestUtil.displayWhen(TEST_NAME); waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); - + // THEN XMLGregorianCalendar endCal = clock.currentTimeXMLGregorianCalendar(); @@ -205,16 +205,16 @@ public void test150NoTriggerAgain() throws Exception { Task task = createTask(TestTriggerTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); testTriggerHandler.reset(); - + XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); - + /// WHEN TestUtil.displayWhen(TEST_NAME); waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); - + // THEN XMLGregorianCalendar endCal = clock.currentTimeXMLGregorianCalendar(); 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 ffd30977321..7f297aa93d6 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 @@ -80,24 +80,24 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestUserTemplate extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/object-template"); - + protected static final File ROLE_RASTAMAN_FILE = new File(TEST_DIR, "role-rastaman.xml"); protected static final String ROLE_RASTAMAN_OID = "81ac6b8c-225c-11e6-ab0f-87a169c85cca"; - + protected static final File ROLE_AUTOMATIC_FILE = new File(TEST_DIR, "role-automatic.xml"); protected static final String ROLE_AUTOMATIC_OID = "8fdb56d8-e3f3-11e6-8be9-cb9862ab7c04"; - + protected static final File ROLE_AUTOCRATIC_FILE = new File(TEST_DIR, "role-autocratic.xml"); protected static final String ROLE_AUTOCRATIC_OID = "4a678382-e3f4-11e6-8c3d-cfd3dba8168f"; - + protected static final File ROLE_AUTODIDACTIC_FILE = new File(TEST_DIR, "role-autodidactic.xml"); protected static final String ROLE_AUTODIDACTIC_OID = "a4f941dc-e3f4-11e6-8eba-9fe432784017"; - + protected static final File ROLE_AUTOGRAPHIC_FILE = new File(TEST_DIR, "role-autographic.xml"); protected static final String ROLE_AUTOGRAPHIC_OID = "be835a70-e3f4-11e6-82cb-9b47ebe57b11"; - + protected static final File USER_TEMPLATE_MAROONED_FILE = new File(TEST_DIR, "user-template-marooned.xml"); protected static final String USER_TEMPLATE_MAROONED_OID = "766215e8-5f1e-11e6-94bb-c3b21af53235"; @@ -110,44 +110,44 @@ public class TestUserTemplate extends AbstractInitializedModelIntegrationTest { private static final int NUMBER_OF_IMPORTED_ROLES = 5; private static String jackEmployeeNumber; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + repoAddObjectFromFile(ROLE_RASTAMAN_FILE, initResult); repoAddObjectFromFile(ROLE_AUTOMATIC_FILE, initResult); repoAddObjectFromFile(ROLE_AUTOCRATIC_FILE, initResult); repoAddObjectFromFile(ROLE_AUTODIDACTIC_FILE, initResult); repoAddObjectFromFile(ROLE_AUTOGRAPHIC_FILE, initResult); - + repoAddObjectFromFile(USER_TEMPLATE_MAROONED_FILE, initResult); setDefaultObjectTemplate(UserType.COMPLEX_TYPE, USER_TEMPLATE_COMPLEX_OID, initResult); setDefaultObjectTemplate(UserType.COMPLEX_TYPE, EMPLOYEE_TYPE_MAROONED, USER_TEMPLATE_MAROONED_OID, initResult); } - + protected int getNumberOfRoles() { return super.getNumberOfRoles() + NUMBER_OF_IMPORTED_ROLES; } - + @Test public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); PrismObject systemConfiguration = modelService.getObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + display("System config", systemConfiguration); assertNotNull("no system config", systemConfiguration); List defaultObjectPolicyConfiguration = systemConfiguration.asObjectable().getDefaultObjectPolicyConfiguration(); @@ -155,10 +155,10 @@ public void test000Sanity() throws Exception { assertEquals("Wrong object policy size", 3, defaultObjectPolicyConfiguration.size()); // third is the conflict resolution rule assertObjectTemplate(defaultObjectPolicyConfiguration, UserType.COMPLEX_TYPE, null, USER_TEMPLATE_COMPLEX_OID); assertObjectTemplate(defaultObjectPolicyConfiguration, UserType.COMPLEX_TYPE, EMPLOYEE_TYPE_MAROONED, USER_TEMPLATE_MAROONED_OID); - + assertRoles(getNumberOfRoles()); } - + private void assertObjectTemplate(List defaultObjectPolicyConfigurations, QName objectType, String subtype, String userTemplateOid) { for (ObjectPolicyConfigurationType objectPolicyConfiguration: defaultObjectPolicyConfigurations) { @@ -179,33 +179,33 @@ public void test100ModifyUserGivenName() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + Collection> deltas = new ArrayList>(); ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_JACK_OID, UserType.F_GIVEN_NAME, prismContext, new PolyString("Jackie")); deltas.add(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); assertUserJack(userJack, "Jackie Sparrow", "Jackie", "Sparrow"); PrismAsserts.assertPropertyValue(userJack, UserType.F_DESCRIPTION, "Where's the rum?"); - + assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertAssignedNoRole(userJack); assertAssignments(userJack, 1); - + result.computeStatus(); TestUtil.assertSuccess(result); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - + PrismAsserts.assertPropertyValue(userJack, UserType.F_ADDITIONAL_NAME, PrismTestUtil.createPolyString("Jackie")); XMLGregorianCalendar now = clock.currentTimeXMLGregorianCalendar(); XMLGregorianCalendar monthLater = XmlTypeConverter.addDuration(now, XmlTypeConverter.createDuration("P1M")); @@ -213,8 +213,8 @@ public void test100ModifyUserGivenName() throws Exception { // original value of 0 should be gone now, because the corresponding item in user template is marked as non-tolerant PrismAsserts.assertPropertyValue(userJack.findContainer(UserType.F_EXTENSION), PIRACY_BAD_LUCK, 123L, 456L); - - // timezone mapping is normal-strength. The source (locality) has not changed. + + // timezone mapping is normal-strength. The source (locality) has not changed. // The mapping should not be activated (MID-3040) PrismAsserts.assertNoItem(userJack, UserType.F_TIMEZONE); } @@ -227,14 +227,14 @@ public void test101ModifyUserEmployeeTypePirate() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + Collection> deltas = new ArrayList>(); ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_JACK_OID, UserType.F_EMPLOYEE_TYPE, prismContext, "PIRATE"); // Make sure that the user has no employeeNumber so it will be generated by userTemplate userDelta.addModificationReplaceProperty(UserType.F_EMPLOYEE_NUMBER); deltas.add(userDelta); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); @@ -243,32 +243,32 @@ public void test101ModifyUserEmployeeTypePirate() throws Exception { displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + 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?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertAssignedRole(userJack, ROLE_PIRATE_OID); assertAssignments(userJack, 2); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 2, userJackType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - + assertEquals("Wrong costCenter", "G001", userJackType.getCostCenter()); - + jackEmployeeNumber = userJackType.getEmployeeNumber(); assertEquals("Unexpected length of employeeNumber, maybe it was not generated?", GenerateExpressionEvaluator.DEFAULT_LENGTH, jackEmployeeNumber.length()); - + XMLGregorianCalendar now = clock.currentTimeXMLGregorianCalendar(); XMLGregorianCalendar monthLater = XmlTypeConverter.addDuration(now, XmlTypeConverter.createDuration("P1M")); assertTrigger(userJack, RecomputeTriggerHandler.HANDLER_URI, monthLater, 100000L); } - + /** * 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. @@ -281,37 +281,37 @@ public void test102ModifyUserEmployeeTypeBuccaneer() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + Collection> deltas = new ArrayList>(); ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_JACK_OID, UserType.F_EMPLOYEE_TYPE, prismContext, "BUCCANEER"); deltas.add(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + 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?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertAssignedRole(userJack, ROLE_PIRATE_OID); assertAssignments(userJack, 2); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 2, userJackType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - + assertEquals("Wrong costCenter", "B666", userJackType.getCostCenter()); assertEquals("Employee number has changed", jackEmployeeNumber, userJackType.getEmployeeNumber()); } - + @Test public void test103ModifyUserEmployeeTypeBartender() throws Exception { final String TEST_NAME = "test103ModifyUserEmployeeTypeBartender"; @@ -320,37 +320,37 @@ public void test103ModifyUserEmployeeTypeBartender() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + Collection> deltas = new ArrayList>(); ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_JACK_OID, UserType.F_EMPLOYEE_TYPE, prismContext, "BARTENDER"); deltas.add(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + 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?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertNotAssignedRole(userJack, ROLE_PIRATE_OID); assertAssignments(userJack, 1); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - + assertEquals("Wrong costCenter", "G001", userJackType.getCostCenter()); assertEquals("Employee number has changed", jackEmployeeNumber, userJackType.getEmployeeNumber()); } - + /** * Cost center has two mappings. Strong mapping should not be applied here as the condition is false. * The weak mapping should be overridden by the change we try here. @@ -363,37 +363,37 @@ public void test104ModifyUserCostCenter() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + Collection> deltas = new ArrayList>(); ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_JACK_OID, UserType.F_COST_CENTER, prismContext, "X000"); deltas.add(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + 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?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertNotAssignedRole(userJack, ROLE_PIRATE_OID); assertAssignments(userJack, 1); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - + assertEquals("Wrong costCenter", "X000", userJackType.getCostCenter()); assertEquals("Employee number has changed", jackEmployeeNumber, userJackType.getEmployeeNumber()); } - + @Test public void test105ModifyUserTelephoneNumber() throws Exception { final String TEST_NAME = "test105ModifyUserTelephoneNumber"; @@ -402,39 +402,39 @@ public void test105ModifyUserTelephoneNumber() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + Collection> deltas = new ArrayList>(); ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_JACK_OID, UserType.F_TELEPHONE_NUMBER, prismContext, "1234"); deltas.add(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + 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?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertNotAssignedRole(userJack, ROLE_PIRATE_OID); assertAssignments(userJack, 1); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - + assertEquals("Wrong costCenter", "X000", userJackType.getCostCenter()); assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1234", userJackType.getTelephoneNumber()); assertNull("Unexpected title: " + userJackType.getTitle(), userJackType.getTitle()); } - + @Test public void test106ModifyUserRemoveTelephoneNumber() throws Exception { final String TEST_NAME = "test106ModifyUserRemoveTelephoneNumber"; @@ -443,39 +443,39 @@ public void test106ModifyUserRemoveTelephoneNumber() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + Collection> deltas = new ArrayList>(); ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_JACK_OID, UserType.F_TELEPHONE_NUMBER, prismContext); deltas.add(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + 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?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertNotAssignedRole(userJack, ROLE_PIRATE_OID); assertAssignments(userJack, 1); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - + assertEquals("Wrong costCenter", "X000", userJackType.getCostCenter()); assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertNull("Unexpected telephone number: " + userJackType.getTelephoneNumber(), userJackType.getTelephoneNumber()); assertEquals("Wrong Title", PrismTestUtil.createPolyStringType("Happy Pirate"), userJackType.getTitle()); } - + @Test public void test107ModifyUserSetTelephoneNumber() throws Exception { final String TEST_NAME = "test107ModifyUserSetTelephoneNumber"; @@ -484,34 +484,34 @@ public void test107ModifyUserSetTelephoneNumber() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_TELEPHONE_NUMBER, task, result, "1 222 3456789"); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + 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?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertNotAssignedRole(userJack, ROLE_PIRATE_OID); assertAssignments(userJack, 1); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - + 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()); } - + /** * Reconcile the user. Check that nothing really changes. * MID-3040 @@ -524,38 +524,38 @@ public void test120ReconcileUser() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN reconcileUser(USER_JACK_OID, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + 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?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertNotAssignedRole(userJack, ROLE_PIRATE_OID); assertAssignments(userJack, 1); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - + 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()); - - // timezone mapping is normal-strength. This is reconciliation. + + // timezone mapping is normal-strength. This is reconciliation. // The mapping should not be activated (MID-3040) PrismAsserts.assertNoItem(userJack, UserType.F_TIMEZONE); } - + /** * MID-3040 */ @@ -567,37 +567,37 @@ public void test121ModifyUserReplaceLocality() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_LOCALITY, task, result, PrismTestUtil.createPolyString("Tortuga")); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + 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?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertNotAssignedRole(userJack, ROLE_PIRATE_OID); assertAssignments(userJack, 1); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - + PrismAsserts.assertEqualsPolyString("Wrong locality", "Tortuga", userJackType.getLocality()); assertEquals("Wrong timezone", "High Seas/Tortuga", userJackType.getTimezone()); - + 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()); } - + @Test public void test140AssignDummy() throws Exception { final String TEST_NAME = "test140AssignDummy"; @@ -606,33 +606,33 @@ public void test140AssignDummy() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignAccount(USER_JACK_OID, RESOURCE_DUMMY_OID, null, task, result); // THEN 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?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertAssignedAccount(userJack, RESOURCE_DUMMY_OID); assertNotAssignedRole(userJack, ROLE_PIRATE_OID); assertAssignments(userJack, 2); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 2, userJackType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - + 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.assertExtensionProperty(userJack, PIRACY_COLORS, "none"); } - + @Test public void test149UnAssignDummy() throws Exception { final String TEST_NAME = "test149UnAssignDummy"; @@ -641,25 +641,25 @@ public void test149UnAssignDummy() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignAccount(USER_JACK_OID, RESOURCE_DUMMY_OID, null, task, result); // THEN 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?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertNotAssignedRole(userJack, ROLE_PIRATE_OID); assertAssignments(userJack, 1); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - + assertEquals("Wrong costCenter", "X000", userJackType.getCostCenter()); assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); @@ -675,27 +675,27 @@ public void test150ModifyJackOrganizationalUnitRum() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, task, result, PrismTestUtil.createPolyString("F0004")); // THEN 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?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertNotAssignedRole(userJack, ROLE_PIRATE_OID); assertAssignedOrg(userJack, ORG_MINISTRY_OF_RUM_OID); assertHasOrg(userJack, ORG_MINISTRY_OF_RUM_OID); assertAssignments(userJack, 2); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - + assertEquals("Wrong costCenter", "X000", userJackType.getCostCenter()); assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); @@ -711,27 +711,27 @@ public void test151ModifyJackOrganizationalUnitOffense() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, task, result, PrismTestUtil.createPolyString("F0003")); // THEN 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?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertNotAssignedRole(userJack, ROLE_PIRATE_OID); assertAssignedOrg(userJack, ORG_MINISTRY_OF_OFFENSE_OID); assertHasOrg(userJack, ORG_MINISTRY_OF_OFFENSE_OID); assertAssignments(userJack, 2); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - + assertEquals("Wrong costCenter", "X000", userJackType.getCostCenter()); assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); @@ -747,14 +747,14 @@ public void test152ModifyJackOrganizationalUnitAddRum() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN modifyUserAdd(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, task, result, PrismTestUtil.createPolyString("F0004")); // THEN 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?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertNotAssignedRole(userJack, ROLE_PIRATE_OID); @@ -763,13 +763,13 @@ public void test152ModifyJackOrganizationalUnitAddRum() throws Exception { assertHasOrg(userJack, ORG_MINISTRY_OF_RUM_OID); assertHasOrg(userJack, ORG_MINISTRY_OF_OFFENSE_OID); assertAssignments(userJack, 3); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - + assertEquals("Wrong costCenter", "X000", userJackType.getCostCenter()); assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); @@ -785,27 +785,27 @@ public void test153ModifyJackOrganizationalUnitDeleteOffense() throws Exception // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN modifyUserDelete(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, task, result, PrismTestUtil.createPolyString("F0003")); // THEN 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?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertNotAssignedRole(userJack, ROLE_PIRATE_OID); assertAssignedOrg(userJack, ORG_MINISTRY_OF_RUM_OID); assertHasOrg(userJack, ORG_MINISTRY_OF_RUM_OID); assertAssignments(userJack, 2); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - + assertEquals("Wrong costCenter", "X000", userJackType.getCostCenter()); assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); @@ -824,14 +824,14 @@ public void test155ModifyJackOrganizationalUnitFD001() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN modifyUserAdd(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, task, result, PrismTestUtil.createPolyString("FD001")); // THEN 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?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertNotAssignedRole(userJack, ROLE_PIRATE_OID); @@ -839,22 +839,22 @@ public void test155ModifyJackOrganizationalUnitFD001() throws Exception { assertHasOrg(userJack, ORG_MINISTRY_OF_RUM_OID); assertOnDemandOrgAssigned("FD001", userJack); - + assertAssignments(userJack, 3); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - + 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); } - + /** * Reconcile user Jack, see that everything is OK. */ @@ -866,14 +866,14 @@ public void test156ReconcileJack() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN reconcileUser(USER_JACK_OID, task, result); // THEN 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?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertNotAssignedRole(userJack, ROLE_PIRATE_OID); @@ -881,21 +881,21 @@ public void test156ReconcileJack() throws Exception { assertHasOrg(userJack, ORG_MINISTRY_OF_RUM_OID); assertOnDemandOrgAssigned("FD001", userJack); - + assertAssignments(userJack, 3); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - + 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()); } - + /** * Creates two orgs on demand. */ @@ -907,41 +907,41 @@ public void test157ModifyJackOrganizationalUnitFD0023() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN - modifyUserAdd(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, task, result, + modifyUserAdd(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, task, result, PrismTestUtil.createPolyString("FD002"), PrismTestUtil.createPolyString("FD003")); // THEN 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?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertNotAssignedRole(userJack, ROLE_PIRATE_OID); - + assertAssignedOrg(userJack, ORG_MINISTRY_OF_RUM_OID); assertHasOrg(userJack, ORG_MINISTRY_OF_RUM_OID); - + assertOnDemandOrgAssigned("FD001", userJack); assertOnDemandOrgAssigned("FD002", userJack); assertOnDemandOrgAssigned("FD003", userJack); - + assertAssignments(userJack, 5); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - + 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); } - + @Test public void test159ModifyJackDeleteOrganizationalUnitFD002() throws Exception { final String TEST_NAME = "test159ModifyJackDeleteOrganizationalUnitFD002"; @@ -950,7 +950,7 @@ public void test159ModifyJackDeleteOrganizationalUnitFD002() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN modifyUserDelete(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, task, result, PrismTestUtil.createPolyString("FD002")); @@ -958,27 +958,27 @@ public void test159ModifyJackDeleteOrganizationalUnitFD002() throws Exception { // THEN 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?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertNotAssignedRole(userJack, ROLE_PIRATE_OID); - + assertAssignedOrg(userJack, ORG_MINISTRY_OF_RUM_OID); assertHasOrg(userJack, ORG_MINISTRY_OF_RUM_OID); - + assertOnDemandOrgAssigned("FD001", userJack); assertOnDemandOrgAssigned("FD003", userJack); - + assertAssignments(userJack, 4); - + assertOnDemandOrgExists("FD002"); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - + assertEquals("Wrong costCenter", "X000", userJackType.getCostCenter()); assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); @@ -1006,7 +1006,7 @@ public void test160ModifyUserGivenNameAgain() throws Exception { // THEN assertSuccess(result); - + PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); PrismAsserts.assertPropertyValue(userJack.findContainer(UserType.F_EXTENSION), PIRACY_BAD_LUCK, 123L); @@ -1038,7 +1038,7 @@ public void test162ModifyUserGivenNameAgainPhantomChange() throws Exception { PrismObject userBefore = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); display("User before", userBefore); - + dummyAuditService.clear(); Collection> deltas = new ArrayList>(); @@ -1053,10 +1053,10 @@ public void test162ModifyUserGivenNameAgainPhantomChange() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); display("User after", userJack); - + PrismAsserts.assertPropertyValue(userJack.findContainer(UserType.F_EXTENSION), PIRACY_BAD_LUCK, 123L); display("Audit", dummyAuditService); @@ -1083,7 +1083,7 @@ public void test165ModifyUserGivenNameAgainAgain() throws Exception { PrismObject userBefore = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); display("User before", userBefore); - + Collection> deltas = new ArrayList>(); ObjectDelta userDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_JACK_OID, UserType.F_GIVEN_NAME, prismContext, new PolyString("jackie")); @@ -1110,14 +1110,14 @@ private PrismObject assertOnDemandOrgExists(String orgName) throws Sche 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 { PrismObject org = assertOnDemandOrgExists(orgName); PrismAsserts.assertPropertyValue(org, OrgType.F_DESCRIPTION, "Created on demand from user "+user.asObjectable().getName()); assertAssignedOrg(user, org.getOid()); - assertHasOrg(user, org.getOid()); + assertHasOrg(user, org.getOid()); } - + /** * Setting employee type to THIEF is just one part of the condition to assign * the Thief role. The role should not be assigned now. @@ -1130,11 +1130,11 @@ public void test170ModifyUserGuybrushEmployeeTypeThief() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); assertAssignedNoRole(userBefore); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_EMPLOYEE_TYPE, task, result, "THIEF"); @@ -1142,13 +1142,13 @@ public void test170ModifyUserGuybrushEmployeeTypeThief() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); - + assertAssignedNoRole(userAfter); } - + /** * Setting honorificPrefix satisfies the condition to assign * the Thief role. @@ -1161,26 +1161,26 @@ public void test172ModifyUserGuybrushHonorificPrefix() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); assertAssignedNoRole(userBefore); - + // WHEN displayWhen(TEST_NAME); - modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_HONORIFIC_PREFIX, task, result, + modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_HONORIFIC_PREFIX, task, result, PrismTestUtil.createPolyString("Thf.")); // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); - + assertAssignedRole(userAfter, ROLE_THIEF_OID); } - + /** * Removing honorificPrefix should make the condition false again, which should cause * that Thief role is unassigned. @@ -1193,11 +1193,11 @@ public void test174ModifyUserGuybrushHonorificPrefixNone() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); assertAssignedRole(userBefore, ROLE_THIEF_OID); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_HONORIFIC_PREFIX, task, result); @@ -1205,13 +1205,13 @@ public void test174ModifyUserGuybrushHonorificPrefixNone() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); - + assertAssignedNoRole(userAfter); } - + /** * Setting employee type to marooned. This should cause switch to different user template. */ @@ -1223,11 +1223,11 @@ public void test180ModifyUserGuybrushEmployeeTypeMarooned() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); assertAssignedNoRole(userBefore); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_EMPLOYEE_TYPE, task, result, EMPLOYEE_TYPE_MAROONED); @@ -1235,15 +1235,15 @@ public void test180ModifyUserGuybrushEmployeeTypeMarooned() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); - + assertEquals("Wrong costCenter", "NOCOST", userAfter.asObjectable().getCostCenter()); - + assertAssignedNoRole(userAfter); } - + @Test public void test189ModifyUserGuybrushEmployeeTypeNone() throws Exception { final String TEST_NAME = "test189ModifyUserGuybrushEmployeeTypeNone"; @@ -1252,11 +1252,11 @@ public void test189ModifyUserGuybrushEmployeeTypeNone() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); assertAssignedNoRole(userBefore); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_EMPLOYEE_TYPE, task, result); @@ -1264,15 +1264,15 @@ public void test189ModifyUserGuybrushEmployeeTypeNone() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); - + assertEquals("Wrong costCenter", "NOCOST", userAfter.asObjectable().getCostCenter()); - + assertAssignedNoRole(userAfter); } - + /** * Assignment mapping with domain. Control: nothing should happen. * MID-3692 @@ -1285,12 +1285,12 @@ public void test190ModifyUserGuybrushOrganizationWhateveric() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); assertAssignedNoRole(userBefore); assertAssignments(userBefore, 1); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_ORGANIZATION, task, result, createPolyString("Whateveric")); @@ -1298,16 +1298,16 @@ public void test190ModifyUserGuybrushOrganizationWhateveric() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(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")); - + assertAssignedNoRole(userAfter); assertAssignments(userAfter, 1); } - + /** * MID-3692 */ @@ -1319,11 +1319,11 @@ public void test191ModifyUserGuybrushOrganizationAutomatic() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); assertAssignedNoRole(userBefore); - + // WHEN displayWhen(TEST_NAME); modifyUserAdd(USER_GUYBRUSH_OID, UserType.F_ORGANIZATION, task, result, createPolyString("AUTO-matic")); @@ -1332,20 +1332,20 @@ public void test191ModifyUserGuybrushOrganizationAutomatic() throws Exception { displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(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"), + + PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, + createPolyString("Whateveric"), createPolyString("AUTO-matic")); - + assertAssignedRole(userAfter, ROLE_AUTOMATIC_OID); assertAssignments(userAfter, 2); - + assertRoles(getNumberOfRoles()); } - + /** * MID-3692 */ @@ -1357,11 +1357,11 @@ public void test192ModifyUserGuybrushOrganizationAddMixed() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); assertAssignments(userBefore, 2); - + // WHEN displayWhen(TEST_NAME); modifyUserAdd(USER_GUYBRUSH_OID, UserType.F_ORGANIZATION, task, result, @@ -1375,28 +1375,28 @@ public void test192ModifyUserGuybrushOrganizationAddMixed() throws Exception { displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(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"), + + PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, + createPolyString("Whateveric"), createPolyString("AUTO-matic"), createPolyString("DEMO-cratic"), createPolyString("AUTO-cratic"), createPolyString("plutocratic"), createPolyString("AUTO-didactic") ); - + assertAssignedRole(userAfter, ROLE_AUTOMATIC_OID); assertAssignedRole(userAfter, ROLE_AUTOCRATIC_OID); assertAssignedRole(userAfter, ROLE_AUTODIDACTIC_OID); assertAssignments(userAfter, 4); - + // Make sure nothing was created on demand assertRoles(getNumberOfRoles()); } - + /** * MID-3692 */ @@ -1408,11 +1408,11 @@ public void test193ModifyUserGuybrushOrganizationAddOutOfDomain() throws Excepti // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); assertAssignments(userBefore, 4); - + // WHEN displayWhen(TEST_NAME); modifyUserAdd(USER_GUYBRUSH_OID, UserType.F_ORGANIZATION, task, result, @@ -1424,12 +1424,12 @@ public void test193ModifyUserGuybrushOrganizationAddOutOfDomain() throws Excepti displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(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"), + + PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, + createPolyString("Whateveric"), createPolyString("AUTO-matic"), createPolyString("DEMO-cratic"), createPolyString("AUTO-cratic"), @@ -1438,16 +1438,16 @@ public void test193ModifyUserGuybrushOrganizationAddOutOfDomain() throws Excepti createPolyString("meritocratic"), createPolyString("piratocratic") ); - + assertAssignedRole(userAfter, ROLE_AUTOMATIC_OID); assertAssignedRole(userAfter, ROLE_AUTOCRATIC_OID); assertAssignedRole(userAfter, ROLE_AUTODIDACTIC_OID); assertAssignments(userAfter, 4); - + // Make sure nothing was created on demand assertRoles(getNumberOfRoles()); } - + /** * MID-3692 */ @@ -1459,11 +1459,11 @@ public void test194ModifyUserGuybrushOrganizationDeleteMixed() throws Exception // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); assertAssignments(userBefore, 4); - + // WHEN displayWhen(TEST_NAME); modifyUserDelete(USER_GUYBRUSH_OID, UserType.F_ORGANIZATION, task, result, @@ -1477,24 +1477,24 @@ public void test194ModifyUserGuybrushOrganizationDeleteMixed() throws Exception displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(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"), + + PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, + createPolyString("Whateveric"), createPolyString("DEMO-cratic"), createPolyString("AUTO-cratic"), createPolyString("piratocratic") ); - + assertAssignedRole(userAfter, ROLE_AUTOCRATIC_OID); assertAssignments(userAfter, 2); - + // Make sure nothing was created on demand assertRoles(getNumberOfRoles()); } - + /** * MID-3692 */ @@ -1506,11 +1506,11 @@ public void test195ModifyUserGuybrushOrganizationDeleteOutOfDomain() throws Exce // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); assertAssignments(userBefore, 2); - + // WHEN displayWhen(TEST_NAME); modifyUserDelete(USER_GUYBRUSH_OID, UserType.F_ORGANIZATION, task, result, @@ -1522,22 +1522,22 @@ public void test195ModifyUserGuybrushOrganizationDeleteOutOfDomain() throws Exce displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); - - PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, + + PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("Whateveric"), createPolyString("AUTO-cratic") ); - + assertAssignedRole(userAfter, ROLE_AUTOCRATIC_OID); assertAssignments(userAfter, 2); - + // Make sure nothing was created on demand assertRoles(getNumberOfRoles()); } - + /** * Make sure that the manually assigned roles will not mess with the mapping. * MID-3692 @@ -1550,11 +1550,11 @@ public void test196GuybrushAssignCaptain() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); assertAssignments(userBefore, 2); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_CAPTAIN_OID, task, result); @@ -1563,23 +1563,23 @@ public void test196GuybrushAssignCaptain() throws Exception { displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); - - PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, + + PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("Whateveric"), createPolyString("AUTO-cratic") ); - + assertAssignedRole(userAfter, ROLE_AUTOCRATIC_OID); assertAssignedRole(userAfter, ROLE_CAPTAIN_OID); assertAssignments(userAfter, 3); - + // Make sure nothing was created on demand assertRoles(getNumberOfRoles()); } - + /** * Make sure that a role automatically assigned by a different mapping will not mess with this mapping. * MID-3692 @@ -1592,7 +1592,7 @@ public void test197ModifyGuybrushEmployeeTypePirate() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_EMPLOYEE_TYPE, task, result, "PIRATE"); @@ -1601,24 +1601,24 @@ public void test197ModifyGuybrushEmployeeTypePirate() throws Exception { displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); - - PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, + + PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("Whateveric"), createPolyString("AUTO-cratic") ); - + assertAssignedRole(userAfter, ROLE_AUTOCRATIC_OID); assertAssignedRole(userAfter, ROLE_CAPTAIN_OID); assertAssignedRole(userAfter, ROLE_PIRATE_OID); assertAssignments(userAfter, 4); - + // Make sure nothing was created on demand assertRoles(getNumberOfRoles()); } - + /** * Make sure that changes in this mapping will not influence other assigned roles. * MID-3692 @@ -1631,11 +1631,11 @@ public void test198AModifyUserGuybrushOrganizationAddInDomain() throws Exception // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); assertAssignments(userBefore, 4); - + // WHEN displayWhen(TEST_NAME); modifyUserAdd(USER_GUYBRUSH_OID, UserType.F_ORGANIZATION, task, result, @@ -1647,28 +1647,28 @@ public void test198AModifyUserGuybrushOrganizationAddInDomain() throws Exception displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); - - PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, + + PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("Whateveric"), createPolyString("AUTO-cratic"), createPolyString("AUTO-graphic"), createPolyString("AUTO-matic") ); - + assertAssignedRole(userAfter, ROLE_AUTOMATIC_OID); assertAssignedRole(userAfter, ROLE_AUTOCRATIC_OID); assertAssignedRole(userAfter, ROLE_AUTOGRAPHIC_OID); assertAssignedRole(userAfter, ROLE_CAPTAIN_OID); assertAssignedRole(userAfter, ROLE_PIRATE_OID); assertAssignments(userAfter, 6); - + // Make sure nothing was created on demand assertRoles(getNumberOfRoles()); } - + /** * Make sure that changes in this mapping will not influence other assigned roles. * MID-3692 @@ -1681,11 +1681,11 @@ public void test198BModifyUserGuybrushOrganizationDeleteMixed() throws Exception // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); assertAssignments(userBefore, 6); - + // WHEN displayWhen(TEST_NAME); modifyUserDelete(USER_GUYBRUSH_OID, UserType.F_ORGANIZATION, task, result, @@ -1697,25 +1697,25 @@ public void test198BModifyUserGuybrushOrganizationDeleteMixed() throws Exception displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); - - PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, + + PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("AUTO-graphic"), createPolyString("AUTO-matic") ); - + assertAssignedRole(userAfter, ROLE_AUTOMATIC_OID); assertAssignedRole(userAfter, ROLE_AUTOGRAPHIC_OID); assertAssignedRole(userAfter, ROLE_CAPTAIN_OID); assertAssignedRole(userAfter, ROLE_PIRATE_OID); assertAssignments(userAfter, 5); - + // Make sure nothing was created on demand assertRoles(getNumberOfRoles()); } - + /** * MID-3692 */ @@ -1727,11 +1727,11 @@ public void test199AGuyBrushModifyEmployeeTypeWannabe() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); assertAssignments(userBefore, 5); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_EMPLOYEE_TYPE, task, result, "wannabe"); @@ -1740,24 +1740,24 @@ public void test199AGuyBrushModifyEmployeeTypeWannabe() throws Exception { displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); - - PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, + + PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("AUTO-graphic"), createPolyString("AUTO-matic") ); - + assertAssignedRole(userAfter, ROLE_AUTOMATIC_OID); assertAssignedRole(userAfter, ROLE_AUTOGRAPHIC_OID); assertAssignedRole(userAfter, ROLE_CAPTAIN_OID); assertAssignments(userAfter, 4); - + // Make sure nothing was created on demand assertRoles(getNumberOfRoles()); } - + /** * MID-3692 */ @@ -1769,11 +1769,11 @@ public void test199BGuyBrushUnassignCaptain() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); assertAssignments(userBefore, 4); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_GUYBRUSH_OID, ROLE_CAPTAIN_OID, task, result); @@ -1782,23 +1782,23 @@ public void test199BGuyBrushUnassignCaptain() throws Exception { displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); - - PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, + + PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("AUTO-graphic"), createPolyString("AUTO-matic") ); - + assertAssignedRole(userAfter, ROLE_AUTOMATIC_OID); assertAssignedRole(userAfter, ROLE_AUTOGRAPHIC_OID); assertAssignments(userAfter, 3); - + // Make sure nothing was created on demand assertRoles(getNumberOfRoles()); } - + /** * MID-3692, MID-3700 */ @@ -1810,10 +1810,10 @@ public void test199CModifyUserGuybrushOrganizationCleanup() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_ORGANIZATION, task, result); @@ -1822,17 +1822,17 @@ public void test199CModifyUserGuybrushOrganizationCleanup() throws Exception { displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); - + PrismAsserts.assertNoItem(userAfter, UserType.F_ORGANIZATION); - + assertAssignedNoRole(userAfter); - + assertRoles(getNumberOfRoles()); } - + @Test public void test200AddUserRapp() throws Exception { final String TEST_NAME = "test200AddUserRapp"; @@ -1841,12 +1841,12 @@ public void test200AddUserRapp() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject user = PrismTestUtil.parseObject(USER_RAPP_FILE); Collection> deltas = new ArrayList>(); ObjectDelta userDelta = ObjectDelta.createAddDelta(user); deltas.add(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); @@ -1854,22 +1854,22 @@ public void test200AddUserRapp() throws Exception { 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); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); assertAssignedNoRole(userAfter); assertAssignments(userAfter, 1); - + UserType userAfterType = userAfter.asObjectable(); assertLinks(userAfter, 1); - + result.computeStatus(); TestUtil.assertSuccess(result); - - assertEquals("Unexpected value of employeeNumber, maybe it was generated and should not be?", + + assertEquals("Unexpected value of employeeNumber, maybe it was generated and should not be?", "D3ADB33F", userAfterType.getEmployeeNumber()); assertEquals("Wrong costCenter", "G001", userAfterType.getCostCenter()); } - + @Test public void test201AddUserLargo() throws Exception { TestUtil.displayTestTitle(this, "test201AddUserLargo"); @@ -1879,12 +1879,12 @@ public void test201AddUserLargo() throws Exception { // This simulates IMPORT to trigger the channel-limited mapping task.setChannel(QNameUtil.qNameToUri(SchemaConstants.CHANGE_CHANNEL_IMPORT)); OperationResult result = task.getResult(); - + PrismObject user = PrismTestUtil.parseObject(USER_LARGO_FILE); Collection> deltas = new ArrayList>(); ObjectDelta userDelta = ObjectDelta.createAddDelta(user); deltas.add(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); @@ -1906,17 +1906,17 @@ public void test201AddUserLargo() throws Exception { assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); assertAssignedRole(userAfter, ROLE_PIRATE_OID); assertAssignments(userAfter, 2); - + UserType userAfterType = userAfter.asObjectable(); assertEquals("Unexpected number of accountRefs", 2, userAfterType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - - assertEquals("Unexpected length of employeeNumber, maybe it was not generated?", + + assertEquals("Unexpected length of employeeNumber, maybe it was not generated?", GenerateExpressionEvaluator.DEFAULT_LENGTH, userAfterType.getEmployeeNumber().length()); } - + @Test public void test202AddUserMonkey() throws Exception { TestUtil.displayTestTitle(this, "test202AddUserMonkey"); @@ -1924,12 +1924,12 @@ public void test202AddUserMonkey() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestUserTemplate.class.getName() + ".test202AddUserMonkey"); OperationResult result = task.getResult(); - + PrismObject user = PrismTestUtil.parseObject(new File(USER_THREE_HEADED_MONKEY_FILENAME)); Collection> deltas = new ArrayList>(); ObjectDelta userDelta = ObjectDelta.createAddDelta(user); deltas.add(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); @@ -1939,21 +1939,21 @@ public void test202AddUserMonkey() throws Exception { // assertUser(userAfter, USER_THREE_HEADED_MONKEY_OID, "monkey", " Monkey", null, "Monkey"); assertUser(userAfter, USER_THREE_HEADED_MONKEY_OID, "monkey", "Three-Headed Monkey", null, "Monkey"); PrismAsserts.assertNoItem(userAfter, UserType.F_DESCRIPTION); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); assertAssignedNoRole(userAfter); assertAssignments(userAfter, 1); - + UserType userAfterType = userAfter.asObjectable(); assertEquals("Unexpected number of accountRefs", 1, userAfterType.getLinkRef().size()); - + result.computeStatus(); TestUtil.assertSuccess(result); - - assertEquals("Unexpected length of employeeNumber, maybe it was not generated?", + + assertEquals("Unexpected length of employeeNumber, maybe it was not generated?", GenerateExpressionEvaluator.DEFAULT_LENGTH, userAfterType.getEmployeeNumber().length()); } - + /** * MID-3186 */ @@ -1965,12 +1965,12 @@ public void test204AddUserHerman() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject user = PrismTestUtil.parseObject(USER_HERMAN_FILE); Collection> deltas = new ArrayList>(); ObjectDelta userDelta = ObjectDelta.createAddDelta(user); deltas.add(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); @@ -1979,20 +1979,20 @@ public void test204AddUserHerman() throws Exception { assertUser(userAfter, USER_HERMAN_OID, USER_HERMAN_USERNAME, USER_HERMAN_FULL_NAME, "Herman", "Toothrot"); PrismAsserts.assertNoItem(userAfter, UserType.F_DESCRIPTION); PrismAsserts.assertPropertyValue(userAfter, UserType.F_TIMEZONE, "High Seas/Monkey Island"); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); assertAssignedNoRole(userAfter); assertAssignments(userAfter, 1); - + UserType userAfterType = userAfter.asObjectable(); assertLinks(userAfter, 1); - + result.computeStatus(); TestUtil.assertSuccess(result); - + assertEquals("Wrong costCenter", "G001", userAfterType.getCostCenter()); } - + @Test public void test220AssignRoleSailorToUserRapp() throws Exception { final String TEST_NAME = "test220AssignRoleSailorToUserRapp"; @@ -2001,7 +2001,7 @@ public void test220AssignRoleSailorToUserRapp() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignRole(USER_RAPP_OID, ROLE_SAILOR_OID, task, result); @@ -2009,22 +2009,22 @@ public void test220AssignRoleSailorToUserRapp() throws Exception { 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); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); assertAssignedRole(userAfter, ROLE_SAILOR_OID); assertAssignments(userAfter, 2); - + UserType userAfterType = userAfter.asObjectable(); assertLinks(userAfter, 2); - + result.computeStatus(); TestUtil.assertSuccess(result); - - assertEquals("Unexpected value of employeeNumber", + + assertEquals("Unexpected value of employeeNumber", "D3ADB33F", userAfterType.getEmployeeNumber()); assertEquals("Wrong costCenter", "CC-TITANIC", userAfterType.getCostCenter()); } - + /** * MID-3028 */ @@ -2036,7 +2036,7 @@ public void test229UnassignRoleSailorFromUserRapp() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignRole(USER_RAPP_OID, ROLE_SAILOR_OID, task, result); @@ -2044,23 +2044,23 @@ public void test229UnassignRoleSailorFromUserRapp() throws Exception { 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); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); assertAssignedNoRole(userAfter); assertAssignments(userAfter, 1); - + UserType userAfterType = userAfter.asObjectable(); assertLinks(userAfter, 1); - + result.computeStatus(); TestUtil.assertSuccess(result); - - assertEquals("Unexpected value of employeeNumber", + + assertEquals("Unexpected value of employeeNumber", "D3ADB33F", userAfterType.getEmployeeNumber()); assertEquals("Wrong costCenter", "G001", userAfterType.getCostCenter()); } - - + + /** * Role Captains has focus mapping for the same costCenter as is given * by the user template. @@ -2073,29 +2073,29 @@ public void test230AssignRoleCaptainToUserRapp() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignRole(USER_RAPP_OID, ROLE_CAPTAIN_OID, task, result); // THEN 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); assertAssignedRole(userAfter, ROLE_CAPTAIN_OID); assertAssignments(userAfter, 2); - + UserType userAfterType = userAfter.asObjectable(); assertLinks(userAfter, 1); - + result.computeStatus(); TestUtil.assertSuccess(result); - - assertEquals("Unexpected value of employeeNumber", + + assertEquals("Unexpected value of employeeNumber", "D3ADB33F", userAfterType.getEmployeeNumber()); assertEquals("Wrong costCenter", "G001", userAfterType.getCostCenter()); } - + /** * Object template mapping for cost center is weak, role mapping is normal. * Direct modification should override both. @@ -2108,29 +2108,29 @@ public void test232ModifyUserRappCostCenter() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN 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); assertUser(userAfter, USER_RAPP_OID, "rapp", "Rapp Scallion", "Rapp", "Scallion"); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); assertAssignedRole(userAfter, ROLE_CAPTAIN_OID); assertAssignments(userAfter, 2); - + UserType userAfterType = userAfter.asObjectable(); assertLinks(userAfter, 1); - + result.computeStatus(); TestUtil.assertSuccess(result); - - assertEquals("Unexpected value of employeeNumber", + + assertEquals("Unexpected value of employeeNumber", "D3ADB33F", userAfterType.getEmployeeNumber()); assertEquals("Wrong costCenter", "CC-RAPP", userAfterType.getCostCenter()); } - + /** * Role Captains has focus mapping for the same costCenter as is given * by the user template. @@ -2144,7 +2144,7 @@ public void test239UnassignRoleCaptainFromUserRapp() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignRole(USER_RAPP_OID, ROLE_CAPTAIN_OID, task, result); @@ -2152,22 +2152,22 @@ public void test239UnassignRoleCaptainFromUserRapp() throws Exception { 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"); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); assertAssignedNoRole(userAfter); assertAssignments(userAfter, 1); - + UserType userAfterType = userAfter.asObjectable(); assertLinks(userAfter, 1); - + result.computeStatus(); TestUtil.assertSuccess(result); - - assertEquals("Unexpected value of employeeNumber", + + assertEquals("Unexpected value of employeeNumber", "D3ADB33F", userAfterType.getEmployeeNumber()); assertEquals("Wrong costCenter", "CC-RAPP", userAfterType.getCostCenter()); } - + @Test public void test240ModifyUserRappLocalityScabb() throws Exception { final String TEST_NAME = "test240ModifyUserRappLocalityScabb"; @@ -2176,39 +2176,39 @@ public void test240ModifyUserRappLocalityScabb() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + 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()); - + // WHEN 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); display("User after", userAfter); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); assertAssignedNoRole(userAfter); assertAssignments(userAfter, 1); - + UserType userAfterType = userAfter.asObjectable(); assertLinks(userAfter, 1); - + assertEquals("Wrong timezone", "High Seas/Scabb Island", userAfterType.getTimezone()); assertEquals("Wrong locale", "SC", userAfterType.getLocale()); - - assertEquals("Unexpected value of employeeNumber", + + assertEquals("Unexpected value of employeeNumber", "D3ADB33F", userAfterType.getEmployeeNumber()); 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 @@ -2224,7 +2224,7 @@ public void test242AssignRoleRastamanToUserRapp() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignRole(USER_RAPP_OID, ROLE_RASTAMAN_OID, task, result); @@ -2234,22 +2234,22 @@ public void test242AssignRoleRastamanToUserRapp() throws Exception { 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); assertAssignedRole(userAfter, ROLE_RASTAMAN_OID); assertAssignments(userAfter, 2); - + UserType userAfterType = userAfter.asObjectable(); assertLinks(userAfter, 1); - + assertEquals("Wrong timezone", "Caribbean/Whatever", userAfterType.getTimezone()); assertEquals("Wrong locale", "WE", userAfterType.getLocale()); - - assertEquals("Unexpected value of employeeNumber", + + assertEquals("Unexpected value of employeeNumber", "D3ADB33F", userAfterType.getEmployeeNumber()); 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. It is evaluated @@ -2265,37 +2265,37 @@ public void test244ModifyUserRappLocalityCoffin() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + 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")); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); display("User after", userAfter); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); assertAssignedRole(userAfter, ROLE_RASTAMAN_OID); assertAssignments(userAfter, 2); - + UserType userAfterType = userAfter.asObjectable(); assertLinks(userAfter, 1); - + assertEquals("Wrong timezone", "High Seas/Coffin", userAfterType.getTimezone()); assertEquals("Wrong locale", "WE", userAfterType.getLocale()); - - assertEquals("Unexpected value of employeeNumber", + + assertEquals("Unexpected value of employeeNumber", "D3ADB33F", userAfterType.getEmployeeNumber()); assertEquals("Wrong costCenter", "CC-RAPP", userAfterType.getCostCenter()); } - + /** - * Similar to test244, but also use reconcile option. + * Similar to test244, but also use reconcile option. * MID-3040 */ @Test @@ -2306,7 +2306,7 @@ public void test245ModifyUserRappLocalityUnderReconcile() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); display("User before", userBefore); @@ -2314,32 +2314,32 @@ public void test245ModifyUserRappLocalityUnderReconcile() throws Exception { PrismTestUtil.createPolyString("Six feet under")); Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); ModelExecuteOptions options = ModelExecuteOptions.createReconcile(); - + // WHEN modelService.executeChanges(deltas, options, task, result); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); display("User after", userAfter); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); assertAssignedRole(userAfter, ROLE_RASTAMAN_OID); assertAssignments(userAfter, 2); - + UserType userAfterType = userAfter.asObjectable(); assertLinks(userAfter, 1); - + assertEquals("Wrong timezone", "High Seas/Six feet under", userAfterType.getTimezone()); assertEquals("Wrong locale", "WE", userAfterType.getLocale()); - - assertEquals("Unexpected value of employeeNumber", + + assertEquals("Unexpected value of employeeNumber", "D3ADB33F", userAfterType.getEmployeeNumber()); assertEquals("Wrong costCenter", "CC-RAPP", userAfterType.getCostCenter()); } - + /** * Changing timezone. timezone is a target of (normal) object template mapping and * (normal) role mapping. But as this is primary delta none of the mappings should @@ -2354,31 +2354,31 @@ public void test246ModifyUserRappTimezoneMonkey() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); display("User before", userBefore); - + // WHEN modifyUserReplace(USER_RAPP_OID, UserType.F_TIMEZONE, task, result, "Monkey Island"); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); display("User after", userAfter); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); assertAssignedRole(userAfter, ROLE_RASTAMAN_OID); assertAssignments(userAfter, 2); - + UserType userAfterType = userAfter.asObjectable(); assertLinks(userAfter, 1); - + assertEquals("Wrong timezone", "Monkey Island", userAfterType.getTimezone()); assertEquals("Wrong locale", "WE", userAfterType.getLocale()); - - assertEquals("Unexpected value of employeeNumber", + + assertEquals("Unexpected value of employeeNumber", "D3ADB33F", userAfterType.getEmployeeNumber()); assertEquals("Wrong costCenter", "CC-RAPP", userAfterType.getCostCenter()); } @@ -2397,34 +2397,34 @@ public void test247ModifyUserRappLocaleMI() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); display("User before", userBefore); - + // WHEN modifyUserReplace(USER_RAPP_OID, UserType.F_LOCALE, task, result, "MI"); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); display("User after", userAfter); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); assertAssignedRole(userAfter, ROLE_RASTAMAN_OID); assertAssignments(userAfter, 2); - + UserType userAfterType = userAfter.asObjectable(); assertLinks(userAfter, 1); - + // The normal mapping from the rastaman role was applied at this point // This is sourceless mapping and there is no a-priori delta assertEquals("Wrong timezone", "Caribbean/Whatever", userAfterType.getTimezone()); - + assertEquals("Wrong locale", "MI", userAfterType.getLocale()); - - assertEquals("Unexpected value of employeeNumber", + + assertEquals("Unexpected value of employeeNumber", "D3ADB33F", userAfterType.getEmployeeNumber()); assertEquals("Wrong costCenter", "CC-RAPP", userAfterType.getCostCenter()); } @@ -2437,7 +2437,7 @@ public void test249UnassignRoleRastamanFromUserRapp() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignRole(USER_RAPP_OID, ROLE_RASTAMAN_OID, task, result); @@ -2448,24 +2448,24 @@ public void test249UnassignRoleRastamanFromUserRapp() throws Exception { 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); - + assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); assertAssignedNoRole(userAfter); assertAssignments(userAfter, 1); - + UserType userAfterType = userAfter.asObjectable(); assertLinks(userAfter, 1); - + // Role is unassigned. The mapping was authoritative, so it removed the value assertEquals("Wrong timezone", null, userAfterType.getTimezone()); - + assertEquals("Wrong locale", "MI", userAfterType.getLocale()); - - assertEquals("Unexpected value of employeeNumber", + + assertEquals("Unexpected value of employeeNumber", "D3ADB33F", userAfterType.getEmployeeNumber()); assertEquals("Wrong costCenter", "CC-RAPP", userAfterType.getCostCenter()); } - + /** * MID-3186 */ @@ -2478,27 +2478,27 @@ public void test300ImportStanFromEmeraldResource() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + DummyAccount dummyAccountBefore = new DummyAccount(ACCOUNT_STAN_USERNAME); - dummyAccountBefore.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, + dummyAccountBefore.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, ACCOUNT_STAN_FULLNAME); - dummyAccountBefore.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, + dummyAccountBefore.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Melee Island"); dummyResourceEmerald.addAccount(dummyAccountBefore); - + PrismObject shadowBefore = findAccountByUsername(ACCOUNT_STAN_USERNAME, resourceDummyEmerald); display("Shadow before", shadowBefore); - + // WHEN displayWhen(TEST_NAME); modelService.importFromResource(shadowBefore.getOid(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); display(result); TestUtil.assertSuccess(result); - + PrismObject userAfter = findUserByUsername(ACCOUNT_STAN_USERNAME); display("User after", userAfter); assertNotNull("No stan user", userAfter); @@ -2507,7 +2507,7 @@ public void test300ImportStanFromEmeraldResource() throws Exception { PrismAsserts.assertPropertyValue(userAfter, UserType.F_LOCALITY, PrismTestUtil.createPolyString("Melee Island")); PrismAsserts.assertPropertyValue(userAfter, UserType.F_TIMEZONE, "High Seas/Melee Island"); } - + /** * Modify stan accoutn and reimport from the emerald resource. Make sure that * the normal mapping for locality in the object template is properly activated (as there is @@ -2523,24 +2523,24 @@ public void test302ModifyStanAccountAndReimport() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + DummyAccount dummyAccountBefore = dummyResourceEmerald.getAccountByUsername(ACCOUNT_STAN_USERNAME); - dummyAccountBefore.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, + dummyAccountBefore.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Booty Island"); - + PrismObject shadowBefore = findAccountByUsername(ACCOUNT_STAN_USERNAME, resourceDummyEmerald); display("Shadow before", shadowBefore); - + // WHEN displayWhen(TEST_NAME); modelService.importFromResource(shadowBefore.getOid(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); display(result); TestUtil.assertSuccess(result); - + PrismObject userAfter = findUserByUsername(ACCOUNT_STAN_USERNAME); display("User after", userAfter); assertNotNull("No stan user", userAfter); @@ -2549,7 +2549,7 @@ public void test302ModifyStanAccountAndReimport() throws Exception { PrismAsserts.assertPropertyValue(userAfter, UserType.F_LOCALITY, PrismTestUtil.createPolyString("Booty Island")); PrismAsserts.assertPropertyValue(userAfter, UserType.F_TIMEZONE, "High Seas/Booty Island"); } - + /** * Move the time to the future. See if the time-based mapping in user template is properly recomputed. */ @@ -2557,28 +2557,28 @@ public void test302ModifyStanAccountAndReimport() throws Exception { public void test800Kaboom() throws Exception { final String TEST_NAME = "test800Kaboom"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + importObjectFromFile(TASK_TRIGGER_SCANNER_FILE); waitForTaskStart(TASK_TRIGGER_SCANNER_OID, false); - + XMLGregorianCalendar now = clock.currentTimeXMLGregorianCalendar(); now.add(XmlTypeConverter.createDuration("P1M1D")); clock.override(now); - + // WHEN waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); - + // THEN PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); PrismAsserts.assertPropertyValue(userJack, UserType.F_ADDITIONAL_NAME, PrismTestUtil.createPolyString("Kaboom!")); assertNoTrigger(userJack); } - + @Test public void test900DeleteUser() throws Exception { final String TEST_NAME = "test900DeleteUser"; @@ -2588,12 +2588,12 @@ public void test900DeleteUser() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + Collection> deltas = new ArrayList>(); ObjectDelta userDelta = ObjectDelta.createDeleteDelta(UserType.class, USER_JACK_OID, prismContext); deltas.add(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); @@ -2607,43 +2607,43 @@ public void test900DeleteUser() throws Exception { } // TODO: check on resource - + result.computeStatus(); TestUtil.assertFailure(result); } - + @Test public void test950CreateUserJackWithoutTemplate() throws Exception { final String TEST_NAME = "test950CreateUserJackWithoutTemplate"; displayTestTitle(TEST_NAME); - + // GIVEN - setDefaultUserTemplate(null); + setDefaultUserTemplate(null); Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + // WHEN addObject(USER_JACK_FILE, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); 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?"); assertAssignments(userJack, 0); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 0, userJackType.getLinkRef().size()); PrismAsserts.assertNoItem(userJack, UserType.F_ORGANIZATIONAL_UNIT); - + } - + /** * Would creates org on demand if the template would be active. But it is not. */ @@ -2655,26 +2655,26 @@ public void test952ModifyJackOrganizationalUnitFD004() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN modifyUserAdd(USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, task, result, PrismTestUtil.createPolyString("FD004")); // THEN 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_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("FD004")); - + assertAssignments(userJack, 0); - + UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 0, userJackType.getLinkRef().size()); - + PrismObject org = findObjectByName(OrgType.class, "FD004"); assertNull("Found org "+org+" but not expecting it", org); } - + /** * Set the template. Reconcile the user that should have org created on demand (but does not). * The org should be created. @@ -2686,24 +2686,24 @@ public void test960ReconcileUserJackWithTemplate() throws Exception { // GIVEN setDefaultUserTemplate(USER_TEMPLATE_COMPLEX_OID); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + // WHEN reconcileUser(USER_JACK_OID, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); 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?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertOnDemandOrgAssigned("FD004", userJack); - + assertAssignments(userJack, 2); assertLinks(userJack, 1); } 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 bcbec45442b..9896ab74886 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 @@ -46,7 +46,7 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestUserTemplateWithRanges extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/object-template-ranges"); public static final QName MANAGER_ID_QNAME = new QName("http://sample.evolveum.com/xml/ns/sample-idm/extension", "managerId"); @@ -67,7 +67,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); repoAddObjectsFromFile(ORG_MONKEY_ISLAND_LOCAL_FILE, OrgType.class, initResult); - + repoAddObjectFromFile(USER_TEMPLATE_RANGES_FILE, initResult); setDefaultObjectTemplate(UserType.COMPLEX_TYPE, USER_TEMPLATE_RANGES_OID, initResult); @@ -92,7 +92,7 @@ public void test100RecomputeElaine() throws Exception { // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userElaine = getUser(USER_ELAINE_OID); display("elaine after recompute", userElaine); assertAssignedOrg(userElaine, ORG_GOVERNOR_OFFICE_OID, SchemaConstants.ORG_MANAGER); 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 f7179f6297d..1882d262547 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 @@ -58,7 +58,7 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestVolatility extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/volatility"); protected static final File RESOURCE_DUMMY_HR_FILE = new File(TEST_DIR, "resource-dummy-hr.xml"); @@ -68,7 +68,7 @@ public class TestVolatility extends AbstractInitializedModelIntegrationTest { protected static final File RESOURCE_DUMMY_VOLATILE_FILE = new File(TEST_DIR, "resource-dummy-volatile.xml"); protected static final String RESOURCE_DUMMY_VOLATILE_OID = "10000000-0000-0000-0000-00000000f104"; protected static final String RESOURCE_DUMMY_VOLATILE_NAME = "volatile"; - + protected static final File RESOURCE_DUMMY_MONSTERIZED_FILE = new File(TEST_DIR, "resource-dummy-monsterized.xml"); protected static final String RESOURCE_DUMMY_MONSTERIZED_OID = "67a954d2-f391-11e6-a1d7-078381fe0e6f"; protected static final String RESOURCE_DUMMY_MONSTERIZED_NAME = "monsterized"; @@ -94,10 +94,10 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti ctl.getDummyResource().setSyncStyle(DummySyncStyle.SMART); ctl.getDummyResource().populateWithDefaultSchema(); }, initTask, initResult); - + initDummyResource(RESOURCE_DUMMY_VOLATILE_NAME, RESOURCE_DUMMY_VOLATILE_FILE, RESOURCE_DUMMY_VOLATILE_OID, initTask, initResult); - - initDummyResource(RESOURCE_DUMMY_MONSTERIZED_NAME, RESOURCE_DUMMY_MONSTERIZED_FILE, RESOURCE_DUMMY_MONSTERIZED_OID, initTask, initResult); + + initDummyResource(RESOURCE_DUMMY_MONSTERIZED_NAME, RESOURCE_DUMMY_MONSTERIZED_FILE, RESOURCE_DUMMY_MONSTERIZED_OID, initTask, initResult); } @Test @@ -144,8 +144,8 @@ public void test110AddDummyHrAccountMancomb() throws Exception { // THEN TestUtil.displayThen(TEST_NAME); - - PrismObject accountMancombHr = findAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME, + + PrismObject accountMancombHr = findAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME, getDummyResourceObject(RESOURCE_DUMMY_HR_NAME)); display("Account mancomb on HR", accountMancombHr); assertNotNull("No mancomb HR account shadow", accountMancombHr); @@ -153,7 +153,7 @@ public void test110AddDummyHrAccountMancomb() throws Exception { accountMancombHr.asObjectable().getResourceRef().getOid()); assertShadowOperationalData(accountMancombHr, SynchronizationSituationType.LINKED, null); - PrismObject accountMancombVolatileTarget = findAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME, + PrismObject accountMancombVolatileTarget = findAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME, getDummyResourceObject(RESOURCE_DUMMY_VOLATILE_NAME)); display("Account mancomb on target", accountMancombVolatileTarget); assertNotNull("No mancomb target account shadow", accountMancombVolatileTarget); @@ -205,7 +205,7 @@ public void test120UpdateDummyHrAccountMancomb() throws Exception { // THEN TestUtil.displayThen(TEST_NAME); - PrismObject accountMancombHr = findAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME, + PrismObject accountMancombHr = findAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME, getDummyResourceObject(RESOURCE_DUMMY_HR_NAME)); display("Account mancomb on HR", accountMancombHr); assertNotNull("No mancomb HR account shadow", accountMancombHr); @@ -216,7 +216,7 @@ public void test120UpdateDummyHrAccountMancomb() throws Exception { DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_QNAME)); assertShadowOperationalData(accountMancombHr, SynchronizationSituationType.LINKED, null); - PrismObject accountMancombVolatileTarget = findAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME, + PrismObject accountMancombVolatileTarget = findAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME, getDummyResourceObject(RESOURCE_DUMMY_VOLATILE_NAME)); display("Account mancomb on target", accountMancombVolatileTarget); assertNotNull("No mancomb target account shadow", accountMancombVolatileTarget); @@ -278,7 +278,7 @@ public void test200ModifyGuybrushAssignAccount() throws Exception { assertNotNull("User guybrush is not there", userGuybrush); assertLinks(userGuybrush, 1); - PrismObject accountGuybrushVolatileTarget = findAccountByUsername(ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + PrismObject accountGuybrushVolatileTarget = findAccountByUsername(ACCOUNT_GUYBRUSH_DUMMY_USERNAME, getDummyResourceObject(RESOURCE_DUMMY_VOLATILE_NAME)); display("Account guybrush on target", accountGuybrushVolatileTarget); assertNotNull("No guybrush target account shadow", accountGuybrushVolatileTarget); @@ -353,7 +353,7 @@ public void test300AddLargo() throws Exception { // notifications notificationManager.setDisabled(true); } - + /** * MID-3727 */ @@ -390,10 +390,10 @@ public void test400AddHerman() throws Exception { DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_MONSTERIZED_NAME, USER_HERMAN_USERNAME); display("Dummy account", dummyAccount); - assertDummyAccountAttribute(RESOURCE_DUMMY_MONSTERIZED_NAME, USER_HERMAN_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MONSTERIZED_NAME, USER_HERMAN_USERNAME, DummyAccount.ATTR_INTERESTS_NAME, "foo", "bar", DummyResource.VALUE_COOKIE); } - + /** * Monsterized resource is volatile: Monster has eaten the cookie. But we still * want the cookie to be in the values. The volatility=explosive should fix it. @@ -410,7 +410,7 @@ public void test402ModifyHermanMonster() throws Exception { // WHEN TestUtil.displayWhen(TEST_NAME); - modifyUserAdd(USER_HERMAN_OID, UserType.F_ORGANIZATION, task, result, + modifyUserAdd(USER_HERMAN_OID, UserType.F_ORGANIZATION, task, result, createPolyString(DummyResource.VALUE_MONSTER)); // THEN @@ -425,8 +425,8 @@ public void test402ModifyHermanMonster() throws Exception { DummyAccount dummyAccount = assertDummyAccount(RESOURCE_DUMMY_MONSTERIZED_NAME, USER_HERMAN_USERNAME); display("Dummy account", dummyAccount); - assertDummyAccountAttribute(RESOURCE_DUMMY_MONSTERIZED_NAME, USER_HERMAN_USERNAME, - DummyAccount.ATTR_INTERESTS_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MONSTERIZED_NAME, USER_HERMAN_USERNAME, + DummyAccount.ATTR_INTERESTS_NAME, "foo", "bar", DummyResource.VALUE_COOKIE, DummyResource.VALUE_MONSTER); } @@ -441,5 +441,5 @@ protected void waitForSyncTaskStart() throws Exception { protected void waitForSyncTaskNextRun() throws Exception { waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_HR_OID, false, 10000); } - + } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/AbstractGenericSyncTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/AbstractGenericSyncTest.java index ad61d5fddbd..1023d755b0e 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/AbstractGenericSyncTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/AbstractGenericSyncTest.java @@ -29,20 +29,20 @@ /** * 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"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class AbstractGenericSyncTest extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/gensync"); protected static final File USER_OTIS_FILE = new File(TEST_DIR, "user-otis.xml"); protected static final String USER_OTIS_OID = "fd5039c8-ddc8-11e4-8ec7-001e8c717e5b"; protected static final String USER_OTIS_USERNAME = "otis"; - + protected static final File ROLE_SWASHBUCKLER_FILE = new File(TEST_DIR, "role-swashbuckler.xml"); protected static final String ROLE_SWASHBUCKLER_OID = "12345678-d34d-b33f-f00d-5b5b5b5b5b5b"; protected static final String ROLE_SWASHBUCKLER_NAME = "Swashbuckler"; @@ -50,7 +50,7 @@ public class AbstractGenericSyncTest extends AbstractInitializedModelIntegration protected static final File ROLE_PRISONER_FILE = new File(TEST_DIR, "role-prisoner.xml"); protected static final String ROLE_PRISONER_OID = "90c332ec-ddc8-11e4-bb3b-001e8c717e5b"; - + protected static final String GROUP_SWASHBUCKLER_DUMMY_NAME = "swashbuckler"; protected static final File ROLE_META_DUMMYGROUP_FILE = new File(TEST_DIR, "role-meta-dummygroup.xml"); @@ -59,7 +59,7 @@ public class AbstractGenericSyncTest extends AbstractInitializedModelIntegration protected static final File SYSTEM_CONFIGURATION_GENSYNC_FILE = new File(TEST_DIR, "system-configuration.xml"); protected static final File OBJECT_TEMPLATE_ROLE_FILE = new File(TEST_DIR, "object-template-role.xml"); - + public static final File LOOKUP_ROLE_TYPE_FILE = new File(TEST_DIR, "lookup-role-type.xml"); public static final String LOOKUP_ROLE_TYPE_OID = "70000000-0000-0000-1111-000000000021"; @@ -71,7 +71,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti repoAddObjectFromFile(ROLE_META_DUMMYGROUP_FILE, initResult); repoAddObjectFromFile(LOOKUP_ROLE_TYPE_FILE, initResult); } - + @Override protected File getSystemConfigurationFile() { return SYSTEM_CONFIGURATION_GENSYNC_FILE; 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 ee66f4128a0..e5ff5b70579 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 @@ -97,14 +97,14 @@ public class TestEditSchema extends AbstractGenericSyncTest { @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + setDefaultUserTemplate(USER_TEMPLATE_COMPLEX_OID); importObjectFromFile(ROLE_PRISONER_FILE); importObjectFromFile(USER_OTIS_FILE); - + rememberSteadyResources(); } - + @Test public void test100LookupLanguagesGet() throws Exception { final String TEST_NAME="test100LookupLanguagesGet"; @@ -113,26 +113,26 @@ public void test100LookupLanguagesGet() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject lookup = modelService.getObject(LookupTableType.class, LOOKUP_LANGUAGES_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); IntegrationTestTools.display("Languages", lookup); - + assertEquals("Wrong lang lookup name", LOOKUP_LANGUAGES_NAME, lookup.asObjectable().getName().getOrig()); - + PrismContainer tableContainer = lookup.findContainer(LookupTableType.F_ROW); assertNull("Table container sneaked in", tableContainer); - + assertSteadyResources(); } - + @Test public void test102LookupLanguagesGetExclude() throws Exception { final String TEST_NAME="test102LookupLanguagesGetExclude"; @@ -141,29 +141,29 @@ public void test102LookupLanguagesGetExclude() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + Collection> options = SelectorOptions.createCollection(LookupTableType.F_ROW, GetOperationOptions.createRetrieve(RetrieveOption.EXCLUDE)); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject lookup = modelService.getObject(LookupTableType.class, LOOKUP_LANGUAGES_OID, options, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); IntegrationTestTools.display("Languages", lookup); - + assertEquals("Wrong lang lookup name", LOOKUP_LANGUAGES_NAME, lookup.asObjectable().getName().getOrig()); - + PrismContainer tableContainer = lookup.findContainer(LookupTableType.F_ROW); assertNull("Table container sneaked in", tableContainer); - + assertSteadyResources(); } - + @Test public void test110LookupLanguagesGetAll() throws Exception { final String TEST_NAME="test110LookupLanguagesGetAll"; @@ -172,11 +172,11 @@ public void test110LookupLanguagesGetAll() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject lookup = getLookupTableAll(LOOKUP_LANGUAGES_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -186,7 +186,7 @@ public void test110LookupLanguagesGetAll() throws Exception { new String[]{"sk_SK", "sk", "Slovak"}, new String[]{"tr_TR", "tr", "Turkish"}); } - + @Test public void test120LookupLanguagesGetByKeyExact() throws Exception { final String TEST_NAME="test120LookupLanguagesGetByKeyExact"; @@ -450,32 +450,32 @@ public void test150LookupLanguagesAddRowFull() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + LookupTableRowType row = new LookupTableRowType(); row.setKey("gi_GI"); row.setValue("gi"); row.setLabel(PrismTestUtil.createPolyStringType("Gibberish")); ObjectDelta delta = ObjectDelta.createModificationAddContainer(LookupTableType.class, LOOKUP_LANGUAGES_OID, LookupTableType.F_ROW, prismContext, row); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject lookup = getLookupTableAll(LOOKUP_LANGUAGES_OID, task, result); - + result.computeStatus(); TestUtil.assertSuccess(result); IntegrationTestTools.display("Languages", lookup); - + assertEquals("Wrong lang lookup name", LOOKUP_LANGUAGES_NAME, lookup.asObjectable().getName().getOrig()); - + PrismContainer tableContainer = lookup.findContainer(LookupTableType.F_ROW); assertNotNull("Table container missing", tableContainer); assertEquals("Unexpected table container size", 5, tableContainer.size()); @@ -484,9 +484,9 @@ public void test150LookupLanguagesAddRowFull() throws Exception { assertLookupRow(tableContainer, "en_PR", "en", "English (pirate)"); assertLookupRow(tableContainer, "sk_SK", "sk", "Slovak"); assertLookupRow(tableContainer, "tr_TR", "tr", "Turkish"); - + assertLookupRow(tableContainer, "gi_GI", "gi", "Gibberish"); - + assertSteadyResources(); } @@ -498,31 +498,31 @@ public void test152LookupLanguagesAddRowKeyLabel() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + LookupTableRowType row = new LookupTableRowType(); row.setKey("gi_GO"); row.setLabel(PrismTestUtil.createPolyStringType("Gobbledygook")); ObjectDelta delta = ObjectDelta.createModificationAddContainer(LookupTableType.class, LOOKUP_LANGUAGES_OID, LookupTableType.F_ROW, prismContext, row); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject lookup = getLookupTableAll(LOOKUP_LANGUAGES_OID, task, result); - + result.computeStatus(); TestUtil.assertSuccess(result); IntegrationTestTools.display("Languages", lookup); - + assertEquals("Wrong lang lookup name", LOOKUP_LANGUAGES_NAME, lookup.asObjectable().getName().getOrig()); - + PrismContainer tableContainer = lookup.findContainer(LookupTableType.F_ROW); assertNotNull("Table container missing", tableContainer); assertEquals("Unexpected table container size", 6, tableContainer.size()); @@ -532,12 +532,12 @@ public void test152LookupLanguagesAddRowKeyLabel() throws Exception { assertLookupRow(tableContainer, "sk_SK", "sk", "Slovak"); assertLookupRow(tableContainer, "tr_TR", "tr", "Turkish"); assertLookupRow(tableContainer, "gi_GI", "gi", "Gibberish"); - + assertLookupRow(tableContainer, "gi_GO", null, "Gobbledygook"); - + assertSteadyResources(); } - + @Test public void test154LookupLanguagesAddRowKeyValue() throws Exception { final String TEST_NAME="test154LookupLanguagesAddRowKeyValue"; @@ -546,31 +546,31 @@ public void test154LookupLanguagesAddRowKeyValue() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + LookupTableRowType row = new LookupTableRowType(); row.setKey("gi_HU"); row.setValue("gi"); ObjectDelta delta = ObjectDelta.createModificationAddContainer(LookupTableType.class, LOOKUP_LANGUAGES_OID, LookupTableType.F_ROW, prismContext, row); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject lookup = getLookupTableAll(LOOKUP_LANGUAGES_OID, task, result); - + result.computeStatus(); TestUtil.assertSuccess(result); IntegrationTestTools.display("Languages", lookup); - + assertEquals("Wrong lang lookup name", LOOKUP_LANGUAGES_NAME, lookup.asObjectable().getName().getOrig()); - + PrismContainer tableContainer = lookup.findContainer(LookupTableType.F_ROW); assertNotNull("Table container missing", tableContainer); assertEquals("Unexpected table container size", 7, tableContainer.size()); @@ -581,12 +581,12 @@ public void test154LookupLanguagesAddRowKeyValue() throws Exception { assertLookupRow(tableContainer, "tr_TR", "tr", "Turkish"); assertLookupRow(tableContainer, "gi_GI", "gi", "Gibberish"); assertLookupRow(tableContainer, "gi_GO", null, "Gobbledygook"); - + assertLookupRow(tableContainer, "gi_HU", "gi", null); - + assertSteadyResources(); } - + @Test public void test156LookupLanguagesAddRowExistingKey() throws Exception { final String TEST_NAME="test156LookupLanguagesAddRowExistingKey"; @@ -595,14 +595,14 @@ public void test156LookupLanguagesAddRowExistingKey() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + LookupTableRowType row = new LookupTableRowType(); row.setKey("gi_HU"); row.setValue("gi"); row.setLabel(PrismTestUtil.createPolyStringType("Humbug")); ObjectDelta delta = ObjectDelta.createModificationAddContainer(LookupTableType.class, LOOKUP_LANGUAGES_OID, LookupTableType.F_ROW, prismContext, row); - + // WHEN TestUtil.displayWhen(TEST_NAME); boolean exception = false; @@ -612,7 +612,7 @@ public void test156LookupLanguagesAddRowExistingKey() throws Exception { exception = true; } AssertJUnit.assertFalse(exception); // as per description in https://wiki.evolveum.com/display/midPoint/Development+with+LookupTable - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -621,14 +621,14 @@ public void test156LookupLanguagesAddRowExistingKey() throws Exception { task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); result = task.getResult(); PrismObject lookup = getLookupTableAll(LOOKUP_LANGUAGES_OID, task, result); - + result.computeStatus(); TestUtil.assertSuccess(result); IntegrationTestTools.display("Languages", lookup); - + assertEquals("Wrong lang lookup name", LOOKUP_LANGUAGES_NAME, lookup.asObjectable().getName().getOrig()); - + PrismContainer tableContainer = lookup.findContainer(LookupTableType.F_ROW); assertNotNull("Table container missing", tableContainer); assertEquals("Unexpected table container size", 7, tableContainer.size()); @@ -639,9 +639,9 @@ public void test156LookupLanguagesAddRowExistingKey() throws Exception { assertLookupRow(tableContainer, "tr_TR", "tr", "Turkish"); assertLookupRow(tableContainer, "gi_GI", "gi", "Gibberish"); assertLookupRow(tableContainer, "gi_GO", null, "Gobbledygook"); - + assertLookupRow(tableContainer, "gi_HU", "gi", "Humbug"); - + assertSteadyResources(); } @@ -656,32 +656,32 @@ public void test162LookupLanguagesDeleteRowFullNoId() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + LookupTableRowType row = new LookupTableRowType(); row.setKey("sk_SK"); row.setValue("sk"); row.setLabel(PrismTestUtil.createPolyStringType("Slovak")); ObjectDelta delta = ObjectDelta.createModificationDeleteContainer(LookupTableType.class, LOOKUP_LANGUAGES_OID, LookupTableType.F_ROW, prismContext, row); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject lookup = getLookupTableAll(LOOKUP_LANGUAGES_OID, task, result); - + result.computeStatus(); TestUtil.assertSuccess(result); IntegrationTestTools.display("Languages", lookup); - + assertEquals("Wrong lang lookup name", LOOKUP_LANGUAGES_NAME, lookup.asObjectable().getName().getOrig()); - + PrismContainer tableContainer = lookup.findContainer(LookupTableType.F_ROW); assertNotNull("Table container missing", tableContainer); assertEquals("Unexpected table container size", 6, tableContainer.size()); @@ -692,10 +692,10 @@ public void test162LookupLanguagesDeleteRowFullNoId() throws Exception { assertLookupRow(tableContainer, "gi_GI", "gi", "Gibberish"); assertLookupRow(tableContainer, "gi_GO", null, "Gobbledygook"); assertLookupRow(tableContainer, "gi_HU", "gi", "Humbug"); - + assertSteadyResources(); } - + @Test public void test164LookupLanguagesDeleteRowFullId() throws Exception { final String TEST_NAME="test164LookupLanguagesDeleteRowFullId"; @@ -704,7 +704,7 @@ public void test164LookupLanguagesDeleteRowFullId() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + LookupTableRowType row = new LookupTableRowType(); row.setKey("en_US"); row.setValue("en"); @@ -712,25 +712,25 @@ public void test164LookupLanguagesDeleteRowFullId() throws Exception { row.setId(1L); ObjectDelta delta = ObjectDelta.createModificationDeleteContainer(LookupTableType.class, LOOKUP_LANGUAGES_OID, LookupTableType.F_ROW, prismContext, row); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject lookup = getLookupTableAll(LOOKUP_LANGUAGES_OID, task, result); - + result.computeStatus(); TestUtil.assertSuccess(result); IntegrationTestTools.display("Languages", lookup); - + assertEquals("Wrong lang lookup name", LOOKUP_LANGUAGES_NAME, lookup.asObjectable().getName().getOrig()); - + PrismContainer tableContainer = lookup.findContainer(LookupTableType.F_ROW); assertNotNull("Table container missing", tableContainer); assertEquals("Unexpected table container size", 5, tableContainer.size()); @@ -743,7 +743,7 @@ public void test164LookupLanguagesDeleteRowFullId() throws Exception { assertSteadyResources(); } - + @Test public void test166LookupLanguagesDeleteRowIdOnly() throws Exception { final String TEST_NAME="test166LookupLanguagesDeleteRowIdOnly"; @@ -752,30 +752,30 @@ public void test166LookupLanguagesDeleteRowIdOnly() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + LookupTableRowType row = new LookupTableRowType(); row.setId(2L); ObjectDelta delta = ObjectDelta.createModificationDeleteContainer(LookupTableType.class, LOOKUP_LANGUAGES_OID, LookupTableType.F_ROW, prismContext, row); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject lookup = getLookupTableAll(LOOKUP_LANGUAGES_OID, task, result); - + result.computeStatus(); TestUtil.assertSuccess(result); IntegrationTestTools.display("Languages", lookup); - + assertEquals("Wrong lang lookup name", LOOKUP_LANGUAGES_NAME, lookup.asObjectable().getName().getOrig()); - + PrismContainer tableContainer = lookup.findContainer(LookupTableType.F_ROW); assertNotNull("Table container missing", tableContainer); assertEquals("Unexpected table container size", 4, tableContainer.size()); @@ -784,7 +784,7 @@ public void test166LookupLanguagesDeleteRowIdOnly() throws Exception { assertLookupRow(tableContainer, "gi_GO", null, "Gobbledygook"); assertLookupRow(tableContainer, "gi_HU", "gi", "Humbug"); assertLookupRow(tableContainer, "tr_TR", "tr", "Turkish"); - + assertSteadyResources(); } @@ -796,30 +796,30 @@ public void test168LookupLanguagesDeleteRowByKey() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + LookupTableRowType row = new LookupTableRowType(); row.setKey("gi_GI"); ObjectDelta delta = ObjectDelta.createModificationDeleteContainer(LookupTableType.class, LOOKUP_LANGUAGES_OID, LookupTableType.F_ROW, prismContext, row); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject lookup = getLookupTableAll(LOOKUP_LANGUAGES_OID, task, result); - + result.computeStatus(); TestUtil.assertSuccess(result); IntegrationTestTools.display("Languages", lookup); - + assertEquals("Wrong lang lookup name", LOOKUP_LANGUAGES_NAME, lookup.asObjectable().getName().getOrig()); - + PrismContainer tableContainer = lookup.findContainer(LookupTableType.F_ROW); assertNotNull("Table container missing", tableContainer); assertEquals("Unexpected table container size", 3, tableContainer.size()); @@ -839,7 +839,7 @@ public void test170LookupLanguagesReplaceRows() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + LookupTableRowType row1 = new LookupTableRowType(); row1.setKey("ja_JA"); row1.setValue("ja"); @@ -857,25 +857,25 @@ public void test170LookupLanguagesReplaceRows() throws Exception { ObjectDelta delta = ObjectDelta.createModificationReplaceContainer(LookupTableType.class, LOOKUP_LANGUAGES_OID, LookupTableType.F_ROW, prismContext, row1, row2, row3); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject lookup = getLookupTableAll(LOOKUP_LANGUAGES_OID, task, result); - + result.computeStatus(); TestUtil.assertSuccess(result); IntegrationTestTools.display("Languages", lookup); - + assertEquals("Wrong lang lookup name", LOOKUP_LANGUAGES_NAME, lookup.asObjectable().getName().getOrig()); - + PrismContainer tableContainer = lookup.findContainer(LookupTableType.F_ROW); assertNotNull("Table container missing", tableContainer); assertEquals("Unexpected table container size", 3, tableContainer.size()); @@ -883,7 +883,7 @@ public void test170LookupLanguagesReplaceRows() throws Exception { assertLookupRow(tableContainer, "ja_JA", "ja", "Jabber"); assertLookupRow(tableContainer, "ja_MJ", "ja", "Mumbojumbo"); assertLookupRow(tableContainer, "en_PR", "en1", "English (pirate1)"); - + assertSteadyResources(); } @@ -926,7 +926,7 @@ public void test180LookupLanguagesReplaceObject() throws Exception { assertLookupRow(tableContainer, "fr_FR", "fr", "Français"); assertSteadyResources(); } - + @Test public void test182LookupLanguagesReimport() throws Exception { final String TEST_NAME="test182LookupLanguagesReimport"; @@ -939,7 +939,7 @@ public void test182LookupLanguagesReimport() throws Exception { ImportOptionsType options = new ImportOptionsType(); options.setOverwrite(true); options.setKeepOid(true); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.importObjectsFromFile(LOOKUP_LANGUAGES_FILE, options, task, result); @@ -962,7 +962,7 @@ public void test182LookupLanguagesReimport() throws Exception { new String[]{"en_PR", "en", "English (pirate)"}, new String[]{"sk_SK", "sk", "Slovak"}, new String[]{"tr_TR", "tr", "Turkish"}); - + assertSteadyResources(); } @@ -989,7 +989,7 @@ private PrismObject getLookupTableAll(String oid, Task task, Op GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE)); return modelService.getObject(LookupTableType.class, oid, options, task, result); } - + @Test public void test200EditSchemaUser() throws Exception { final String TEST_NAME="test200EditSchemaUser"; @@ -998,36 +998,36 @@ public void test200EditSchemaUser() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObjectDefinition userDef = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); PrismObject user = userDef.instantiate(); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObjectDefinition editDef = getEditObjectDefinition(user); - + // THEN TestUtil.displayThen(TEST_NAME); - - + + PrismAsserts.assertEmphasized(editDef, UserType.F_NAME, true); PrismAsserts.assertEmphasized(editDef, UserType.F_GIVEN_NAME, false); PrismAsserts.assertEmphasized(editDef, UserType.F_FAMILY_NAME, true); PrismAsserts.assertEmphasized(editDef, UserType.F_FULL_NAME, true); PrismAsserts.assertEmphasized(editDef, UserType.F_DESCRIPTION, false); - + PrismPropertyDefinition additionalNameDef = editDef.findPropertyDefinition(UserType.F_ADDITIONAL_NAME); assertNotNull("No definition for additionalName in user", additionalNameDef); assertEquals("Wrong additionalName displayName", "Middle Name", additionalNameDef.getDisplayName()); assertTrue("additionalName not readable", additionalNameDef.canRead()); PrismAsserts.assertEmphasized(additionalNameDef, false); - + PrismPropertyDefinition costCenterDef = editDef.findPropertyDefinition(UserType.F_COST_CENTER); assertNotNull("No definition for costCenter in user", costCenterDef); assertEquals("Wrong costCenter displayOrder", (Integer)123, costCenterDef.getDisplayOrder()); assertTrue("costCenter not readable", costCenterDef.canRead()); PrismAsserts.assertEmphasized(costCenterDef, true); - + // This has overridden lookup def in object template PrismPropertyDefinition preferredLanguageDef = editDef.findPropertyDefinition(UserType.F_PREFERRED_LANGUAGE); assertNotNull("No definition for preferredLanguage in user", preferredLanguageDef); @@ -1045,19 +1045,19 @@ public void test200EditSchemaUser() throws Exception { valueEnumerationRef = timezoneDef.getValueEnumerationRef(); assertNotNull("No valueEnumerationRef for timezone", valueEnumerationRef); assertEquals("Wrong valueEnumerationRef OID for timezone", SystemObjectsType.LOOKUP_TIMEZONES.value(), valueEnumerationRef.getOid()); - + PrismContainerDefinition credentialsDef = editDef.findContainerDefinition(UserType.F_CREDENTIALS); assertNotNull("No definition for credentials in user", credentialsDef); assertTrue("Credentials not readable", credentialsDef.canRead()); - + ItemPath passwdValPath = new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE); PrismPropertyDefinition passwdValDef = editDef.findPropertyDefinition(passwdValPath); assertNotNull("No definition for "+passwdValPath+" in user", passwdValDef); assertTrue("Password not readable", passwdValDef.canRead()); - + assertSteadyResources(); } - + @Test public void test210UserDefinition() throws Exception { final String TEST_NAME="test210UserDefinition"; @@ -1066,16 +1066,16 @@ public void test210UserDefinition() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject user = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertPropertyValues(user, UserType.F_ADDITIONAL_NAME, new Validator>() { @Override public void validate(PrismPropertyDefinition propDef, String name) throws Exception { @@ -1084,7 +1084,7 @@ public void validate(PrismPropertyDefinition propDef, String name) t assertTrue("additionalName not readable", propDef.canRead()); } }, PrismTestUtil.createPolyString("Jackie")); - + assertPropertyValues(user, UserType.F_COST_CENTER, new Validator>() { @Override @@ -1094,7 +1094,7 @@ public void validate(PrismPropertyDefinition propDef, String name) throw assertTrue("costCenter not readable", propDef.canRead()); } }); - + assertPropertyValues(user, UserType.F_PREFERRED_LANGUAGE, new Validator>() { @Override public void validate(PrismPropertyDefinition propDef, String name) throws Exception { @@ -1106,7 +1106,7 @@ public void validate(PrismPropertyDefinition propDef, String name) throw assertEquals("Wrong valueEnumerationRef OID for preferredLanguage", LOOKUP_LANGUAGES_OID, valueEnumerationRef.getOid()); } }); - + assertContainer(user, UserType.F_CREDENTIALS, new Validator>() { @Override public void validate(PrismContainerDefinition credentialsDef, String name) @@ -1114,9 +1114,9 @@ public void validate(PrismContainerDefinition credentialsDef, S assertNotNull("No definition for credentials in user", credentialsDef); assertTrue("Credentials not readable", credentialsDef.canRead()); } - + }, true); - + assertProperty(user, new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), new Validator>() { @Override @@ -1124,10 +1124,10 @@ public void validate(PrismPropertyDefinition propDef, String name) throw assertTrue("Password not readable", propDef.canRead()); } }); - + assertSteadyResources(); } - + /** * Check that the user definition in schema registry was not ruined * @throws Exception @@ -1140,7 +1140,7 @@ public void test211SchemaRegistryUntouched() throws Exception { assertUntouchedUserDefinition(); assertSteadyResources(); } - + /** * Modify jack, see if the schema still applies. */ @@ -1152,18 +1152,18 @@ public void test213ModifiedUserJack() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + modifyObjectReplaceProperty(UserType.class, USER_JACK_OID, UserType.F_PREFERRED_LANGUAGE, task, result, "en_PR"); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject user = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertPropertyValues(user, UserType.F_ADDITIONAL_NAME, new Validator>() { @Override public void validate(PrismPropertyDefinition propDef, String name) throws Exception { @@ -1172,7 +1172,7 @@ public void validate(PrismPropertyDefinition propDef, String name) t assertTrue("additionalName not readable", propDef.canRead()); } }, PrismTestUtil.createPolyString("Jackie")); - + assertPropertyValues(user, UserType.F_COST_CENTER, new Validator>() { @Override public void validate(PrismPropertyDefinition propDef, String name) throws Exception { @@ -1181,7 +1181,7 @@ public void validate(PrismPropertyDefinition propDef, String name) throw assertTrue("costCenter not readable", propDef.canRead()); } },"G001"); // This is set by user template - + assertPropertyValues(user, UserType.F_PREFERRED_LANGUAGE, new Validator>() { @Override public void validate(PrismPropertyDefinition propDef, String name) throws Exception { @@ -1193,7 +1193,7 @@ public void validate(PrismPropertyDefinition propDef, String name) throw assertEquals("Wrong valueEnumerationRef OID for preferredLanguage", LOOKUP_LANGUAGES_OID, valueEnumerationRef.getOid()); } }, "en_PR"); - + assertContainer(user, UserType.F_CREDENTIALS, new Validator>() { @Override @@ -1202,9 +1202,9 @@ public void validate(PrismContainerDefinition credentialsDef, S assertNotNull("No definition for credentials in user", credentialsDef); assertTrue("Credentials not readable", credentialsDef.canRead()); } - + }, true); - + assertProperty(user, new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), new Validator>() { @Override @@ -1212,11 +1212,11 @@ public void validate(PrismPropertyDefinition propDef, String name) throw assertTrue("Password not readable", propDef.canRead()); } }); - + assertUntouchedUserDefinition(); assertSteadyResources(); } - + @Test public void test250EditSchemaRole() throws Exception { @@ -1226,17 +1226,17 @@ public void test250EditSchemaRole() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObjectDefinition roleDef = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(RoleType.class); PrismObject role = roleDef.instantiate(); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObjectDefinition editDef = getEditObjectDefinition(role); - + // THEN TestUtil.displayThen(TEST_NAME); - + // TODO PrismPropertyDefinition requestableDef = editDef.findPropertyDefinition(RoleType.F_REQUESTABLE); assertNotNull("No definition for requestable in role", requestableDef); @@ -1244,7 +1244,7 @@ public void test250EditSchemaRole() throws Exception { assertSteadyResources(); } - + @Test public void test260EditShadowSchemaKindIntent() throws Exception { final String TEST_NAME="test260EditShadowSchemaKindIntent"; @@ -1253,28 +1253,28 @@ public void test260EditShadowSchemaKindIntent() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ResourceShadowDiscriminator discr = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, null); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObjectDefinition editDef = modelInteractionService.getEditShadowDefinition(discr, AuthorizationPhaseType.REQUEST, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismPropertyDefinition nameDef = editDef.findPropertyDefinition(ShadowType.F_NAME); assertNotNull("No definition for name in shadow", nameDef); assertEquals("Wrong shadow name displayName", "ObjectType.name", nameDef.getDisplayName()); assertTrue("additionalName not readable", nameDef.canRead()); - + PrismPropertyDefinition attrFullNameDef = editDef.findPropertyDefinition(dummyResourceCtl.getAttributeFullnamePath()); assertNotNull("No definition for fullname attribute in shadow", attrFullNameDef); assertEquals("Wrong shadow fullname attribute displayName", "Full Name", attrFullNameDef.getDisplayName()); assertTrue("additionalName not readable", attrFullNameDef.canRead()); - + assertSteadyResources(); } @@ -1286,29 +1286,29 @@ public void test261EditShadowSchemaObjectclass() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ResourceShadowDiscriminator discr = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, dummyResourceCtl.getAccountObjectClassQName()); IntegrationTestTools.display("Discr", discr); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObjectDefinition editDef = modelInteractionService.getEditShadowDefinition(discr, AuthorizationPhaseType.REQUEST, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismPropertyDefinition nameDef = editDef.findPropertyDefinition(ShadowType.F_NAME); assertNotNull("No definition for name in shadow", nameDef); assertEquals("Wrong shadow name displayName", "ObjectType.name", nameDef.getDisplayName()); assertTrue("additionalName not readable", nameDef.canRead()); - + PrismPropertyDefinition attrFullNameDef = editDef.findPropertyDefinition(dummyResourceCtl.getAttributeFullnamePath()); assertNotNull("No definition for fullname attribute in shadow", attrFullNameDef); assertEquals("Wrong shadow fullname attribute displayName", "Full Name", attrFullNameDef.getDisplayName()); assertTrue("additionalName not readable", attrFullNameDef.canRead()); - + assertSteadyResources(); } @@ -1320,27 +1320,27 @@ public void test263EditShadowSchemaEmpty() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ResourceShadowDiscriminator discr = new ResourceShadowDiscriminator(null, null); IntegrationTestTools.display("Discr", discr); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObjectDefinition editDef = modelInteractionService.getEditShadowDefinition(discr, AuthorizationPhaseType.REQUEST, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismPropertyDefinition nameDef = editDef.findPropertyDefinition(ShadowType.F_NAME); assertNotNull("No definition for name in shadow", nameDef); assertEquals("Wrong shadow name displayName", "ObjectType.name", nameDef.getDisplayName()); assertTrue("additionalName not readable", nameDef.canRead()); - + PrismPropertyDefinition attrFullNameDef = editDef.findPropertyDefinition(dummyResourceCtl.getAttributeFullnamePath()); assertNull("Unexpected definition for fullname attribute in shadow", attrFullNameDef); - + assertSteadyResources(); } @@ -1352,24 +1352,24 @@ public void test265EditShadowSchemaNull() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObjectDefinition editDef = modelInteractionService.getEditShadowDefinition(null, AuthorizationPhaseType.REQUEST, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismPropertyDefinition nameDef = editDef.findPropertyDefinition(ShadowType.F_NAME); assertNotNull("No definition for name in shadow", nameDef); assertEquals("Wrong shadow name displayName", "ObjectType.name", nameDef.getDisplayName()); assertTrue("additionalName not readable", nameDef.canRead()); - + PrismPropertyDefinition attrFullNameDef = editDef.findPropertyDefinition(dummyResourceCtl.getAttributeFullnamePath()); assertNull("Unexpected definition for fullname attribute in shadow", attrFullNameDef); - + assertSteadyResources(); } @@ -1379,9 +1379,9 @@ public void test300RoleTypes() throws Exception { final String TEST_NAME="test300RoleTypes"; TestUtil.displayTestTitle(this, TEST_NAME); - assertRoleTypes(getUser(USER_JACK_OID), "application","system","it"); + assertRoleTypes(getUser(USER_JACK_OID), "application","system","it"); } - + /** * Login as Otis. Otis has a restricted authorizations. Check that schema is presented accordingly to * these limitations. @@ -1393,42 +1393,42 @@ public void test800OtisEditSchemaUser() throws Exception { // GIVEN login(USER_OTIS_USERNAME); - + Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObjectDefinition userDef = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); PrismObject user = userDef.instantiate(); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObjectDefinition editDef = getEditObjectDefinition(user); IntegrationTestTools.display("Otis edit schema", editDef); - + // THEN TestUtil.displayThen(TEST_NAME); - + PrismPropertyDefinition nameDef = editDef.findPropertyDefinition(UserType.F_NAME); assertNotNull("No definition for name in user", nameDef); assertEquals("Wrong name displayName", "ObjectType.name", nameDef.getDisplayName()); assertTrue("name not readable", nameDef.canRead()); assertTrue("name is creatable", !nameDef.canAdd()); assertTrue("name is modifiable", !nameDef.canModify()); - + PrismPropertyDefinition additionalNameDef = editDef.findPropertyDefinition(UserType.F_ADDITIONAL_NAME); assertNotNull("No definition for additionalName in user", additionalNameDef); assertEquals("Wrong additionalName displayName", "Middle Name", additionalNameDef.getDisplayName()); assertTrue("additionalName is readable", !additionalNameDef.canRead()); assertTrue("additionalName is creatable", !additionalNameDef.canAdd()); assertTrue("additionalName not modifiable", additionalNameDef.canModify()); - + PrismPropertyDefinition costCenterDef = editDef.findPropertyDefinition(UserType.F_COST_CENTER); assertNotNull("No definition for costCenter in user", costCenterDef); assertEquals("Wrong costCenter displayOrder", (Integer)123, costCenterDef.getDisplayOrder()); assertTrue("costCenter is readable", !costCenterDef.canRead()); assertTrue("costCenter is creatable", !costCenterDef.canAdd()); assertTrue("costCenter is modifiable", !costCenterDef.canModify()); - + PrismPropertyDefinition preferredLanguageDef = editDef.findPropertyDefinition(UserType.F_PREFERRED_LANGUAGE); assertNotNull("No definition for preferredLanguage in user", preferredLanguageDef); assertEquals("Wrong preferredLanguage displayName", "Language", preferredLanguageDef.getDisplayName()); @@ -1444,18 +1444,18 @@ public void test800OtisEditSchemaUser() throws Exception { assertTrue("Credentials is readable", !credentialsDef.canRead()); assertTrue("Credentials is creatable", !credentialsDef.canAdd()); assertTrue("Credentials is modifiable", !credentialsDef.canModify()); - + ItemPath passwdValPath = new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE); PrismPropertyDefinition passwdValDef = editDef.findPropertyDefinition(passwdValPath); assertNotNull("No definition for "+passwdValPath+" in user", passwdValDef); assertTrue("Password is readable", !passwdValDef.canRead()); assertTrue("Password is creatable", !passwdValDef.canAdd()); assertTrue("Password is modifiable", !passwdValDef.canModify()); - + assertUntouchedUserDefinition(); assertSteadyResources(); } - + @Test public void test810OtisGetJack() throws Exception { final String TEST_NAME="test810OtisGetJack"; @@ -1463,19 +1463,19 @@ public void test810OtisGetJack() throws Exception { // GIVEN login(USER_OTIS_USERNAME); - + Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject user = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertPropertyValues(user, UserType.F_NAME, new Validator>() { @Override public void validate(PrismPropertyDefinition propDef, String name) throws Exception { @@ -1486,7 +1486,7 @@ public void validate(PrismPropertyDefinition propDef, String name) t assertTrue(name+" is modifiable", !propDef.canModify()); } }, PrismTestUtil.createPolyString("jack")); - + assertPropertyValues(user, UserType.F_DESCRIPTION, new Validator>() { @Override public void validate(PrismPropertyDefinition propDef, String name) throws Exception { @@ -1497,7 +1497,7 @@ public void validate(PrismPropertyDefinition propDef, String name) throw assertTrue(name+" not modifiable", propDef.canModify()); } }, "Where's the rum?"); - + assertPropertyValues(user, UserType.F_ADDITIONAL_NAME, new Validator>() { @Override public void validate(PrismPropertyDefinition propDef, String name) throws Exception { @@ -1508,7 +1508,7 @@ public void validate(PrismPropertyDefinition propDef, String name) t assertTrue(name+" not modifiable", propDef.canModify()); } }); - + assertPropertyValues(user, UserType.F_COST_CENTER, new Validator>() { @Override public void validate(PrismPropertyDefinition propDef, String name) throws Exception { @@ -1519,7 +1519,7 @@ public void validate(PrismPropertyDefinition propDef, String name) throw assertTrue(name+" is modifiable", !propDef.canModify()); } }); - + assertPropertyValues(user, UserType.F_PREFERRED_LANGUAGE, new Validator>() { @Override public void validate(PrismPropertyDefinition propDef, String name) throws Exception { @@ -1535,7 +1535,7 @@ public void validate(PrismPropertyDefinition propDef, String name) throw }); PrismAsserts.assertNoItem(user, UserType.F_CREDENTIALS); - + assertUntouchedUserDefinition(); assertSteadyResources(); } @@ -1547,21 +1547,21 @@ public void test820OtisSearchUsers() throws Exception { // GIVEN login(USER_OTIS_USERNAME); - + Task task = taskManager.createTaskInstance(TestEditSchema.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); SearchResultList> users = modelService.searchObjects(UserType.class, null, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertEquals("Unexepected number of users found", 6, users.size()); - + for (final PrismObject user: users) { assertProperty(user, UserType.F_NAME, new Validator>() { @Override @@ -1593,7 +1593,7 @@ public void validate(PrismPropertyDefinition propDef, String name) throw assertTrue(name+" of "+user+" is modifiable", !propDef.canModify()); } }); - + assertProperty(user, UserType.F_PREFERRED_LANGUAGE, new Validator>() { @Override public void validate(PrismPropertyDefinition propDef, String name) throws Exception { @@ -1609,28 +1609,28 @@ public void validate(PrismPropertyDefinition propDef, String name) throw }); PrismAsserts.assertNoItem(user, UserType.F_CREDENTIALS); - + assertUntouchedUserDefinition(); } - + } - - + + private void assertPropertyValues(PrismObject object, QName propName, Validator> validator, T... expectedValues) throws Exception { assertPropertyValues(object, new ItemPath(propName), validator, expectedValues); } - + private void assertProperty(PrismObject object, ItemPath path, Validator> validator) throws Exception { assertPropertyValues(object, path, validator, (T[])null); } - + private void assertProperty(PrismObject object, QName propname, Validator> validator) throws Exception { assertPropertyValues(object, new ItemPath(propname), validator, (T[])null); } - + private void assertPropertyValues(PrismObject object, ItemPath path, Validator> validator, T... expectedValues) throws Exception { PrismProperty prop = object.findProperty(path); @@ -1659,7 +1659,7 @@ private void assertPropertyValues(PrismObject objec throw e; } } - + PrismPropertyDefinition objPropDef = object.getDefinition().findPropertyDefinition(path); assertNotNull("No definition of property "+path+" in object "+object, objPropDef); try { @@ -1670,7 +1670,7 @@ private void assertPropertyValues(PrismObject objec } } - + private void assertContainer(PrismObject object, QName contName, Validator> validator, boolean valueExpected) throws Exception { PrismContainer container = object.findContainer(contName); @@ -1682,7 +1682,7 @@ private void assertContainer(Pri } else { assertNull("Unexpected container "+contName+" in "+object+": "+container, container); } - + PrismContainerDefinition objContDef = object.getDefinition().findContainerDefinition(contName); assertNotNull("No definition of container "+contName+" in object "+object, objContDef); validator.validate(objContDef, contName.toString()); @@ -1691,24 +1691,24 @@ private void assertContainer(Pri private void assertUntouchedUserDefinition() { // WHEN PrismObjectDefinition userDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class); - - + + // THEN - + PrismPropertyDefinition descriptionDef = userDefinition.findPropertyDefinition(UserType.F_DESCRIPTION); assertNotNull("No definition for description in user", descriptionDef); assertEquals("Wrong description displayName", "ObjectType.description", descriptionDef.getDisplayName()); assertTrue("description not readable", descriptionDef.canRead()); assertTrue("description not creatable", descriptionDef.canAdd()); assertTrue("description not modifiable", descriptionDef.canModify()); - + PrismPropertyDefinition additionalNameDef = userDefinition.findPropertyDefinition(UserType.F_ADDITIONAL_NAME); assertNotNull("No definition for additionalName in user", additionalNameDef); assertEquals("Wrong additionalName displayName", "UserType.additionalName", additionalNameDef.getDisplayName()); assertTrue("additionalName not readable", additionalNameDef.canRead()); assertTrue("additionalName not creatable", additionalNameDef.canAdd()); assertTrue("additionalName not modifiable", additionalNameDef.canModify()); - + PrismPropertyDefinition costCenterDef = userDefinition.findPropertyDefinition(UserType.F_COST_CENTER); assertNotNull("No definition for costCenter in user", costCenterDef); assertEquals("Wrong costCenter displayOrder", (Integer)420, costCenterDef.getDisplayOrder()); @@ -1717,7 +1717,7 @@ private void assertUntouchedUserDefinition() { assertTrue("costCenter not modifiable", costCenterDef.canModify()); PrismReferenceValue valueEnumerationRef = costCenterDef.getValueEnumerationRef(); assertNull("valueEnumerationRef for costCente sneaked in", valueEnumerationRef); - + PrismPropertyDefinition preferredLanguageDef = userDefinition.findPropertyDefinition(UserType.F_PREFERRED_LANGUAGE); assertNotNull("No definition for preferredLanguage in user", preferredLanguageDef); assertEquals("Wrong preferredLanguage displayName", "UserType.preferredLanguage", preferredLanguageDef.getDisplayName()); @@ -1726,7 +1726,7 @@ private void assertUntouchedUserDefinition() { assertTrue("preferredLanguage not modifiable", preferredLanguageDef.canModify()); valueEnumerationRef = preferredLanguageDef.getValueEnumerationRef(); assertNotNull("valueEnumerationRef for preferredLanguage missing", valueEnumerationRef); - assertEquals("wrong OID in valueEnumerationRef for preferredLanguage missing", + assertEquals("wrong OID in valueEnumerationRef for preferredLanguage missing", SystemObjectsType.LOOKUP_LANGUAGES.value(), valueEnumerationRef.getOid()); PrismContainerDefinition credentialsDef = userDefinition.findContainerDefinition(UserType.F_CREDENTIALS); @@ -1734,13 +1734,13 @@ private void assertUntouchedUserDefinition() { assertTrue("Credentials not readable", credentialsDef.canRead()); assertTrue("Credentials not creatable", credentialsDef.canAdd()); assertTrue("Credentials not modifiable", credentialsDef.canModify()); - + ItemPath passwdValPath = new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE); PrismPropertyDefinition passwdValDef = userDefinition.findPropertyDefinition(passwdValPath); assertNotNull("No definition for "+passwdValPath+" in user", passwdValDef); assertTrue("Password not readable", passwdValDef.canRead()); assertTrue("Password not creatable", passwdValDef.canAdd()); assertTrue("Password not modifiable", passwdValDef.canModify()); - + } } 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 7f0fb206820..4d88ac79e4d 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 @@ -61,14 +61,14 @@ /** * 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"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestRoleEntitlement extends AbstractGenericSyncTest { - + private static String groupOid; @Test @@ -82,23 +82,23 @@ public void test050GetRolePirate() throws Exception { // WHEN PrismObject role = modelService.getObject(RoleType.class, ROLE_PIRATE_OID, null, task, result); - + // THEN display("Role pirate", role); assertRolePirate(role); - + result.computeStatus(); TestUtil.assertSuccess("getObject result", result); } - + protected void assertRolePirate(PrismObject role) { assertObject(role); 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()); + PrismAsserts.assertEqualsPolyString("Wrong "+role+" name", "Pirate", roleType.getName()); } - + @Test public void test100ModifyRoleAddEntitlement() throws Exception { final String TEST_NAME = "test100ModifyRoleAddEntitlement"; @@ -108,29 +108,29 @@ public void test100ModifyRoleAddEntitlement() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - + PrismObject group = PrismTestUtil.parseObject(GROUP_PIRATE_DUMMY_FILE); - + ObjectDelta roleDelta = ObjectDelta.createEmptyModifyDelta(RoleType.class, ROLE_PIRATE_OID, prismContext); PrismReferenceValue linkRefVal = new PrismReferenceValue(); linkRefVal.setObject(group); ReferenceDelta groupDelta = ReferenceDelta.createModificationAdd(RoleType.F_LINK_REF, getRoleDefinition(), linkRefVal); roleDelta.addModification(groupDelta); Collection> deltas = MiscUtil.createCollection(roleDelta); - + dummyAuditService.clear(); 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); display("Role pirate after", rolePirate); @@ -138,18 +138,18 @@ public void test100ModifyRoleAddEntitlement() throws Exception { assertLinks(rolePirate, 1); groupOid = getSingleLinkOid(rolePirate); assertFalse("No linkRef oid", StringUtils.isBlank(groupOid)); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, groupOid, null, result); assertDummyGroupShadowRepo(accountShadow, groupOid, GROUP_PIRATE_DUMMY_NAME); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, groupOid, null, task, result); assertDummyGroupShadowModel(accountModel, groupOid, GROUP_PIRATE_DUMMY_NAME); - + // Check account in dummy resource assertDummyGroup(GROUP_PIRATE_DUMMY_NAME, GROUP_PIRATE_DUMMY_DESCRIPTION); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -684,7 +684,7 @@ public void test131ModifyRoleAssignEntitlement() throws Exception { assertDummyGroup(GROUP_PIRATE_DUMMY_NAME, ROLE_PIRATE_DESCRIPTION); // Just to be on a safe side, this is uppercase assertNoDummyGroup(ROLE_PIRATE_NAME); - + displayProvisioningScripts(); assertNoProvisioningScripts(); // MID-4008 @@ -755,7 +755,7 @@ public void test132ModifyEntitlement() throws Exception { assertDummyGroupAttribute(null, GROUP_PIRATE_DUMMY_NAME, DummyResourceContoller.DUMMY_GROUP_ATTRIBUTE_CC, "MELEE123"); assertNoProvisioningScripts(); // MID-4008 - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); @@ -801,7 +801,7 @@ public void test139ModifyRoleUnassignEntitlement() throws Exception { assertNoDummyGroup(GROUP_PIRATE_DUMMY_NAME); // Just to be on a safe side assertNoDummyGroup(ROLE_PIRATE_NAME); - + assertNoProvisioningScripts(); // MID-4008 // Check audit @@ -1229,7 +1229,7 @@ public void test200AddRoleSwashbuckler() throws Exception { dummyAuditService.assertTarget(ROLE_SWASHBUCKLER_OID); dummyAuditService.assertExecutionSuccess(); } - + private void prepareTest(AssignmentPolicyEnforcementType enforcement) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { assumeAssignmentPolicy(enforcement); dummyAuditService.clear(); 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 5ad2fe1bfce..108eb03ac2f 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 @@ -68,7 +68,7 @@ /** * @author Radovan Semancik - * + * */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode=ClassMode.AFTER_CLASS) @@ -85,7 +85,7 @@ public abstract class AbstractImportTest extends AbstractConfiguredModelIntegrat private static final String CONNECTOR_DBTABLE_FILE_NAME = "connector-dbtable"; private static final String CONNECOTR_DBTABLE_OID = "7d3ebd6f-6113-4833-8a6a-596b73a5e434"; private static final String CONNECTOR_NAMESPACE = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/org.forgerock.openicf.connectors.db.databasetable/org.identityconnectors.databasetable.DatabaseTableConnector"; - + private static final String RESOURCE_DERBY_FILE_NAME = "resource-derby"; private static final String RESOURCE_DERBY_OID = "ef2bc95b-76e0-59e2-86d6-9119011311ab"; private static final String RESOURCE_DERBY_NAMESPACE = "http://midpoint.evolveum.com/xml/ns/public/resource/instance/ef2bc95b-76e0-59e2-86d6-9119011311ab"; @@ -93,11 +93,11 @@ public abstract class AbstractImportTest extends AbstractConfiguredModelIntegrat private static final String RESOURCE_DUMMY_FILE_NAME = "resource-dummy"; private static final String RESOURCE_DUMMY_RUNTIME_FILE_NAME = "resource-dummy-runtime-resolution"; private static final String RESOURCE_DUMMY_RUNTIME_OID = "78fc521e-69f0-11e6-9ec5-130eb0c6fb6d"; - + private static final String IMPORT_TASK_FILE_NAME = "import-task"; private static final String TASK1_OID = "00000000-0000-0000-0000-123450000001"; private static final String TASK1_OWNER_OID = "c0c010c0-d34d-b33f-f00d-111111111111"; - + private static final String RESOURCE_DUMMY_CHANGED_FILE_NAME = "resource-dummy-changed"; protected static final String USER_HERMAN_FILE_NAME = "user-herman"; @@ -106,11 +106,11 @@ public abstract class AbstractImportTest extends AbstractConfiguredModelIntegrat private DummyResource dummyResource; private DummyResourceContoller dummyResourceCtl; - + private PrismObject dummyConnector; private PrismObject importedResource; private PrismObject importedRepoResource; - + private static String guybrushOid; private static String hermanOid; @@ -121,32 +121,32 @@ public abstract class AbstractImportTest extends AbstractConfiguredModelIntegrat File getFile(String name, boolean common) { return new File(common ? TEST_FOLDER_COMMON : TEST_FILE_DIRECTORY, name + "." + getSuffix()); } - + @Autowired private Clock clock; - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { LOGGER.trace("initSystem"); super.initSystem(initTask, initResult); - + // Just initialize the resource, do NOT import resource definition dummyResourceCtl = DummyResourceContoller.create(null); dummyResourceCtl.extendSchemaPirate(); dummyResource = dummyResourceCtl.getDummyResource(); - + dummyConnector = findConnectorByTypeAndVersion(CONNECTOR_DUMMY_TYPE, CONNECTOR_DUMMY_VERSION, initResult); } /** * Test integrity of the test setup. - * + * */ @Test public void test000Integrity() { @@ -162,10 +162,10 @@ public void test001ImportConnector() throws FileNotFoundException, ObjectNotFoun Task task = taskManager.createTaskInstance(); OperationResult result = new OperationResult(AbstractImportTest.class.getName() + "test001ImportConnector"); FileInputStream stream = new FileInputStream(getFile(CONNECTOR_DBTABLE_FILE_NAME, true)); - + dummyAuditService.clear(); XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modelService.importObjectsFromStream(stream, getLanguage(), getDefaultImportOptions(), task, result); @@ -182,9 +182,9 @@ public void test001ImportConnector() throws FileNotFoundException, ObjectNotFoun // assertEquals("ICF org.identityconnectors.databasetable.DatabaseTableConnector", connector.getName()); assertEquals(CONNECTOR_NAMESPACE, connector.getNamespace()); assertEquals("org.identityconnectors.databasetable.DatabaseTableConnector", connector.getConnectorType()); - + assertMetadata(connector, startTime, endTime); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -202,7 +202,7 @@ public void test003ImportUsers() throws Exception { Task task = taskManager.createTaskInstance(); OperationResult result = new OperationResult(AbstractImportTest.class.getName() + "test003ImportUsers"); FileInputStream stream = new FileInputStream(getFile(IMPORT_USERS_FILE_NAME, false)); - + dummyAuditService.clear(); XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); @@ -229,12 +229,12 @@ public void test003ImportUsers() throws Exception { assertNotNull("Er? The pirate sectrets were lost!",protectedString.getEncryptedDataType()); assertMetadata(jack, startTime, endTime); - + // Check import with generated OID // EqualsFilter equal = EqualsFilter.createEqual(UserType.class, PrismTestUtil.getPrismContext(), UserType.F_NAME, "guybrush"); // ObjectQuery query = ObjectQuery.createObjectQuery(equal); ObjectQuery query = ObjectQueryUtil.createNameQuery("guybrush", PrismTestUtil.getPrismContext()); - + List> users = repositoryService.searchObjects(UserType.class, query, null, result); assertNotNull(users); @@ -247,9 +247,9 @@ public void test003ImportUsers() throws Exception { PrismAsserts.assertEqualsPolyString("wrong familyName", "Threepwood", guybrush.getFamilyName()); PrismAsserts.assertEqualsPolyString("wrong fullName", "Guybrush Threepwood", guybrush.getFullName()); assertMetadata(guybrush, startTime, endTime); - + assertUsers(4); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(6); @@ -263,7 +263,7 @@ public void test004DuplicateImportUsers() throws Exception { Task task = taskManager.createTaskInstance(); OperationResult result = new OperationResult(AbstractImportTest.class.getName() + "test004DuplicateImportUsers"); FileInputStream stream = new FileInputStream(getFile(IMPORT_USERS_FILE_NAME, false)); - + dummyAuditService.clear(); // WHEN @@ -282,12 +282,12 @@ public void test004DuplicateImportUsers() throws Exception { } assertUsers(4); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(6); // 3 requests + 3 failed executions } - + // Import the same thing again, this time with overwrite option. This should go well. @Test public void test005ImportUsersWithOverwrite() throws Exception { @@ -298,7 +298,7 @@ public void test005ImportUsersWithOverwrite() throws Exception { FileInputStream stream = new FileInputStream(getFile(IMPORT_USERS_OVERWRITE_FILE_NAME, false)); ImportOptionsType options = getDefaultImportOptions(); options.setOverwrite(true); - + dummyAuditService.clear(); // WHEN @@ -313,7 +313,7 @@ public void test005ImportUsersWithOverwrite() throws Exception { List> users = modelService.searchObjects(UserType.class, new ObjectQuery(), null, task, result); // Three old users, one new assertEquals(5,users.size()); - + for (PrismObject user : users) { UserType userType = user.asObjectable(); if (userType.getName().toString().equals("jack")) { @@ -327,13 +327,13 @@ public void test005ImportUsersWithOverwrite() throws Exception { // OID should be the same, and there should be an employee type assertEquals(USER_WILL_OID,userType.getOid()); assertTrue("Wrong Will's employee type", userType.getEmployeeType().contains("legendary")); - } + } if (userType.getName().toString().equals("guybrush")) { // OID may be different, there should be a locality attribute guybrushOid = userType.getOid(); assertNotNull(guybrushOid); PrismAsserts.assertEqualsPolyString("Guybrush is not in the Caribbean", "Deep in the Caribbean", userType.getLocality()); - } + } if (userType.getName().toString().equals("ht")) { // Herman should be here now hermanOid = userType.getOid(); @@ -341,17 +341,17 @@ public void test005ImportUsersWithOverwrite() throws Exception { PrismAsserts.assertEqualsPolyString("Herman is confused", "Herman Toothrot", userType.getFullName()); PrismAsserts.assertEqualsPolyString("Herman is confused", "Herman", userType.getGivenName()); PrismAsserts.assertEqualsPolyString("Herman is confused", "Toothrot", userType.getFamilyName()); - } + } } - + assertUsers(5); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(8); // 1 failed, 7 succeeded } - + // Import the same thing again, with overwrite and also while keeping OIDs @Test public void test006ImportUsersWithOverwriteKeepOid() throws Exception { @@ -363,7 +363,7 @@ public void test006ImportUsersWithOverwriteKeepOid() throws Exception { ImportOptionsType options = getDefaultImportOptions(); options.setOverwrite(true); options.setKeepOid(true); - + dummyAuditService.clear(); // WHEN @@ -378,7 +378,7 @@ public void test006ImportUsersWithOverwriteKeepOid() throws Exception { List> users = modelService.searchObjects(UserType.class, new ObjectQuery(), null, task, result); // Three old users, one new assertEquals(5,users.size()); - + for (PrismObject user : users) { UserType userType = user.asObjectable(); if (userType.getName().toString().equals("jack")) { @@ -392,7 +392,7 @@ public void test006ImportUsersWithOverwriteKeepOid() throws Exception { // OID should be the same, and there should be an employee type assertEquals(USER_WILL_OID,userType.getOid()); assertTrue("Wrong Will's employee type", userType.getEmployeeType().contains("legendary")); - } + } if (userType.getName().toString().equals("guybrush")) { // OID should be the same, there should be a locality attribute assertEquals("Guybrush's OID went leeway", guybrushOid, userType.getOid()); @@ -404,11 +404,11 @@ public void test006ImportUsersWithOverwriteKeepOid() throws Exception { PrismAsserts.assertEqualsPolyString("Herman is confused", "Herman Toothrot", userType.getFullName()); PrismAsserts.assertEqualsPolyString("Herman is confused", "Herman", userType.getGivenName()); PrismAsserts.assertEqualsPolyString("Herman is confused", "Toothrot", userType.getFamilyName()); - } + } } - + assertUsers(5); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(6); @@ -422,13 +422,13 @@ public void test020ImportTask() throws Exception { Task task = taskManager.createTaskInstance(AbstractImportTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(IMPORT_TASK_FILE_NAME, false)); - + // well, let's check whether task owner really exists PrismObject ownerPrism = repositoryService.getObject(UserType.class, TASK1_OWNER_OID, null, result); assertEquals("Task owner does not exist or has an unexpected OID", TASK1_OWNER_OID, ownerPrism.getOid()); - + dummyAuditService.clear(); - + // WHEN modelService.importObjectsFromStream(stream, getLanguage(), getDefaultImportOptions(), task, result); @@ -443,12 +443,12 @@ public void test020ImportTask() throws Exception { assertNotNull(task1AsType); PrismAsserts.assertEqualsPolyString("Task name not imported correctly", "Task1: basic single-run task (takes 180x1 sec)", task1AsType.getName()); // assertEquals("Task name not imported correctly", "Task1: basic single-run task (takes 180x1 sec)", task1AsType.getName()); - + Task task1 = taskManager.createTaskInstance(task1AsPrism, result); PrismProperty delayProp = task1.getExtensionProperty(SchemaConstants.NOOP_DELAY_QNAME); assertEquals("xsi:type'd property has incorrect type", Integer.class, delayProp.getValues().get(0).getValue().getClass()); assertEquals("xsi:type'd property not imported correctly", Integer.valueOf(1000), delayProp.getValues().get(0).getValue()); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -458,7 +458,7 @@ public void test020ImportTask() throws Exception { dummyAuditService.assertHasDelta(ChangeType.ADD, TaskType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test030ImportResource() throws Exception { final String TEST_NAME = "test030ImportResource"; @@ -467,7 +467,7 @@ public void test030ImportResource() throws Exception { Task task = taskManager.createTaskInstance(AbstractImportTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(RESOURCE_DUMMY_FILE_NAME, true)); - + IntegrationTestTools.assertNoRepoCache(); dummyAuditService.clear(); @@ -480,26 +480,26 @@ public void test030ImportResource() throws Exception { TestUtil.assertSuccess("Import of "+RESOURCE_DUMMY_FILE_NAME+" has failed (result)", result, 2); IntegrationTestTools.assertNoRepoCache(); - + importedRepoResource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, result); display("Imported resource (repo)", importedRepoResource); IntegrationTestTools.assertNoRepoCache(); assertDummyResource(importedRepoResource, true); - + importedResource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, task, result); display("Imported resource (model)", importedResource); IntegrationTestTools.assertNoRepoCache(); assertDummyResource(importedResource, false); - + ResourceType importedResourceType = importedResource.asObjectable(); assertNotNull("No synchronization", importedResourceType.getSynchronization()); - + // Read it from repo again. The read from model triggers schema fetch which increases version importedRepoResource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, result); display("Imported resource (repo2)", importedRepoResource); IntegrationTestTools.assertNoRepoCache(); assertDummyResource(importedRepoResource, true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -509,7 +509,7 @@ public void test030ImportResource() throws Exception { dummyAuditService.assertHasDelta(ChangeType.ADD, ResourceType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test031ReimportResource() throws Exception { final String TEST_NAME = "test031ReimportResource"; @@ -518,10 +518,10 @@ public void test031ReimportResource() throws Exception { Task task = taskManager.createTaskInstance(AbstractImportTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(RESOURCE_DUMMY_CHANGED_FILE_NAME, false)); - + ImportOptionsType options = getDefaultImportOptions(); options.setOverwrite(true); - + IntegrationTestTools.assertNoRepoCache(); dummyAuditService.clear(); @@ -532,29 +532,29 @@ public void test031ReimportResource() throws Exception { result.computeStatus(); display("Result after import", result); TestUtil.assertSuccess("Import of "+RESOURCE_DUMMY_CHANGED_FILE_NAME+" has failed (result)", result, 2); - + IntegrationTestTools.assertNoRepoCache(); PrismObject repoResource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, result); display("Reimported resource (repo)", repoResource); assertDummyResource(repoResource, true); - + IntegrationTestTools.assertNoRepoCache(); - + MidPointAsserts.assertVersionIncrease(importedRepoResource, repoResource); - + PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, task, result); display("Reimported resource (model)", resource); - + IntegrationTestTools.assertNoRepoCache(); - + assertDummyResource(resource, false); - + MidPointAsserts.assertVersionIncrease(importedResource, resource); - + ResourceType resourceType = resource.asObjectable(); assertNull("Synchronization not gone", resourceType.getSynchronization()); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -564,7 +564,7 @@ public void test031ReimportResource() throws Exception { dummyAuditService.assertHasDelta(ChangeType.ADD, ResourceType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test032ImportResourceOidAndFilter() throws Exception { final String TEST_NAME = "test032ImportResourceOidAndFilter"; @@ -573,7 +573,7 @@ public void test032ImportResourceOidAndFilter() throws Exception { Task task = taskManager.createTaskInstance(AbstractImportTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(RESOURCE_DERBY_FILE_NAME, false)); - + IntegrationTestTools.assertNoRepoCache(); dummyAuditService.clear(); @@ -586,26 +586,26 @@ public void test032ImportResourceOidAndFilter() throws Exception { TestUtil.assertSuccess("Import of "+RESOURCE_DERBY_FILE_NAME+" has failed (result)", result, 2); IntegrationTestTools.assertNoRepoCache(); - + importedRepoResource = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, result); display("Imported resource (repo)", importedRepoResource); IntegrationTestTools.assertNoRepoCache(); assertResource(importedRepoResource, "Embedded Test Derby: Import test", RESOURCE_DERBY_NAMESPACE, CONNECOTR_DBTABLE_OID, true); - + importedResource = modelService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, task, result); display("Imported resource (model)", importedResource); IntegrationTestTools.assertNoRepoCache(); assertResource(importedResource, "Embedded Test Derby: Import test", RESOURCE_DERBY_NAMESPACE, CONNECOTR_DBTABLE_OID, false); - + // Read it from repo again. The read from model triggers schema fetch which increases version importedRepoResource = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, result); display("Imported resource (repo2)", importedRepoResource); IntegrationTestTools.assertNoRepoCache(); assertResource(importedRepoResource, "Embedded Test Derby: Import test", RESOURCE_DERBY_NAMESPACE, CONNECOTR_DBTABLE_OID, true); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -627,7 +627,7 @@ public void test033ImportResourceDummyRuntime() throws Exception { Task task = taskManager.createTaskInstance(AbstractImportTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(RESOURCE_DUMMY_RUNTIME_FILE_NAME, false)); - + IntegrationTestTools.assertNoRepoCache(); dummyAuditService.clear(); @@ -640,17 +640,17 @@ public void test033ImportResourceDummyRuntime() throws Exception { TestUtil.assertSuccess("Import of "+RESOURCE_DUMMY_RUNTIME_FILE_NAME+" has failed (result)", result, 2); IntegrationTestTools.assertNoRepoCache(); - + importedRepoResource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_RUNTIME_OID, null, result); display("Imported resource (repo)", importedRepoResource); IntegrationTestTools.assertNoRepoCache(); assertResource(importedRepoResource, "Dummy Resource (runtime)", MidPointConstants.NS_RI, null, true); - + importedResource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_RUNTIME_OID, null, task, result); display("Imported resource (model)", importedResource); IntegrationTestTools.assertNoRepoCache(); assertResource(importedRepoResource, "Dummy Resource (runtime)", MidPointConstants.NS_RI, null,false); - + // Read it from repo again. The read from model triggers schema fetch which increases version importedRepoResource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_RUNTIME_OID, null, result); display("Imported resource (repo2)", importedRepoResource); @@ -663,16 +663,16 @@ public void test040ImportUserHermanNoEncryption() throws Exception { final String TEST_NAME = "test040ImportUserHermanNoEncryption"; TestUtil.displayTestTitle(this,TEST_NAME); // GIVEN - + InternalsConfig.readEncryptionChecks = false; - + Task task = taskManager.createTaskInstance(); OperationResult result = new OperationResult(AbstractImportTest.class.getName() + "." + TEST_NAME); FileInputStream stream = new FileInputStream(getFile(USER_HERMAN_FILE_NAME, true)); - + ImportOptionsType importOptions = getDefaultImportOptions(); importOptions.setEncryptProtectedValues(false); - + dummyAuditService.clear(); // WHEN @@ -687,14 +687,14 @@ public void test040ImportUserHermanNoEncryption() throws Exception { PrismObject userHerman = getUser(USER_HERMAN_OID); display("Herman", userHerman); assertUser(userHerman, USER_HERMAN_OID, USER_HERMAN_USERNAME, "Herman Toothrot", "Herman", "Toothrot"); - + // Check if the password was NOT encrypted ProtectedStringType protectedString = userHerman.asObjectable().getCredentials().getPassword().getValue(); assertEquals("Er? Pirate sectrets still hidden?", "m0nk3y", protectedString.getClearValue()); assertNull("Er? Encrypted data together with clear value?", protectedString.getEncryptedDataType()); assertUsers(6); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -772,7 +772,7 @@ public void test200BadImport() throws FileNotFoundException, SchemaException, Ob private void assertDummyResource(PrismObject resource, boolean fromRepo) { - PrismContainer configurationPropertiesContainer = assertResource(resource, "Dummy Resource", RESOURCE_DUMMY_NAMESPACE, + PrismContainer configurationPropertiesContainer = assertResource(resource, "Dummy Resource", RESOURCE_DUMMY_NAMESPACE, dummyConnector.getOid(), fromRepo); PrismProperty guardedProperty = configurationPropertiesContainer.findProperty( new QName(CONNECTOR_DUMMY_NAMESPACE, "uselessGuardedString")); @@ -780,7 +780,7 @@ private void assertDummyResource(PrismObject resource, boolean fro // and inspect the DOM elements there assertNotNull("No uselessGuardedString property in configuration properties", guardedProperty); PrismPropertyValue guardedPVal = guardedProperty.getValue(); - + if (fromRepo) { Object passwordRawElement = guardedPVal.getRawElement(); if (!(passwordRawElement instanceof MapXNode)) { @@ -796,20 +796,20 @@ private void assertDummyResource(PrismObject resource, boolean fro } } - private PrismContainer assertResource(PrismObject resource, String resourceName, String namespace, + private PrismContainer assertResource(PrismObject resource, String resourceName, String namespace, String connectorOid, boolean fromRepo) { ResourceType resourceType = resource.asObjectable(); assertNotNull(resourceType); PrismAsserts.assertEqualsPolyString("Wrong resource name", resourceName, resourceType.getName()); assertEquals("Wrong namespace of "+resource, namespace, ResourceTypeUtil.getResourceNamespace(resourceType)); assertEquals("Wrong connector OID in "+resource, connectorOid, resourceType.getConnectorRef().getOid()); - + // The password in the resource configuration should be encrypted after import PrismContainer configurationContainer = resource.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); - PrismContainer configurationPropertiesContainer = + PrismContainer configurationPropertiesContainer = configurationContainer.findContainer(SchemaTestConstants.ICFC_CONFIGURATION_PROPERTIES); assertNotNull("No configurationProperties in resource", configurationPropertiesContainer); - + return configurationPropertiesContainer; } 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 e6dd0529b9a..75ab497bdfe 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 @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.model.intest.manual; @@ -33,6 +33,7 @@ import java.util.Random; import java.util.function.Consumer; +import javax.xml.bind.JAXBElement; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; @@ -59,6 +60,8 @@ 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.provisioning.ucf.impl.builtin.ManualConnectorInstance; +import com.evolveum.midpoint.repo.common.expression.evaluator.LiteralExpressionEvaluatorFactory; import com.evolveum.midpoint.schema.CapabilityUtil; import com.evolveum.midpoint.schema.GetOperationOptions; import com.evolveum.midpoint.schema.PointInTimeType; @@ -87,15 +90,21 @@ 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.CaseType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ConflictResolutionActionType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ConflictResolutionType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType; +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.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultStatusType; import com.evolveum.midpoint.xml.ns._public.common.common_3.PendingOperationType; +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.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.SystemConfigurationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; import com.evolveum.midpoint.xml.ns._public.common.common_3.XmlSchemaType; import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.AbstractWriteCapabilityType; @@ -115,45 +124,45 @@ public abstract class AbstractManualResourceTest extends AbstractConfiguredModelIntegrationTest { protected static final File TEST_DIR = new File("src/test/resources/manual/"); - + protected static final File RESOURCE_MANUAL_FILE = new File(TEST_DIR, "resource-manual.xml"); protected static final String RESOURCE_MANUAL_OID = "0ef80ab8-2906-11e7-b81a-3f343e28c264"; - + protected static final File RESOURCE_SEMI_MANUAL_FILE = new File(TEST_DIR, "resource-semi-manual.xml"); protected static final String RESOURCE_SEMI_MANUAL_OID = "aea5a57c-2904-11e7-8020-7b121a9e3595"; - + protected static final File RESOURCE_SEMI_MANUAL_DISABLE_FILE = new File(TEST_DIR, "resource-semi-manual-disable.xml"); protected static final String RESOURCE_SEMI_MANUAL_DISABLE_OID = "5e497cb0-5cdb-11e7-9cfe-4bfe0342d181"; - + protected static final File RESOURCE_SEMI_MANUAL_SLOW_PROPOSED_FILE = new File(TEST_DIR, "resource-semi-manual-slow-proposed.xml"); protected static final String RESOURCE_SEMI_MANUAL_SLOW_PROPOSED_OID = "512d749a-75ff-11e7-8176-8be7fb6f4e45"; protected static final File ROLE_ONE_MANUAL_FILE = new File(TEST_DIR, "role-one-manual.xml"); protected static final String ROLE_ONE_MANUAL_OID = "9149b3ca-5da1-11e7-8e84-130a91fb5876"; - + protected static final File ROLE_ONE_SEMI_MANUAL_FILE = new File(TEST_DIR, "role-one-semi-manual.xml"); protected static final String ROLE_ONE_SEMI_MANUAL_OID = "29eab2c8-5da2-11e7-85d3-c78728e05ca3"; - + protected static final File ROLE_ONE_SEMI_MANUAL_DISABLE_FILE = new File(TEST_DIR, "role-one-semi-manual-disable.xml"); protected static final String ROLE_ONE_SEMI_MANUAL_DISABLE_OID = "3b8cb17a-5da2-11e7-b260-a760972b54fb"; - + protected static final File ROLE_ONE_SEMI_MANUAL_SLOW_PROPOSED_FILE = new File(TEST_DIR, "role-one-semi-manual-slow-proposed.xml"); protected static final String ROLE_ONE_SEMI_MANUAL_SLOW_PROPOSED_OID = "ca7fefc6-75ff-11e7-9833-572f6bf86a81"; - + protected static final File ROLE_TWO_MANUAL_FILE = new File(TEST_DIR, "role-two-manual.xml"); protected static final String ROLE_TWO_MANUAL_OID = "414e3766-775e-11e7-b8cb-c7ca37c1dc9e"; - + protected static final File ROLE_TWO_SEMI_MANUAL_FILE = new File(TEST_DIR, "role-two-semi-manual.xml"); protected static final String ROLE_TWO_SEMI_MANUAL_OID = "b95f7252-7776-11e7-bd96-cf05f4c21966"; - + protected static final File ROLE_TWO_SEMI_MANUAL_DISABLE_FILE = new File(TEST_DIR, "role-two-semi-manual-disable.xml"); protected static final String ROLE_TWO_SEMI_MANUAL_DISABLE_OID = "d1eaa4f4-7776-11e7-bb53-eb1218c49dd9"; - + protected static final File ROLE_TWO_SEMI_MANUAL_SLOW_PROPOSED_FILE = new File(TEST_DIR, "role-two-semi-manual-slow-proposed.xml"); protected static final String ROLE_TWO_SEMI_MANUAL_SLOW_PROPOSED_OID = "eaf3569e-7776-11e7-93f3-3f1b853d6525"; - + public static final QName RESOURCE_ACCOUNT_OBJECTCLASS = new QName(MidPointConstants.NS_RI, "AccountObjectClass"); - + private static final Trace LOGGER = TraceManager.getTrace(AbstractManualResourceTest.class); protected static final String NS_MANUAL_CONF = "http://midpoint.evolveum.com/xml/ns/public/connector/builtin-1/bundle/com.evolveum.midpoint.provisioning.ucf.impl.builtin/ManualConnector"; @@ -167,39 +176,39 @@ public abstract class AbstractManualResourceTest extends AbstractConfiguredModel protected static final String ACCOUNT_WILL_DESCRIPTION_MANUAL = "manual"; protected static final String USER_WILL_PASSWORD_OLD = "3lizab3th"; protected static final String USER_WILL_PASSWORD_NEW = "ELIZAbeth"; - + protected static final String ACCOUNT_JACK_DESCRIPTION_MANUAL = "Manuel"; protected static final String USER_JACK_PASSWORD_OLD = "deadM3NtellN0tales"; - + private static final File TASK_SHADOW_REFRESH_FILE = new File(TEST_DIR, "task-shadow-refresh.xml"); private static final String TASK_SHADOW_REFRESH_OID = "eb8f5be6-2b51-11e7-848c-2fd84a283b03"; protected static final String ATTR_USERNAME = "username"; protected static final QName ATTR_USERNAME_QNAME = new QName(MidPointConstants.NS_RI, ATTR_USERNAME); - + protected static final String ATTR_FULLNAME = "fullname"; protected static final QName ATTR_FULLNAME_QNAME = new QName(MidPointConstants.NS_RI, ATTR_FULLNAME); - + protected static final String ATTR_INTERESTS = "interests"; protected static final QName ATTR_INTERESTS_QNAME = new QName(MidPointConstants.NS_RI, ATTR_INTERESTS); - + protected static final String ATTR_DESCRIPTION = "description"; protected static final QName ATTR_DESCRIPTION_QNAME = new QName(MidPointConstants.NS_RI, ATTR_DESCRIPTION); protected static final String INTEREST_ONE = "one"; - + protected PrismObject resource; protected ResourceType resourceType; - + protected String userWillOid; protected String accountWillOid; - + protected XMLGregorianCalendar accountWillReqestTimestampStart; protected XMLGregorianCalendar accountWillReqestTimestampEnd; - + protected XMLGregorianCalendar accountWillCompletionTimestampStart; protected XMLGregorianCalendar accountWillCompletionTimestampEnd; - + protected XMLGregorianCalendar accountWillSecondReqestTimestampStart; protected XMLGregorianCalendar accountWillSecondReqestTimestampEnd; @@ -208,46 +217,52 @@ public abstract class AbstractManualResourceTest extends AbstractConfiguredModel protected String willLastCaseOid; protected String willSecondLastCaseOid; - + protected String accountJackOid; - + protected XMLGregorianCalendar accountJackReqestTimestampStart; protected XMLGregorianCalendar accountJackReqestTimestampEnd; - + protected XMLGregorianCalendar accountJackCompletionTimestampStart; protected XMLGregorianCalendar accountJackCompletionTimestampEnd; - + protected String jackLastCaseOid; private XMLGregorianCalendar roleTwoValidFromTimestamp; - - + + protected String accountBarbossaOid; + + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + repoAddObjectFromFile(SECURITY_POLICY_FILE, initResult); - + importObjectFromFile(getResourceFile(), initResult); - + importObjectFromFile(getRoleOneFile(), initResult); importObjectFromFile(getRoleTwoFile(), initResult); - + addObject(USER_JACK_FILE); addObject(USER_BARBOSSA_FILE); - + PrismObject userWill = createUserWill(); addObject(userWill, initTask, initResult); display("User will", userWill); userWillOid = userWill.getOid(); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + + ConflictResolutionType conflictResolutionType = new ConflictResolutionType(); + conflictResolutionType.action(ConflictResolutionActionType.RECOMPUTE); + setConflictResolution(UserType.COMPLEX_TYPE, null, conflictResolutionType, initResult); + // Turns on checks for connection in manual connector InternalsConfig.setSanityChecks(true); } - + private PrismObject createUserWill() throws SchemaException { PrismObject user = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class).instantiate(); user.asObjectable() @@ -257,47 +272,63 @@ private PrismObject createUserWill() throws SchemaException { .fullName(USER_WILL_FULL_NAME) .beginActivation().administrativeStatus(ActivationStatusType.ENABLED).end() .beginCredentials().beginPassword().beginValue().setClearValue(USER_WILL_PASSWORD_OLD); - return user; + return user; } protected abstract File getResourceFile(); - + protected abstract String getResourceOid(); - + protected abstract File getRoleOneFile(); - + protected abstract String getRoleOneOid(); - + protected abstract File getRoleTwoFile(); - + protected abstract String getRoleTwoOid(); - + protected boolean supportsBackingStore() { return false; } + protected boolean hasMultivalueInterests() { + return true; + } + + protected int getConcurrentTestNumberOfThreads() { + return 4; + } + + protected int getConcurrentTestRandomStartDelayRange() { + return 1000; + } + + protected int getConcurrentTestRandomStartDelayRangeDelete() { + return 5; + } + @Test public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; TestUtil.displayTestTitle(TEST_NAME); - + OperationResult result = new OperationResult(AbstractManualResourceTest.class.getName() + "." + TEST_NAME); ResourceType repoResource = repositoryService.getObject(ResourceType.class, getResourceOid(), null, result).asObjectable(); assertNotNull("No connector ref", repoResource.getConnectorRef()); - + String connectorOid = repoResource.getConnectorRef().getOid(); assertNotNull("No connector ref OID", connectorOid); ConnectorType repoConnector = repositoryService .getObject(ConnectorType.class, connectorOid, null, result).asObjectable(); assertNotNull(repoConnector); display("Manual Connector", repoConnector); - + // Check connector schema IntegrationTestTools.assertConnectorSchemaSanity(repoConnector, prismContext); - + PrismObject userWill = getUser(userWillOid); assertUser(userWill, userWillOid, USER_WILL_NAME, USER_WILL_FULL_NAME, USER_WILL_GIVEN_NAME, USER_WILL_FAMILY_NAME); assertAdministrativeStatus(userWill, ActivationStatusType.ENABLED); @@ -311,14 +342,14 @@ public void test003Connection() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // Check that there is a schema, but no capabilities before test (pre-condition) ResourceType resourceBefore = repositoryService.getObject(ResourceType.class, getResourceOid(), null, result).asObjectable(); - + Element resourceXsdSchemaElementBefore = ResourceTypeUtil.getResourceXsdSchema(resourceBefore); assertResourceSchemaBeforeTest(resourceXsdSchemaElementBefore); - + CapabilitiesType capabilities = resourceBefore.getCapabilities(); if (capabilities != null) { AssertJUnit.assertNull("Native capabilities present before test connection. Bad test setup?", capabilities.getNative()); @@ -332,14 +363,14 @@ public void test003Connection() throws Exception { TestUtil.assertSuccess("Test resource failed (result)", testResult); PrismObject resourceRepoAfter = repositoryService.getObject(ResourceType.class, getResourceOid(), null, result); - ResourceType resourceTypeRepoAfter = resourceRepoAfter.asObjectable(); + ResourceType resourceTypeRepoAfter = resourceRepoAfter.asObjectable(); display("Resource after test", resourceTypeRepoAfter); XmlSchemaType xmlSchemaTypeAfter = resourceTypeRepoAfter.getSchema(); assertNotNull("No schema after test connection", xmlSchemaTypeAfter); Element resourceXsdSchemaElementAfter = ResourceTypeUtil.getResourceXsdSchema(resourceTypeRepoAfter); assertNotNull("No schema after test connection", resourceXsdSchemaElementAfter); - + String resourceXml = prismContext.serializeObjectToString(resourceRepoAfter, PrismContext.LANG_XML); display("Resource XML", resourceXml); @@ -354,7 +385,7 @@ public void test003Connection() throws Exception { // schema will be checked in next test } - + protected abstract void assertResourceSchemaBeforeTest(Element resourceXsdSchemaElementBefore); @Test @@ -375,11 +406,11 @@ public void test004Configuration() throws Exception { assertNotNull("No configuration container definition", confContDef); PrismProperty propDefaultAssignee = configurationContainer.findProperty(CONF_PROPERTY_DEFAULT_ASSIGNEE_QNAME); assertNotNull("No defaultAssignee conf prop", propDefaultAssignee); - + // assertNotNull("No configuration properties container", confingurationPropertiesContainer); // PrismContainerDefinition confPropDef = confingurationPropertiesContainer.getDefinition(); // assertNotNull("No configuration properties container definition", confPropDef); - + } @Test @@ -395,22 +426,22 @@ public void test005ParsedSchema() throws Exception { // Also test if the utility method returns the same thing ResourceSchema resourceSchema = RefinedResourceSchemaImpl.getResourceSchema(resourceType, prismContext); - + display("Parsed resource schema", resourceSchema); // 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)); - + ObjectClassComplexTypeDefinition accountDef = resourceSchema.findObjectClassDefinition(RESOURCE_ACCOUNT_OBJECTCLASS); assertNotNull("Account definition is missing", accountDef); assertNotNull("Null identifiers in account", accountDef.getPrimaryIdentifiers()); assertFalse("Empty identifiers in account", accountDef.getPrimaryIdentifiers().isEmpty()); assertNotNull("No naming attribute in account", accountDef.getNamingAttribute()); - + assertEquals("Unexpected number of definitions", getNumberOfAccountAttributeDefinitions(), accountDef.getDefinitions().size()); - + ResourceAttributeDefinition usernameDef = accountDef.findAttributeDefinition(ATTR_USERNAME); assertNotNull("No definition for username", usernameDef); assertEquals(1, usernameDef.getMaxOccurs()); @@ -418,7 +449,7 @@ public void test005ParsedSchema() throws Exception { assertTrue("No username create", usernameDef.canAdd()); assertTrue("No username update", usernameDef.canModify()); assertTrue("No username read", usernameDef.canRead()); - + ResourceAttributeDefinition fullnameDef = accountDef.findAttributeDefinition(ATTR_FULLNAME); assertNotNull("No definition for fullname", fullnameDef); assertEquals(1, fullnameDef.getMaxOccurs()); @@ -427,7 +458,7 @@ public void test005ParsedSchema() throws Exception { assertTrue("No fullname update", fullnameDef.canModify()); assertTrue("No fullname read", fullnameDef.canRead()); } - + protected int getNumberOfAccountAttributeDefinitions() { return 4; } @@ -442,11 +473,11 @@ public void test006Capabilities() throws Exception { // WHEN ResourceType resource = modelService.getObject(ResourceType.class, getResourceOid(), null, null, result).asObjectable(); - + // THEN display("Resource from provisioninig", resource); display("Resource from provisioninig (XML)", PrismTestUtil.serializeObjectToString(resource.asPrismObject(), PrismContext.LANG_XML)); - + CapabilityCollectionType nativeCapabilities = resource.getCapabilities().getNative(); List nativeCapabilitiesList = nativeCapabilities.getAny(); assertFalse("Empty capabilities returned",nativeCapabilitiesList.isEmpty()); @@ -454,19 +485,19 @@ public void test006Capabilities() throws Exception { CreateCapabilityType capCreate = CapabilityUtil.getCapability(nativeCapabilitiesList, CreateCapabilityType.class); assertNotNull("Missing create capability", capCreate); assertManual(capCreate); - + ActivationCapabilityType capAct = CapabilityUtil.getCapability(nativeCapabilitiesList, ActivationCapabilityType.class); assertNotNull("Missing activation capability", capAct); - + ReadCapabilityType capRead = CapabilityUtil.getCapability(nativeCapabilitiesList, ReadCapabilityType.class); assertNotNull("Missing read capability" ,capRead); assertEquals("Wrong caching-only setting in read capability", Boolean.TRUE, capRead.isCachingOnly()); - + List effectiveCapabilities = ResourceTypeUtil.getEffectiveCapabilities(resource); for (Object capability : effectiveCapabilities) { System.out.println("Capability: "+CapabilityUtil.getCapabilityDisplayName(capability)+" : "+capability); } - + } @Test @@ -481,7 +512,7 @@ public void test102GetAccountWillFuture() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)); // WHEN @@ -490,8 +521,8 @@ public void test102GetAccountWillFuture() throws Exception { // THEN displayThen(TEST_NAME); - assertSuccess(result); - + assertSuccess(result); + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -502,7 +533,7 @@ public void test102GetAccountWillFuture() throws Exception { assertNoAttribute(shadowModel, ATTR_DESCRIPTION_QNAME); assertShadowActivationAdministrativeStatus(shadowModel, ActivationStatusType.ENABLED); assertShadowExists(shadowModel, true); - // TODO + // TODO // assertShadowPassword(shadowProvisioning); } @@ -513,7 +544,7 @@ public void test104RecomputeWill() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); recomputeUser(userWillOid, task, result); @@ -521,7 +552,7 @@ public void test104RecomputeWill() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); @@ -535,7 +566,7 @@ public void test104RecomputeWill() throws Exception { PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -548,10 +579,10 @@ public void test104RecomputeWill() throws Exception { assertNoShadowPassword(shadowModel); PendingOperationType pendingOperation = assertSinglePendingOperation(shadowModel, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); - + assertCase(pendingOperation.getAsynchronousOperationReference(), SchemaConstants.CASE_STATE_OPEN); } - + @Test public void test106AddToBackingStoreAndGetAccountWill() throws Exception { final String TEST_NAME = "test106AddToBackingStoreAndGetAccountWill"; @@ -559,17 +590,17 @@ public void test106AddToBackingStoreAndGetAccountWill() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + backingStoreProvisionWill(INTEREST_ONE); - + // WHEN displayWhen(TEST_NAME); PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); // THEN displayThen(TEST_NAME); - assertSuccess(result); - + assertSuccess(result); + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -580,7 +611,7 @@ public void test106AddToBackingStoreAndGetAccountWill() throws Exception { assertShadowActivationAdministrativeStatus(shadowModel, ActivationStatusType.ENABLED); assertShadowExists(shadowModel, supportsBackingStore()); assertShadowPassword(shadowModel); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); @@ -591,7 +622,7 @@ public void test106AddToBackingStoreAndGetAccountWill() throws Exception { assertNoShadowPassword(shadowRepo); assertShadowExists(shadowRepo, supportsBackingStore()); } - + @Test public void test108GetAccountWillFuture() throws Exception { final String TEST_NAME = "test108GetAccountWillFuture"; @@ -599,29 +630,29 @@ public void test108GetAccountWillFuture() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)); - + // WHEN displayWhen(TEST_NAME); PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, options, task, result); // THEN displayThen(TEST_NAME); - assertSuccess(result); - + assertSuccess(result); + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); assertEquals("Wrong kind (provisioning)", ShadowKindType.ACCOUNT, shadowTypeProvisioning.getKind()); assertAttribute(shadowModel, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertAttribute(shadowModel, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME); - assertAttributeFromBackingStore(shadowModel, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); + assertAttributeFromBackingStore(shadowModel, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowActivationAdministrativeStatus(shadowModel, ActivationStatusType.ENABLED); assertShadowExists(shadowModel, true); // TODO // assertShadowPassword(shadowProvisioning); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); @@ -632,7 +663,7 @@ public void test108GetAccountWillFuture() throws Exception { assertNoShadowPassword(shadowRepo); assertShadowExists(shadowRepo, supportsBackingStore()); } - + /** * Case is closed. The operation is complete. */ @@ -643,11 +674,11 @@ public void test110CloseCaseAndRecomputeWill() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + closeCase(willLastCaseOid); - + accountWillCompletionTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); // We need reconcile and not recompute here. We need to fetch the updated case status. @@ -656,12 +687,12 @@ public void test110CloseCaseAndRecomputeWill() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + accountWillCompletionTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + assertWillAfterCreateCaseClosed(TEST_NAME, true); } - + /** * ff 5min, everything should be the same (grace not expired yet) */ @@ -674,7 +705,7 @@ public void test120RecomputeWillAfter5min() throws Exception { OperationResult result = task.getResult(); clockForward("PT5M"); - + // WHEN displayWhen(TEST_NAME); recomputeUser(userWillOid, task, result); @@ -682,10 +713,10 @@ public void test120RecomputeWillAfter5min() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); - assertSinglePendingOperation(shadowRepo, + assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); @@ -693,14 +724,14 @@ public void test120RecomputeWillAfter5min() throws Exception { PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowModel, + PendingOperationType pendingOperation = assertSinglePendingOperation(shadowModel, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + /** * ff 20min, grace should expire */ @@ -713,7 +744,7 @@ public void test130RecomputeWillAfter25min() throws Exception { OperationResult result = task.getResult(); clockForward("PT20M"); - + // WHEN displayWhen(TEST_NAME); recomputeUser(userWillOid, task, result); @@ -721,7 +752,7 @@ public void test130RecomputeWillAfter25min() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); assertNoPendingOperation(shadowRepo); @@ -729,7 +760,7 @@ public void test130RecomputeWillAfter25min() throws Exception { PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); assertNoPendingOperation(shadowModel); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } @@ -740,25 +771,25 @@ public void test200ModifyUserWillFullname() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, - accountWillOid, new ItemPath(ShadowType.F_ATTRIBUTES, ATTR_FULLNAME_QNAME), prismContext, + + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, + accountWillOid, new ItemPath(ShadowType.F_ATTRIBUTES, ATTR_FULLNAME_QNAME), prismContext, USER_WILL_FULL_NAME_PIRATE); display("ObjectDelta", delta); accountWillReqestTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(userWillOid, UserType.F_FULL_NAME, task, result, createPolyString(USER_WILL_FULL_NAME_PIRATE)); - + // THEN displayThen(TEST_NAME); display("result", result); willLastCaseOid = assertInProgress(result); - + accountWillReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); PendingOperationType pendingOperation = assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); @@ -767,10 +798,10 @@ accountWillOid, new ItemPath(ShadowType.F_ATTRIBUTES, ATTR_FULLNAME_QNAME), pris assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -782,9 +813,9 @@ accountWillOid, new ItemPath(ShadowType.F_ATTRIBUTES, ATTR_FULLNAME_QNAME), pris assertShadowPassword(shadowModel); assertSinglePendingOperation(shadowModel, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); - + PrismObject shadowProvisioningFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowProvisioningFuture); @@ -795,12 +826,12 @@ accountWillOid, new ItemPath(ShadowType.F_ATTRIBUTES, ATTR_FULLNAME_QNAME), pris assertAttribute(shadowProvisioningFuture, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioningFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioningFuture); - + assertNotNull("No async reference in result", willLastCaseOid); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } - + @Test public void test202RecomputeWill() throws Exception { final String TEST_NAME = "test202RecomputeWill"; @@ -808,15 +839,15 @@ public void test202RecomputeWill() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); recomputeUser(userWillOid, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); PendingOperationType pendingOperation = assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); @@ -825,10 +856,10 @@ public void test202RecomputeWill() throws Exception { assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -839,9 +870,9 @@ public void test202RecomputeWill() throws Exception { assertShadowPassword(shadowModel); assertSinglePendingOperation(shadowModel, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); - + PrismObject shadowProvisioningFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowProvisioningFuture); @@ -851,11 +882,11 @@ public void test202RecomputeWill() throws Exception { assertAttribute(shadowProvisioningFuture, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertAttribute(shadowProvisioningFuture, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertShadowPassword(shadowProvisioningFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_OPEN); - + } - + /** * Case is closed. The operation is complete. */ @@ -868,9 +899,9 @@ public void test204CloseCaseAndRecomputeWill() throws Exception { OperationResult result = task.getResult(); closeCase(willLastCaseOid); - + accountWillCompletionTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); recomputeUser(userWillOid, task, result); @@ -878,12 +909,12 @@ public void test204CloseCaseAndRecomputeWill() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + accountWillCompletionTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); - assertSinglePendingOperation(shadowRepo, + assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); @@ -893,7 +924,7 @@ public void test204CloseCaseAndRecomputeWill() throws Exception { PrismObject shadowProvisioning = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - + display("Model shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, USER_WILL_NAME); @@ -906,15 +937,15 @@ public void test204CloseCaseAndRecomputeWill() throws Exception { assertAttribute(shadowProvisioning, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); } assertAttributeFromBackingStore(shadowProvisioning, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); - assertShadowPassword(shadowProvisioning); + assertShadowPassword(shadowProvisioning); - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowProvisioning, + PendingOperationType pendingOperation = assertSinglePendingOperation(shadowProvisioning, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + PrismObject shadowProvisioningFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowProvisioningFuture); @@ -925,10 +956,10 @@ public void test204CloseCaseAndRecomputeWill() throws Exception { assertAttribute(shadowProvisioningFuture, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioningFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioningFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + /** * ff 5min, everything should be the same (grace not expired yet) */ @@ -941,7 +972,7 @@ public void test210RecomputeWillAfter5min() throws Exception { OperationResult result = task.getResult(); clockForward("PT5M"); - + // WHEN displayWhen(TEST_NAME); recomputeUser(userWillOid, task, result); @@ -949,14 +980,14 @@ public void test210RecomputeWillAfter5min() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); - assertSinglePendingOperation(shadowRepo, + assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); assertShadowActivationAdministrativeStatus(shadowModel, ActivationStatusType.ENABLED); @@ -969,13 +1000,13 @@ public void test210RecomputeWillAfter5min() throws Exception { assertAttributeFromBackingStore(shadowModel, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModel); - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowModel, + PendingOperationType pendingOperation = assertSinglePendingOperation(shadowModel, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowModelFuture); @@ -986,10 +1017,10 @@ public void test210RecomputeWillAfter5min() throws Exception { assertAttribute(shadowModelFuture, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertAttributeFromBackingStore(shadowModelFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModelFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + @Test public void test212UpdateBackingStoreAndGetAccountWill() throws Exception { final String TEST_NAME = "test212UpdateBackingStoreAndGetAccountWill"; @@ -997,9 +1028,9 @@ public void test212UpdateBackingStoreAndGetAccountWill() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + backingStoreUpdateWill(USER_WILL_FULL_NAME_PIRATE, INTEREST_ONE, ActivationStatusType.ENABLED, USER_WILL_PASSWORD_OLD); - + // WHEN displayWhen(TEST_NAME); PrismObject shadowModel = modelService.getObject(ShadowType.class, @@ -1008,27 +1039,27 @@ public void test212UpdateBackingStoreAndGetAccountWill() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + assertShadowActivationAdministrativeStatus(shadowModel, ActivationStatusType.ENABLED); assertAttribute(shadowModel, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertAttribute(shadowModel, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertAttributeFromBackingStore(shadowModel, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModel); - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowModel, + PendingOperationType pendingOperation = assertSinglePendingOperation(shadowModel, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); - assertSinglePendingOperation(shadowRepo, + assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowModelFuture); @@ -1039,11 +1070,11 @@ public void test212UpdateBackingStoreAndGetAccountWill() throws Exception { assertAttribute(shadowModelFuture, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertAttributeFromBackingStore(shadowModelFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModelFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + /** * disable - do not complete yet (do not wait for delta to expire, we want several deltas at once). */ @@ -1054,36 +1085,36 @@ public void test220ModifyUserWillDisable() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + accountWillReqestTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(userWillOid, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.DISABLED); - + // THEN displayThen(TEST_NAME); display("result", result); willLastCaseOid = assertInProgress(result); - + accountWillReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); assertPendingOperationDeltas(shadowRepo, 2); - PendingOperationType pendingOperation = findPendingOperation(shadowRepo, + PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.IN_PROGRESS, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS); assertPendingOperation(shadowRepo, pendingOperation, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); - + assertNotNull("No ID in pending operation", pendingOperation.getId()); // Still old data in the repo. The operation is not completed yet. assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -1095,12 +1126,12 @@ public void test220ModifyUserWillDisable() throws Exception { assertShadowPassword(shadowModel); assertPendingOperationDeltas(shadowModel, 2); - pendingOperation = findPendingOperation(shadowModel, + pendingOperation = findPendingOperation(shadowModel, OperationResultStatusType.IN_PROGRESS, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS); assertPendingOperation(shadowModel, pendingOperation, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); - + PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowModelFuture); @@ -1111,12 +1142,12 @@ public void test220ModifyUserWillDisable() throws Exception { assertAttribute(shadowModelFuture, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertAttributeFromBackingStore(shadowModelFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModelFuture); - + assertNotNull("No async reference in result", willLastCaseOid); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } - + /** * Change password, enable. There is still pending disable delta. Make sure all the deltas are * stored correctly. @@ -1128,9 +1159,9 @@ public void test230ModifyAccountWillChangePasswordAndEnable() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, - userWillOid, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, prismContext, + + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(UserType.class, + userWillOid, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, prismContext, ActivationStatusType.ENABLED); ProtectedStringType ps = new ProtectedStringType(); ps.setClearValue(USER_WILL_PASSWORD_NEW); @@ -1138,34 +1169,34 @@ public void test230ModifyAccountWillChangePasswordAndEnable() throws Exception { display("ObjectDelta", delta); accountWillSecondReqestTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); executeChanges(delta, null, task, result); - + // THEN displayThen(TEST_NAME); display("result", result); willSecondLastCaseOid = assertInProgress(result); - + accountWillSecondReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); assertPendingOperationDeltas(shadowRepo, 3); - PendingOperationType pendingOperation = findPendingOperation(shadowRepo, + PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.IN_PROGRESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd); - + assertNotNull("No ID in pending operation", pendingOperation.getId()); // Still old data in the repo. The operation is not completed yet. assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); - + PrismObject shadowProvisioning = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - + display("Model shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, USER_WILL_NAME); @@ -1175,15 +1206,15 @@ public void test230ModifyAccountWillChangePasswordAndEnable() throws Exception { assertAttribute(shadowProvisioning, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioning, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioning); - + assertPendingOperationDeltas(shadowProvisioning, 3); - pendingOperation = findPendingOperation(shadowProvisioning, + pendingOperation = findPendingOperation(shadowProvisioning, OperationResultStatusType.IN_PROGRESS, SchemaConstants.PATH_PASSWORD_VALUE); - assertPendingOperation(shadowProvisioning, pendingOperation, + assertPendingOperation(shadowProvisioning, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd); - + PrismObject shadowProvisioningFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowProvisioningFuture); @@ -1194,13 +1225,13 @@ public void test230ModifyAccountWillChangePasswordAndEnable() throws Exception { assertAttribute(shadowProvisioningFuture, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioningFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadow(shadowProvisioningFuture); - + assertNotNull("No async reference in result", willSecondLastCaseOid); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_OPEN); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } - + /** * Disable case is closed. The account should be disabled. But there is still the other * delta pending. @@ -1217,7 +1248,7 @@ public void test240CloseDisableCaseAndReadAccountWill() throws Exception { closeCase(willLastCaseOid); accountWillCompletionTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); PrismObject shadowModel = modelService.getObject(ShadowType.class, @@ -1226,29 +1257,29 @@ public void test240CloseDisableCaseAndReadAccountWill() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + accountWillCompletionTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); - + assertPendingOperationDeltas(shadowRepo, 3); - - PendingOperationType pendingOperation = findPendingOperation(shadowRepo, + + PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS); assertPendingOperation(shadowRepo, pendingOperation, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - - pendingOperation = findPendingOperation(shadowRepo, + + pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.IN_PROGRESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd); - + assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.DISABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); - + display("Model shadow", shadowModel); ShadowType shadowTypeModel = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -1258,22 +1289,22 @@ public void test240CloseDisableCaseAndReadAccountWill() throws Exception { } else { assertShadowActivationAdministrativeStatus(shadowModel, ActivationStatusType.DISABLED); } - + assertAttribute(shadowModel, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertAttribute(shadowModel, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertAttributeFromBackingStore(shadowModel, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModel); - + assertPendingOperationDeltas(shadowModel, 3); - pendingOperation = findPendingOperation(shadowModel, + pendingOperation = findPendingOperation(shadowModel, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS); assertPendingOperation(shadowModel, pendingOperation, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowModelFuture); @@ -1285,11 +1316,11 @@ public void test240CloseDisableCaseAndReadAccountWill() throws Exception { assertAttributeFromBackingStore(shadowModelFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); // TODO // assertShadowPassword(shadowProvisioningFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } - + /** * lets ff 5min just for fun. Refresh, make sure everything should be the same (grace not expired yet) */ @@ -1302,10 +1333,10 @@ public void test250RecomputeWillAfter5min() throws Exception { OperationResult result = task.getResult(); clockForward("PT5M"); - + PrismObject shadowBefore = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); display("Shadow before", shadowBefore); - + // WHEN displayWhen(TEST_NAME); recomputeUser(userWillOid, task, result); @@ -1313,30 +1344,30 @@ public void test250RecomputeWillAfter5min() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); - + assertPendingOperationDeltas(shadowRepo, 3); - - PendingOperationType pendingOperation = findPendingOperation(shadowRepo, + + PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS); assertPendingOperation(shadowRepo, pendingOperation, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - - pendingOperation = findPendingOperation(shadowRepo, + + pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.IN_PROGRESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd); - + assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.DISABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -1350,17 +1381,17 @@ public void test250RecomputeWillAfter5min() throws Exception { assertAttribute(shadowModel, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertAttributeFromBackingStore(shadowModel, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModel); - + assertPendingOperationDeltas(shadowModel, 3); - pendingOperation = findPendingOperation(shadowModel, + pendingOperation = findPendingOperation(shadowModel, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS); assertPendingOperation(shadowModel, pendingOperation, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + PrismObject shadowProvisioningFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowProvisioningFuture); @@ -1372,11 +1403,11 @@ public void test250RecomputeWillAfter5min() throws Exception { assertAttributeFromBackingStore(shadowProvisioningFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); // TODO // assertShadowPassword(shadowProvisioningFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } - + @Test public void test252UpdateBackingStoreAndGetAccountWill() throws Exception { final String TEST_NAME = "test252UpdateBackingStoreAndGetAccountWill"; @@ -1384,9 +1415,9 @@ public void test252UpdateBackingStoreAndGetAccountWill() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + backingStoreUpdateWill(USER_WILL_FULL_NAME_PIRATE, INTEREST_ONE, ActivationStatusType.DISABLED, USER_WILL_PASSWORD_OLD); - + // WHEN displayWhen(TEST_NAME); PrismObject shadowModel = modelService.getObject(ShadowType.class, @@ -1395,7 +1426,7 @@ public void test252UpdateBackingStoreAndGetAccountWill() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + display("Model shadow", shadowModel); ShadowType shadowTypeModel = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -1405,15 +1436,15 @@ public void test252UpdateBackingStoreAndGetAccountWill() throws Exception { assertAttribute(shadowModel, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertAttributeFromBackingStore(shadowModel, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModel); - + assertPendingOperationDeltas(shadowModel, 3); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); - assertPendingOperationDeltas(shadowRepo, 3); - + assertPendingOperationDeltas(shadowRepo, 3); + PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowModelFuture); @@ -1425,7 +1456,7 @@ public void test252UpdateBackingStoreAndGetAccountWill() throws Exception { assertAttributeFromBackingStore(shadowModelFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); // TODO // assertShadowPassword(shadowProvisioningFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } @@ -1443,9 +1474,9 @@ public void test260ClosePasswordChangeCaseAndRecomputeWill() throws Exception { OperationResult result = task.getResult(); closeCase(willSecondLastCaseOid); - + accountWillSecondCompletionTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); recomputeUser(userWillOid, task, result); @@ -1453,35 +1484,35 @@ public void test260ClosePasswordChangeCaseAndRecomputeWill() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + accountWillSecondCompletionTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); - + assertPendingOperationDeltas(shadowRepo, 3); - - PendingOperationType pendingOperation = findPendingOperation(shadowRepo, + + PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillSecondCompletionTimestampStart, accountWillSecondCompletionTimestampEnd); - - pendingOperation = findPendingOperation(shadowRepo, + + pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillSecondCompletionTimestampStart, accountWillSecondCompletionTimestampEnd); - + assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -1495,17 +1526,17 @@ public void test260ClosePasswordChangeCaseAndRecomputeWill() throws Exception { assertAttribute(shadowModel, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertAttributeFromBackingStore(shadowModel, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModel); - + assertPendingOperationDeltas(shadowModel, 3); - pendingOperation = findPendingOperation(shadowModel, + pendingOperation = findPendingOperation(shadowModel, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillSecondCompletionTimestampStart, accountWillSecondCompletionTimestampEnd); - + PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowModelFuture); @@ -1516,11 +1547,11 @@ public void test260ClosePasswordChangeCaseAndRecomputeWill() throws Exception { assertAttribute(shadowModelFuture, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertAttributeFromBackingStore(shadowModelFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModelFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + /** * ff 10min. Refresh. Oldest delta should expire. */ @@ -1533,10 +1564,10 @@ public void test270RecomputeWillAfter10min() throws Exception { OperationResult result = task.getResult(); clockForward("PT10M"); - + PrismObject shadowBefore = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); display("Shadow before", shadowBefore); - + // WHEN displayWhen(TEST_NAME); recomputeUser(userWillOid, task, result); @@ -1544,33 +1575,33 @@ public void test270RecomputeWillAfter10min() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); - + assertPendingOperationDeltas(shadowRepo, 2); - - PendingOperationType pendingOperation = findPendingOperation(shadowRepo, + + PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillSecondCompletionTimestampStart, accountWillSecondCompletionTimestampEnd); - - pendingOperation = findPendingOperation(shadowRepo, + + pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillSecondCompletionTimestampStart, accountWillSecondCompletionTimestampEnd); - + assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -1584,17 +1615,17 @@ public void test270RecomputeWillAfter10min() throws Exception { assertAttribute(shadowModel, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertAttributeFromBackingStore(shadowModel, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModel); - + assertPendingOperationDeltas(shadowModel, 2); - pendingOperation = findPendingOperation(shadowModel, + pendingOperation = findPendingOperation(shadowModel, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillSecondCompletionTimestampStart, accountWillSecondCompletionTimestampEnd); - + PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowModelFuture); @@ -1605,11 +1636,11 @@ public void test270RecomputeWillAfter10min() throws Exception { assertAttribute(shadowModelFuture, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertAttributeFromBackingStore(shadowModelFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModelFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + @Test public void test272UpdateBackingStoreAndGetAccountWill() throws Exception { final String TEST_NAME = "test272UpdateBackingStoreAndGetAccountWill"; @@ -1617,9 +1648,9 @@ public void test272UpdateBackingStoreAndGetAccountWill() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + backingStoreUpdateWill(USER_WILL_FULL_NAME_PIRATE, INTEREST_ONE, ActivationStatusType.ENABLED, USER_WILL_PASSWORD_NEW); - + // WHEN displayWhen(TEST_NAME); PrismObject shadowModel = modelService.getObject(ShadowType.class, @@ -1628,7 +1659,7 @@ public void test272UpdateBackingStoreAndGetAccountWill() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -1638,15 +1669,15 @@ public void test272UpdateBackingStoreAndGetAccountWill() throws Exception { assertAttribute(shadowModel, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertAttributeFromBackingStore(shadowModel, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModel); - + assertPendingOperationDeltas(shadowModel, 2); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); assertPendingOperationDeltas(shadowRepo, 2); - + PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowModelFuture); @@ -1658,11 +1689,11 @@ public void test272UpdateBackingStoreAndGetAccountWill() throws Exception { assertAttributeFromBackingStore(shadowModelFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); // TODO // assertShadowPassword(shadowProvisioningFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + /** * ff 5min. Refresh. Another delta should expire. */ @@ -1675,7 +1706,7 @@ public void test280RecomputeWillAfter5min() throws Exception { OperationResult result = task.getResult(); clockForward("PT5M"); - + // WHEN displayWhen(TEST_NAME); recomputeUser(userWillOid, task, result); @@ -1683,33 +1714,33 @@ public void test280RecomputeWillAfter5min() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); - + assertPendingOperationDeltas(shadowRepo, 1); - - PendingOperationType pendingOperation = findPendingOperation(shadowRepo, + + PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillSecondCompletionTimestampStart, accountWillSecondCompletionTimestampEnd); - - pendingOperation = findPendingOperation(shadowRepo, + + pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillSecondCompletionTimestampStart, accountWillSecondCompletionTimestampEnd); - + assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -1719,17 +1750,17 @@ public void test280RecomputeWillAfter5min() throws Exception { assertAttribute(shadowModel, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertAttributeFromBackingStore(shadowModel, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModel); - + assertPendingOperationDeltas(shadowModel, 1); - pendingOperation = findPendingOperation(shadowModel, + pendingOperation = findPendingOperation(shadowModel, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillSecondCompletionTimestampStart, accountWillSecondCompletionTimestampEnd); - + PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowModelFuture); @@ -1740,11 +1771,11 @@ public void test280RecomputeWillAfter5min() throws Exception { assertAttribute(shadowModelFuture, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertAttributeFromBackingStore(shadowModelFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModelFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + /** * ff 5min. Refresh. All delta should expire. */ @@ -1757,7 +1788,7 @@ public void test290RecomputeWillAfter5min() throws Exception { OperationResult result = task.getResult(); clockForward("PT5M"); - + // WHEN displayWhen(TEST_NAME); recomputeUser(userWillOid, task, result); @@ -1765,19 +1796,19 @@ public void test290RecomputeWillAfter5min() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); - + assertPendingOperationDeltas(shadowRepo, 0); - + assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -1787,11 +1818,11 @@ public void test290RecomputeWillAfter5min() throws Exception { assertAttribute(shadowModel, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertAttributeFromBackingStore(shadowModel, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModel); - + assertPendingOperationDeltas(shadowModel, 0); - + PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowModelFuture); @@ -1802,11 +1833,11 @@ public void test290RecomputeWillAfter5min() throws Exception { assertAttribute(shadowModelFuture, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertAttributeFromBackingStore(shadowModelFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowModelFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + @Test public void test300UnassignAccountWill() throws Exception { final String TEST_NAME = "test300UnassignAccountWill"; @@ -1814,35 +1845,35 @@ public void test300UnassignAccountWill() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + accountWillReqestTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); unassignRole(userWillOid, getRoleOneOid(), task, result); - + // THEN displayThen(TEST_NAME); display("result", result); willLastCaseOid = assertInProgress(result); - + accountWillReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); assertPendingOperationDeltas(shadowRepo, 1); PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.IN_PROGRESS); assertPendingOperation(shadowRepo, pendingOperation, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); - + assertNotNull("No ID in pending operation", pendingOperation.getId()); // Still old data in the repo. The operation is not completed yet. assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -1856,26 +1887,26 @@ public void test300UnassignAccountWill() throws Exception { assertPendingOperationDeltas(shadowModel, 1); pendingOperation = findPendingOperation(shadowModel, OperationResultStatusType.IN_PROGRESS); assertPendingOperation(shadowModel, pendingOperation, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); - + PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowModelFuture); assertWillUnassignedFuture(shadowModelFuture, true); - + // Make sure that the account is still linked PrismObject userAfter = getUser(userWillOid); display("User after", userAfter); String accountWillOidAfter = getSingleLinkOid(userAfter); assertEquals(accountWillOid, accountWillOidAfter); assertNoAssignments(userAfter); - + assertNotNull("No async reference in result", willLastCaseOid); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } - + /** * Recompute. Make sure model will not try to delete the account again. */ @@ -1886,31 +1917,31 @@ public void test302RecomputeWill() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); recomputeUser(userWillOid, task, result); - + // THEN displayThen(TEST_NAME); display("result", result); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); assertPendingOperationDeltas(shadowRepo, 1); PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.IN_PROGRESS); assertPendingOperation(shadowRepo, pendingOperation, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); - + assertNotNull("No ID in pending operation", pendingOperation.getId()); // Still old data in the repo. The operation is not completed yet. assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -1924,26 +1955,26 @@ public void test302RecomputeWill() throws Exception { assertPendingOperationDeltas(shadowModel, 1); pendingOperation = findPendingOperation(shadowModel, OperationResultStatusType.IN_PROGRESS); assertPendingOperation(shadowModel, pendingOperation, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); - + PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowModelFuture); assertWillUnassignedFuture(shadowModelFuture, true); - + // Make sure that the account is still linked PrismObject userAfter = getUser(userWillOid); display("User after", userAfter); String accountWillOidAfter = getSingleLinkOid(userAfter); assertEquals(accountWillOid, accountWillOidAfter); assertNoAssignments(userAfter); - + assertNotNull("No async reference in result", willLastCaseOid); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } - + /** * Case is closed. The operation is complete. */ @@ -1956,9 +1987,9 @@ public void test310CloseCaseAndRecomputeWill() throws Exception { OperationResult result = task.getResult(); closeCase(willLastCaseOid); - + accountWillCompletionTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); // We need reconcile and not recompute here. We need to fetch the updated case status. @@ -1968,20 +1999,20 @@ public void test310CloseCaseAndRecomputeWill() throws Exception { displayThen(TEST_NAME); display("result", result); assertSuccess(result); - + accountWillCompletionTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); - assertSinglePendingOperation(shadowRepo, + assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); assertUnassignedShadow(shadowRepo, null); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -1989,25 +2020,25 @@ public void test310CloseCaseAndRecomputeWill() throws Exception { assertUnassignedShadow(shadowModel, ActivationStatusType.ENABLED); // backing store not yet updated assertShadowPassword(shadowModel); - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowModel, + PendingOperationType pendingOperation = assertSinglePendingOperation(shadowModel, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowModelFuture); assertWillUnassignedFuture(shadowModelFuture, true); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + protected void assertUnassignedShadow(PrismObject shadow, ActivationStatusType expectAlternativeActivationStatus) { assertShadowDead(shadow); } - + /** * ff 5min, everything should be the same (grace not expired yet) */ @@ -2020,7 +2051,7 @@ public void test320RecomputeWillAfter5min() throws Exception { OperationResult result = task.getResult(); clockForward("PT5M"); - + // WHEN displayWhen(TEST_NAME); recomputeUser(userWillOid, task, result); @@ -2028,40 +2059,40 @@ public void test320RecomputeWillAfter5min() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); - assertSinglePendingOperation(shadowRepo, + assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); assertUnassignedShadow(shadowRepo, null); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); assertEquals("Wrong kind (provisioning)", ShadowKindType.ACCOUNT, shadowTypeProvisioning.getKind()); assertUnassignedShadow(shadowModel, ActivationStatusType.ENABLED); // backing store not yet updated assertShadowPassword(shadowModel); - - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowModel, + + PendingOperationType pendingOperation = assertSinglePendingOperation(shadowModel, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowModelFuture); assertWillUnassignedFuture(shadowModelFuture, true); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + @Test public void test330UpdateBackingStoreAndRecomputeWill() throws Exception { final String TEST_NAME = "test330UpdateBackingStoreAndRecomputeWill"; @@ -2072,7 +2103,7 @@ public void test330UpdateBackingStoreAndRecomputeWill() throws Exception { backingStoreDeprovisionWill(); displayBackingStore(); - + // WHEN displayWhen(TEST_NAME); recomputeUser(userWillOid, task, result); @@ -2080,39 +2111,39 @@ public void test330UpdateBackingStoreAndRecomputeWill() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); - assertSinglePendingOperation(shadowRepo, + assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); assertUnassignedShadow(shadowRepo, null); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); assertEquals("Wrong kind (provisioning)", ShadowKindType.ACCOUNT, shadowTypeProvisioning.getKind()); assertUnassignedShadow(shadowModel, ActivationStatusType.DISABLED); - - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowModel, + + PendingOperationType pendingOperation = assertSinglePendingOperation(shadowModel, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowModelFuture); assertWillUnassignedFuture(shadowModelFuture, false); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + // TODO: nofetch, nofetch+future /** @@ -2127,7 +2158,7 @@ public void test340RecomputeWillAfter25min() throws Exception { OperationResult result = task.getResult(); clockForward("PT20M"); - + // WHEN displayWhen(TEST_NAME); recomputeUser(userWillOid, task, result); @@ -2135,23 +2166,23 @@ public void test340RecomputeWillAfter25min() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(userWillOid); display("User after", userAfter); assertDeprovisionedTimedOutUser(userAfter, accountWillOid); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + // TODO: create, close case, then update backing store. - + // TODO: let grace period expire without updating the backing store (semi-manual-only) - + protected void assertDeprovisionedTimedOutUser(PrismObject userAfter, String accountOid) throws Exception { assertLinks(userAfter, 0); assertNoShadow(accountOid); } - + /** * Put everything in a clean state so we can start over. */ @@ -2159,7 +2190,7 @@ protected void assertDeprovisionedTimedOutUser(PrismObject userAfter, public void test349CleanUp() throws Exception { final String TEST_NAME = "test349CleanUp"; displayTestTitle(TEST_NAME); - + cleanupUser(TEST_NAME, userWillOid, USER_WILL_NAME, accountWillOid); } @@ -2174,7 +2205,7 @@ protected void cleanupUser(final String TEST_NAME, String userOid, String userna public void test500AssignWillRoleOne() throws Exception { assignWillRoleOne("test500AssignWillRoleOne", USER_WILL_FULL_NAME_PIRATE); } - + /** * Unassign account before anybody had the time to do anything about it. * Create ticket is not closed, the account is not yet created and we @@ -2188,42 +2219,42 @@ public void test510UnassignWillRoleOne() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + accountWillSecondReqestTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); unassignRole(userWillOid, getRoleOneOid(), task, result); - + // THEN displayThen(TEST_NAME); display("result", result); willSecondLastCaseOid = assertInProgress(result); - + accountWillSecondReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); assertPendingOperationDeltas(shadowRepo, 2); - - PendingOperationType pendingOperation = findPendingOperation(shadowRepo, + + PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.IN_PROGRESS, ChangeTypeType.ADD); assertPendingOperation(shadowRepo, pendingOperation, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.IN_PROGRESS, null, null); assertNotNull("No ID in pending operation", pendingOperation.getId()); - + assertWillUnassignPendingOperation(shadowRepo, OperationResultStatusType.IN_PROGRESS); - + // Still old data in the repo. The operation is not completed yet. assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -2231,28 +2262,28 @@ public void test510UnassignWillRoleOne() throws Exception { assertAttribute(shadowModel, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertPendingOperationDeltas(shadowModel, 2); - + PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowModelFuture); assertShadowName(shadowModelFuture, USER_WILL_NAME); assertWillUnassignedFuture(shadowModelFuture, false); - + // Make sure that the account is still linked PrismObject userAfter = getUser(userWillOid); display("User after", userAfter); String accountWillOidAfter = getSingleLinkOid(userAfter); assertEquals(accountWillOid, accountWillOidAfter); assertNoAssignments(userAfter); - + assertNotNull("No async reference in result", willSecondLastCaseOid); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_OPEN); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } - + /** * Just make sure recon does not ruin anything. * MID-4037 @@ -2264,38 +2295,38 @@ public void test512ReconcileWill() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); reconcileUser(userWillOid, task, result); - + // THEN displayThen(TEST_NAME); display("result", result); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); assertPendingOperationDeltas(shadowRepo, 2); - - PendingOperationType pendingOperation = findPendingOperation(shadowRepo, + + PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.IN_PROGRESS, ChangeTypeType.ADD); assertPendingOperation(shadowRepo, pendingOperation, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.IN_PROGRESS, null, null); assertNotNull("No ID in pending operation", pendingOperation.getId()); - + assertWillUnassignPendingOperation(shadowRepo, OperationResultStatusType.IN_PROGRESS); - + // Still old data in the repo. The operation is not completed yet. assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -2303,28 +2334,28 @@ public void test512ReconcileWill() throws Exception { assertAttribute(shadowModel, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertPendingOperationDeltas(shadowModel, 2); - + PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowModelFuture); assertShadowName(shadowModelFuture, USER_WILL_NAME); assertWillUnassignedFuture(shadowModelFuture, false); - + // Make sure that the account is still linked PrismObject userAfter = getUser(userWillOid); display("User after", userAfter); String accountWillOidAfter = getSingleLinkOid(userAfter); assertEquals(accountWillOid, accountWillOidAfter); assertNoAssignments(userAfter); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_OPEN); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } - + protected void assertWillUnassignPendingOperation(PrismObject shadowRepo, OperationResultStatusType expectedStatus) { - PendingOperationType pendingOperation = findPendingOperation(shadowRepo, + PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.IN_PROGRESS, ChangeTypeType.DELETE); if (expectedStatus == OperationResultStatusType.IN_PROGRESS) { assertPendingOperation(shadowRepo, pendingOperation, @@ -2332,7 +2363,7 @@ protected void assertWillUnassignPendingOperation(PrismObject shadow OperationResultStatusType.IN_PROGRESS, null, null); } else { - pendingOperation = findPendingOperation(shadowRepo, + pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.SUCCESS, ChangeTypeType.DELETE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd, @@ -2357,9 +2388,9 @@ public void test515CloseCasesAndRecomputeWill() throws Exception { closeCase(willLastCaseOid); closeCase(willSecondLastCaseOid); - + accountWillCompletionTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); // We need reconcile and not recompute here. We need to fetch the updated case status. @@ -2369,29 +2400,29 @@ public void test515CloseCasesAndRecomputeWill() throws Exception { displayThen(TEST_NAME); display("result", result); assertSuccess(result); - + accountWillCompletionTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); - + assertPendingOperationDeltas(shadowRepo, 2); - - PendingOperationType pendingOperation = findPendingOperation(shadowRepo, + + PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.SUCCESS, ChangeTypeType.ADD); assertPendingOperation(shadowRepo, pendingOperation, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); assertNotNull("No ID in pending operation", pendingOperation.getId()); - + assertWillUnassignPendingOperation(shadowRepo, OperationResultStatusType.SUCCESS); - + assertUnassignedShadow(shadowRepo, null); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -2399,16 +2430,16 @@ public void test515CloseCasesAndRecomputeWill() throws Exception { assertUnassignedShadow(shadowModel, null); // Shadow in not in the backing store PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, - accountWillOid, + accountWillOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowModelFuture); assertWillUnassignedFuture(shadowModelFuture, true); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + /** * ff 35min, grace period expired, shadow should be gone, linkRef shoud be gone. * So we have clean state for next tests. @@ -2423,7 +2454,7 @@ public void test517RecomputeWillAfter35min() throws Exception { OperationResult result = task.getResult(); clockForward("PT35M"); - + // WHEN displayWhen(TEST_NAME); recomputeUser(userWillOid, task, result); @@ -2431,20 +2462,20 @@ public void test517RecomputeWillAfter35min() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(userWillOid); display("User after", userAfter); // Shadow will not stay even in the "disable" case. // It was never created in the backing store assertLinks(userAfter, 0); - + // TODO: why? // assertNoShadow(accountWillOid); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + /** * Put everything in a clean state so we can start over. */ @@ -2454,17 +2485,17 @@ public void test519CleanUp() throws Exception { displayTestTitle(TEST_NAME); Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + cleanupUser(TEST_NAME, userWillOid, USER_WILL_NAME, accountWillOid); - + // Make sure that all pending operations are expired clockForward("PT1H"); recomputeUser(userWillOid, task, result); assertSuccess(result); - + assertNoShadow(accountWillOid); } - + /** * MID-4095 */ @@ -2472,8 +2503,8 @@ public void test519CleanUp() throws Exception { public void test520AssignWillRoleOne() throws Exception { assignWillRoleOne("test520AssignWillRoleOne", USER_WILL_FULL_NAME_PIRATE); } - - + + /** * Not much happens here yet. Role two is assigned. But it has validity in the future. * Therefore there are no changes in the account, no new pending deltas. @@ -2486,30 +2517,30 @@ public void test522AssignWillRoleTwoValidFrom() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ActivationType activationType = new ActivationType(); roleTwoValidFromTimestamp = getTimestamp("PT2H"); activationType.setValidFrom(roleTwoValidFromTimestamp); - + // WHEN displayWhen(TEST_NAME); assignRole(userWillOid, getRoleTwoOid(), activationType, task, result); - + // THEN displayThen(TEST_NAME); display("result", result); assertSuccess(result); - + PrismObject userAfter = getUser(userWillOid); display("User after", userAfter); accountWillOid = getSingleLinkOid(userAfter); - + accountWillReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); assertAccountWillAfterAssign(TEST_NAME, USER_WILL_FULL_NAME_PIRATE); } - - + + /** * Two hours forward. Role two is valid now. * MID-4095 @@ -2519,33 +2550,33 @@ public void test524TwoHoursForRoleTwo() throws Exception { final String TEST_NAME = "test524TwoHoursForRoleTwo"; displayTestTitle(TEST_NAME); // GIVEN - + clockForward("PT2H5M"); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + accountWillSecondReqestTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); reconcileUser(userWillOid, task, result); - + // THEN displayThen(TEST_NAME); display("result", result); willSecondLastCaseOid = assertInProgress(result); - + PrismObject userAfter = getUser(userWillOid); display("User after", userAfter); accountWillOid = getSingleLinkOid(userAfter); - + accountWillSecondReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); assertPendingOperationDeltas(shadowRepo, 2); - + ObjectDeltaType deltaModify = null; ObjectDeltaType deltaAdd = null; for (PendingOperationType pendingOperation: shadowRepo.asObjectable().getPendingOperation()) { @@ -2561,21 +2592,21 @@ public void test524TwoHoursForRoleTwo() throws Exception { } assertNotNull("No add pending delta", deltaAdd); assertNotNull("No modify pending delta", deltaModify); - + assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME_PIRATE); assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertShadowExists(shadowRepo, false); assertNoShadowPassword(shadowRepo); - + // TODO: assert future - + assertNotNull("No async reference in result", willSecondLastCaseOid); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_OPEN); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } - + /** * MID-4095 */ @@ -2589,9 +2620,9 @@ public void test525CloseCasesAndRecomputeWill() throws Exception { closeCase(willLastCaseOid); closeCase(willSecondLastCaseOid); - + accountWillCompletionTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); // We need reconcile and not recompute here. We need to fetch the updated case status. @@ -2601,18 +2632,18 @@ public void test525CloseCasesAndRecomputeWill() throws Exception { displayThen(TEST_NAME); display("result", result); assertSuccess(result); - + accountWillCompletionTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); - + assertPendingOperationDeltas(shadowRepo, 2); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + /** * Unassign both roles at the same time. * Note: In semi-manual cases the backing store is never updated. @@ -2624,36 +2655,36 @@ public void test526UnassignWillBothRoles() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(userWillOid); - + accountWillSecondReqestTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); - + unassignAll(userBefore, task, result); - + // THEN displayThen(TEST_NAME); display("result", result); willLastCaseOid = assertInProgress(result); - + accountWillSecondReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); - + assertTest526Deltas(shadowRepo, result); - + assertNotNull("No async reference in result", willLastCaseOid); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } - + protected void assertTest526Deltas(PrismObject shadowRepo, OperationResult result) { assertPendingOperationDeltas(shadowRepo, 3); - + ObjectDeltaType deltaModify = null; ObjectDeltaType deltaAdd = null; ObjectDeltaType deltaDelete = null; @@ -2686,9 +2717,9 @@ public void test528CloseCaseAndRecomputeWill() throws Exception { OperationResult result = task.getResult(); closeCase(willLastCaseOid); - + accountWillCompletionTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); // We need reconcile and not recompute here. We need to fetch the updated case status. @@ -2698,20 +2729,20 @@ public void test528CloseCaseAndRecomputeWill() throws Exception { displayThen(TEST_NAME); display("result", result); assertSuccess(result); - + accountWillCompletionTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); - + assertTest528Deltas(shadowRepo, result); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + protected void assertTest528Deltas(PrismObject shadowRepo, OperationResult result) { assertPendingOperationDeltas(shadowRepo, 3); - + ObjectDeltaType deltaModify = null; ObjectDeltaType deltaAdd = null; ObjectDeltaType deltaDelete = null; @@ -2743,19 +2774,19 @@ public void test529CleanUp() throws Exception { displayTestTitle(TEST_NAME); Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + cleanupUser(TEST_NAME, userWillOid, USER_WILL_NAME, accountWillOid); - + // Make sure that all pending operations are expired clockForward("PT1H"); recomputeUser(userWillOid, task, result); assertSuccess(result); - + assertNoShadow(accountWillOid); } - + // Tests 7xx are in the subclasses - + /** * The 8xx tests is similar routine as 1xx,2xx,3xx, but this time * with automatic updates using refresh task. @@ -2765,36 +2796,36 @@ public void test800ImportShadowRefreshTask() throws Exception { final String TEST_NAME = "test800ImportShadowRefreshTask"; displayTestTitle(TEST_NAME); // GIVEN - + // WHEN displayWhen(TEST_NAME); addTask(TASK_SHADOW_REFRESH_FILE); - + // THEN displayThen(TEST_NAME); - + waitForTaskStart(TASK_SHADOW_REFRESH_OID, false); } - + @Test public void test810AssignAccountWill() throws Exception { final String TEST_NAME = "test810AssignAccountWill"; - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + modifyUserReplace(userWillOid, UserType.F_FULL_NAME, task, result, createPolyString(USER_WILL_FULL_NAME)); - + // WHEN assignWillRoleOne(TEST_NAME, USER_WILL_FULL_NAME); - + // THEN restartTask(TASK_SHADOW_REFRESH_OID); waitForTaskFinish(TASK_SHADOW_REFRESH_OID, false); - + assertAccountWillAfterAssign(TEST_NAME, USER_WILL_FULL_NAME); } - + @Test public void test820AssignAccountJack() throws Exception { final String TEST_NAME = "test820AssignAccountJack"; @@ -2802,9 +2833,9 @@ public void test820AssignAccountJack() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + clockForward("PT5M"); - + accountJackReqestTimestampStart = clock.currentTimeXMLGregorianCalendar(); // WHEN @@ -2819,18 +2850,18 @@ public void test820AssignAccountJack() throws Exception { PrismObject userAfter = getUser(USER_JACK_OID); display("User after", userAfter); accountJackOid = getSingleLinkOid(userAfter); - + accountJackReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); assertAccountJackAfterAssign(TEST_NAME); - + // THEN restartTask(TASK_SHADOW_REFRESH_OID); waitForTaskFinish(TASK_SHADOW_REFRESH_OID, false); - + assertAccountJackAfterAssign(TEST_NAME); } - + @Test public void test830CloseCaseAndWaitForRefresh() throws Exception { final String TEST_NAME = "test830CloseCaseAndWaitForRefresh"; @@ -2838,11 +2869,11 @@ public void test830CloseCaseAndWaitForRefresh() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + closeCase(willLastCaseOid); - + accountWillCompletionTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); restartTask(TASK_SHADOW_REFRESH_OID); @@ -2851,14 +2882,14 @@ public void test830CloseCaseAndWaitForRefresh() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + accountWillCompletionTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + assertWillAfterCreateCaseClosed(TEST_NAME, false); - + assertAccountJackAfterAssign(TEST_NAME); } - + @Test public void test840AddToBackingStoreAndGetAccountWill() throws Exception { final String TEST_NAME = "test840AddToBackingStoreAndGetAccountWill"; @@ -2866,17 +2897,17 @@ public void test840AddToBackingStoreAndGetAccountWill() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + backingStoreProvisionWill(INTEREST_ONE); - + // WHEN displayWhen(TEST_NAME); PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); // THEN displayThen(TEST_NAME); - assertSuccess(result); - + assertSuccess(result); + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -2887,10 +2918,10 @@ public void test840AddToBackingStoreAndGetAccountWill() throws Exception { assertShadowActivationAdministrativeStatus(shadowModel, ActivationStatusType.ENABLED); assertShadowExists(shadowModel, true); assertShadowPassword(shadowModel); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); - assertSinglePendingOperation(shadowRepo, + assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); @@ -2902,68 +2933,30 @@ public void test840AddToBackingStoreAndGetAccountWill() throws Exception { assertShadowExists(shadowRepo, true); } - // MID-4047 - @Test - public void test900ConcurrentConstructions() throws Exception { - final String TEST_NAME = "test900ConcurrentConstructions"; - displayTestTitle(TEST_NAME); - // GIVEN - Task task = createTask(TEST_NAME); - OperationResult result = task.getResult(); - - final long TIMEOUT = 60000L; - // WHEN - displayWhen(TEST_NAME); - - ParallelTestThread[] threads = multithread(TEST_NAME, - () -> { - login(userAdministrator); - Task localTask = createTask(TEST_NAME + ".local"); - - assignAccount(USER_BARBOSSA_OID, getResourceOid(), SchemaConstants.INTENT_DEFAULT, localTask, localTask.getResult()); - - }, getConcurrentTestNumberOfThreads(), getConcurrentTestRandomStartDelayRange()); - - // THEN - displayThen(TEST_NAME); - waitForThreads(threads, TIMEOUT); - - PrismObject barbossa = getUser(USER_BARBOSSA_OID); - display("barbossa", barbossa); - assertEquals("Wrong # of links", 1, barbossa.asObjectable().getLinkRef().size()); - } - - protected int getConcurrentTestNumberOfThreads() { - return 4; - } - - protected int getConcurrentTestRandomStartDelayRange() { - return 1000; - } protected void backingStoreProvisionWill(String interest) throws IOException { // nothing to do here } - + protected void backingStoreUpdateWill(String newFullName, String interest, ActivationStatusType newAdministrativeStatus, String password) throws IOException { // nothing to do here } - + protected void backingStoreDeprovisionWill() throws IOException { // Nothing to do here } - + protected void displayBackingStore() throws IOException { // Nothing to do here } - + private void assignWillRoleOne(final String TEST_NAME, String expectedFullName) throws Exception { displayTestTitle(TEST_NAME); // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + accountWillReqestTimestampStart = clock.currentTimeXMLGregorianCalendar(); // WHEN @@ -2978,7 +2971,7 @@ private void assignWillRoleOne(final String TEST_NAME, String expectedFullName) PrismObject userAfter = getUser(userWillOid); display("User after", userAfter); accountWillOid = getSingleLinkOid(userAfter); - + accountWillReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); assertAccountWillAfterAssign(TEST_NAME, expectedFullName); @@ -2987,7 +2980,7 @@ private void assignWillRoleOne(final String TEST_NAME, String expectedFullName) private void assertAccountWillAfterAssign(final String TEST_NAME, String expectedFullName) throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); PendingOperationType pendingOperation = assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); @@ -2997,10 +2990,10 @@ private void assertAccountWillAfterAssign(final String TEST_NAME, String expecte assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertShadowExists(shadowRepo, false); assertNoShadowPassword(shadowRepo); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -3012,16 +3005,16 @@ private void assertAccountWillAfterAssign(final String TEST_NAME, String expecte assertNoShadowPassword(shadowModel); assertSinglePendingOperation(shadowModel, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); - + assertNotNull("No async reference in result", willLastCaseOid); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } - + protected void assertAccountJackAfterAssign(final String TEST_NAME) throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); display("Repo shadow", shadowRepo); PendingOperationType pendingOperation = assertSinglePendingOperation(shadowRepo, accountJackReqestTimestampStart, accountJackReqestTimestampEnd); @@ -3031,10 +3024,10 @@ protected void assertAccountJackAfterAssign(final String TEST_NAME) throws Excep assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertShadowExists(shadowRepo, false); assertNoShadowPassword(shadowRepo); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_JACK_USERNAME); @@ -3046,29 +3039,29 @@ protected void assertAccountJackAfterAssign(final String TEST_NAME) throws Excep assertNoShadowPassword(shadowModel); assertSinglePendingOperation(shadowModel, accountJackReqestTimestampStart, accountJackReqestTimestampEnd); - + assertNotNull("No async reference in result", jackLastCaseOid); - + assertCase(jackLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } private void assertWillAfterCreateCaseClosed(final String TEST_NAME, boolean backingStoreUpdated) throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountWillOid, null, result); display("Repo shadow", shadowRepo); - assertSinglePendingOperation(shadowRepo, + assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, USER_WILL_NAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, USER_WILL_FULL_NAME); assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountWillOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_WILL_NAME); @@ -3080,12 +3073,12 @@ private void assertWillAfterCreateCaseClosed(final String TEST_NAME, boolean bac assertShadowActivationAdministrativeStatus(shadowModel, ActivationStatusType.ENABLED); assertShadowPassword(shadowModel); } - - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowModel, + + PendingOperationType pendingOperation = assertSinglePendingOperation(shadowModel, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } @@ -3093,26 +3086,26 @@ protected void assertWillUnassignedFuture(PrismObject shadowModelFut assertShadowName(shadowModelFuture, USER_WILL_NAME); assertUnassignedFuture(shadowModelFuture, assertPassword); } - + protected void assertUnassignedFuture(PrismObject shadowModelFuture, boolean assertPassword) { assertShadowDead(shadowModelFuture); if (assertPassword) { assertShadowPassword(shadowModelFuture); } } - + protected void assertPendingOperationDeltas(PrismObject shadow, int expectedNumber) { List pendingOperations = shadow.asObjectable().getPendingOperation(); assertEquals("Wroung number of pending operations in "+shadow, expectedNumber, pendingOperations.size()); } - protected PendingOperationType assertSinglePendingOperation(PrismObject shadow, + protected PendingOperationType assertSinglePendingOperation(PrismObject shadow, XMLGregorianCalendar requestStart, XMLGregorianCalendar requestEnd) { - return assertSinglePendingOperation(shadow, requestStart, requestEnd, + return assertSinglePendingOperation(shadow, requestStart, requestEnd, OperationResultStatusType.IN_PROGRESS, null, null); } - - protected PendingOperationType assertSinglePendingOperation(PrismObject shadow, + + protected PendingOperationType assertSinglePendingOperation(PrismObject shadow, XMLGregorianCalendar requestStart, XMLGregorianCalendar requestEnd, OperationResultStatusType expectedStatus, XMLGregorianCalendar completionStart, XMLGregorianCalendar completionEnd) { @@ -3120,53 +3113,53 @@ protected PendingOperationType assertSinglePendingOperation(PrismObject shadow, PendingOperationType pendingOperation, + PrismObject shadow, PendingOperationType pendingOperation, XMLGregorianCalendar requestStart, XMLGregorianCalendar requestEnd) { - return assertPendingOperation(shadow, pendingOperation, requestStart, requestEnd, + return assertPendingOperation(shadow, pendingOperation, requestStart, requestEnd, OperationResultStatusType.IN_PROGRESS, null, null); } - + protected PendingOperationType assertPendingOperation( PrismObject shadow, PendingOperationType pendingOperation, XMLGregorianCalendar requestStart, XMLGregorianCalendar requestEnd, OperationResultStatusType expectedStatus, XMLGregorianCalendar completionStart, XMLGregorianCalendar completionEnd) { assertNotNull("No operation ", pendingOperation); - + ObjectDeltaType deltaType = pendingOperation.getDelta(); assertNotNull("No delta in pending operation in "+shadow, deltaType); // TODO: check content of pending operations in the shadow - + TestUtil.assertBetween("No request timestamp in pending operation in "+shadow, requestStart, requestEnd, pendingOperation.getRequestTimestamp()); - + OperationResultStatusType status = pendingOperation.getResultStatus(); assertEquals("Wrong status in pending operation in "+shadow, expectedStatus, status); - + if (expectedStatus != OperationResultStatusType.IN_PROGRESS) { TestUtil.assertBetween("No completion timestamp in pending operation in "+shadow, completionStart, completionEnd, pendingOperation.getCompletionTimestamp()); } - + return pendingOperation; } - - protected PendingOperationType findPendingOperation(PrismObject shadow, + + protected PendingOperationType findPendingOperation(PrismObject shadow, OperationResultStatusType expectedResult) { return findPendingOperation(shadow, expectedResult, null, null); } - - protected PendingOperationType findPendingOperation(PrismObject shadow, + + protected PendingOperationType findPendingOperation(PrismObject shadow, OperationResultStatusType expectedResult, ItemPath itemPath) { return findPendingOperation(shadow, expectedResult, null, itemPath); } - - protected PendingOperationType findPendingOperation(PrismObject shadow, + + protected PendingOperationType findPendingOperation(PrismObject shadow, OperationResultStatusType expectedResult, ChangeTypeType expectedChangeType) { return findPendingOperation(shadow, expectedResult, expectedChangeType, null); } - - protected PendingOperationType findPendingOperation(PrismObject shadow, + + protected PendingOperationType findPendingOperation(PrismObject shadow, OperationResultStatusType expectedResult, ChangeTypeType expectedChangeType, ItemPath itemPath) { List pendingOperations = shadow.asObjectable().getPendingOperation(); for (PendingOperationType pendingOperation: pendingOperations) { @@ -3192,19 +3185,19 @@ protected PendingOperationType findPendingOperation(PrismObject shad if (itemPath.equivalent(deltaPath)) { return pendingOperation; } - } + } } return null; } - + protected void assertAttribute(PrismObject shadow, QName attrName, T... expectedValues) { assertAttribute(resource, shadow.asObjectable(), attrName, expectedValues); } - + protected void assertNoAttribute(PrismObject shadow, QName attrName) { assertNoAttribute(resource, shadow.asObjectable(), attrName); } - + protected void assertAttributeFromCache(PrismObject shadow, QName attrQName, String... attrVals) { if (supportsBackingStore()) { @@ -3213,7 +3206,7 @@ protected void assertAttributeFromCache(PrismObject shadow, QName at assertAttribute(shadow, attrQName, attrVals); } } - + protected void assertAttributeFromBackingStore(PrismObject shadow, QName attrQName, String... attrVals) { if (supportsBackingStore()) { @@ -3222,7 +3215,7 @@ protected void assertAttributeFromBackingStore(PrismObject shadow, Q assertNoAttribute(shadow, attrQName); } } - + protected void assertShadowActivationAdministrativeStatusFromCache(PrismObject shadow, ActivationStatusType expectedStatus) { if (supportsBackingStore()) { assertShadowActivationAdministrativeStatus(shadow, null); @@ -3230,16 +3223,16 @@ protected void assertShadowActivationAdministrativeStatusFromCache(PrismObject shadow, ActivationStatusType expectedStatus) { assertActivationAdministrativeStatus(shadow, expectedStatus); } - + protected void assertShadowPassword(PrismObject shadow) { // pure manual resource should never "read" password assertNoShadowPassword(shadow); } - + private void assertManual(AbstractWriteCapabilityType cap) { assertEquals("Manual flag not set in capability "+cap, Boolean.TRUE, cap.isManual()); } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestManual.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestManual.java index 92f98c467e7..000bf606180 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestManual.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestManual.java @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.model.intest.manual; @@ -33,7 +33,7 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestManual extends AbstractManualResourceTest { - + @Override protected String getResourceOid() { return RESOURCE_MANUAL_OID; @@ -43,27 +43,27 @@ protected String getResourceOid() { protected File getResourceFile() { return RESOURCE_MANUAL_FILE; } - + @Override protected String getRoleOneOid() { return ROLE_ONE_MANUAL_OID; } - + @Override protected File getRoleOneFile() { return ROLE_ONE_MANUAL_FILE; } - + @Override protected String getRoleTwoOid() { return ROLE_TWO_MANUAL_OID; } - + @Override protected File getRoleTwoFile() { return ROLE_TWO_MANUAL_FILE; } - + @Override protected void assertResourceSchemaBeforeTest(Element resourceXsdSchemaElementBefore) { AssertJUnit.assertNotNull("No schema before test connection. Bad test setup?", resourceXsdSchemaElementBefore); 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 a3c4ada164a..5155d42e4e0 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 @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.model.intest.manual; @@ -71,22 +71,22 @@ @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class TestSemiManual extends AbstractManualResourceTest { - + protected static final File CSV_SOURCE_FILE = new File(TEST_DIR, "semi-manual.csv"); protected static final File CSV_TARGET_FILE = new File("target/semi-manual.csv"); - + private static final Trace LOGGER = TraceManager.getTrace(TestSemiManual.class); - + protected static final String ATTR_DISABLED = "disabled"; protected static final QName ATTR_DISABLED_QNAME = new QName(MidPointConstants.NS_RI, ATTR_DISABLED); - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + FileUtils.copyFile(CSV_SOURCE_FILE, CSV_TARGET_FILE); } - + @Override protected String getResourceOid() { return RESOURCE_SEMI_MANUAL_OID; @@ -96,42 +96,47 @@ protected String getResourceOid() { protected File getResourceFile() { return RESOURCE_SEMI_MANUAL_FILE; } - + @Override protected String getRoleOneOid() { return ROLE_ONE_SEMI_MANUAL_OID; } - + @Override protected File getRoleOneFile() { return ROLE_ONE_SEMI_MANUAL_FILE; } - + @Override protected String getRoleTwoOid() { return ROLE_TWO_SEMI_MANUAL_OID; } - + @Override protected File getRoleTwoFile() { return ROLE_TWO_SEMI_MANUAL_FILE; } - + @Override protected boolean supportsBackingStore() { return true; } - + + @Override + protected boolean hasMultivalueInterests() { + return false; + } + @Override protected void assertResourceSchemaBeforeTest(Element resourceXsdSchemaElementBefore) { AssertJUnit.assertNull("Resource schema sneaked in before test connection", resourceXsdSchemaElementBefore); } - + @Override protected int getNumberOfAccountAttributeDefinitions() { return 5; } - + /** * MID-4002 */ @@ -142,17 +147,17 @@ public void test700AssignAccountJackExisting() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + if (accountJackOid != null) { PrismObject shadowRepoBefore = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); display("Repo shadow before", shadowRepoBefore); assertPendingOperationDeltas(shadowRepoBefore, 0); } - + backingStoreAddJack(); - + clock.overrideDuration("PT5M"); - + accountJackReqestTimestampStart = clock.currentTimeXMLGregorianCalendar(); // WHEN @@ -166,20 +171,20 @@ public void test700AssignAccountJackExisting() throws Exception { assertNull("Unexpected ticket in result", result.getAsynchronousOperationReference()); accountJackReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", userAfter); accountJackOid = getSingleLinkOid(userAfter); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); display("Repo shadow", shadowRepo); assertPendingOperationDeltas(shadowRepo, 0); assertShadowExists(shadowRepo, true); assertNoShadowPassword(shadowRepo); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_JACK_USERNAME); @@ -188,10 +193,10 @@ public void test700AssignAccountJackExisting() throws Exception { assertAttribute(shadowModel, ATTR_FULLNAME_QNAME, USER_JACK_FULL_NAME); assertShadowActivationAdministrativeStatus(shadowModel, ActivationStatusType.ENABLED); assertShadowExists(shadowModel, true); - - assertPendingOperationDeltas(shadowModel, 0); + + assertPendingOperationDeltas(shadowModel, 0); } - + /** * MID-4002 */ @@ -202,9 +207,9 @@ public void test710UnassignAccountJack() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + clock.overrideDuration("PT5M"); - + accountJackReqestTimestampStart = clock.currentTimeXMLGregorianCalendar(); // WHEN @@ -219,20 +224,20 @@ public void test710UnassignAccountJack() throws Exception { PrismObject userAfter = getUser(USER_JACK_OID); display("User after", userAfter); accountJackOid = getSingleLinkOid(userAfter); - + accountJackReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); display("Repo shadow", shadowRepo); - + assertPendingOperationDeltas(shadowRepo, 1); PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.IN_PROGRESS); assertPendingOperation(shadowRepo, pendingOperation, accountJackReqestTimestampStart, accountJackReqestTimestampEnd); assertNotNull("No ID in pending operation", pendingOperation.getId()); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeProvisioning = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_JACK_USERNAME); @@ -242,18 +247,18 @@ public void test710UnassignAccountJack() throws Exception { assertPendingOperationDeltas(shadowModel, 1); pendingOperation = findPendingOperation(shadowModel, OperationResultStatusType.IN_PROGRESS); assertPendingOperation(shadowModel, pendingOperation, accountJackReqestTimestampStart, accountJackReqestTimestampEnd); - + PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, - accountJackOid, + accountJackOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowModelFuture); assertShadowName(shadowModelFuture, USER_JACK_USERNAME); assertUnassignedFuture(shadowModelFuture, true); - + assertCase(jackLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } - + /** * MID-4002 */ @@ -266,11 +271,11 @@ public void test712CloseCaseAndRecomputeJack() throws Exception { OperationResult result = task.getResult(); backingStoreDeleteJack(); - + closeCase(jackLastCaseOid); - + accountJackCompletionTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); // We need reconcile and not recompute here. We need to fetch the updated case status. @@ -280,42 +285,42 @@ public void test712CloseCaseAndRecomputeJack() throws Exception { displayThen(TEST_NAME); display("result", result); assertSuccess(result); - + accountJackCompletionTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); display("Repo shadow", shadowRepo); - assertSinglePendingOperation(shadowRepo, + assertSinglePendingOperation(shadowRepo, accountJackReqestTimestampStart, accountJackReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountJackCompletionTimestampStart, accountJackCompletionTimestampEnd); assertUnassignedShadow(shadowRepo, null); - + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); - + display("Model shadow", shadowModel); ShadowType shadowTypeModel = shadowModel.asObjectable(); assertShadowName(shadowModel, USER_JACK_USERNAME); assertEquals("Wrong kind (model)", ShadowKindType.ACCOUNT, shadowTypeModel.getKind()); assertUnassignedShadow(shadowModel, ActivationStatusType.DISABLED); - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowModel, + PendingOperationType pendingOperation = assertSinglePendingOperation(shadowModel, accountJackReqestTimestampStart, accountJackReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountJackCompletionTimestampStart, accountJackCompletionTimestampEnd); - + PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, - accountJackOid, + accountJackOid, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Model shadow (future)", shadowModelFuture); assertShadowName(shadowModelFuture, USER_JACK_USERNAME); assertUnassignedFuture(shadowModelFuture, false); - + assertCase(jackLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + /** * MID-4002 */ @@ -328,7 +333,7 @@ public void test717RecomputeJackAfter30min() throws Exception { OperationResult result = task.getResult(); clock.overrideDuration("PT30M"); - + // WHEN displayWhen(TEST_NAME); // We need reconcile and not recompute here. We need to fetch the updated case status. @@ -342,10 +347,10 @@ public void test717RecomputeJackAfter30min() throws Exception { PrismObject userAfter = getUser(USER_JACK_OID); display("User after", userAfter); assertDeprovisionedTimedOutUser(userAfter, accountJackOid); - + assertCase(jackLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + /** * Put everything in a clean state so we can start over. */ @@ -353,15 +358,15 @@ public void test717RecomputeJackAfter30min() throws Exception { public void test719CleanUp() throws Exception { final String TEST_NAME = "test719CleanUp"; displayTestTitle(TEST_NAME); - + cleanupUser(TEST_NAME, USER_JACK_OID, USER_JACK_USERNAME, accountJackOid); } - + @Override protected void backingStoreProvisionWill(String interest) throws IOException { appendToCsv(new String[]{USER_WILL_NAME, USER_WILL_FULL_NAME, ACCOUNT_WILL_DESCRIPTION_MANUAL, interest, "false", USER_WILL_PASSWORD_OLD}); } - + @Override protected void backingStoreUpdateWill(String newFullName, String interest, ActivationStatusType newAdministrativeStatus, String password) throws IOException { String disabled; @@ -372,20 +377,20 @@ protected void backingStoreUpdateWill(String newFullName, String interest, Activ } replaceInCsv(new String[]{USER_WILL_NAME, newFullName, ACCOUNT_WILL_DESCRIPTION_MANUAL, interest, disabled, password}); } - + @Override protected void backingStoreDeprovisionWill() throws IOException { deprovisionInCsv(USER_WILL_NAME); } - + protected void backingStoreAddJack() throws IOException { appendToCsv(new String[]{USER_JACK_USERNAME, USER_JACK_FULL_NAME, ACCOUNT_JACK_DESCRIPTION_MANUAL, "", "false", USER_JACK_PASSWORD_OLD}); } - + protected void backingStoreDeleteJack() throws IOException { deprovisionInCsv(USER_JACK_USERNAME); } - + protected void deprovisionInCsv(String username) throws IOException { deleteInCsv(username); } @@ -395,7 +400,7 @@ protected void disableInCsv(String username) throws IOException { data[4] = "true"; replaceInCsv(data); } - + protected String[] readFromCsv(String username) throws IOException { List lines = Files.readAllLines(Paths.get(CSV_TARGET_FILE.getPath())); for (int i = 0; i < lines.size(); i++) { @@ -407,7 +412,7 @@ protected String[] readFromCsv(String username) throws IOException { } return null; } - + private String[] unescape(String[] cols) { String[] out = new String[cols.length]; for (int i = 0; i < cols.length; i++) { @@ -422,7 +427,7 @@ protected void appendToCsv(String[] data) throws IOException { String line = formatCsvLine(data); Files.write(Paths.get(CSV_TARGET_FILE.getPath()), line.getBytes(), StandardOpenOption.APPEND); } - + protected void replaceInCsv(String[] data) throws IOException { List lines = Files.readAllLines(Paths.get(CSV_TARGET_FILE.getPath())); boolean found = false; @@ -440,7 +445,7 @@ protected void replaceInCsv(String[] data) throws IOException { Files.write(Paths.get(CSV_TARGET_FILE.getPath()), lines, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); } - + protected void deleteInCsv(String username) throws IOException { List lines = Files.readAllLines(Paths.get(CSV_TARGET_FILE.getPath())); Iterator iterator = lines.iterator(); @@ -458,12 +463,12 @@ protected void deleteInCsv(String username) throws IOException { private String formatCsvLine(String[] data) { return Arrays.stream(data).map(s -> "\""+s+"\"").collect(Collectors.joining(",")); } - + @Override protected void displayBackingStore() throws IOException { display("CSV", dumpCsv()); } - + protected String dumpCsv() throws IOException { return StringUtils.join(Files.readAllLines(Paths.get(CSV_TARGET_FILE.getPath())), "\n"); } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualDisable.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualDisable.java index 190b09e738b..d3d09efb74b 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualDisable.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualDisable.java @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.model.intest.manual; @@ -52,14 +52,14 @@ @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class TestSemiManualDisable extends TestSemiManual { - + private static final Trace LOGGER = TraceManager.getTrace(TestSemiManualDisable.class); - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); } - + @Override protected String getResourceOid() { return RESOURCE_SEMI_MANUAL_DISABLE_OID; @@ -69,12 +69,12 @@ protected String getResourceOid() { protected File getResourceFile() { return RESOURCE_SEMI_MANUAL_DISABLE_FILE; } - + @Override protected String getRoleOneOid() { return ROLE_ONE_SEMI_MANUAL_DISABLE_OID; } - + @Override protected File getRoleOneFile() { return ROLE_ONE_SEMI_MANUAL_DISABLE_FILE; @@ -84,7 +84,7 @@ protected File getRoleOneFile() { protected String getRoleTwoOid() { return ROLE_TWO_SEMI_MANUAL_DISABLE_OID; } - + @Override protected File getRoleTwoFile() { return ROLE_TWO_SEMI_MANUAL_DISABLE_FILE; @@ -94,13 +94,13 @@ protected File getRoleTwoFile() { protected void deprovisionInCsv(String username) throws IOException { disableInCsv(username); } - + @Override protected void assertUnassignedShadow(PrismObject shadow, ActivationStatusType expectAlternativeActivationStatus) { assertShadowNotDead(shadow); assertShadowActivationAdministrativeStatus(shadow, expectAlternativeActivationStatus); } - + @Override protected void assertUnassignedFuture(PrismObject shadowModelFuture, boolean assertPassword) { assertShadowActivationAdministrativeStatus(shadowModelFuture, ActivationStatusType.DISABLED); @@ -108,7 +108,7 @@ protected void assertUnassignedFuture(PrismObject shadowModelFuture, assertShadowPassword(shadowModelFuture); } } - + @Override protected void assertDeprovisionedTimedOutUser(PrismObject userAfter, String accountOid) throws Exception { assertLinks(userAfter, 1); @@ -116,10 +116,10 @@ protected void assertDeprovisionedTimedOutUser(PrismObject userAfter, display("Model shadow", shadowModel); assertShadowActivationAdministrativeStatus(shadowModel, ActivationStatusType.DISABLED); } - + @Override protected void assertWillUnassignPendingOperation(PrismObject shadowRepo, OperationResultStatusType expectedStatus) { - PendingOperationType pendingOperation = findPendingOperation(shadowRepo, + PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.IN_PROGRESS, ChangeTypeType.MODIFY, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS); if (expectedStatus == OperationResultStatusType.IN_PROGRESS) { assertPendingOperation(shadowRepo, pendingOperation, @@ -127,7 +127,7 @@ protected void assertWillUnassignPendingOperation(PrismObject shadow OperationResultStatusType.IN_PROGRESS, null, null); } else { - pendingOperation = findPendingOperation(shadowRepo, + pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.SUCCESS, ChangeTypeType.MODIFY, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd, @@ -137,13 +137,13 @@ protected void assertWillUnassignPendingOperation(PrismObject shadow } assertNotNull("No ID in pending operation", pendingOperation.getId()); } - + @Override protected void cleanupUser(final String TEST_NAME, String userOid, String username, String accountOid) throws Exception { - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + deleteInCsv(username); try { repositoryService.deleteObject(ShadowType.class, accountOid, result); @@ -151,17 +151,17 @@ protected void cleanupUser(final String TEST_NAME, String userOid, String userna // no problem } recomputeUser(userOid, task, result); - + PrismObject userAfter = getUser(userOid); display("User after", userAfter); assertLinks(userAfter, 0); assertNoShadow(accountOid); } - + @Override protected void assertTest526Deltas(PrismObject shadowRepo, OperationResult result) { assertPendingOperationDeltas(shadowRepo, 3); - + ObjectDeltaType deltaModify = null; ObjectDeltaType deltaAdd = null; ObjectDeltaType deltaDisable = null; @@ -180,13 +180,13 @@ protected void assertTest526Deltas(PrismObject shadowRepo, Operation } assertNotNull("No add pending delta", deltaAdd); assertNotNull("No modify pending delta", deltaModify); - assertNotNull("No disable pending delta", deltaDisable); + assertNotNull("No disable pending delta", deltaDisable); } - + @Override protected void assertTest528Deltas(PrismObject shadowRepo, OperationResult result) { assertPendingOperationDeltas(shadowRepo, 3); - + ObjectDeltaType deltaModify = null; ObjectDeltaType deltaAdd = null; ObjectDeltaType deltaDelete = null; diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualSlowProposed.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualSlowProposed.java index d46f80a9e52..a90e87dd4fa 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualSlowProposed.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualSlowProposed.java @@ -15,43 +15,77 @@ */ /** - * + * */ package com.evolveum.midpoint.model.intest.manual; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; + import java.io.File; +import java.util.Collection; +import java.util.List; +import javax.xml.bind.JAXBElement; + +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 org.testng.annotations.Listeners; +import org.testng.annotations.Test; +import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.provisioning.ucf.impl.builtin.ManualConnectorInstance; +import com.evolveum.midpoint.repo.api.RepositoryService; +import com.evolveum.midpoint.repo.cache.RepositoryCache; +import com.evolveum.midpoint.schema.GetOperationOptions; +import com.evolveum.midpoint.schema.PointInTimeType; +import com.evolveum.midpoint.schema.SelectorOptions; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.test.util.ParallelTestThread; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.xml.ns._public.common.common_3.CaseType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ConflictResolutionActionType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.PendingOperationType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceAttributeDefinitionType; +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.UserType; +import com.evolveum.prism.xml.ns._public.types_3.ChangeTypeType; +import com.evolveum.prism.xml.ns._public.types_3.ObjectDeltaType; /** * Tests a slow semi manual resource with the use of proposed shadows. * The resource is "slow" in a way that it takes approx. a second to process a ticket. * This may cause all sorts of race conditions. - * + * * @author Radovan Semancik */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class TestSemiManualSlowProposed extends TestSemiManual { - + private static final Trace LOGGER = TraceManager.getTrace(TestSemiManualSlowProposed.class); - + + @Autowired(required = true) + @Qualifier("cacheRepositoryService") + private RepositoryCache repositoryCache; + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); initManualConnector(); + + repositoryCache.setModifyRandomDelayRange(150); } - + @Override protected String getResourceOid() { return RESOURCE_SEMI_MANUAL_SLOW_PROPOSED_OID; @@ -61,12 +95,12 @@ protected String getResourceOid() { protected File getResourceFile() { return RESOURCE_SEMI_MANUAL_SLOW_PROPOSED_FILE; } - + @Override protected String getRoleOneOid() { return ROLE_ONE_SEMI_MANUAL_SLOW_PROPOSED_OID; } - + @Override protected File getRoleOneFile() { return ROLE_ONE_SEMI_MANUAL_SLOW_PROPOSED_FILE; @@ -76,7 +110,7 @@ protected File getRoleOneFile() { protected String getRoleTwoOid() { return ROLE_TWO_SEMI_MANUAL_SLOW_PROPOSED_OID; } - + @Override protected File getRoleTwoFile() { return ROLE_TWO_SEMI_MANUAL_SLOW_PROPOSED_FILE; @@ -88,15 +122,175 @@ protected int getConcurrentTestRandomStartDelayRange() { return 300; } + protected int getConcurrentTestRandomStartDelayRangeDelete() { + return 3; + } + // ... and intense ... @Override protected int getConcurrentTestNumberOfThreads() { return 10; } - + // TODO: .. and make the resource slow. private void initManualConnector() { ManualConnectorInstance.setRandomDelayRange(1000); } + /** + * Set up roles used in parallel tests. + */ + @Test + public void test900SetUpRoles() throws Exception { + final String TEST_NAME = "test900SetUpRoles"; + displayTestTitle(TEST_NAME); + // GIVEN + Task task = createTask(TEST_NAME); + OperationResult result = task.getResult(); + + SystemConfigurationType systemConfiguration = getSystemConfiguration(); + display("System config", systemConfiguration); + assertEquals("Wrong conflict resolution", ConflictResolutionActionType.RECOMPUTE, systemConfiguration.getDefaultObjectPolicyConfiguration().get(0).getConflictResolution().getAction()); + + for (int i = 0; i < getConcurrentTestNumberOfThreads(); i++) { + PrismObject role = parseObject(getRoleOneFile()); + role.setOid(getRoleOid(i)); + role.asObjectable().setName(createPolyStringType(getRoleName(i))); + List outboundAttributes = role.asObjectable().getInducement().get(0).getConstruction().getAttribute(); + if (hasMultivalueInterests()) { + ExpressionType outboundExpression = outboundAttributes.get(0).getOutbound().getExpression(); + JAXBElement jaxbElement = outboundExpression.getExpressionEvaluator().get(0); + jaxbElement.setValue(getRoleInterest(i)); + } else { + outboundAttributes.remove(0); + } + addObject(role); + } + } + + private String getRoleOid(int i) { + return String.format("f363260a-8d7a-11e7-bd67-%012d", i); + } + + private String getRoleName(int i) { + return String.format("role-%012d", i); + } + + private String getRoleInterest(int i) { + return String.format("i%012d", i); + } + + // MID-4047, MID-4112 + @Test + public void test910ConcurrentRolesAssign() throws Exception { + final String TEST_NAME = "test910ConcurrentRolesAssign"; + displayTestTitle(TEST_NAME); + // GIVEN + Task task = createTask(TEST_NAME); + OperationResult result = task.getResult(); + + int numberOfCasesBefore = getObjectCount(CaseType.class); + PrismObject userBefore = getUser(USER_BARBOSSA_OID); + display("user before", userBefore); + + final long TIMEOUT = 60000L; + + // WHEN + displayWhen(TEST_NAME); + + ParallelTestThread[] threads = multithread(TEST_NAME, + (i) -> { + login(userAdministrator); + Task localTask = createTask(TEST_NAME + ".local"); + + assignRole(USER_BARBOSSA_OID, getRoleOid(i), localTask, localTask.getResult()); + + }, getConcurrentTestNumberOfThreads(), getConcurrentTestRandomStartDelayRange()); + + // THEN + displayThen(TEST_NAME); + waitForThreads(threads, TIMEOUT); + + PrismObject userAfter = getUser(USER_BARBOSSA_OID); + display("user after", userAfter); + assertAssignments(userAfter, getConcurrentTestNumberOfThreads()); + assertEquals("Wrong # of links", 1, userAfter.asObjectable().getLinkRef().size()); + accountBarbossaOid = userAfter.asObjectable().getLinkRef().get(0).getOid(); + + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountBarbossaOid, null, result); + display("Repo shadow", shadowRepo); + assertShadowNotDead(shadowRepo); + + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)); + PrismObject shadowModel = modelService.getObject(ShadowType.class, accountBarbossaOid, options, task, result); + display("Shadow after (model, future)", shadowModel); + +// assertObjects(CaseType.class, numberOfCasesBefore + getConcurrentTestNumberOfThreads()); + } + + // MID-4112 + @Test + public void test919ConcurrentRoleUnassign() throws Exception { + final String TEST_NAME = "test919ConcurrentRoleUnassign"; + displayTestTitle(TEST_NAME); + // GIVEN + Task task = createTask(TEST_NAME); + OperationResult result = task.getResult(); + + int numberOfCasesBefore = getObjectCount(CaseType.class); + PrismObject userBefore = getUser(USER_BARBOSSA_OID); + display("user before", userBefore); + assertAssignments(userBefore, getConcurrentTestNumberOfThreads()); + + final long TIMEOUT = 60000L; + + // WHEN + displayWhen(TEST_NAME); + + ParallelTestThread[] threads = multithread(TEST_NAME, + (i) -> { + display("Thread "+Thread.currentThread().getName()+" START"); + login(userAdministrator); + Task localTask = createTask(TEST_NAME + ".local"); + OperationResult localResult = localTask.getResult(); + + unassignRole(USER_BARBOSSA_OID, getRoleOid(i), localTask, localResult); + + localResult.computeStatus(); + + display("Thread "+Thread.currentThread().getName()+" DONE, result", localResult); + + }, getConcurrentTestNumberOfThreads(), getConcurrentTestRandomStartDelayRangeDelete()); + + // THEN + displayThen(TEST_NAME); + waitForThreads(threads, TIMEOUT); + + PrismObject userAfter = getUser(USER_BARBOSSA_OID); + display("user after", userAfter); + assertAssignments(userAfter, 0); + assertEquals("Wrong # of links", 1, userAfter.asObjectable().getLinkRef().size()); + + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, accountBarbossaOid, null, result); + display("Repo shadow", shadowRepo); + + ObjectDeltaType deletePendingDelta = null; + for (PendingOperationType pendingOperation: shadowRepo.asObjectable().getPendingOperation()) { + ObjectDeltaType delta = pendingOperation.getDelta(); + if (delta.getChangeType() == ChangeTypeType.DELETE) { + if (deletePendingDelta != null) { + fail("More than one delete pending delta found:\n"+deletePendingDelta+"\n"+delta); + } + deletePendingDelta = delta; + } + } + assertNotNull("No delete pending delta", deletePendingDelta); + + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)); + PrismObject shadowModelFuture = modelService.getObject(ShadowType.class, accountBarbossaOid, options, task, result); + display("Shadow after (model, future)", shadowModelFuture); + assertShadowDead(shadowModelFuture); + +// assertObjects(CaseType.class, numberOfCasesBefore + getConcurrentTestNumberOfThreads() + 1); + } } \ No newline at end of file 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 a30b2351f15..0b597938414 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 @@ -73,17 +73,17 @@ /** * 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"}) @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"; @@ -106,12 +106,12 @@ public class TestAssignmentErrors extends AbstractInitializedModelIntegrationTes private PrismObject resource; private String userLemonheadOid; private String userSharptoothOid; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); } - + @Test public void test010RefinedSchemaWhite() throws Exception { final String TEST_NAME = "test010RefinedSchemaWhite"; @@ -122,7 +122,7 @@ public void test010RefinedSchemaWhite() throws Exception { PrismObject resourceWhite = getObject(ResourceType.class, RESOURCE_DUMMY_WHITE_OID); RefinedResourceSchema refinedSchema = RefinedResourceSchemaImpl.getRefinedSchema(resourceWhite, prismContext); display("Refined schema", refinedSchema); - + RefinedObjectClassDefinition accountDef = refinedSchema.getDefaultRefinedDefinition(ShadowKindType.ACCOUNT); assertNotNull("Account definition is missing", accountDef); assertNotNull("Null identifiers in account", accountDef.getPrimaryIdentifiers()); @@ -131,7 +131,7 @@ public void test010RefinedSchemaWhite() throws Exception { assertFalse("Empty secondary identifiers in account", accountDef.getSecondaryIdentifiers().isEmpty()); assertNotNull("No naming attribute in account", accountDef.getNamingAttribute()); assertFalse("No nativeObjectClass in account", StringUtils.isEmpty(accountDef.getNativeObjectClass())); - + assertEquals("Unexpected kind in account definition", ShadowKindType.ACCOUNT, accountDef.getKind()); assertTrue("Account definition in not default", accountDef.isDefaultInAKind()); assertEquals("Wrong intent in account definition", SchemaConstants.INTENT_DEFAULT, accountDef.getIntent()); @@ -165,9 +165,9 @@ public void test010RefinedSchemaWhite() throws Exception { assertTrue("No fullname read", fullnameDef.canRead()); assertNull("The _PASSSWORD_ attribute sneaked into schema", - accountDef.findAttributeDefinition(new QName(SchemaConstants.NS_ICF_SCHEMA, "password"))); + accountDef.findAttributeDefinition(new QName(SchemaConstants.NS_ICF_SCHEMA, "password"))); } - + /** * The "white" resource has no outbound mapping and there is also no mapping in the assignment. Therefore * this results in account without any attributes. It should fail. @@ -183,23 +183,23 @@ public void test100UserJackAssignBlankAccount() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_WHITE_OID, null, true); deltas.add(accountAssignmentUserDelta); - + dummyAuditService.clear(); - + // WHEN //not expected that it fails, insted the fatal error in the result is excpected modelService.executeChanges(deltas, null, task, result); - + result.computeStatus(); - + display(result); // This has to be a partial error as some changes were executed (user) and others were not (account) TestUtil.assertPartialError(result); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); @@ -208,9 +208,9 @@ public void test100UserJackAssignBlankAccount() throws Exception { dummyAuditService.assertTarget(USER_JACK_OID); dummyAuditService.assertExecutionOutcome(OperationResultStatus.PARTIAL_ERROR); dummyAuditService.assertExecutionMessage(); - + } - + /** * The "while" resource has no outbound mapping and there is also no mapping in the assignment. Therefore * this results in account without any attributes. It should fail. @@ -225,27 +225,27 @@ public void test101AddUserCharlesAssignBlankAccount() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - + PrismObject userCharles = createUser("charles", "Charles L. Charles"); fillinUserAssignmentAccountConstruction(userCharles, RESOURCE_DUMMY_WHITE_OID); - + ObjectDelta userDelta = ObjectDelta.createAddDelta(userCharles); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + // WHEN //we do not expect this to throw an exception. instead the fatal error in the result is excpected modelService.executeChanges(deltas, null, task, result); - + result.computeStatus(); TestUtil.assertFailure(result); - + // Even though the operation failed the addition of a user should be successful. Let's check if user was really added. String userOid = userDelta.getOid(); assertNotNull("No user OID in delta after operation", userOid); - + PrismObject userAfter = getUser(userOid); assertUser(userAfter, userOid, "charles", "Charles L. Charles", null, null, null); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); @@ -253,9 +253,9 @@ public void test101AddUserCharlesAssignBlankAccount() throws Exception { dummyAuditService.assertAnyRequestDeltas(); dummyAuditService.assertExecutionOutcome(OperationResultStatus.PARTIAL_ERROR); dummyAuditService.assertExecutionMessage(); - + } - + @Test public void test200UserLemonheadAssignAccountBrokenNetwork() throws Exception { @@ -266,28 +266,28 @@ public void test200UserLemonheadAssignAccountBrokenNetwork() throws Exception { Task task = taskManager.createTaskInstance(TestAssignmentErrors.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + 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); deltas.add(accountAssignmentUserDelta); - + getDummyResource().setBreakMode(BreakMode.NETWORK); dummyAuditService.clear(); - + // WHEN //not expected that it fails, instead the error in the result is expected modelService.executeChanges(deltas, null, task, result); - + result.computeStatus(); - + display(result); // This has to be a partial error as some changes were executed (user) and others were not (account) TestUtil.assertResultStatus(result, OperationResultStatus.HANDLED_ERROR); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); @@ -296,9 +296,9 @@ public void test200UserLemonheadAssignAccountBrokenNetwork() throws Exception { dummyAuditService.assertTarget(user.getOid()); dummyAuditService.assertExecutionOutcome(OperationResultStatus.HANDLED_ERROR); dummyAuditService.assertExecutionMessage(); - + } - + // PARTIAL_ERROR: Unable to get object from the resource. Probably it has not been created yet because of previous unavailability of the resource. // TODO: timeout or explicit retry // @Test @@ -310,20 +310,20 @@ public void test200UserLemonheadAssignAccountBrokenNetwork() throws Exception { // Task task = taskManager.createTaskInstance(TestAssignmentErrors.class.getName() + "." + TEST_NAME); // OperationResult result = task.getResult(); // assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); -// +// // dummyResource.setBreakMode(BreakMode.NONE); // dummyAuditService.clear(); -// +// // // WHEN // //not expected that it fails, instead the error in the result is expected // modelService.recompute(UserType.class, userLemonheadOid, task, result); -// +// // result.computeStatus(); -// +// // display(result); // // This has to be a partial error as some changes were executed (user) and others were not (account) // TestUtil.assertSuccess(result); -// +// // // Check audit // display("Audit", dummyAuditService); // dummyAuditService.assertSimpleRecordSanity(); @@ -332,7 +332,7 @@ public void test200UserLemonheadAssignAccountBrokenNetwork() throws Exception { // dummyAuditService.assertTarget(userLemonheadOid); // dummyAuditService.assertExecutionOutcome(OperationResultStatus.HANDLED_ERROR); // dummyAuditService.assertExecutionMessage(); -// +// // } @Test @@ -344,7 +344,7 @@ public void test210UserSharptoothAssignAccountBrokenGeneric() throws Exception { Task task = taskManager.createTaskInstance(TestAssignmentErrors.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + PrismObject user = createUser(USER_SHARPTOOTH_NAME, USER_SHARPTOOTH_FULLNAME); CredentialsType credentialsType = new CredentialsType(); PasswordType passwordType = new PasswordType(); @@ -355,27 +355,27 @@ public void test210UserSharptoothAssignAccountBrokenGeneric() throws Exception { user.asObjectable().setCredentials(credentialsType); addObject(user); userSharptoothOid = user.getOid(); - + Collection> deltas = new ArrayList>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(user.getOid(), RESOURCE_DUMMY_OID, null, true); deltas.add(accountAssignmentUserDelta); - + getDummyResource().setBreakMode(BreakMode.GENERIC); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); //not expected that it fails, instead the error in the result is expected modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); - + display(result); // This has to be a partial error as some changes were executed (user) and others were not (account) TestUtil.assertPartialError(result); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); @@ -387,7 +387,7 @@ public void test210UserSharptoothAssignAccountBrokenGeneric() throws Exception { dummyAuditService.assertTarget(user.getOid()); dummyAuditService.assertExecutionOutcome(OperationResultStatus.PARTIAL_ERROR); dummyAuditService.assertExecutionMessage(); - + LensContext lastLensContext = lensDebugListener.getLastLensContext(); Collection> executedDeltas = lastLensContext.getExecutedDeltas(); display("Executed deltas", executedDeltas); @@ -397,9 +397,9 @@ public void test210UserSharptoothAssignAccountBrokenGeneric() throws Exception { assertEquals("Unexpected result of first executed deltas", OperationResultStatus.SUCCESS, deltaop1.getExecutionResult().getStatus()); ObjectDeltaOperation deltaop2 = i.next(); assertEquals("Unexpected result of second executed deltas", OperationResultStatus.FATAL_ERROR, deltaop2.getExecutionResult().getStatus()); - + } - + /** * User has assigned account. We recover the resource (clear break mode) and recompute. * The account should be created. @@ -413,10 +413,10 @@ public void test212UserSharptoothAssignAccountRecovery() throws Exception { Task task = taskManager.createTaskInstance(TestAssignmentErrors.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + getDummyResource().resetBreakMode(); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); recomputeUser(userSharptoothOid, task, result); @@ -425,11 +425,11 @@ public void test212UserSharptoothAssignAccountRecovery() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertDummyAccount(null, USER_SHARPTOOTH_NAME, USER_SHARPTOOTH_FULLNAME, true); assertDummyPassword(null, USER_SHARPTOOTH_NAME, USER_SHARPTOOTH_PASSWORD_1_CLEAR); } - + /** * Change user password. But there is error on the resource. * User password should be changed, account password unchanged and there @@ -463,10 +463,10 @@ public void testUserSharptoothChangePasswordError(final String TEST_NAME, BreakM Task task = taskManager.createTaskInstance(TestAssignmentErrors.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + getDummyResource().setBreakMode(breakMode); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserChangePassword(userSharptoothOid, newPassword, task, result); @@ -475,65 +475,65 @@ public void testUserSharptoothChangePasswordError(final String TEST_NAME, BreakM TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertStatus(result, expectedResultStatus); - + getDummyResource().resetBreakMode(); - + PrismObject userAfter = getUser(userSharptoothOid); display("User afte", userAfter); assertEncryptedUserPassword(userAfter, newPassword); - + assertDummyAccount(null, USER_SHARPTOOTH_NAME, USER_SHARPTOOTH_FULLNAME, true); assertDummyPassword(null, USER_SHARPTOOTH_NAME, oldPassword); } - + /** - * Assign account to user, delete the account shadow (not the account), recompute the user. + * 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"; TestUtil.displayTestTitle(this, TEST_NAME); - + //GIVEN PrismObject user = setupUserAssignAccountDeletedShadowRecompute(TEST_NAME, RESOURCE_DUMMY_OID, null, USER_AFET_NAME, USER_AFET_FULLNAME); String shadowOidBefore = getSingleLinkOid(user); Task task = taskManager.createTaskInstance(TestAssignmentErrors.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN recomputeUser(user.getOid(), task, result); - + // THEN result.computeStatus(); display("Recompute result", result); TestUtil.assertSuccess(result,2); - + user = getUser(user.getOid()); display("User after", user); String shadowOidAfter = getSingleLinkOid(user); display("Shadow OID after", shadowOidAfter); 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)); - + // ... and again ... - + task = taskManager.createTaskInstance(TestAssignmentErrors.class.getName() + "." + TEST_NAME); result = task.getResult(); - + // WHEN recomputeUser(user.getOid(), task, result); - + // THEN result.computeStatus(); display("Recompute result", result); TestUtil.assertSuccess(result,2); - + user = getUser(user.getOid()); display("User after", user); String shadowOidAfterAfter = getSingleLinkOid(user); @@ -541,120 +541,120 @@ public void test220UserAssignAccountDeletedShadowRecomputeSync() throws Exceptio assertEquals("The shadow OIDs has changed after second recompute", shadowOidAfter, shadowOidAfterAfter); } - + /** - * Assign account to user, delete the account shadow (not the account), recompute the user. + * Assign account to user, delete the account shadow (not the account), recompute the user. * We expect ObjectAlreadyExistsException. - * + * * This is tried on the red dummy resource where there is no synchronization. */ @Test public void test222UserAssignAccountDeletedShadowRecomputeNoSync() throws Exception { final String TEST_NAME = "test222UserAssignAccountDeletedShadowRecomputeNoSync"; TestUtil.displayTestTitle(this, TEST_NAME); - + //GIVEN PrismObject user = setupUserAssignAccountDeletedShadowRecompute(TEST_NAME, 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(); - + try { // WHEN recomputeUser(user.getOid(), task, result); - + AssertJUnit.fail("Unexpected success"); } catch (ObjectAlreadyExistsException e) { // this is expected result.computeStatus(); TestUtil.assertFailure(result); } - + user = getUser(user.getOid()); display("User after", user); assertNoLinkedAccount(user); - + // and again ... - + task = taskManager.createTaskInstance(TestAssignmentErrors.class.getName() + "." + TEST_NAME); result = task.getResult(); - + try { // WHEN recomputeUser(user.getOid(), task, result); - + AssertJUnit.fail("Unexpected success"); } catch (ObjectAlreadyExistsException e) { // this is expected result.computeStatus(); TestUtil.assertFailure(result); } - + user = getUser(user.getOid()); display("User after", user); assertNoLinkedAccount(user); - + } - + /** - * Assign account to user, delete the account shadow (not the account), recompute the user. + * 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"; TestUtil.displayTestTitle(this, TEST_NAME); - + //GIVEN - PrismObject user = setupUserAssignAccountDeletedShadowRecompute(TEST_NAME, + PrismObject user = setupUserAssignAccountDeletedShadowRecompute(TEST_NAME, RESOURCE_DUMMY_YELLOW_OID, RESOURCE_DUMMY_YELLOW_NAME, USER_CFET_NAME, USER_CFET_FULLNAME); String shadowOidBefore = getSingleLinkOid(user); Task task = taskManager.createTaskInstance(TestAssignmentErrors.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN recomputeUser(user.getOid(), task, result); - + // THEN result.computeStatus(); display("Recompute result", result); TestUtil.assertSuccess(result,2); - + user = getUser(user.getOid()); display("User after", user); String shadowOidAfter = getSingleLinkOid(user); display("Shadow OID after", shadowOidAfter); 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)); - + // ... and again ... - + task = taskManager.createTaskInstance(TestAssignmentErrors.class.getName() + "." + TEST_NAME); result = task.getResult(); - + // WHEN recomputeUser(user.getOid(), task, result); - + // THEN result.computeStatus(); display("Recompute result", result); TestUtil.assertSuccess(result,2); - + user = getUser(user.getOid()); display("User after", user); String shadowOidAfterAfter = getSingleLinkOid(user); display("Shadow OID after the second time", shadowOidAfterAfter); assertEquals("The shadow OIDs has changed after second recompute", shadowOidAfter, shadowOidAfterAfter); - + } - - private PrismObject setupUserAssignAccountDeletedShadowRecompute(final String TEST_NAME, String dummyResourceOid, + + private PrismObject setupUserAssignAccountDeletedShadowRecompute(final String TEST_NAME, String dummyResourceOid, String dummyResourceName, String userName, String userFullName) throws Exception { // GIVEN @@ -662,7 +662,7 @@ private PrismObject setupUserAssignAccountDeletedShadowRecompute(final OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); getDummyResource().resetBreakMode(); - + PrismObject user = createUser(userName, userFullName); AssignmentType assignmentType = createConstructionAssignment(dummyResourceOid, ShadowKindType.ACCOUNT, null); user.asObjectable().getAssignment().add(assignmentType); @@ -671,30 +671,30 @@ private PrismObject setupUserAssignAccountDeletedShadowRecompute(final user.asObjectable().setActivation(activationType); setPassword(user, "blablabla"); addObject(user); - + // precondition assertDummyAccount(dummyResourceName, userName, userFullName, true); - + // Re-read user to get the links user = getUser(user.getOid()); display("User before", user); String shadowOidBefore = getSingleLinkOid(user); - + // precondition PrismObject shadowBefore = repositoryService.getObject(ShadowType.class, shadowOidBefore, null, result); display("Shadow before", shadowBefore); - + // delete just the shadow, not the account repositoryService.deleteObject(ShadowType.class, shadowOidBefore, result); result.computeStatus(); TestUtil.assertSuccess(result); - - assertNoRepoCache(); + + assertNoRepoCache(); dummyAuditService.clear(); - - return user; + + 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 8e7e3954be2..c94584b6784 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 @@ -65,26 +65,26 @@ /** * 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"}) @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 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"; - + private static final File RESOURCE_CSVFILE_NOTFOUND_FILE = new File(TEST_DIR, "resource-csvfile-notfound.xml"); private static final String RESOURCE_CSVFILE_NOTFOUND_OID = "ef2bc95b-76e0-48e2-86d6-f0f002d3f0f0"; - + 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"; @@ -93,7 +93,7 @@ public class TestBrokenResources extends AbstractConfiguredModelIntegrationTest 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 String RESOURCE_DUMMY_UNACCESSIBLE_NAME = "unaccessible"; private static final String RESOURCE_DUMMY_UNACCESSIBLE_OID = "10000000-0000-0000-0000-666600660007"; @@ -101,66 +101,66 @@ public class TestBrokenResources extends AbstractConfiguredModelIntegrationTest 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"; - + 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 String ACCOUNT_SHADOW_MURRAY_CSVFILE_OID = "ef2bc95b-76e0-1111-d3ad-3d4f12120666"; - + private static final String BROKEN_CSV_FILE_NAME = "broken.csv"; private static final String BROKEN_CSV_SOURCE_FILE_NAME = TEST_DIR + "/" + BROKEN_CSV_FILE_NAME; private static final String BROKEN_CSV_TARGET_FILE_NAME = TEST_TARGET_DIR + "/" + BROKEN_CSV_FILE_NAME; - + private static final int NUMBER_OF_RESOURCES = 6; - + protected static final Trace LOGGER = TraceManager.getTrace(TestBrokenResources.class); - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); LOGGER.trace("initSystem"); - + // Resources File targetDir = new File(TEST_TARGET_DIR); if (!targetDir.exists()) { targetDir.mkdirs(); } - + MiscUtil.copyFile(new File(BROKEN_CSV_SOURCE_FILE_NAME), new File(BROKEN_CSV_TARGET_FILE_NAME)); - + repoAddObjectFromFile(CONNECTOR_DUMMY_NOJARS_FILE, initResult); - + initDummyResourcePirate(RESOURCE_DUMMY_BLACK_NAME, RESOURCE_DUMMY_BLACK_FILE, RESOURCE_DUMMY_BLACK_OID, initTask, initResult); initDummyResourcePirate(RESOURCE_DUMMY_EBONY_NAME, RESOURCE_DUMMY_EBONY_FILE, RESOURCE_DUMMY_EBONY_OID, initTask, initResult); initDummyResourcePirate(null, RESOURCE_DUMMY_FILE, RESOURCE_DUMMY_OID, initTask, initResult); initDummyResourcePirate(RESOURCE_DUMMY_UNACCESSIBLE_NAME, null, null, initTask, initResult); - + importObjectFromFile(RESOURCE_CSVFILE_BROKEN_FILE, initResult); importObjectFromFile(RESOURCE_CSVFILE_NOTFOUND_FILE, initResult); importObjectFromFile(RESOURCE_DUMMY_NOJARS_FILE, initResult); - + repoAddObjectFromFile(SECURITY_POLICY_FILE, initResult); repoAddObjectFromFile(PASSWORD_POLICY_BENEVOLENT_FILE, initResult); - + // Accounts repoAddObjectFromFile(ACCOUNT_SHADOW_MURRAY_CSVFILE_FILE, initResult); - + // Users repoAddObjectFromFile(USER_JACK_FILE, UserType.class, initResult).asObjectable(); repoAddObjectFromFile(USER_GUYBRUSH_FILE, UserType.class, initResult).asObjectable(); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + } - + @Override public void postInitSystem(Task initTask, OperationResult initResult) throws Exception { super.postInitSystem(initTask, initResult); // Break it only after resource are reset in super.postInitSystem() getDummyResource(RESOURCE_DUMMY_UNACCESSIBLE_NAME).setBreakMode(BreakMode.NETWORK); } - + @Test public void test010TestResourceBroken() throws Exception { final String TEST_NAME = "test010TestResourceBroken"; @@ -169,15 +169,15 @@ public void test010TestResourceBroken() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN OperationResult testResult = modelService.testResource(RESOURCE_CSVFILE_BROKEN_OID, task); - + // THEN display("testResource result", testResult); TestUtil.assertSuccess("testResource result", testResult); } - + @Test public void test020GetResourceBroken() throws Exception { final String TEST_NAME = "test020GetResourceBroken"; @@ -186,23 +186,23 @@ public void test020GetResourceBroken() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_CSVFILE_BROKEN_OID, null, task, result); - + // THEN display("getObject resource", resource); result.computeStatus(); display("getObject result", result); TestUtil.assertSuccess("getObject result", result); - + OperationResultType fetchResult = resource.asObjectable().getFetchResult(); TestUtil.assertSuccess("resource.fetchResult", fetchResult); - + // TODO: better asserts assertNotNull("Null resource", resource); } - + @Test public void test030ListResources() throws Exception { final String TEST_NAME = "test030ListResources"; @@ -217,7 +217,7 @@ public void test100GetAccountMurray() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + try { // WHEN @@ -233,9 +233,9 @@ public void test100GetAccountMurray() throws Exception { display("getObject result", result); TestUtil.assertFailure("getObject result", result); } - + } - + @Test public void test101GetAccountMurrayNoFetch() throws Exception { final String TEST_NAME = "test101GetAccountMurrayNoFetch"; @@ -244,9 +244,9 @@ public void test101GetAccountMurrayNoFetch() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createNoFetch()); - + // WHEN PrismObject account = modelService.getObject(ShadowType.class, ACCOUNT_SHADOW_MURRAY_CSVFILE_OID, options, task, result); @@ -258,7 +258,7 @@ public void test101GetAccountMurrayNoFetch() throws Exception { // TODO: better asserts assertNotNull("Null resource", account); } - + @Test public void test102GetAccountMurrayRaw() throws Exception { TestUtil.displayTestTitle(this, "test102GetAccountMurrayRaw"); @@ -266,9 +266,9 @@ public void test102GetAccountMurrayRaw() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestBrokenResources.class.getName() + ".test102GetAccountMurrayRaw"); OperationResult result = task.getResult(); - + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createRaw()); - + // WHEN PrismObject account = modelService.getObject(ShadowType.class, ACCOUNT_SHADOW_MURRAY_CSVFILE_OID, options, task, result); @@ -281,7 +281,7 @@ public void test102GetAccountMurrayRaw() throws Exception { assertNotNull("Null resource", account); } - + @Test public void test120SearchAccountByUsernameJack() throws Exception { TestUtil.displayTestTitle(this, "test120SearchAccountByUsernameJack"); @@ -289,9 +289,9 @@ public void test120SearchAccountByUsernameJack() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestBrokenResources.class.getName() + ".test120SearchAccountByUsernameJack"); OperationResult result = task.getResult(); - + PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_CSVFILE_BROKEN_OID, null, task, result); - + try { // WHEN @@ -304,9 +304,9 @@ public void test120SearchAccountByUsernameJack() throws Exception { display("findAccountByUsername result", result); TestUtil.assertFailure("findAccountByUsername result", result); } - + } - + @Test public void test210TestResourceNotFound() throws Exception { TestUtil.displayTestTitle(this, "test210TestResourceNotFound"); @@ -314,16 +314,16 @@ public void test210TestResourceNotFound() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestBrokenResources.class.getName() + ".test210TestResourceNotFound"); OperationResult result = task.getResult(); - - + + // WHEN OperationResult testResult = modelService.testResource(RESOURCE_CSVFILE_NOTFOUND_OID, task); - + // THEN display("testResource result", testResult); TestUtil.assertFailure("testResource result", testResult); } - + @Test public void test220GetResourceNotFound() throws Exception { final String TEST_NAME = "test220GetResourceNotFound"; @@ -332,24 +332,24 @@ public void test220GetResourceNotFound() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestBrokenResources.class.getName() + "."+TEST_NAME); OperationResult result = task.getResult(); - + // WHEN PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_CSVFILE_NOTFOUND_OID, null, task, result); - + // THEN display("getObject resource", resource); result.computeStatus(); display("getObject result", result); assertEquals("Expected partial errror 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()); - + // TODO: better asserts assertNotNull("Null resource", resource); } - + @Test public void test221GetResourceNotFoundResolveConnector() throws Exception { final String TEST_NAME = "test221GetResourceNotFoundResolveConnector"; @@ -358,45 +358,45 @@ public void test221GetResourceNotFoundResolveConnector() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestBrokenResources.class.getName() + "."+TEST_NAME); OperationResult result = task.getResult(); - + Collection> options = SelectorOptions.createCollection( ResourceType.F_CONNECTOR_REF, GetOperationOptions.createResolve()); - + // WHEN PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_CSVFILE_NOTFOUND_OID, options, task, result); - + // THEN display("getObject resource", resource); result.computeStatus(); display("getObject result", result); assertEquals("Expected partial errror 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()); - + // TODO: better asserts assertNotNull("Null resource", resource); - + assertNotNull("Connector was not resolved", resource.asObjectable().getConnector()); } - - + + @Test public void test310TestResourceNoJars() throws Exception { TestUtil.displayTestTitle(this, "test310TestResourceNoJars"); // GIVEN Task task = taskManager.createTaskInstance(TestBrokenResources.class.getName() + ".test310TestResourceNoJars"); - + // WHEN OperationResult testResult = modelService.testResource(RESOURCE_DUMMY_NOJARS_OID, task); - + // THEN display("testResource result", testResult); TestUtil.assertFailure("testResource result", testResult); } - + @Test public void test320GetResourceNoJars() throws Exception { final String TEST_NAME = "test320GetResourceNoJars"; @@ -405,20 +405,20 @@ public void test320GetResourceNoJars() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_NOJARS_OID, null, task, result); - + // THEN display("getObject resource", resource); result.computeStatus(); display("getObject result", result); assertEquals("Expected partial errror 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()); - + // TODO: better asserts assertNotNull("Null resource", resource); } @@ -431,20 +431,20 @@ public void test350AddResourceWrongConnectorOid() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject resource = PrismTestUtil.parseObject(RESOURCE_DUMMY_WRONG_CONNECTOR_OID_FILE); ObjectDelta delta = ObjectDelta.createAddDelta(resource); Collection> deltas = MiscSchemaUtil.createCollection(delta); - + try { // WHEN modelService.executeChanges(deltas, null, task, result); - + AssertJUnit.fail("Unexpected success"); } catch (ObjectNotFoundException e) { // This is expected } - + // THEN result.computeStatus(); display(result); @@ -463,26 +463,26 @@ public void test352AddResourceWrongConnectorOidRaw() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject resource = PrismTestUtil.parseObject(RESOURCE_DUMMY_WRONG_CONNECTOR_OID_FILE); ObjectDelta delta = ObjectDelta.createAddDelta(resource); Collection> deltas = MiscSchemaUtil.createCollection(delta); - + try { // WHEN modelService.executeChanges(deltas, null, task, result); - + AssertJUnit.fail("Unexpected success"); } catch (ObjectNotFoundException e) { // This is expected } - + // THEN result.computeStatus(); display(result); TestUtil.assertFailure(result); } - + /** * Store directly to repo. This is not really a test, it is more like a hack to prepare @@ -496,15 +496,15 @@ public void test355AddResourceWrongConnectorOidRepo() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject resource = PrismTestUtil.parseObject(RESOURCE_DUMMY_WRONG_CONNECTOR_OID_FILE); - + // WHEN repositoryService.addObject(resource, null, result); - + // THEN result.computeStatus(); - TestUtil.assertSuccess(result); + TestUtil.assertSuccess(result); } @Test @@ -515,20 +515,20 @@ public void test358GetResourceWrongConnectorOid() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_WRONG_CONNECTOR_OID_OID, null, task, result); - + // THEN display("getObject resource", resource); result.computeStatus(); display("getObject result", result); assertEquals("Expected partial errror 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()); - + // TODO: better asserts assertNotNull("Null resource", resource); } @@ -541,18 +541,18 @@ public void test359DeleteResourceWrongConnectorOid() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta delta = ObjectDelta.createDeleteDelta(ResourceType.class, RESOURCE_DUMMY_WRONG_CONNECTOR_OID_OID, prismContext); Collection> deltas = MiscSchemaUtil.createCollection(delta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); display("getObject result", result); assertEquals("Expected partial errror in result", OperationResultStatus.PARTIAL_ERROR, result.getStatus()); - + assertNoObject(ResourceType.class, RESOURCE_DUMMY_WRONG_CONNECTOR_OID_OID, task, result); } @@ -564,17 +564,17 @@ public void test360AddResourceNoConfiguration() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject resource = PrismTestUtil.parseObject(RESOURCE_DUMMY_NO_CONFIGURATION_FILE); PrismObject connectorDummy = findConnectorByTypeAndVersion(CONNECTOR_DUMMY_TYPE, CONNECTOR_DUMMY_VERSION, result); resource.asObjectable().getConnectorRef().setOid(connectorDummy.getOid()); ObjectDelta delta = ObjectDelta.createAddDelta(resource); Collection> deltas = MiscSchemaUtil.createCollection(delta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); @@ -588,20 +588,20 @@ public void test362GetResourceNoConfiguration() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_NO_CONFIGURATION_OID, null, task, result); - + // THEN display("getObject resource", resource); result.computeStatus(); display("getObject result", result); assertEquals("Expected partial errror 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()); - + // TODO: better asserts assertNotNull("Null resource", resource); } @@ -611,7 +611,7 @@ public void test368ListResources() throws Exception { final String TEST_NAME = "test368ListResources"; testListResources(TEST_NAME, NUMBER_OF_RESOURCES + 1, null); } - + @Test public void test369DeleteResourceNoConfiguration() throws Exception { final String TEST_NAME = "test369DeleteResourceNoConfiguration"; @@ -620,13 +620,13 @@ public void test369DeleteResourceNoConfiguration() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta delta = ObjectDelta.createDeleteDelta(ResourceType.class, RESOURCE_DUMMY_NO_CONFIGURATION_OID, prismContext); Collection> deltas = MiscSchemaUtil.createCollection(delta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); display("getObject result", result); @@ -649,10 +649,10 @@ public void test371ImportUnaccessibleResource() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN importObjectFromFile(RESOURCE_DUMMY_UNACCESSIBLE_FILE, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); @@ -670,28 +670,28 @@ public void test372GetUnaccessibleResourceNoFetch() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + rememberCounter(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT); rememberCounter(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT); - + // WHEN - PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_UNACCESSIBLE_OID, + PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_UNACCESSIBLE_OID, GetOperationOptions.createNoFetchCollection(), task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); display("Resource after", resource); assertNotNull("No resource", resource); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); } - + /** * No fetch operation should NOT try to read the schema. * MID-3509 @@ -699,36 +699,36 @@ 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_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT); - + testListResources(TEST_NAME, NUMBER_OF_RESOURCES + 1, GetOperationOptions.createNoFetchCollection()); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); } - + @Test public void test375ListResources() throws Exception { final String TEST_NAME = "test375ListResources"; testListResources(TEST_NAME, NUMBER_OF_RESOURCES + 1, null); } - + public void testListResources(final String TEST_NAME, int expectedNumber, Collection> options) throws Exception { displayTestTitle(TEST_NAME); // GIVEN (1) Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN (1) final SearchResultList> resources = modelService.searchObjects(ResourceType.class, null, options, task, result); - + // THEN (1) result.computeStatus(); display("getObject result", result); @@ -741,12 +741,12 @@ public void testListResources(final String TEST_NAME, int expectedNumber, Collec } display("Got resources: "+resources); assertEquals("Wrong number of resources", expectedNumber, resources.size()); - + // GIVEN (2) resources.clear(); task = createTask(TEST_NAME); result = task.getResult(); - + ResultHandler handler = new ResultHandler() { @Override public boolean handle(PrismObject object, OperationResult parentResult) { @@ -754,10 +754,10 @@ public boolean handle(PrismObject object, OperationResult parentRe return true; } }; - + // WHEN (2) modelService.searchObjectsIterative(ResourceType.class, null, handler, options, task, result); - + // THEN (2) result.computeStatus(); display("getObject result", result); @@ -770,9 +770,9 @@ public boolean handle(PrismObject object, OperationResult parentRe } display("Got resources: "+resources); assertEquals("Wrong number of resources", expectedNumber, resources.size()); - + } - + @Test public void test377GetResourceNoConfiguration() throws Exception { final String TEST_NAME = "test377GetResourceNoConfiguration"; @@ -781,27 +781,27 @@ public void test377GetResourceNoConfiguration() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_UNACCESSIBLE_OID, null, task, result); - + // THEN display("getObject resource", resource); result.computeStatus(); display("getObject result", result); assertEquals("Expected partial errror 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()); - + assertNotNull("Null resource", resource); } - + /** * 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 @@ -813,14 +813,14 @@ 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 { testAssignTwoResoures("test401AssignTwoResouresBroken", RESOURCE_CSVFILE_BROKEN_OID); } - + /** * 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. @@ -832,30 +832,30 @@ private void testAssignTwoResoures(final String TEST_NAME, String badResourceOid Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - + ObjectDelta userDelta = createAccountAssignmentUserDelta(USER_JACK_OID, badResourceOid, null, true); userDelta.addModification(createAccountAssignmentModification(RESOURCE_DUMMY_OID, null, true)); display("input delta", userDelta); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); display("executeChanges result", result); - - //TODO: ugly hack, see MID-1248 + + //TODO: ugly hack, see MID-1248 if ("test401AssignTwoResouresBroken".equals(TEST_NAME)){ assertEquals("Expected partial error in result", OperationResultStatus.PARTIAL_ERROR, result.getStatus()); - } - + } + DummyAccount jackDummyAccount = getDummyResource().getAccountByUsername(USER_JACK_USERNAME); assertNotNull("No jack dummy account", jackDummyAccount); } - + /** * No error here yet. Provisioning scripts run without a problem. * This tests is just used as a control and to prepare the environment. @@ -870,30 +870,30 @@ public void test500AssignResourceBlack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest5xx(); - + PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); assertAssignments(userBefore, 0); assertNoDummyAccount(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - + // WHEN displayWhen(TEST_NAME); assignAccount(USER_GUYBRUSH_OID, RESOURCE_DUMMY_BLACK_OID, null, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignments(userAfter, 1); String accountOid = getSingleLinkOid(userAfter); - + assertDummyAccount(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); - + assertDummyScripts(RESOURCE_DUMMY_BLACK_NAME, "add/after", null); } - + /** * No error here yet. Provisioning scripts run without a problem. * This tests is just used as a control and to prepare the environment. @@ -908,25 +908,25 @@ public void test502ModifyUserEmployeeNumberNone() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest5xx(); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_EMPLOYEE_NUMBER, task, result, "none"); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignments(userAfter, 1); String accountOid = getSingleLinkOid(userAfter); - + assertDummyAccount(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); - + assertDummyScripts(RESOURCE_DUMMY_BLACK_NAME, "modify/after", "none"); } - + /** * No error here yet. Provisioning scripts run without a problem. * This tests is just used as a control and to prepare the environment. @@ -941,25 +941,25 @@ public void test509UnassignResourceBlack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest5xx(); - + // WHEN displayWhen(TEST_NAME); unassignAccount(USER_GUYBRUSH_OID, RESOURCE_DUMMY_BLACK_OID, null, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignments(userAfter, 0); assertLinks(userAfter, 0); - + assertNoDummyAccount(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - + assertDummyScripts(RESOURCE_DUMMY_BLACK_NAME, "delete/after", "none"); } - + /** * Causing an error in provisioning script. Default criticality. * The error should stop operation. @@ -974,33 +974,33 @@ public void test510AssignResourceBlackError() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest5xx(); - + modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_EMPLOYEE_NUMBER, task, result, DummyResource.POWERFAIL_ARG_ERROR_GENERIC); PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); assertAssignments(userBefore, 0); assertNoDummyAccount(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - + // WHEN displayWhen(TEST_NAME); assignAccount(USER_GUYBRUSH_OID, RESOURCE_DUMMY_BLACK_OID, null, task, result); - + // THEN displayThen(TEST_NAME); assertPartialError(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignments(userAfter, 1); // Failed after script. Account is not linked (may not really be created). assertLinks(userAfter, 0); - + // But we know that the account was created and that it exists assertDummyAccount(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); - + assertDummyScripts(RESOURCE_DUMMY_BLACK_NAME, "add/after", DummyResource.POWERFAIL_ARG_ERROR_GENERIC); } - + /** * Recon should fix the linking. * MID-4060 @@ -1014,23 +1014,23 @@ public void test512ReconcileUser() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest5xx(); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_GUYBRUSH_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignments(userAfter, 1); String accountOid = getSingleLinkOid(userAfter); - + assertDummyAccount(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); } - + /** * Causing an error in provisioning script. Default criticality. * The error should stop operation. @@ -1045,25 +1045,25 @@ public void test514ModifyUserEmployeeNumberRuntime() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest5xx(); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_EMPLOYEE_NUMBER, task, result, DummyResource.POWERFAIL_ARG_ERROR_RUNTIME); - + // THEN displayThen(TEST_NAME); assertPartialError(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignments(userAfter, 1); String accountOid = getSingleLinkOid(userAfter); - + assertDummyAccount(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); - + assertDummyScripts(RESOURCE_DUMMY_BLACK_NAME, "modify/after", DummyResource.POWERFAIL_ARG_ERROR_RUNTIME); } - + /** * Causing an error in provisioning script. Default criticality. * The error should stop operation. @@ -1078,27 +1078,27 @@ public void test518UnassignResourceBlack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest5xx(); - + // WHEN displayWhen(TEST_NAME); unassignAccount(USER_GUYBRUSH_OID, RESOURCE_DUMMY_BLACK_OID, null, task, result); - + // THEN displayThen(TEST_NAME); assertPartialError(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); 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); - + // But we know that it is gone ... assertNoDummyAccount(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - + assertDummyScripts(RESOURCE_DUMMY_BLACK_NAME, "delete/after", DummyResource.POWERFAIL_ARG_ERROR_RUNTIME); } - + /** * Recon should fix the linking. * MID-4060 @@ -1112,23 +1112,23 @@ public void test519ReconcileUser() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest5xx(); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_GUYBRUSH_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignments(userAfter, 0); assertLinks(userAfter, 0); - + assertNoDummyAccount(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); } - + /** * Causing an error in provisioning script. Partial criticality. * Error should be indicated, but the operation should go on. @@ -1143,33 +1143,33 @@ public void test520AssignResourceEbonyError() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest5xx(); - + modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_EMPLOYEE_NUMBER, task, result, DummyResource.POWERFAIL_ARG_ERROR_GENERIC); PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); assertAssignments(userBefore, 0); assertNoDummyAccount(RESOURCE_DUMMY_EBONY_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - + // WHEN displayWhen(TEST_NAME); assignAccount(USER_GUYBRUSH_OID, RESOURCE_DUMMY_EBONY_OID, null, task, result); - + // THEN displayThen(TEST_NAME); assertPartialError(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignments(userAfter, 1); // Partial criticality. We assume that the account exists. assertLinks(userAfter, 1); - + // But we know that the account was created and that it exists assertDummyAccount(RESOURCE_DUMMY_EBONY_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); - + assertDummyScripts(RESOURCE_DUMMY_EBONY_NAME, "add/after", DummyResource.POWERFAIL_ARG_ERROR_GENERIC); } - + /** * Causing an error in provisioning script. partial criticality. * The operation should go on. @@ -1184,25 +1184,25 @@ public void test524ModifyUserEmployeeNumberRuntime() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest5xx(); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_EMPLOYEE_NUMBER, task, result, DummyResource.POWERFAIL_ARG_ERROR_RUNTIME); - + // THEN displayThen(TEST_NAME); assertPartialError(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignments(userAfter, 1); String accountOid = getSingleLinkOid(userAfter); - + assertDummyAccount(RESOURCE_DUMMY_EBONY_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); - + assertDummyScripts(RESOURCE_DUMMY_EBONY_NAME, "modify/after", DummyResource.POWERFAIL_ARG_ERROR_RUNTIME); } - + /** * Causing an error in provisioning script. Partial criticality. * The operation should go on. @@ -1217,39 +1217,39 @@ public void test528UnassignResourceEbony() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest5xx(); - + // WHEN displayWhen(TEST_NAME); unassignAccount(USER_GUYBRUSH_OID, RESOURCE_DUMMY_EBONY_OID, null, task, result); - + // THEN displayThen(TEST_NAME); assertPartialError(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignments(userAfter, 0); assertLinks(userAfter, 0); - + assertNoDummyAccount(RESOURCE_DUMMY_EBONY_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - + assertDummyScripts(RESOURCE_DUMMY_EBONY_NAME, "delete/after", DummyResource.POWERFAIL_ARG_ERROR_RUNTIME); } - + private void prepareTest5xx() throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); purgeProvisioningScriptHistory(RESOURCE_DUMMY_BLACK_NAME); purgeProvisioningScriptHistory(RESOURCE_DUMMY_EBONY_NAME); } - + 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 211ae3bf2cc..1252b1b3dd7 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 @@ -55,18 +55,18 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) 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. */ @@ -77,18 +77,18 @@ public void test100ModifyAccountExplicitType() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestModelWebServiceNegative.class.getName() + "." + TEST_NAME); - - ObjectDeltaType objectChange = createShadowReplaceChange(ACCOUNT_SHADOW_GUYBRUSH_OID, - "attributes/"+DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + + ObjectDeltaType objectChange = createShadowReplaceChange(ACCOUNT_SHADOW_GUYBRUSH_OID, + "attributes/"+DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "foo", DOMUtil.XSD_STRING); ObjectDeltaListType deltaList = new ObjectDeltaListType(); deltaList.getDelta().add(objectChange); - + // WHEN modelWeb.executeChanges(deltaList, null); - + // THEN - + // Check account in dummy resource assertDefaultDummyAccount(ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, @@ -105,18 +105,18 @@ public void test110ModifyAccountImplicitType() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestModelWebServiceNegative.class.getName() + "." + TEST_NAME); - - ObjectDeltaType objectChange = createShadowReplaceChange(ACCOUNT_SHADOW_GUYBRUSH_OID, - "attributes/"+DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + + ObjectDeltaType objectChange = createShadowReplaceChange(ACCOUNT_SHADOW_GUYBRUSH_OID, + "attributes/"+DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "bar", null); ObjectDeltaListType deltaList = new ObjectDeltaListType(); deltaList.getDelta().add(objectChange); - + // WHEN modelWeb.executeChanges(deltaList, null); - + // THEN - + // Check account in dummy resource assertDefaultDummyAccount(ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, @@ -130,25 +130,25 @@ public void test200ModifyAccountWrongExplicitType() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestModelWebServiceNegative.class.getName() + "." + TEST_NAME); - - ObjectDeltaType objectChange = createShadowReplaceChange(ACCOUNT_SHADOW_GUYBRUSH_OID, - "attributes/"+DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + + 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"); assertExecuteChangesFailure(deltaList, null, SchemaViolationFaultType.class, "Expected", "but got class"); } - + private void assertExecuteChangesFailure(ObjectDeltaListType deltaList, ModelExecuteOptionsType options, Class expectedFaultTypeClass, String... messagePatterns) throws Exception { - + try { modelWeb.executeChanges(deltaList, options); - + AssertJUnit.fail("Unexpected success"); } catch (FaultMessage f) { FaultType faultInfo = f.getFaultInfo(); @@ -167,7 +167,7 @@ private void assertExecuteChangesFailure(ObjectDeltaListType deltaList, ModelExe } // TODO: more negative tests - + private ObjectDeltaType createShadowReplaceChange(String oid, String path, final String value, QName type) { ObjectDeltaType objectChange = new ObjectDeltaType(); objectChange.setOid(oid); 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 4cb7e737d39..da2998d3d36 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 @@ -80,27 +80,27 @@ @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class TestOrgStruct extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/orgstruct"); public static final File ROLE_DEFENDER_FILE = new File(TEST_DIR, "role-defender.xml"); public static final String ROLE_DEFENDER_OID = "12345111-1111-2222-1111-121212111567"; - + public static final File ROLE_META_DEFENDER_FILE = new File(TEST_DIR, "role-meta-defender.xml"); public static final String ROLE_META_DEFENDER_OID = "12345111-1111-2222-1111-121212111568"; - + public static final File ROLE_OFFENDER_FILE = new File(TEST_DIR, "role-offender.xml"); public static final String ROLE_OFFENDER_OID = "12345111-1111-2222-1111-121212111569"; - + public static final File ROLE_OFFENDER_ADMIN_FILE = new File(TEST_DIR, "role-offender-admin.xml"); public static final String ROLE_OFFENDER_ADMIN_OID = "12345111-1111-2222-1111-121212111566"; - + public static final File ROLE_META_DEFENDER_ADMIN_FILE = new File(TEST_DIR, "role-meta-defender-admin.xml"); public static final String ROLE_META_DEFENDER_ADMIN_OID = "12345111-1111-2222-1111-121212111565"; public static final File ORG_TEMP_FILE = new File(TEST_DIR, "org-temp.xml"); public static final String ORG_TEMP_OID = "43214321-4311-0952-4762-854392584320"; - + public static final File ORG_FICTIONAL_FILE = new File(TEST_DIR, "org-fictional.xml"); public static final String ORG_FICTIONAL_OID = "b5b179cc-03c7-11e5-9839-001e8c717e5b"; @@ -121,11 +121,11 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti public void test010AddOrgStruct() throws Exception { final String TEST_NAME = "test010AddOrgStruct"; displayTestTitle(TEST_NAME); - + // Dummy, just to be overridden in subclasses addOrgStruct(); } - + protected void addOrgStruct() throws Exception { // Dummy, just to be overridden in subclasses } @@ -134,32 +134,32 @@ protected void addOrgStruct() throws Exception { public void test051OrgStructSanity() throws Exception { final String TEST_NAME = "test051OrgStructSanity"; displayTestTitle(TEST_NAME); - + // WHEN assertMonkeyIslandOrgSanity(); } - + @Test public void test052RootOrgQuery() throws Exception { final String TEST_NAME = "test052RootOrgQuery"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createRootOrgQuery(prismContext); - + // WHEN List> rootOrgs = modelService.searchObjects(OrgType.class, query, null, task, result); - + // THEN assertEquals("Unexpected number of root orgs", 2, rootOrgs.size()); - + // Post-condition assertMonkeyIslandOrgSanity(); } - + /** * Scumm bar org also acts as a role, assigning account on dummy resource. */ @@ -170,20 +170,20 @@ public void test101JackAssignScummBar() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // Precondition assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); - + // WHEN assignOrg(USER_JACK_OID, ORG_SCUMM_BAR_OID, task, result); - + // THEN PrismObject userJack = getUser(USER_JACK_OID); display("User jack after", userJack); assertUserOrg(userJack, ORG_SCUMM_BAR_OID); - + assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); - + // Postcondition assertMonkeyIslandOrgSanity(); } @@ -195,19 +195,19 @@ public void test102JackUnassignScummBar() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignOrg(USER_JACK_OID, ORG_SCUMM_BAR_OID, task, result); - + // THEN PrismObject userJack = getUser(USER_JACK_OID); display("User jack after", userJack); assertUserNoOrg(userJack); - + // Postcondition assertMonkeyIslandOrgSanity(); } - + /** * Assign jack to both functional and project orgstruct. * Assign both orgs at the same time. @@ -219,25 +219,25 @@ public void test201JackAssignScummBarAndSaveElaine() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + 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 = ObjectDelta.createModifyDelta(USER_JACK_OID, modifications, UserType.class, prismContext); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN PrismObject userJack = getUser(USER_JACK_OID); display("User jack after", userJack); assertUserOrg(userJack, ORG_SCUMM_BAR_OID, ORG_SAVE_ELAINE_OID); - + // Postcondition assertMonkeyIslandOrgSanity(); } - + /** * Assign jack to functional orgstruct again. */ @@ -248,15 +248,15 @@ public void test202JackAssignMinistryOfOffense() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignOrg(USER_JACK_OID, ORG_MINISTRY_OF_OFFENSE_OID, task, result); - + // THEN PrismObject userJack = getUser(USER_JACK_OID); display("User jack after", userJack); assertUserOrg(userJack, ORG_SCUMM_BAR_OID, ORG_SAVE_ELAINE_OID, ORG_MINISTRY_OF_OFFENSE_OID); - + // Postcondition assertMonkeyIslandOrgSanity(); } @@ -268,19 +268,19 @@ public void test207JackUnAssignScummBar() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignOrg(USER_JACK_OID, ORG_SCUMM_BAR_OID, task, result); - + // THEN PrismObject userJack = getUser(USER_JACK_OID); display("User jack after", userJack); assertUserOrg(userJack, ORG_SAVE_ELAINE_OID, ORG_MINISTRY_OF_OFFENSE_OID); - + // Postcondition assertMonkeyIslandOrgSanity(); } - + @Test public void test208JackUnassignAll() throws Exception { final String TEST_NAME = "test208JackUnassignAll"; @@ -288,19 +288,19 @@ public void test208JackUnassignAll() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); unassignAllReplace(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User jack after", userJack); assertUserNoOrg(userJack); - + // Postcondition assertMonkeyIslandOrgSanity(); } @@ -328,11 +328,11 @@ public void test210JackAssignMinistryOfOffenseMember() throws Exception { display("User jack after", userJack); assertAssignedOrgs(userJack, ORG_MINISTRY_OF_OFFENSE_OID); assertHasOrgs(userJack, ORG_MINISTRY_OF_OFFENSE_OID, ORG_MINISTRY_OF_DEFENSE_OID); - + // Postcondition assertMonkeyIslandOrgSanity(); } - + @Test public void test211JackAssignMinistryOfOffenseMinister() throws Exception { final String TEST_NAME = "test211JackAssignMinistryOfOffenseMinister"; @@ -340,10 +340,10 @@ public void test211JackAssignMinistryOfOffenseMinister() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignOrg(USER_JACK_OID, ORG_MINISTRY_OF_OFFENSE_OID, SchemaConstants.ORG_MANAGER, task, result); - + // THEN PrismObject userJack = getUser(USER_JACK_OID); display("User jack after", userJack); @@ -358,7 +358,7 @@ public void test211JackAssignMinistryOfOffenseMinister() throws Exception { // Postcondition assertMonkeyIslandOrgSanity(); } - + @Test public void test212JackUnassignMinistryOfOffenseMember() throws Exception { final String TEST_NAME = "test212JackUnassignMinistryOfOffenseMember"; @@ -366,10 +366,10 @@ public void test212JackUnassignMinistryOfOffenseMember() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignOrg(USER_JACK_OID, ORG_MINISTRY_OF_OFFENSE_OID, null, task, result); - + // THEN PrismObject userJack = getUser(USER_JACK_OID); display("User jack after", userJack); @@ -377,11 +377,11 @@ public void test212JackUnassignMinistryOfOffenseMember() throws Exception { assertAssignedOrg(userJack, ORG_MINISTRY_OF_OFFENSE_OID, SchemaConstants.ORG_MANAGER); assertHasOrgs(userJack, ORG_MINISTRY_OF_OFFENSE_OID, ORG_MINISTRY_OF_DEFENSE_OID); assertHasOrg(userJack, ORG_MINISTRY_OF_OFFENSE_OID, SchemaConstants.ORG_MANAGER); - + // Postcondition assertMonkeyIslandOrgSanity(); } - + @Test public void test213JackUnassignMinistryOfOffenseManager() throws Exception { final String TEST_NAME = "test213JackUnassignMinistryOfOffenseManager"; @@ -389,16 +389,16 @@ public void test213JackUnassignMinistryOfOffenseManager() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignOrg(USER_JACK_OID, ORG_MINISTRY_OF_OFFENSE_OID, SchemaConstants.ORG_MANAGER, task, result); - + // THEN PrismObject userJack = getUser(USER_JACK_OID); display("User jack after", userJack); assertAssignedNoOrg(userJack); assertHasOrgs(userJack, ORG_MINISTRY_OF_DEFENSE_OID); - + // Postcondition assertMonkeyIslandOrgSanity(); } @@ -512,8 +512,8 @@ public void test223JackChangeMinistryOfOffenseMemberToManager() throws Exception // Postcondition assertMonkeyIslandOrgSanity(); } - - + + /** * Recompute jack. Make sure nothing is changed. * MID-3384 @@ -535,11 +535,11 @@ public void test230JackRecompute() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertRefs23x(); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); } - + /** * Destroy parentOrgRef and roleMembershipRef in the repo. Then recompute. * Make sure that the refs are fixed. @@ -552,9 +552,9 @@ public void test232JackDestroyRefsAndRecompute() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + clearUserOrgAndRoleRefs(USER_JACK_OID); - + rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); @@ -566,12 +566,12 @@ public void test232JackDestroyRefsAndRecompute() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertRefs23x(); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 4); } - + /** * Destroy parentOrgRef and roleMembershipRef in the repo. Then light recompute. * Make sure that the refs are fixed and that the resources were not touched. @@ -584,9 +584,9 @@ public void test234JackDestroyRefsAndLightRecompute() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + clearUserOrgAndRoleRefs(USER_JACK_OID); - + rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); @@ -598,7 +598,7 @@ public void test234JackDestroyRefsAndLightRecompute() throws Exception { partialProcessing.setApprovals(PartialProcessingTypeType.SKIP); ModelExecuteOptions options = ModelExecuteOptions.createPartialProcessing(partialProcessing); options.setReconcileFocus(true); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.recompute(UserType.class, USER_JACK_OID, options, task, result); @@ -607,14 +607,14 @@ public void test234JackDestroyRefsAndLightRecompute() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertRefs23x(); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 0); } - - + + private void assertRefs23x() throws Exception { PrismObject userAfter = getUser(USER_JACK_OID); display("User after", userAfter); @@ -679,7 +679,7 @@ public void test301JackAssignMinistryOfOffense() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignOrg(USER_JACK_OID, ORG_MINISTRY_OF_DEFENSE_OID, SchemaConstants.ORG_MANAGER, task, result); assignOrg(USER_JACK_OID, ORG_MINISTRY_OF_DEFENSE_OID, task, result); @@ -690,7 +690,7 @@ public void test301JackAssignMinistryOfOffense() throws Exception { assertUserOrg(userJack, ORG_MINISTRY_OF_DEFENSE_OID, ORG_MINISTRY_OF_DEFENSE_OID); assertAssignedOrg(userJack, ORG_MINISTRY_OF_DEFENSE_OID, SchemaConstants.ORG_MANAGER); assertHasOrg(userJack, ORG_MINISTRY_OF_DEFENSE_OID, SchemaConstants.ORG_MANAGER); - + // Postcondition assertMonkeyIslandOrgSanity(); } @@ -813,7 +813,7 @@ public void test309JackConflictPlusAndMinusAgain() throws Exception { executeConflictPlusAndMinus(TEST_NAME); } - + /** * MID-3874 */ @@ -833,7 +833,7 @@ public void test310JackConflictParentOrgRefAndAssignmentsAddOrg() throws Excepti // WHEN displayWhen(TEST_NAME); addObject(orgBefore, task, result); - + assertNotReached(); } catch (PolicyViolationException e) { // THEN @@ -845,7 +845,7 @@ public void test310JackConflictParentOrgRefAndAssignmentsAddOrg() throws Excepti // Postcondition assertMonkeyIslandOrgSanity(); } - + // TODO: modify org: add parentOrgRef, removeParentOrgRef /** @@ -891,16 +891,16 @@ public void test350AddJackAsMinistryOfOffenseManager() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userJack = prismContext.parseObject(USER_JACK_FILE); - + AssignmentType assignmentType = new AssignmentType(); ObjectReferenceType targetRef = new ObjectReferenceType(); targetRef.setOid(ORG_MINISTRY_OF_OFFENSE_OID); targetRef.setType(OrgType.COMPLEX_TYPE); assignmentType.setTargetRef(targetRef); userJack.asObjectable().getAssignment().add(assignmentType); - + assignmentType = new AssignmentType(); targetRef = new ObjectReferenceType(); targetRef.setOid(ORG_MINISTRY_OF_OFFENSE_OID); @@ -908,11 +908,11 @@ public void test350AddJackAsMinistryOfOffenseManager() throws Exception { targetRef.setRelation(SchemaConstants.ORG_MANAGER); assignmentType.setTargetRef(targetRef); userJack.asObjectable().getAssignment().add(assignmentType); - + Collection> deltas = MiscSchemaUtil.createCollection(userJack.createAddDelta()); // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN userJack = getUser(USER_JACK_OID); display("User jack after", userJack); @@ -929,11 +929,11 @@ public void test350AddJackAsMinistryOfOffenseManager() throws Exception { assertManager(USER_JACK_OID, USER_JACK_OID, null, true, result); assertManager(USER_JACK_OID, USER_JACK_OID, ORG_TYPE_FUNCTIONAL, true, result); assertManager(USER_JACK_OID, null, ORG_TYPE_PROJECT, true, result); - + // Postcondition assertMonkeyIslandOrgSanity(); } - + @Test public void test360ElaineAssignGovernor() throws Exception { final String TEST_NAME = "test360ElaineAssignGovernor"; @@ -941,10 +941,10 @@ public void test360ElaineAssignGovernor() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignOrg(USER_ELAINE_OID, ORG_GOVERNOR_OFFICE_OID, SchemaConstants.ORG_MANAGER, task, result); - + // THEN PrismObject userElaine = getUser(USER_ELAINE_OID); display("User jack after", userElaine); @@ -952,14 +952,14 @@ public void test360ElaineAssignGovernor() throws Exception { assertHasOrgs(userElaine, ORG_GOVERNOR_OFFICE_OID); assertAssignedOrg(userElaine, ORG_GOVERNOR_OFFICE_OID, SchemaConstants.ORG_MANAGER); assertHasOrg(userElaine, ORG_GOVERNOR_OFFICE_OID, SchemaConstants.ORG_MANAGER); - + assertManager(USER_JACK_OID, USER_ELAINE_OID, null, false, result); assertManager(USER_JACK_OID, USER_ELAINE_OID, ORG_TYPE_FUNCTIONAL, false, result); assertManager(USER_JACK_OID, null, ORG_TYPE_PROJECT, false, result); assertManager(USER_JACK_OID, USER_JACK_OID, null, true, result); assertManager(USER_JACK_OID, USER_JACK_OID, ORG_TYPE_FUNCTIONAL, true, result); assertManager(USER_JACK_OID, null, ORG_TYPE_PROJECT, true, result); - + assertManager(USER_ELAINE_OID, null, null, false, result); assertManager(USER_ELAINE_OID, null, ORG_TYPE_FUNCTIONAL, false, result); assertManager(USER_ELAINE_OID, null, ORG_TYPE_PROJECT, false, result); @@ -970,7 +970,7 @@ public void test360ElaineAssignGovernor() throws Exception { // Postcondition assertMonkeyIslandOrgSanity(); } - + @Test public void test362ElaineAssignGovernmentMember() throws Exception { final String TEST_NAME = "test362ElaineAssignGovernmentMember"; @@ -978,10 +978,10 @@ public void test362ElaineAssignGovernmentMember() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignOrg(USER_ELAINE_OID, ORG_GOVERNOR_OFFICE_OID, null, task, result); - + // THEN PrismObject userElaine = getUser(USER_ELAINE_OID); display("User jack after", userElaine); @@ -990,14 +990,14 @@ public void test362ElaineAssignGovernmentMember() throws Exception { assertAssignedOrg(userElaine, ORG_GOVERNOR_OFFICE_OID, SchemaConstants.ORG_MANAGER); assertAssignedOrg(userElaine, ORG_GOVERNOR_OFFICE_OID); assertHasOrg(userElaine, ORG_GOVERNOR_OFFICE_OID, SchemaConstants.ORG_MANAGER); - + assertManager(USER_JACK_OID, USER_ELAINE_OID, null, false, result); assertManager(USER_JACK_OID, USER_ELAINE_OID, ORG_TYPE_FUNCTIONAL, false, result); assertManager(USER_JACK_OID, null, ORG_TYPE_PROJECT, false, result); assertManager(USER_JACK_OID, USER_JACK_OID, null, true, result); assertManager(USER_JACK_OID, USER_JACK_OID, ORG_TYPE_FUNCTIONAL, true, result); assertManager(USER_JACK_OID, null, ORG_TYPE_PROJECT, true, result); - + assertManager(USER_ELAINE_OID, null, null, false, result); assertManager(USER_ELAINE_OID, null, ORG_TYPE_FUNCTIONAL, false, result); assertManager(USER_ELAINE_OID, null, ORG_TYPE_PROJECT, false, result); @@ -1008,7 +1008,7 @@ public void test362ElaineAssignGovernmentMember() throws Exception { // Postcondition assertMonkeyIslandOrgSanity(); } - + @Test public void test365GuybrushAssignSwashbucklerMember() throws Exception { final String TEST_NAME = "test365GuybrushAssignSwashbucklerMember"; @@ -1016,10 +1016,10 @@ public void test365GuybrushAssignSwashbucklerMember() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignOrg(USER_GUYBRUSH_OID, ORG_SWASHBUCKLER_SECTION_OID, null, task, result); - + // THEN PrismObject userGuybrush = getUser(USER_GUYBRUSH_OID); display("User jack after", userGuybrush); @@ -1027,14 +1027,14 @@ public void test365GuybrushAssignSwashbucklerMember() throws Exception { assertHasOrgs(userGuybrush, ORG_SWASHBUCKLER_SECTION_OID); assertAssignedOrg(userGuybrush, ORG_SWASHBUCKLER_SECTION_OID); assertHasOrg(userGuybrush, ORG_SWASHBUCKLER_SECTION_OID); - + assertManager(USER_JACK_OID, USER_ELAINE_OID, null, false, result); assertManager(USER_JACK_OID, USER_ELAINE_OID, ORG_TYPE_FUNCTIONAL, false, result); assertManager(USER_JACK_OID, null, ORG_TYPE_PROJECT, false, result); assertManager(USER_JACK_OID, USER_JACK_OID, null, true, result); assertManager(USER_JACK_OID, USER_JACK_OID, ORG_TYPE_FUNCTIONAL, true, result); assertManager(USER_JACK_OID, null, ORG_TYPE_PROJECT, true, result); - + assertManager(USER_ELAINE_OID, null, null, false, result); assertManager(USER_ELAINE_OID, null, ORG_TYPE_FUNCTIONAL, false, result); assertManager(USER_ELAINE_OID, null, ORG_TYPE_PROJECT, false, result); @@ -1048,11 +1048,11 @@ public void test365GuybrushAssignSwashbucklerMember() throws Exception { assertManager(USER_GUYBRUSH_OID, USER_JACK_OID, null, true, result); assertManager(USER_GUYBRUSH_OID, USER_JACK_OID, ORG_TYPE_FUNCTIONAL, true, result); assertManager(USER_GUYBRUSH_OID, null, ORG_TYPE_PROJECT, true, result); - + // Postcondition assertMonkeyIslandOrgSanity(); } - + @Test public void test368GuybrushAssignSwashbucklerManager() throws Exception { final String TEST_NAME = "test368GuybrushAssignSwashbucklerManager"; @@ -1060,10 +1060,10 @@ public void test368GuybrushAssignSwashbucklerManager() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignOrg(USER_GUYBRUSH_OID, ORG_SWASHBUCKLER_SECTION_OID, SchemaConstants.ORG_MANAGER, task, result); - + // THEN PrismObject userGuybrush = getUser(USER_GUYBRUSH_OID); display("User jack after", userGuybrush); @@ -1073,14 +1073,14 @@ public void test368GuybrushAssignSwashbucklerManager() throws Exception { assertAssignedOrg(userGuybrush, ORG_SWASHBUCKLER_SECTION_OID, SchemaConstants.ORG_MANAGER); assertHasOrg(userGuybrush, ORG_SWASHBUCKLER_SECTION_OID); assertHasOrg(userGuybrush, ORG_SWASHBUCKLER_SECTION_OID, SchemaConstants.ORG_MANAGER); - + assertManager(USER_JACK_OID, USER_ELAINE_OID, null, false, result); assertManager(USER_JACK_OID, USER_ELAINE_OID, ORG_TYPE_FUNCTIONAL, false, result); assertManager(USER_JACK_OID, null, ORG_TYPE_PROJECT, false, result); assertManager(USER_JACK_OID, USER_JACK_OID, null, true, result); assertManager(USER_JACK_OID, USER_JACK_OID, ORG_TYPE_FUNCTIONAL, true, result); assertManager(USER_JACK_OID, null, ORG_TYPE_PROJECT, true, result); - + assertManager(USER_ELAINE_OID, null, null, false, result); assertManager(USER_ELAINE_OID, null, ORG_TYPE_FUNCTIONAL, false, result); assertManager(USER_ELAINE_OID, null, ORG_TYPE_PROJECT, false, result); @@ -1094,11 +1094,11 @@ public void test368GuybrushAssignSwashbucklerManager() throws Exception { assertManager(USER_GUYBRUSH_OID, USER_GUYBRUSH_OID, null, true, result); assertManager(USER_GUYBRUSH_OID, USER_GUYBRUSH_OID, ORG_TYPE_FUNCTIONAL, true, result); assertManager(USER_GUYBRUSH_OID, null, ORG_TYPE_PROJECT, true, result); - + // Postcondition assertMonkeyIslandOrgSanity(); } - + @Test public void test370BarbossaAssignOffenseMember() throws Exception { final String TEST_NAME = "test370BarbossaAssignOffenseMember"; @@ -1106,10 +1106,10 @@ public void test370BarbossaAssignOffenseMember() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignOrg(USER_BARBOSSA_OID, ORG_MINISTRY_OF_OFFENSE_OID, null, task, result); - + // THEN PrismObject userBarbossa = getUser(USER_BARBOSSA_OID); display("User jack after", userBarbossa); @@ -1117,14 +1117,14 @@ public void test370BarbossaAssignOffenseMember() throws Exception { assertHasOrgs(userBarbossa, ORG_MINISTRY_OF_OFFENSE_OID); assertAssignedOrg(userBarbossa, ORG_MINISTRY_OF_OFFENSE_OID); assertHasOrg(userBarbossa, ORG_MINISTRY_OF_OFFENSE_OID); - + assertManager(USER_JACK_OID, USER_ELAINE_OID, null, false, result); assertManager(USER_JACK_OID, USER_ELAINE_OID, ORG_TYPE_FUNCTIONAL, false, result); assertManager(USER_JACK_OID, null, ORG_TYPE_PROJECT, false, result); assertManager(USER_JACK_OID, USER_JACK_OID, null, true, result); assertManager(USER_JACK_OID, USER_JACK_OID, ORG_TYPE_FUNCTIONAL, true, result); assertManager(USER_JACK_OID, null, ORG_TYPE_PROJECT, true, result); - + assertManager(USER_ELAINE_OID, null, null, false, result); assertManager(USER_ELAINE_OID, null, ORG_TYPE_FUNCTIONAL, false, result); assertManager(USER_ELAINE_OID, null, ORG_TYPE_PROJECT, false, result); @@ -1138,18 +1138,18 @@ public void test370BarbossaAssignOffenseMember() throws Exception { assertManager(USER_GUYBRUSH_OID, USER_GUYBRUSH_OID, null, true, result); assertManager(USER_GUYBRUSH_OID, USER_GUYBRUSH_OID, ORG_TYPE_FUNCTIONAL, true, result); assertManager(USER_GUYBRUSH_OID, null, ORG_TYPE_PROJECT, true, result); - + assertManager(USER_BARBOSSA_OID, USER_JACK_OID, null, false, result); assertManager(USER_BARBOSSA_OID, USER_JACK_OID, ORG_TYPE_FUNCTIONAL, false, result); assertManager(USER_BARBOSSA_OID, null, ORG_TYPE_PROJECT, false, result); assertManager(USER_BARBOSSA_OID, USER_JACK_OID, null, true, result); assertManager(USER_BARBOSSA_OID, USER_JACK_OID, ORG_TYPE_FUNCTIONAL, true, result); assertManager(USER_BARBOSSA_OID, null, ORG_TYPE_PROJECT, true, result); - + // Postcondition assertMonkeyIslandOrgSanity(); } - + @Test public void test372HermanAssignSwashbucklerMember() throws Exception { final String TEST_NAME = "test365GuybrushAssignSwashbucklerMember"; @@ -1159,10 +1159,10 @@ public void test372HermanAssignSwashbucklerMember() throws Exception { OperationResult result = task.getResult(); PrismObject userHerman = getUser(USER_HERMAN_OID); assertHasNoOrg(userHerman); - + // WHEN assignOrg(USER_HERMAN_OID, ORG_SWASHBUCKLER_SECTION_OID, null, task, result); - + // THEN userHerman = getUser(USER_HERMAN_OID); display("User jack after", userHerman); @@ -1170,14 +1170,14 @@ public void test372HermanAssignSwashbucklerMember() throws Exception { assertHasOrgs(userHerman, ORG_SWASHBUCKLER_SECTION_OID); assertAssignedOrg(userHerman, ORG_SWASHBUCKLER_SECTION_OID); assertHasOrg(userHerman, ORG_SWASHBUCKLER_SECTION_OID); - + assertManager(USER_JACK_OID, USER_ELAINE_OID, null, false, result); assertManager(USER_JACK_OID, USER_ELAINE_OID, ORG_TYPE_FUNCTIONAL, false, result); assertManager(USER_JACK_OID, null, ORG_TYPE_PROJECT, false, result); assertManager(USER_JACK_OID, USER_JACK_OID, null, true, result); assertManager(USER_JACK_OID, USER_JACK_OID, ORG_TYPE_FUNCTIONAL, true, result); assertManager(USER_JACK_OID, null, ORG_TYPE_PROJECT, true, result); - + assertManager(USER_ELAINE_OID, null, null, false, result); assertManager(USER_ELAINE_OID, null, ORG_TYPE_FUNCTIONAL, false, result); assertManager(USER_ELAINE_OID, null, ORG_TYPE_PROJECT, false, result); @@ -1191,7 +1191,7 @@ public void test372HermanAssignSwashbucklerMember() throws Exception { assertManager(USER_GUYBRUSH_OID, USER_GUYBRUSH_OID, null, true, result); assertManager(USER_GUYBRUSH_OID, USER_GUYBRUSH_OID, ORG_TYPE_FUNCTIONAL, true, result); assertManager(USER_GUYBRUSH_OID, null, ORG_TYPE_PROJECT, true, result); - + assertManager(USER_BARBOSSA_OID, USER_JACK_OID, null, false, result); assertManager(USER_BARBOSSA_OID, USER_JACK_OID, ORG_TYPE_FUNCTIONAL, false, result); assertManager(USER_BARBOSSA_OID, null, ORG_TYPE_PROJECT, false, result); @@ -1205,7 +1205,7 @@ public void test372HermanAssignSwashbucklerMember() throws Exception { assertManager(USER_HERMAN_OID, USER_GUYBRUSH_OID, null, true, result); assertManager(USER_HERMAN_OID, USER_GUYBRUSH_OID, ORG_TYPE_FUNCTIONAL, true, result); assertManager(USER_HERMAN_OID, null, ORG_TYPE_PROJECT, true, result); - + // Postcondition assertMonkeyIslandOrgSanity(); } @@ -1456,7 +1456,7 @@ public void test425JackUnassignDeletedOrg() throws Exception { // Postcondition assertMonkeyIslandOrgSanity(); } - + @Test public void test430JackAssignMetaroleOffender() throws Exception { final String TEST_NAME = "test430JackAssignMetaroleOffender"; @@ -1464,7 +1464,7 @@ public void test430JackAssignMetaroleOffender() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userJackBefore = getUser(USER_JACK_OID); display("User jack before", userJackBefore); assertAssignedOrgs(userJackBefore, ORG_MINISTRY_OF_OFFENSE_OID); @@ -1478,20 +1478,20 @@ public void test430JackAssignMetaroleOffender() throws Exception { // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User jack after", userJack); assertAssignedOrgs(userJack, ORG_MINISTRY_OF_OFFENSE_OID); assertHasOrgs(userJack, ORG_MINISTRY_OF_OFFENSE_OID, ORG_MINISTRY_OF_DEFENSE_OID); - + // Postcondition assertMonkeyIslandOrgSanity(); } - + @Test public void test431JackAssignMetaroleOffenderAdmin() throws Exception { final String TEST_NAME = "test431JackAssignMetaroleOffenderAdmin"; @@ -1508,18 +1508,18 @@ public void test431JackAssignMetaroleOffenderAdmin() throws Exception { // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN PrismObject userJack = getUser(USER_JACK_OID); display("User jack after", userJack); assertAssignedOrgs(userJack, ORG_MINISTRY_OF_OFFENSE_OID); assertHasOrgs(userJack, ORG_MINISTRY_OF_OFFENSE_OID, ORG_MINISTRY_OF_DEFENSE_OID, ORG_MINISTRY_OF_DEFENSE_OID); MidPointAsserts.assertHasOrg(userJack, ORG_MINISTRY_OF_DEFENSE_OID, SchemaConstants.ORG_MANAGER); - + // Postcondition assertMonkeyIslandOrgSanity(); } - + @Test public void test437JackUnassignOffender() throws Exception { final String TEST_NAME = "test437JackUnassignOffender"; @@ -1527,7 +1527,7 @@ public void test437JackUnassignOffender() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("user before", userBefore); @@ -1547,7 +1547,7 @@ public void test437JackUnassignOffender() throws Exception { // Postcondition assertMonkeyIslandOrgSanity(); } - + @Test public void test438JackUnassignOffenderAdmin() throws Exception { final String TEST_NAME = "test438JackUnassignOffenderAdmin"; @@ -1555,7 +1555,7 @@ public void test438JackUnassignOffenderAdmin() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("user before", userBefore); @@ -1574,7 +1574,7 @@ public void test438JackUnassignOffenderAdmin() throws Exception { // Postcondition assertMonkeyIslandOrgSanity(); } - + @Test public void test439JackCleanup() throws Exception { final String TEST_NAME = "test439JackCleanup"; @@ -1597,7 +1597,7 @@ public void test439JackCleanup() throws Exception { // Postcondition assertMonkeyIslandOrgSanity(); } - + /** * MID-3545 */ @@ -1612,7 +1612,7 @@ public void test440JackModifyEmployeeTypeRolePirate() throws Exception { PrismObject userBefore = getUser(USER_JACK_OID); display("user before", userBefore); assertNoAssignments(userBefore); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, UserType.F_EMPLOYEE_TYPE, task, result, "ROLE:Pirate"); @@ -1641,7 +1641,7 @@ public void test441JackModifyEmployeeTypeRoleCaptain() throws Exception { PrismObject userBefore = getUser(USER_JACK_OID); display("user before", userBefore); - + // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_EMPLOYEE_TYPE, task, result, "ROLE:Captain"); @@ -1654,7 +1654,7 @@ public void test441JackModifyEmployeeTypeRoleCaptain() throws Exception { // Postcondition assertMonkeyIslandOrgSanity(); } - + /** * MID-3545 */ @@ -1668,7 +1668,7 @@ public void test443JackModifyEmployeeTypeRoleNotExist() throws Exception { PrismObject userBefore = getUser(USER_JACK_OID); display("user before", userBefore); - + // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_EMPLOYEE_TYPE, task, result, "ROLE:TheRoleThatDoesNotExist"); @@ -1682,7 +1682,7 @@ public void test443JackModifyEmployeeTypeRoleNotExist() throws Exception { assertMonkeyIslandOrgSanity(); } - + /** * MID-3545 */ @@ -1696,7 +1696,7 @@ public void test449JackModifyEmployeeTypeNull() throws Exception { PrismObject userBefore = getUser(USER_JACK_OID); display("user before", userBefore); - + // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_EMPLOYEE_TYPE, task, result); @@ -1708,7 +1708,7 @@ public void test449JackModifyEmployeeTypeNull() throws Exception { // Postcondition assertMonkeyIslandOrgSanity(); } - + /** * Now let's test working with assignments when there is an object template that prescribes an org assignment * based on organizationalUnit property. @@ -1722,11 +1722,11 @@ public void test799DeleteJack() throws Exception { executeDeleteJack(TEST_NAME); } - - + + // 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) { assertAssignedOrg(user, orgOid); @@ -1734,7 +1734,7 @@ protected void assertUserOrg(PrismObject user, String... orgOids) thro } assertHasOrgs(user, orgOids.length); } - + protected void assertUserNoOrg(PrismObject user) throws Exception { assertAssignedNoOrg(user); assertHasNoOrg(user); @@ -1742,7 +1742,7 @@ protected void assertUserNoOrg(PrismObject user) throws Exception { assertHasOrgs(user, 0); } - + private void assertManager(String userOid, String managerOid, String orgType, boolean allowSelf, OperationResult result) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject user = getUser(userOid); ModelExpressionThreadLocalHolder.pushExpressionEnvironment(new ExpressionEnvironment<>(null, result)); 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 f4e75e06165..13851f18a7c 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 @@ -45,9 +45,9 @@ @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class TestOrgStructCaribbean extends AbstractInitializedModelIntegrationTest { - + 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"; @@ -55,31 +55,31 @@ public class TestOrgStructCaribbean extends AbstractInitializedModelIntegrationT protected static final String ORG_CARIBBEAN_DEPARTMENT_OF_THINGS_OID = "00000000-8888-6666-0000-c00000000004"; protected static final String ORG_CARIBBEAN_DEPARTMENT_OF_PEOPLE_OID = "00000000-8888-6666-0000-c00000000005"; protected static final String ORG_CARIBBEAN_ENTERTAINMENT_SECTION_OID = "00000000-8888-6666-0000-c00000000006"; - + public static final File USER_GIBBS_FILE = new File(TEST_DIR, "user-gibbs.xml"); public static final String USER_GIBBS_OID = "aca242ae-a29e-11e6-8bb4-1f8a1be2bd79"; public static final String USER_GIBBS_USERNAME = "gibbs"; - + public static final File USER_PINTEL_FILE = new File(TEST_DIR, "user-pintel.xml"); public static final String USER_PINTEL_OID = "16522760-a2a3-11e6-bf77-8baa83388f4b"; 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 { super.initSystem(initTask, initResult); - + addObject(USER_GIBBS_FILE); addObject(USER_PINTEL_FILE); - + addObject(ROLE_META_PIRACY_ORG_FILE); - + //DebugUtil.setDetailedDebugDump(true); } - + /** * MID-3448 */ @@ -87,35 +87,35 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti public void test100AddOrgCaribbean() throws Exception { final String TEST_NAME = "test100AddOrgCaribbean"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); // WHEN TestUtil.displayWhen(TEST_NAME); repoAddObjectsFromFile(ORG_CARIBBEAN_FILE, OrgType.class, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject orgJamaica = getObject(OrgType.class, ORG_CARIBBEAN_JAMAICA_OID); display("Jamaica", orgJamaica); assertAssignedOrgs(orgJamaica, ORG_CARIBBEAN_THE_CROWN_OID); assertHasOrgs(orgJamaica, ORG_CARIBBEAN_THE_CROWN_OID); - + PrismObject orgMonkeyGovernor = getObject(OrgType.class, ORG_GOVERNOR_OFFICE_OID); display("Moneky Governor", orgMonkeyGovernor); assertHasNoOrg(orgMonkeyGovernor, ORG_GOVERNOR_OFFICE_OID); - + PrismObject orgDoT = getObject(OrgType.class, ORG_CARIBBEAN_DEPARTMENT_OF_THINGS_OID); display("Department of Things", orgDoT); assertAssignedOrgs(orgDoT, ORG_CARIBBEAN_JAMAICA_OID); assertHasOrgs(orgDoT, ORG_CARIBBEAN_JAMAICA_OID); assertHasNoOrg(orgDoT, ORG_GOVERNOR_OFFICE_OID); } - + /** * MID-3448 */ @@ -123,30 +123,30 @@ public void test100AddOrgCaribbean() throws Exception { public void test102RecomputeJamaica() throws Exception { final String TEST_NAME = "test102RecomputeJamaica"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); // WHEN TestUtil.displayWhen(TEST_NAME); modelService.recompute(OrgType.class, ORG_CARIBBEAN_JAMAICA_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject orgJamaica = getObject(OrgType.class, ORG_CARIBBEAN_JAMAICA_OID); display("Jamaica", orgJamaica); assertAssignedOrgs(orgJamaica, ORG_CARIBBEAN_THE_CROWN_OID); assertHasOrgs(orgJamaica, ORG_CARIBBEAN_THE_CROWN_OID); assertHasNoOrg(orgJamaica, ORG_GOVERNOR_OFFICE_OID); - + PrismObject orgMonkeyGovernor = getObject(OrgType.class, ORG_GOVERNOR_OFFICE_OID); display("Monkey Governor", orgMonkeyGovernor); - assertHasNoOrg(orgMonkeyGovernor, ORG_CARIBBEAN_JAMAICA_OID); + assertHasNoOrg(orgMonkeyGovernor, ORG_CARIBBEAN_JAMAICA_OID); } - + /** * MID-3448 */ @@ -154,30 +154,30 @@ public void test102RecomputeJamaica() throws Exception { public void test103ReconcileJamaica() throws Exception { final String TEST_NAME = "test103ReconcileJamaica"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); // WHEN TestUtil.displayWhen(TEST_NAME); reconcileOrg(ORG_CARIBBEAN_JAMAICA_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject orgJamaica = getObject(OrgType.class, ORG_CARIBBEAN_JAMAICA_OID); display("Jamaica", orgJamaica); assertAssignedOrgs(orgJamaica, ORG_CARIBBEAN_THE_CROWN_OID); assertHasOrgs(orgJamaica, ORG_CARIBBEAN_THE_CROWN_OID); assertHasNoOrg(orgJamaica, ORG_GOVERNOR_OFFICE_OID); - + PrismObject orgMonkeyGovernor = getObject(OrgType.class, ORG_GOVERNOR_OFFICE_OID); display("Monkey Governor", orgMonkeyGovernor); assertHasNoOrg(orgMonkeyGovernor, ORG_CARIBBEAN_JAMAICA_OID); } - + /** * MID-3448 */ @@ -185,30 +185,30 @@ public void test103ReconcileJamaica() throws Exception { public void test104RecomputeGovernor() throws Exception { final String TEST_NAME = "test104RecomputeGovernor"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); // WHEN TestUtil.displayWhen(TEST_NAME); modelService.recompute(OrgType.class, ORG_GOVERNOR_OFFICE_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject orgJamaica = getObject(OrgType.class, ORG_CARIBBEAN_JAMAICA_OID); display("Jamaica", orgJamaica); assertAssignedOrgs(orgJamaica, ORG_CARIBBEAN_THE_CROWN_OID); assertHasOrgs(orgJamaica, ORG_CARIBBEAN_THE_CROWN_OID); assertHasNoOrg(orgJamaica, ORG_GOVERNOR_OFFICE_OID); - + PrismObject orgMonkeyGovernor = getObject(OrgType.class, ORG_GOVERNOR_OFFICE_OID); display("Monkey Governor", orgMonkeyGovernor); assertHasNoOrg(orgMonkeyGovernor, ORG_CARIBBEAN_JAMAICA_OID); } - + /** * MID-3448 */ @@ -216,70 +216,70 @@ public void test104RecomputeGovernor() throws Exception { public void test105ReconcileGovernor() throws Exception { final String TEST_NAME = "test105ReconcileGovernor"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); // WHEN TestUtil.displayWhen(TEST_NAME); reconcileOrg(ORG_GOVERNOR_OFFICE_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject orgJamaica = getObject(OrgType.class, ORG_CARIBBEAN_JAMAICA_OID); display("Jamaica", orgJamaica); assertAssignedOrgs(orgJamaica, ORG_CARIBBEAN_THE_CROWN_OID); assertHasOrgs(orgJamaica, ORG_CARIBBEAN_THE_CROWN_OID); assertHasNoOrg(orgJamaica, ORG_GOVERNOR_OFFICE_OID); - + PrismObject orgMonkeyGovernor = getObject(OrgType.class, ORG_GOVERNOR_OFFICE_OID); display("Monkey Governor", orgMonkeyGovernor); assertHasNoOrg(orgMonkeyGovernor, ORG_CARIBBEAN_JAMAICA_OID); } - + /** * Jamaica has an inducement to Monkey Island Governor Office. - * Sub-orgs of Jamaica should appear under Governor office. - * + * Sub-orgs of Jamaica should appear under Governor office. + * * MID-3448 */ @Test public void test106RecomputeDoT() throws Exception { final String TEST_NAME = "test106RecomputeDoT"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); // WHEN TestUtil.displayWhen(TEST_NAME); - modelService.recompute(OrgType.class, ORG_CARIBBEAN_DEPARTMENT_OF_THINGS_OID, + modelService.recompute(OrgType.class, ORG_CARIBBEAN_DEPARTMENT_OF_THINGS_OID, ModelExecuteOptions.createReconcileFocus(), task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject orgJamaica = getObject(OrgType.class, ORG_CARIBBEAN_JAMAICA_OID); display("Jamaica", orgJamaica); assertAssignedOrgs(orgJamaica, ORG_CARIBBEAN_THE_CROWN_OID); assertHasOrgs(orgJamaica, ORG_CARIBBEAN_THE_CROWN_OID); assertHasNoOrg(orgJamaica, ORG_GOVERNOR_OFFICE_OID); - + PrismObject orgMonkeyGovernor = getObject(OrgType.class, ORG_GOVERNOR_OFFICE_OID); display("Monkey Governor", orgMonkeyGovernor); assertHasNoOrg(orgMonkeyGovernor, ORG_CARIBBEAN_JAMAICA_OID); - + PrismObject orgDoT = getObject(OrgType.class, ORG_CARIBBEAN_DEPARTMENT_OF_THINGS_OID); display("Department of Things", orgDoT); assertAssignedOrgs(orgDoT, ORG_CARIBBEAN_JAMAICA_OID); assertHasOrgs(orgDoT, ORG_CARIBBEAN_JAMAICA_OID, ORG_GOVERNOR_OFFICE_OID); } - + /** * MID-3448 */ @@ -287,108 +287,108 @@ public void test106RecomputeDoT() throws Exception { public void test107ReconcileDoT() throws Exception { final String TEST_NAME = "test107ReconcileDoT"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); // WHEN TestUtil.displayWhen(TEST_NAME); reconcileOrg(ORG_CARIBBEAN_DEPARTMENT_OF_THINGS_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject orgJamaica = getObject(OrgType.class, ORG_CARIBBEAN_JAMAICA_OID); display("Jamaica", orgJamaica); assertAssignedOrgs(orgJamaica, ORG_CARIBBEAN_THE_CROWN_OID); assertHasOrgs(orgJamaica, ORG_CARIBBEAN_THE_CROWN_OID); assertHasNoOrg(orgJamaica, ORG_GOVERNOR_OFFICE_OID); - + PrismObject orgMonkeyGovernor = getObject(OrgType.class, ORG_GOVERNOR_OFFICE_OID); display("Monkey Governor", orgMonkeyGovernor); assertHasNoOrg(orgMonkeyGovernor, ORG_CARIBBEAN_JAMAICA_OID); - + PrismObject orgDoT = getObject(OrgType.class, ORG_CARIBBEAN_DEPARTMENT_OF_THINGS_OID); display("Department of Things", orgDoT); assertAssignedOrgs(orgDoT, ORG_CARIBBEAN_JAMAICA_OID); assertHasOrgs(orgDoT, ORG_CARIBBEAN_JAMAICA_OID, ORG_GOVERNOR_OFFICE_OID); } - + /** * 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"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); // WHEN TestUtil.displayWhen(TEST_NAME); modelService.recompute(OrgType.class, ORG_CARIBBEAN_DEPARTMENT_OF_PEOPLE_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject orgEntertainmentSection = getObject(OrgType.class, ORG_CARIBBEAN_ENTERTAINMENT_SECTION_OID); display("Entertainment Section", orgEntertainmentSection); assertHasNoOrg(orgEntertainmentSection, ORG_SCUMM_BAR_OID); - + PrismObject orgScummBar = getObject(OrgType.class, ORG_SCUMM_BAR_OID); display("Scumm Bar", orgScummBar); assertHasNoOrg(orgScummBar, ORG_CARIBBEAN_ENTERTAINMENT_SECTION_OID); - + } - + /** * Department of People (DoP) has in inducement to Monkey Island Scumm Bar. * 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"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + assertNoDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, USER_JACK_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_JACK_USERNAME); - + PrismObject userJackBefore = getUser(USER_JACK_OID); dumpFocus("User Jack before", userJackBefore); // WHEN TestUtil.displayWhen(TEST_NAME); assignOrg(USER_JACK_OID, ORG_CARIBBEAN_DEPARTMENT_OF_PEOPLE_OID, null); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject orgEntertainmentSection = getObject(OrgType.class, ORG_CARIBBEAN_ENTERTAINMENT_SECTION_OID); display("Entertainment Section", orgEntertainmentSection); assertHasNoOrg(orgEntertainmentSection, ORG_SCUMM_BAR_OID); - + PrismObject orgScummBar = getObject(OrgType.class, ORG_SCUMM_BAR_OID); display("Scumm Bar", orgScummBar); assertHasNoOrg(orgScummBar, ORG_CARIBBEAN_ENTERTAINMENT_SECTION_OID); - + PrismObject userJackAfter = getUser(USER_JACK_OID); dumpFocus("User Jack after", userJackAfter); assertHasOrgs(userJackAfter, ORG_CARIBBEAN_DEPARTMENT_OF_PEOPLE_OID, ORG_SCUMM_BAR_OID); @@ -396,15 +396,15 @@ public void test115AssignJackToDoP() throws Exception { assertAccount(userJackAfter, RESOURCE_DUMMY_OID); // From Scumm Bar assertAccount(userJackAfter, RESOURCE_DUMMY_YELLOW_OID); assertLinks(userJackAfter, 2); - + assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, USER_JACK_USERNAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_YELLOW_NAME, USER_JACK_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_YELLOW_NAME, USER_JACK_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Pirate"); - + assertNoDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_JACK_USERNAME); - + } - + /** * Barbossa is a manager. He should get the red account from the piracy metarole. * But he should NOT get the yellow account. @@ -413,37 +413,37 @@ public void test115AssignJackToDoP() throws Exception { public void test120AssignBarbossaDoTManager() throws Exception { final String TEST_NAME = "test120AssignBarbossaDoTManager"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + assertNoDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, USER_BARBOSSA_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME); // WHEN TestUtil.displayWhen(TEST_NAME); assignOrg(USER_BARBOSSA_OID, ORG_CARIBBEAN_DEPARTMENT_OF_THINGS_OID, SchemaConstants.ORG_MANAGER); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); dumpFocus("User barbossa after", userBarbossaAfter); assertHasOrgs(userBarbossaAfter, ORG_CARIBBEAN_DEPARTMENT_OF_THINGS_OID); assertRoleMembershipRef(userBarbossaAfter, ORG_CARIBBEAN_DEPARTMENT_OF_THINGS_OID); assertAccount(userBarbossaAfter, RESOURCE_DUMMY_RED_OID); assertLinks(userBarbossaAfter, 1); - + assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Captain"); - + assertNoDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, USER_BARBOSSA_USERNAME); - + } - + /** * MID-3472 */ @@ -451,22 +451,22 @@ public void test120AssignBarbossaDoTManager() throws Exception { public void test130AssignGibbsAsJacksDeputy() throws Exception { final String TEST_NAME = "test130AssignGibbsAsJacksDeputy"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + assertNoDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, USER_GIBBS_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_GIBBS_USERNAME); // WHEN TestUtil.displayWhen(TEST_NAME); assignDeputy(USER_GIBBS_OID, USER_JACK_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userGibbsAfter = getUser(USER_GIBBS_OID); dumpFocus("User Gibbs after", userGibbsAfter); assertHasOrgs(userGibbsAfter, ORG_CARIBBEAN_DEPARTMENT_OF_PEOPLE_OID, ORG_SCUMM_BAR_OID); @@ -475,15 +475,15 @@ public void test130AssignGibbsAsJacksDeputy() throws Exception { assertAccount(userGibbsAfter, RESOURCE_DUMMY_OID); // From Scumm Bar assertAccount(userGibbsAfter, RESOURCE_DUMMY_YELLOW_OID); assertLinks(userGibbsAfter, 2); - + assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, USER_GIBBS_USERNAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_YELLOW_NAME, USER_GIBBS_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_YELLOW_NAME, USER_GIBBS_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Pirate"); - + assertNoDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_GIBBS_USERNAME); - + } - + /** * MID-3472 */ @@ -491,22 +491,22 @@ public void test130AssignGibbsAsJacksDeputy() throws Exception { public void test140AssignPintelAsBarbossasDeputy() throws Exception { final String TEST_NAME = "test140AssignPintelAsBarbossasDeputy"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + assertNoDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, USER_PINTEL_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_PINTEL_USERNAME); // WHEN TestUtil.displayWhen(TEST_NAME); assignDeputy(USER_PINTEL_OID, USER_BARBOSSA_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userPintelAfter = getUser(USER_PINTEL_OID); dumpFocus("User pintel after", userPintelAfter); assertHasOrgs(userPintelAfter, ORG_CARIBBEAN_DEPARTMENT_OF_THINGS_OID); @@ -514,13 +514,13 @@ public void test140AssignPintelAsBarbossasDeputy() throws Exception { assertDelegatedRef(userPintelAfter, ORG_CARIBBEAN_DEPARTMENT_OF_THINGS_OID, USER_BARBOSSA_OID); assertAccount(userPintelAfter, RESOURCE_DUMMY_RED_OID); assertLinks(userPintelAfter, 1); - + assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_PINTEL_USERNAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_PINTEL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_PINTEL_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Captain"); - + assertNoDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, USER_PINTEL_USERNAME); - + } } 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 05b84a1307d..d96c0cceb38 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 @@ -50,7 +50,7 @@ /** * Orgstruct test with a meta-role and focus mappings. - * + * * @author Radovan Semancik * */ @@ -58,10 +58,10 @@ @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class TestOrgStructMeta extends TestOrgStruct { - + private static final File OBJECT_TEMPLATE_ORG_FILE = new File(TEST_DIR, "object-template-org.xml"); protected static final String OBJECT_TEMPLATE_ORG_OID = "3e62558c-ca0f-11e3-ba83-001e8c717e5b"; - + protected static final File ROLE_META_FUNCTIONAL_ORG_FILE = new File(TEST_DIR, "role-meta-functional-org.xml"); protected static final String ROLE_META_FUNCTIONAL_ORG_OID = "74aac2c8-ca0f-11e3-bb29-001e8c717e5b"; @@ -79,11 +79,11 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti repoAddObjectFromFile(OBJECT_TEMPLATE_ORG_FILE, initResult); setDefaultObjectTemplate(OrgType.COMPLEX_TYPE, OBJECT_TEMPLATE_ORG_OID); - + repoAddObjectFromFile(ROLE_META_FUNCTIONAL_ORG_FILE, initResult); repoAddObjectFromFile(ROLE_ORGANIZED_FILE, initResult); } - + @Override protected ResultHandler getOrgSanityCheckHandler() { return (org, parentResult) -> { @@ -107,13 +107,13 @@ protected ResultHandler getOrgSanityCheckHandler() { @Override protected void addOrgStruct() throws Exception { List> orgs = (List) PrismTestUtil.parseObjects(ORG_MONKEY_ISLAND_FILE); - + // WHEN for (PrismObject org: orgs) { display("Adding", org); addObject(org); } - + // Sanity is asserted in the inherited tests } @@ -144,7 +144,7 @@ protected void assertUserNoOrg(PrismObject user) throws Exception { } // test05x - test7xx inherited from superclass - + @Test public void test800JackAssignScummBar() throws Exception { final String TEST_NAME = "test800JackAssignScummBar"; @@ -153,26 +153,26 @@ public void test800JackAssignScummBar() throws Exception { Task task = taskManager.createTaskInstance(TestOrgStruct.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); addObject(USER_JACK_FILE); - + // Precondition assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); - + // WHEN assignOrg(USER_JACK_OID, ORG_SCUMM_BAR_OID, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); PrismObject user = getUser(USER_JACK_OID); display("User after", user); assertUserOrg(user, ORG_SCUMM_BAR_OID); - + assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_FULL_NAME, true); - + // Postcondition assertMonkeyIslandOrgSanity(); } - + @Test public void test802JackAssignOrganized() throws Exception { final String TEST_NAME = "test802JackAssignOrganized"; @@ -180,10 +180,10 @@ public void test802JackAssignOrganized() throws Exception { Task task = taskManager.createTaskInstance(TestOrgStruct.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignRole(USER_JACK_OID, ROLE_ORGANIZED_OID, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); @@ -191,17 +191,17 @@ public void test802JackAssignOrganized() throws Exception { display("User after", user); assertUserOrg(user, ORG_SCUMM_BAR_OID); assertAssignedRole(user, ROLE_ORGANIZED_OID); - + assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_FULL_NAME, true); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Proud member of F0006"); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "Arr!", "I say: Hosting the worst scumm of the Caribbean."); - + // Postcondition assertMonkeyIslandOrgSanity(); } - + @Test public void test804JackUnAssignOrganized() throws Exception { final String TEST_NAME = "test804JackUnAssignOrganized"; @@ -209,27 +209,27 @@ public void test804JackUnAssignOrganized() throws Exception { Task task = taskManager.createTaskInstance(TestOrgStruct.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignRole(USER_JACK_OID, ROLE_ORGANIZED_OID, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); PrismObject user = getUser(USER_JACK_OID); display("User after", user); assertUserOrg(user, ORG_SCUMM_BAR_OID); - + assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_FULL_NAME, true); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "Arr!"); - + // Postcondition assertMonkeyIslandOrgSanity(); } - + @Test public void test809JackUnassignScummBar() throws Exception { final String TEST_NAME = "test809JackUnassignScummBar"; @@ -237,23 +237,23 @@ public void test809JackUnassignScummBar() throws Exception { Task task = taskManager.createTaskInstance(TestOrgStruct.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignOrg(USER_JACK_OID, ORG_SCUMM_BAR_OID, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); PrismObject userJack = getUser(USER_JACK_OID); display("User jack after", userJack); assertUserNoOrg(userJack); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); - + // Postcondition assertMonkeyIslandOrgSanity(); } - + /** * Now do the same things as 80x but do it all at once. */ @@ -264,7 +264,7 @@ public void test810JackAssignScummBarOrganized() throws Exception { Task task = taskManager.createTaskInstance(TestOrgStruct.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // Precondition assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); @@ -272,10 +272,10 @@ public void test810JackAssignScummBarOrganized() throws Exception { modifications.add((createAssignmentModification(ROLE_ORGANIZED_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); modifications.add((createAssignmentModification(ORG_SCUMM_BAR_OID, OrgType.COMPLEX_TYPE, null, null, null, true))); ObjectDelta userDelta = ObjectDelta.createModifyDelta(USER_JACK_OID, modifications, UserType.class, prismContext); - + // WHEN modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); @@ -283,15 +283,15 @@ public void test810JackAssignScummBarOrganized() throws Exception { display("User after", user); assertUserOrg(user, ORG_SCUMM_BAR_OID); assertAssignedRole(user, ROLE_ORGANIZED_OID); - + assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_FULL_NAME, true); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Proud member of F0006"); - + // Postcondition assertMonkeyIslandOrgSanity(); } - + @Test public void test890AddFictionalOrg() throws Exception { final String TEST_NAME = "test890AddFictionalOrg"; @@ -314,5 +314,5 @@ public void test890AddFictionalOrg() throws Exception { // Postcondition assertMonkeyIslandOrgSanity(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 eb57a4e766f..66564b66252 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 @@ -79,7 +79,7 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public abstract class AbstractPasswordTest extends AbstractInitializedModelIntegrationTest { - + protected static final String USER_PASSWORD_1_CLEAR = "d3adM3nT3llN0Tal3s"; protected static final String USER_PASSWORD_2_CLEAR = "bl4ckP3arl"; protected static final String USER_PASSWORD_3_CLEAR = "wh3r3sTheRum?"; @@ -99,24 +99,24 @@ public abstract class AbstractPasswordTest extends AbstractInitializedModelInteg protected static final File RESOURCE_DUMMY_UGLY_FILE = new File(TEST_DIR, "resource-dummy-ugly.xml"); protected static final String RESOURCE_DUMMY_UGLY_OID = "10000000-0000-0000-0000-000000344104"; protected static final String RESOURCE_DUMMY_UGLY_NAME = "ugly"; - + protected static final File RESOURCE_DUMMY_LIFECYCLE_FILE = new File(TEST_DIR, "resource-dummy-lifecycle.xml"); protected static final String RESOURCE_DUMMY_LIFECYCLE_OID = "519f131a-147b-11e7-a270-c38e2b225751"; protected static final String RESOURCE_DUMMY_LIFECYCLE_NAME = "lifecycle"; protected static final File PASSWORD_POLICY_UGLY_FILE = new File(TEST_DIR, "password-policy-ugly.xml"); protected static final String PASSWORD_POLICY_UGLY_OID = "cfb3fa9e-027a-11e7-8e2c-dbebaacaf4ee"; - + protected static final File SECURITY_POLICY_DEFAULT_STORAGE_HASHING_FILE = new File(TEST_DIR, "security-policy-default-storage-hashing.xml"); protected static final String SECURITY_POLICY_DEFAULT_STORAGE_HASHING_OID = "0ea3b93c-0425-11e7-bbc1-73566dc53d59"; - + protected static final File SECURITY_POLICY_PASSWORD_STORAGE_NONE_FILE = new File(TEST_DIR, "security-policy-password-storage-none.xml"); protected static final String SECURITY_POLICY_PASSWORD_STORAGE_NONE_OID = "2997a20a-0423-11e7-af65-a7ab7d19442c"; - + protected static final String USER_JACK_EMPLOYEE_NUMBER_NEW_BAD = "No1"; protected static final String USER_JACK_EMPLOYEE_NUMBER_NEW_GOOD = "pir321"; protected static final String USER_RAPP_EMAIL = "rapp.scallion@evolveum.com"; - + protected String accountJackOid; protected String accountJackRedOid; protected String accountJackUglyOid; @@ -124,16 +124,16 @@ public abstract class AbstractPasswordTest extends AbstractInitializedModelInteg protected String accountJackYellowOid; protected XMLGregorianCalendar lastPasswordChangeStart; protected XMLGregorianCalendar lastPasswordChangeEnd; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { InternalsConfig.setAvoidLoggingChange(true); super.initSystem(initTask, initResult); - + importObjectFromFile(PASSWORD_POLICY_UGLY_FILE); importObjectFromFile(SECURITY_POLICY_DEFAULT_STORAGE_HASHING_FILE); importObjectFromFile(SECURITY_POLICY_PASSWORD_STORAGE_NONE_FILE); - + setGlobalSecurityPolicy(getSecurityPolicyOid(), initResult); initDummyResourcePirate(RESOURCE_DUMMY_UGLY_NAME, RESOURCE_DUMMY_UGLY_FILE, RESOURCE_DUMMY_UGLY_OID, initTask, initResult); @@ -141,9 +141,9 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti login(USER_ADMINISTRATOR_USERNAME); } - + protected abstract String getSecurityPolicyOid(); - + @Test public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; @@ -159,7 +159,7 @@ public void test000Sanity() throws Exception { accountActivationNotifier = accountActivationNotifiers.get(0); } } - + display("Account activation notifier", accountActivationNotifier); assertNotNull("No accountActivationNotifier", accountActivationNotifier); } @@ -173,14 +173,14 @@ public void test010AddPasswordPolicy() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + // WHEN PrismObject passwordPolicy = addObject(PASSWORD_POLICY_GLOBAL_FILE, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + assertEquals("Wrong OID after add", PASSWORD_POLICY_GLOBAL_OID, passwordPolicy.getOid()); // Check object @@ -188,7 +188,7 @@ public void test010AddPasswordPolicy() throws Exception { // TODO: more asserts } - + @Test public void test050CheckJackPassword() throws Exception { final String TEST_NAME = "test050CheckJackPassword"; @@ -196,19 +196,19 @@ public void test050CheckJackPassword() throws Exception { // GIVEN, WHEN // this happens during test initialization when user-jack.xml is added - + // THEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); - + // Password still encrypted. We haven't changed it yet. assertUserPassword(userJack, USER_JACK_PASSWORD, CredentialsStorageTypeType.ENCRYPTION); } - + @Test public void test051ModifyUserJackPassword() throws Exception { @@ -219,29 +219,29 @@ public void test051ModifyUserJackPassword() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); modifyUserChangePassword(USER_JACK_OID, USER_PASSWORD_1_CLEAR, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + XMLGregorianCalendar endCal = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); - + assertUserPassword(userJack, USER_PASSWORD_1_CLEAR); assertPasswordMetadata(userJack, false, startCal, endCal); // Password policy is not active yet. No history should be kept. assertPasswordHistoryEntries(userJack); } - + @Test public void test060CheckJackPasswordModelInteraction() throws Exception { final String TEST_NAME = "test060CheckJackPasswordModelInteraction"; @@ -251,31 +251,31 @@ public void test060CheckJackPasswordModelInteraction() throws Exception { // Nothing to check in this case return; } - + // GIVEN Task task = createTask(AbstractPasswordTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN, THEN ProtectedStringType userPasswordPsGood = new ProtectedStringType(); userPasswordPsGood.setClearValue(USER_PASSWORD_1_CLEAR); assertTrue("Good password check failed", modelInteractionService.checkPassword(USER_JACK_OID, userPasswordPsGood, task, result)); - + ProtectedStringType userPasswordPsBad = new ProtectedStringType(); - userPasswordPsBad.setClearValue("this is not a password"); + userPasswordPsBad.setClearValue("this is not a password"); assertFalse("Bad password check failed", modelInteractionService.checkPassword(USER_JACK_OID, userPasswordPsBad, task, result)); ProtectedStringType userPasswordPsEmpty = new ProtectedStringType(); assertFalse("Empty password check failed", modelInteractionService.checkPassword(USER_JACK_OID, userPasswordPsEmpty, task, result)); - + assertFalse("Null password check failed", modelInteractionService.checkPassword(USER_JACK_OID, null, task, result)); } - + @Test public void test070AddUserHerman() throws Exception { final String TEST_NAME = "test070AddUserHerman"; @@ -284,25 +284,25 @@ public void test070AddUserHerman() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); addObject(USER_HERMAN_FILE, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - + XMLGregorianCalendar endCal = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userAfter = getUser(USER_HERMAN_OID); display("User after", userAfter); - assertUser(userAfter, USER_HERMAN_OID, USER_HERMAN_USERNAME, + assertUser(userAfter, USER_HERMAN_OID, USER_HERMAN_USERNAME, USER_HERMAN_FULL_NAME, USER_HERMAN_GIVEN_NAME, USER_HERMAN_FAMILY_NAME); - + assertUserPassword(userAfter, USER_HERMAN_PASSWORD); assertPasswordMetadata(userAfter, true, startCal, endCal); // Password policy is not active yet. No history should be kept. @@ -318,23 +318,23 @@ public void test100ModifyUserJackAssignAccount() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); - + // WHEN assignAccount(USER_JACK_OID, RESOURCE_DUMMY_OID, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + XMLGregorianCalendar endCal = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); accountJackOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadowRepo = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); display("Repo shadow", accountShadowRepo); @@ -342,19 +342,19 @@ public void test100ModifyUserJackAssignAccount() throws Exception { // MID-3860 assertShadowPasswordMetadata(accountShadowRepo, startCal, endCal, false, true); assertShadowLifecycle(accountShadowRepo, false); - + // Check account PrismObject accountShadowModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); display("Model shadow", accountShadowModel); assertDummyAccountShadowModel(accountShadowModel, accountJackOid, USER_JACK_USERNAME, USER_JACK_FULL_NAME); assertShadowPasswordMetadata(accountShadowModel, startCal, endCal, false, true); assertShadowLifecycle(accountShadowModel, false); - + // Check account in dummy resource assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); - + assertDummyPasswordConditional(ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_1_CLEAR); - + assertSinglePasswordNotificationConditional(null, USER_JACK_USERNAME, USER_PASSWORD_1_CLEAR); } @@ -370,26 +370,26 @@ public void test110ModifyUserJackPassword() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + lastPasswordChangeStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modifyUserChangePassword(USER_JACK_OID, USER_PASSWORD_2_CLEAR, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + lastPasswordChangeEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); - + assertUserPassword(userJack, USER_PASSWORD_2_CLEAR); assertDummyPassword(ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_2_CLEAR); assertPasswordMetadata(userJack, false, lastPasswordChangeStart, lastPasswordChangeEnd); - + // Check shadow PrismObject accountShadowRepo = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); display("Repo shadow", accountShadowRepo); @@ -397,17 +397,17 @@ public void test110ModifyUserJackPassword() throws Exception { // MID-3860 assertShadowPasswordMetadata(accountShadowRepo, lastPasswordChangeStart, lastPasswordChangeEnd, true, false); assertShadowLifecycle(accountShadowRepo, false); - + // Check account PrismObject accountShadowModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); display("Model shadow", accountShadowModel); assertDummyAccountShadowModel(accountShadowModel, accountJackOid, "jack", "Jack Sparrow"); assertShadowPasswordMetadata(accountShadowModel, lastPasswordChangeStart, lastPasswordChangeEnd, true, false); assertShadowLifecycle(accountShadowModel, false); - + assertSinglePasswordNotification(null, USER_JACK_USERNAME, USER_PASSWORD_2_CLEAR); } - + /** * Modify account password. User's password should be unchanged */ @@ -420,28 +420,28 @@ public void test111ModifyAccountJackPassword() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + // WHEN modifyAccountChangePassword(accountJackOid, USER_PASSWORD_3_CLEAR, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); - + // User should still have old password assertUserPassword(userJack, USER_PASSWORD_2_CLEAR); // Account has new password assertDummyPassword(ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_3_CLEAR); - + assertPasswordMetadata(userJack, false, lastPasswordChangeStart, lastPasswordChangeEnd); - + assertSinglePasswordNotification(null, USER_JACK_USERNAME, USER_PASSWORD_3_CLEAR); } - + /** * Modify both user and account password. As password outbound mapping is weak the user should have its own password * and account should have its own password. @@ -455,44 +455,44 @@ public void test112ModifyJackPasswordUserAndAccount() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + ProtectedStringType userPasswordPs4 = new ProtectedStringType(); userPasswordPs4.setClearValue(USER_PASSWORD_4_CLEAR); ObjectDelta userDelta = createModifyUserReplaceDelta(USER_JACK_OID, PASSWORD_VALUE_PATH, userPasswordPs4); - + ProtectedStringType userPasswordPs5 = new ProtectedStringType(); userPasswordPs5.setClearValue(USER_PASSWORD_5_CLEAR); - ObjectDelta accountDelta = createModifyAccountShadowReplaceDelta(accountJackOid, getDummyResourceObject(), - PASSWORD_VALUE_PATH, userPasswordPs5); - + ObjectDelta accountDelta = createModifyAccountShadowReplaceDelta(accountJackOid, getDummyResourceObject(), + PASSWORD_VALUE_PATH, userPasswordPs5); + Collection> deltas = MiscSchemaUtil.createCollection(accountDelta, userDelta); - + lastPasswordChangeStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + lastPasswordChangeEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); - + // User should still have old password assertUserPassword(userJack, USER_PASSWORD_4_CLEAR); // Account has new password assertDummyPassword(ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_5_CLEAR); - + assertPasswordMetadata(userJack, false, lastPasswordChangeStart, lastPasswordChangeEnd); - + assertSinglePasswordNotification(null, USER_JACK_USERNAME, USER_PASSWORD_5_CLEAR); } - - + + /** * Add red and ugly dummy resource to the mix. This would be fun. */ @@ -505,7 +505,7 @@ public void test120ModifyUserJackAssignAccountDummyRedAndUgly() throws Exception Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + // WHEN assignAccount(USER_JACK_OID, RESOURCE_DUMMY_RED_OID, null, task, result); assignAccount(USER_JACK_OID, RESOURCE_DUMMY_UGLY_OID, null, task, result); @@ -513,7 +513,7 @@ public void test120ModifyUserJackAssignAccountDummyRedAndUgly() throws Exception // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); @@ -531,9 +531,9 @@ public void test120ModifyUserJackAssignAccountDummyRedAndUgly() throws Exception // User and default dummy account should have unchanged passwords assertUserPassword(userJack, USER_PASSWORD_4_CLEAR); assertDummyPassword(USER_JACK_USERNAME, USER_PASSWORD_5_CLEAR); - + assertPasswordMetadata(userJack, false, lastPasswordChangeStart, lastPasswordChangeEnd); - + if (isPasswordEncryption()) { assertPasswordNotifications(2); assertHasPasswordNotification(RESOURCE_DUMMY_RED_NAME, USER_JACK_USERNAME, USER_PASSWORD_4_CLEAR); @@ -556,47 +556,47 @@ public void test121ModifyJackPasswordUserAndAccountRed() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + ProtectedStringType userPasswordPs1 = new ProtectedStringType(); userPasswordPs1.setClearValue(USER_PASSWORD_1_CLEAR); ObjectDelta userDelta = createModifyUserReplaceDelta(USER_JACK_OID, PASSWORD_VALUE_PATH, userPasswordPs1); - + ProtectedStringType userPasswordPs2 = new ProtectedStringType(); userPasswordPs2.setClearValue(USER_PASSWORD_2_CLEAR); ObjectDelta accountDelta = createModifyAccountShadowReplaceDelta(accountJackRedOid, getDummyResourceObject(), - PASSWORD_VALUE_PATH, userPasswordPs2); - + PASSWORD_VALUE_PATH, userPasswordPs2); + Collection> deltas = MiscSchemaUtil.createCollection(userDelta, accountDelta); - + lastPasswordChangeStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + lastPasswordChangeEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, USER_JACK_FULL_NAME); - + // User should still have old password assertUserPassword(userJack, USER_PASSWORD_1_CLEAR); // Red account has the same account as user assertDummyPassword(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_1_CLEAR); - // ... and default account has also the same password as user now. There was no other change on default dummy instance + // ... and default account has also the same password as user now. There was no other change on default dummy instance // so even the weak mapping took place. assertDummyPassword(ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_1_CLEAR); // this one is not changed assertDummyPassword(RESOURCE_DUMMY_UGLY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_EMPLOYEE_NUMBER); assertLinks(userJack, 3); - + assertPasswordMetadata(userJack, false, lastPasswordChangeStart, lastPasswordChangeEnd); - + displayPasswordNotifications(); assertPasswordNotifications(2); assertHasPasswordNotification(null, USER_JACK_USERNAME, USER_PASSWORD_1_CLEAR); @@ -615,12 +615,12 @@ public void test122ModifyAccountUglyJackPasswordBad() throws Exception { // GIVEN Task task = createTask(AbstractPasswordTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + try { // WHEN displayWhen(TEST_NAME); modifyAccountChangePassword(accountJackUglyOid, "#badPassword!", task, result); - + fail("Expected policy violation because password doesn't satisfy password policy but didn't get one."); } catch (PolicyViolationException ex) { // THEN @@ -630,8 +630,8 @@ public void test122ModifyAccountUglyJackPasswordBad() throws Exception { assertNoPasswordNotifications(); } - - + + /** * Jack employee number is mapped to ugly resource password. * Change employee number to something that does NOT comply with ugly resource password policy. @@ -646,24 +646,24 @@ public void test125ModifyJackEmployeeNumberBad() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + try { // WHEN - modifyUserReplace(USER_JACK_OID, UserType.F_EMPLOYEE_NUMBER, task, result, + modifyUserReplace(USER_JACK_OID, UserType.F_EMPLOYEE_NUMBER, task, result, USER_JACK_EMPLOYEE_NUMBER_NEW_BAD); assertNotReached(); } catch (PolicyViolationException e) { // this is expected display("Expected exception", e); } - + // THEN result.computeStatus(); TestUtil.assertFailure(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after", userJack); - + assertUserPassword(userJack, USER_PASSWORD_1_CLEAR); assertDummyPassword(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_1_CLEAR); assertDummyPassword(ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_1_CLEAR); @@ -671,12 +671,12 @@ public void test125ModifyJackEmployeeNumberBad() throws Exception { assertDummyPassword(RESOURCE_DUMMY_UGLY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_EMPLOYEE_NUMBER); assertLinks(userJack, 3); - + assertPasswordMetadata(userJack, false, lastPasswordChangeStart, lastPasswordChangeEnd); - + assertNoPasswordNotifications(); } - + /** * Jack employee number is mapped to ugly resource password. * Change employee number to something that does comply with ugly resource password policy. @@ -691,18 +691,18 @@ public void test128ModifyJackEmployeeNumberGood() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + // WHEN - modifyUserReplace(USER_JACK_OID, UserType.F_EMPLOYEE_NUMBER, task, result, + modifyUserReplace(USER_JACK_OID, UserType.F_EMPLOYEE_NUMBER, task, result, USER_JACK_EMPLOYEE_NUMBER_NEW_GOOD); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after", userJack); - + assertUserPassword(userJack, USER_PASSWORD_1_CLEAR); assertDummyPassword(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_1_CLEAR); assertDummyPassword(ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_1_CLEAR); @@ -710,12 +710,12 @@ public void test128ModifyJackEmployeeNumberGood() throws Exception { assertDummyPassword(RESOURCE_DUMMY_UGLY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_EMPLOYEE_NUMBER_NEW_GOOD); assertLinks(userJack, 3); - + assertPasswordMetadata(userJack, false, lastPasswordChangeStart, lastPasswordChangeEnd); - + assertSinglePasswordNotification(RESOURCE_DUMMY_UGLY_NAME, USER_JACK_USERNAME, USER_JACK_EMPLOYEE_NUMBER_NEW_GOOD); } - + /** * Black resource has minimum password length constraint (enforced by midPoint). */ @@ -728,13 +728,13 @@ public void test130ModifyUserJackAssignAccountDummyBlack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + // WHEN assignAccount(USER_JACK_OID, RESOURCE_DUMMY_BLACK_OID, null, task, result); - + // THEN assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertLinks(userJack, 4); @@ -743,7 +743,7 @@ public void test130ModifyUserJackAssignAccountDummyBlack() throws Exception { // Check account in dummy resource (black) assertDummyAccount(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyPasswordConditional(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_1_CLEAR); - + // Other resources should have unchanged passwords assertUserPassword(userJack, USER_PASSWORD_1_CLEAR); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); @@ -752,12 +752,12 @@ public void test130ModifyUserJackAssignAccountDummyBlack() throws Exception { assertDummyPassword(RESOURCE_DUMMY_UGLY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_EMPLOYEE_NUMBER_NEW_GOOD); assertPasswordMetadata(userJack, false, lastPasswordChangeStart, lastPasswordChangeEnd); - + assertPasswordHistoryEntries(userJack); - + assertSinglePasswordNotificationConditional(RESOURCE_DUMMY_BLACK_NAME, USER_JACK_USERNAME, USER_PASSWORD_1_CLEAR); } - + /** * MID-3682 */ @@ -770,22 +770,22 @@ public void test132ModifyAccountBlackJackPasswordBad() throws Exception { Task task = createTask(AbstractPasswordTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + try { // WHEN displayWhen(TEST_NAME); modifyAccountChangePassword(accountJackBlackOid, USER_PASSWORD_A_CLEAR, task, result); - + fail("Expected policy violation because password doesn't satisfy password policy but didn't get one."); } catch (PolicyViolationException ex) { // THEN displayThen(TEST_NAME); assertDummyPasswordConditional(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_1_CLEAR); } - + assertNoPasswordNotifications(); } - + @Test public void test139ModifyUserJackUnassignAccountDummyBlack() throws Exception { final String TEST_NAME = "test139ModifyUserJackUnassignAccountDummyBlack"; @@ -795,13 +795,13 @@ public void test139ModifyUserJackUnassignAccountDummyBlack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + // WHEN unassignAccount(USER_JACK_OID, RESOURCE_DUMMY_BLACK_OID, null, task, result); - + // THEN assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertLinks(userJack, 3); @@ -809,7 +809,7 @@ public void test139ModifyUserJackUnassignAccountDummyBlack() throws Exception { // Check account in dummy resource (black) assertNoDummyAccount(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_JACK_DUMMY_USERNAME); - + // Other resources should have unchanged passwords assertUserPassword(userJack, USER_PASSWORD_1_CLEAR); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); @@ -818,14 +818,14 @@ public void test139ModifyUserJackUnassignAccountDummyBlack() throws Exception { assertDummyPassword(RESOURCE_DUMMY_UGLY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_EMPLOYEE_NUMBER_NEW_GOOD); assertPasswordMetadata(userJack, false, lastPasswordChangeStart, lastPasswordChangeEnd); - + assertPasswordHistoryEntries(userJack); - + assertNoPasswordNotifications(); } - + /** - * Yellow resource has minimum password length constraint (enforced by resource). + * Yellow resource has minimum password length constraint (enforced by resource). * But this time the password is OK. */ @Test @@ -837,15 +837,15 @@ public void test140ModifyUserJackAssignAccountDummyYellow() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + // WHEN displayWhen(TEST_NAME); assignAccount(USER_JACK_OID, RESOURCE_DUMMY_YELLOW_OID, null, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertLinks(userJack, 4); @@ -855,7 +855,7 @@ public void test140ModifyUserJackAssignAccountDummyYellow() throws Exception { DummyAccount dummyAccountYellow = assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); display("Yellow dummy account", dummyAccountYellow); assertDummyPasswordConditionalGenerated(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_1_CLEAR); - + // Other resources should have unchanged passwords assertUserPassword(userJack, USER_PASSWORD_1_CLEAR); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); @@ -864,13 +864,13 @@ public void test140ModifyUserJackAssignAccountDummyYellow() throws Exception { assertDummyPassword(RESOURCE_DUMMY_UGLY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_EMPLOYEE_NUMBER_NEW_GOOD); assertPasswordMetadata(userJack, false, lastPasswordChangeStart, lastPasswordChangeEnd); - + assertPasswordHistoryEntries(userJack); displayPasswordNotifications(); assertSinglePasswordNotificationConditionalGenerated(RESOURCE_DUMMY_YELLOW_NAME, USER_JACK_USERNAME, USER_PASSWORD_1_CLEAR); } - + /** * Yellow resource has minimum password length constraint. Change password to something shorter. * MID-3033, MID-2134 @@ -884,20 +884,20 @@ public void test142ModifyUserJackPasswordAA() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + lastPasswordChangeStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); modifyUserChangePassword(USER_JACK_OID, USER_PASSWORD_AA_CLEAR, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertPartialError(result); - + lastPasswordChangeEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertLinks(userJack, 4); @@ -905,26 +905,26 @@ public void test142ModifyUserJackPasswordAA() throws Exception { // Check account in dummy resource (yellow): password is too short for this, original password should remain there assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyPasswordConditional(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_1_CLEAR); - + // Check account in dummy resource (red) assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyPassword(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_AA_CLEAR); - + // User and default dummy account should have unchanged passwords assertUserPassword(userJack, USER_PASSWORD_AA_CLEAR); assertDummyPassword(ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_AA_CLEAR); // this one is not changed assertDummyPassword(RESOURCE_DUMMY_UGLY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_EMPLOYEE_NUMBER_NEW_GOOD); - + assertPasswordHistoryEntries(userJack); - + displayPasswordNotifications(); assertPasswordNotifications(2); assertHasPasswordNotification(null, USER_JACK_USERNAME, USER_PASSWORD_AA_CLEAR); assertHasPasswordNotification(RESOURCE_DUMMY_RED_NAME, USER_JACK_USERNAME, USER_PASSWORD_AA_CLEAR); } - + @Test public void test200ApplyPasswordPolicy() throws Exception { final String TEST_NAME = "test200ApplyPasswordPolicy"; @@ -934,21 +934,21 @@ public void test200ApplyPasswordPolicy() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + // WHEN displayWhen(TEST_NAME); applyPasswordPolicy(PASSWORD_POLICY_GLOBAL_OID, getSecurityPolicyOid(), task, result); modifyObjectReplaceProperty(SecurityPolicyType.class, getSecurityPolicyOid(), new ItemPath(SecurityPolicyType.F_CREDENTIALS, CredentialsPolicyType.F_PASSWORD, PasswordCredentialsPolicyType.F_HISTORY_LENGTH), task, result, 3); - + // THEN displayThen(TEST_NAME); assertSuccess(result); } - + // test202 is in subclasses. Different behavior for encryption and hashing - + /** * Unassign red account. Red resource has a strong password mapping. That would cause a lot * of trouble. We have tested that enough. @@ -962,46 +962,46 @@ public void test204UnassignAccountRed() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User before", userBefore); assertLinks(userBefore, 4); - + // Red resource has disable-instead-of-delete. So we need to be brutal to get rid of the red account ObjectDelta userDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_RED_OID, null, false); ObjectDelta shadowDelta = ObjectDelta.createDeleteDelta(ShadowType.class, accountJackRedOid, prismContext); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta, shadowDelta), null, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", userAfter); assertLinks(userAfter, 3); assertNotLinked(userAfter, accountJackRedOid); assertNoDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME); - + // Check account in dummy resource (yellow): password is too short for this, original password should remain there assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyPasswordConditional(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_1_CLEAR); - + // User and default dummy account should have unchanged passwords assertUserPassword(userAfter, USER_PASSWORD_AA_CLEAR); assertDummyPassword(ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_AA_CLEAR); // this one is not changed assertDummyPassword(RESOURCE_DUMMY_UGLY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_EMPLOYEE_NUMBER_NEW_GOOD); - + assertPasswordHistoryEntries(userAfter); - + assertNoPasswordNotifications(); } - + /** * Reconcile user after password policy change. Nothing should be changed in the user. * Password history should still be empty. We haven't changed the password yet. @@ -1016,18 +1016,18 @@ public void test206ReconcileUserJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User before", userBefore); assertLinks(userBefore, 3); - + // WHEN reconcileUser(USER_JACK_OID, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", userAfter); assertLinks(userAfter, 3); @@ -1035,19 +1035,19 @@ public void test206ReconcileUserJack() throws Exception { // Check account in dummy resource (yellow): password is too short for this, original password should remain there assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyPasswordConditional(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_1_CLEAR); - + // User and default dummy account should have unchanged passwords assertUserPassword(userAfter, USER_PASSWORD_AA_CLEAR); assertDummyPassword(ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_AA_CLEAR); // this one is not changed assertDummyPassword(RESOURCE_DUMMY_UGLY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_EMPLOYEE_NUMBER_NEW_GOOD); - + assertPasswordHistoryEntries(userAfter); - + assertNoPasswordNotifications(); } - + /** * Change to password that complies with password policy. */ @@ -1056,7 +1056,7 @@ public void test210ModifyUserJackPasswordGood() throws Exception { doTestModifyUserJackPasswordSuccessWithHistory("test210ModifyUserJackPasswordGood", USER_PASSWORD_VALID_1, USER_PASSWORD_AA_CLEAR); } - + /** * Reconcile user. Nothing should be changed. * MID-3567 @@ -1070,17 +1070,17 @@ public void test212ReconcileUserJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + // WHEN reconcileUser(USER_JACK_OID, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + assertJackPasswordsWithHistory(USER_PASSWORD_VALID_1, USER_PASSWORD_AA_CLEAR); } - + /** * Recompute user. Nothing should be changed. * MID-3567 @@ -1094,17 +1094,17 @@ public void test214RecomputeUserJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + // WHEN recomputeUser(USER_JACK_OID, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + assertJackPasswordsWithHistory(USER_PASSWORD_VALID_1, USER_PASSWORD_AA_CLEAR); } - + /** * Change to password that violates the password policy (but is still OK for yellow resource). */ @@ -1113,7 +1113,7 @@ public void test220ModifyUserJackPasswordBadA() throws Exception { doTestModifyUserJackPasswordFailureWithHistory("test220ModifyUserJackPasswordBadA", USER_PASSWORD_1_CLEAR, USER_PASSWORD_VALID_1, USER_PASSWORD_AA_CLEAR); } - + /** * Change to password that violates the password policy (but is still OK for yellow resource). * Use a different delta (container delta instead of property delta). @@ -1128,35 +1128,35 @@ public void test222ModifyUserJackPasswordBadContainer() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + ProtectedStringType userPasswordPs = new ProtectedStringType(); userPasswordPs.setClearValue(USER_PASSWORD_1_CLEAR); PasswordType passwordType = new PasswordType(); passwordType.setValue(userPasswordPs); - - ObjectDelta objectDelta = ObjectDelta.createModificationReplaceContainer(UserType.class, USER_JACK_OID, + + ObjectDelta objectDelta = ObjectDelta.createModificationReplaceContainer(UserType.class, USER_JACK_OID, new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD), prismContext, passwordType); Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); - + try { // WHEN modelService.executeChanges(deltas, null, task, result); - + AssertJUnit.fail("Unexpected success"); - + } catch (PolicyViolationException e) { // This is expected display("Exected exception", e); } - + // THEN result.computeStatus(); TestUtil.assertFailure(result); - + assertJackPasswordsWithHistory(USER_PASSWORD_VALID_1, USER_PASSWORD_AA_CLEAR); } - + /** * Change to password that violates the password policy (contains username) * MID-1657 @@ -1166,7 +1166,7 @@ public void test224ModifyUserJackPasswordBadJack() throws Exception { doTestModifyUserJackPasswordFailureWithHistory("test224ModifyUserJackPasswordBadJack", USER_PASSWORD_JACK_CLEAR, USER_PASSWORD_VALID_1, USER_PASSWORD_AA_CLEAR); } - + /** * Change to password that violates the password policy (contains family name) * MID-1657 @@ -1176,9 +1176,9 @@ public void test226ModifyUserJackPasswordBadSparrow() throws Exception { doTestModifyUserJackPasswordFailureWithHistory("test226ModifyUserJackPasswordBadSparrow", USER_PASSWORD_SPARROW_CLEAR, USER_PASSWORD_VALID_1, USER_PASSWORD_AA_CLEAR); } - + /** - * Change to password that complies with password policy. Again. See that + * Change to password that complies with password policy. Again. See that * the change is applied correctly and that it is included in the history. */ @Test @@ -1186,7 +1186,7 @@ public void test230ModifyUserJackPasswordGoodAgain() throws Exception { doTestModifyUserJackPasswordSuccessWithHistory("test230ModifyUserJackPasswordGoodAgain", USER_PASSWORD_VALID_2, USER_PASSWORD_AA_CLEAR, USER_PASSWORD_VALID_1); } - + /** * Change to password that is good but it is the same as current password. */ @@ -1195,7 +1195,7 @@ public void test235ModifyUserJackPasswordGoodSameAsCurrent() throws Exception { doTestModifyUserJackPasswordFailureWithHistory("test235ModifyUserJackPasswordGoodSameAsCurrent", USER_PASSWORD_VALID_2, USER_PASSWORD_VALID_2, USER_PASSWORD_AA_CLEAR, USER_PASSWORD_VALID_1); } - + /** * Change to password that is good but it is already in the history. */ @@ -1204,7 +1204,7 @@ public void test236ModifyUserJackPasswordGoodInHistory() throws Exception { doTestModifyUserJackPasswordFailureWithHistory("test236ModifyUserJackPasswordGoodInHistory", USER_PASSWORD_VALID_1, USER_PASSWORD_VALID_2, USER_PASSWORD_AA_CLEAR, USER_PASSWORD_VALID_1); } - + /** * Change to password that is bad and it is already in the history. */ @@ -1213,7 +1213,7 @@ public void test237ModifyUserJackPasswordBadInHistory() throws Exception { doTestModifyUserJackPasswordFailureWithHistory("test237ModifyUserJackPasswordBadInHistory", USER_PASSWORD_AA_CLEAR, USER_PASSWORD_VALID_2, USER_PASSWORD_AA_CLEAR, USER_PASSWORD_VALID_1); } - + /** * Change to password that complies with password policy. Again. * This time there are enough passwords in the history. So the history should @@ -1224,7 +1224,7 @@ public void test240ModifyUserJackPasswordGoodAgainOverHistory() throws Exception doTestModifyUserJackPasswordSuccessWithHistory("test240ModifyUserJackPasswordGoodAgainOverHistory", USER_PASSWORD_VALID_3, USER_PASSWORD_VALID_1, USER_PASSWORD_VALID_2); } - + /** * Change to password that complies with password policy. Again. * This time there are enough passwords in the history. So the history should @@ -1235,7 +1235,7 @@ public void test241ModifyUserJackPasswordGoodAgainOverHistoryAgain() throws Exce doTestModifyUserJackPasswordSuccessWithHistory("test241ModifyUserJackPasswordGoodAgainOverHistoryAgain", USER_PASSWORD_VALID_4, USER_PASSWORD_VALID_2, USER_PASSWORD_VALID_3); } - + /** * Reuse old password. Now the password should be out of the history, so * the system should allow its reuse. @@ -1245,8 +1245,8 @@ public void test248ModifyUserJackPasswordGoodReuse() throws Exception { doTestModifyUserJackPasswordSuccessWithHistory("test248ModifyUserJackPasswordGoodReuse", USER_PASSWORD_VALID_1, USER_PASSWORD_VALID_3, USER_PASSWORD_VALID_4); } - - private void doTestModifyUserJackPasswordSuccessWithHistory(final String TEST_NAME, + + private void doTestModifyUserJackPasswordSuccessWithHistory(final String TEST_NAME, String newPassword, String... expectedPasswordHistory) throws Exception { displayTestTitle(TEST_NAME); @@ -1254,27 +1254,27 @@ private void doTestModifyUserJackPasswordSuccessWithHistory(final String TEST_NA Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + lastPasswordChangeStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modifyUserChangePassword(USER_JACK_OID, newPassword, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + lastPasswordChangeEnd = clock.currentTimeXMLGregorianCalendar(); - + assertJackPasswordsWithHistory(newPassword, expectedPasswordHistory); - + displayPasswordNotifications(); assertPasswordNotifications(2); assertHasPasswordNotification(null, USER_JACK_USERNAME, newPassword); assertHasPasswordNotification(RESOURCE_DUMMY_YELLOW_NAME, USER_JACK_USERNAME, newPassword); } - - private void doTestModifyUserJackPasswordFailureWithHistory(final String TEST_NAME, + + private void doTestModifyUserJackPasswordFailureWithHistory(final String TEST_NAME, String newPassword, String oldPassword, String... expectedPasswordHistory) throws Exception { displayTestTitle(TEST_NAME); @@ -1282,27 +1282,27 @@ private void doTestModifyUserJackPasswordFailureWithHistory(final String TEST_NA Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + try { // WHEN modifyUserChangePassword(USER_JACK_OID, newPassword, task, result); - + AssertJUnit.fail("Unexpected success"); - + } catch (PolicyViolationException e) { // This is expected display("Exected exception", e); } - + // THEN result.computeStatus(); TestUtil.assertFailure(result); - + assertJackPasswordsWithHistory(oldPassword, expectedPasswordHistory); - + assertNoPasswordNotifications(); } - + private void assertJackPasswordsWithHistory(String expectedCurrentPassword, String... expectedPasswordHistory) throws Exception { PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); @@ -1311,18 +1311,18 @@ private void assertJackPasswordsWithHistory(String expectedCurrentPassword, Stri assertUserPassword(userJack, expectedCurrentPassword); assertPasswordMetadata(userJack, false, lastPasswordChangeStart, lastPasswordChangeEnd); - + assertDummyPassword(ACCOUNT_JACK_DUMMY_USERNAME, expectedCurrentPassword); - + assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyPassword(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, expectedCurrentPassword); - + // this one is not changed assertDummyPassword(RESOURCE_DUMMY_UGLY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_EMPLOYEE_NUMBER_NEW_GOOD); - + assertPasswordHistoryEntries(userJack, expectedPasswordHistory); } - + // TODO: add user with password that violates the policy /** @@ -1384,7 +1384,7 @@ public void test300TwoParentOrgRefs() throws Exception { assertDummyPassword(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_VALID_1); assertDummyPassword(RESOURCE_DUMMY_UGLY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_EMPLOYEE_NUMBER_NEW_GOOD); - + assertNoPasswordNotifications(); } @@ -1438,7 +1438,7 @@ public void test310PreparePasswordStrengthTests() throws Exception { // this one is not changed assertDummyPassword(RESOURCE_DUMMY_UGLY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_EMPLOYEE_NUMBER_NEW_GOOD); - + if (isPasswordEncryption()) { assertPasswordNotifications(2); assertHasPasswordNotification(RESOURCE_DUMMY_RED_NAME, USER_JACK_USERNAME, USER_PASSWORD_VALID_1); @@ -1448,7 +1448,7 @@ public void test310PreparePasswordStrengthTests() throws Exception { assertNoPasswordNotifications(); } } - + @Test public void test312ChangeUserPassword() throws Exception { final String TEST_NAME = "test312ChangeUserPassword"; @@ -1488,7 +1488,7 @@ public void test312ChangeUserPassword() throws Exception { // this one is not changed assertDummyPassword(RESOURCE_DUMMY_UGLY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_EMPLOYEE_NUMBER_NEW_GOOD); - + displayPasswordNotifications(); if (isPasswordEncryption()) { assertPasswordNotifications(2); @@ -1502,9 +1502,9 @@ public void test312ChangeUserPassword() throws Exception { assertHasPasswordNotification(RESOURCE_DUMMY_BLUE_NAME, USER_JACK_USERNAME, USER_PASSWORD_VALID_2); } } - + protected abstract void assert31xBluePasswordAfterAssignment(PrismObject userAfter) throws Exception; - + protected abstract void assert31xBluePasswordAfterPasswordChange(PrismObject userAfter) throws Exception; /* @@ -1533,9 +1533,9 @@ public void test314RemovePassword() throws Exception { display("User after change execution", userAfter); assertNull("User password is not null", userAfter.asObjectable().getCredentials().getPassword().getValue()); assertLinks(userAfter, 4); - + // password mapping is normal - assertDummyPassword(ACCOUNT_JACK_DUMMY_USERNAME, null); + assertDummyPassword(ACCOUNT_JACK_DUMMY_USERNAME, null); // password mapping is strong assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_FULL_NAME, true); @@ -1544,15 +1544,15 @@ public void test314RemovePassword() throws Exception { // password mapping is weak here - so no change is expected assertDummyAccount(RESOURCE_DUMMY_BLUE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_FULL_NAME, true); assert31xBluePasswordAfterPasswordChange(userAfter); - + assertNoDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME); // this one is not changed assertDummyPassword(RESOURCE_DUMMY_UGLY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_EMPLOYEE_NUMBER_NEW_GOOD); - + assertNoPasswordNotifications(); } - + /* * User has no password. There is an inbound/generate mapping from default dummy * resource. This should kick in now and set a random password. @@ -1580,11 +1580,11 @@ public void test316UserRecompute() throws Exception { display("User after change execution", userAfter); assertNotNull("User password is still null", userAfter.asObjectable().getCredentials().getPassword().getValue()); assertLinks(userAfter, 4); - + // TODO: why are the resource passwords null ??? - + // password mapping is normal - assertDummyPassword(ACCOUNT_JACK_DUMMY_USERNAME, null); + assertDummyPassword(ACCOUNT_JACK_DUMMY_USERNAME, null); // password mapping is strong assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_FULL_NAME, true); @@ -1593,12 +1593,12 @@ public void test316UserRecompute() throws Exception { // password mapping is weak here - so no change is expected assertDummyAccount(RESOURCE_DUMMY_BLUE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_FULL_NAME, true); assert31xBluePasswordAfterPasswordChange(userAfter); - + assertNoDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME); // this one is not changed assertDummyPassword(RESOURCE_DUMMY_UGLY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_EMPLOYEE_NUMBER_NEW_GOOD); - + displayPasswordNotifications(); assertNoPasswordNotifications(); } @@ -1644,14 +1644,14 @@ public void test318ChangeUserPassword() throws Exception { // this one is not changed assertDummyPassword(RESOURCE_DUMMY_UGLY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_EMPLOYEE_NUMBER_NEW_GOOD); - + displayPasswordNotifications(); assertPasswordNotifications(2); assertHasPasswordNotification(null, USER_JACK_USERNAME, USER_PASSWORD_VALID_3); assertHasPasswordNotification(RESOURCE_DUMMY_RED_NAME, USER_JACK_USERNAME, USER_PASSWORD_VALID_3); // not BLUE, it already has a password } - + @Test public void test320ChangeEmployeeNumber() throws Exception { final String TEST_NAME = "test320ChangeEmployeeNumber"; @@ -1681,7 +1681,7 @@ public void test320ChangeEmployeeNumber() throws Exception { assertDummyPassword(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_VALID_3); assertDummyPassword(RESOURCE_DUMMY_UGLY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "emp0000"); - + assertSinglePasswordNotification(RESOURCE_DUMMY_UGLY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "emp0000"); } @@ -1714,10 +1714,10 @@ public void test330RemoveEmployeeNumber() throws Exception { assertDummyPassword(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_VALID_3); assertDummyPassword(RESOURCE_DUMMY_UGLY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, null); - + assertNoPasswordNotifications(); } - + /** * Add user with password and an assignment. check that the account is provisioned and has password. * Tests proper initial cleartext password handling in all cases. @@ -1730,7 +1730,7 @@ public void test400AddUserRappWithAssignment() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = PrismTestUtil.parseObject(USER_RAPP_FILE); AssignmentType assignmentType = createConstructionAssignment(RESOURCE_DUMMY_OID, null, null); UserType userBeforeType = userBefore.asObjectable(); @@ -1753,23 +1753,23 @@ public void test400AddUserRappWithAssignment() throws Exception { PrismObject userAfter = getUser(USER_RAPP_OID); display("User after", userAfter); String accountOid = getSingleLinkOid(userAfter); - + PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountOid, USER_RAPP_USERNAME); assertShadowLifecycle(accountShadow, true); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, USER_RAPP_USERNAME, USER_RAPP_FULLNAME); assertShadowLifecycle(accountModel, true); - + // Check account in dummy resource assertDefaultDummyAccount(USER_RAPP_USERNAME, USER_RAPP_FULLNAME, true); assertDummyPassword(null, USER_RAPP_USERNAME, USER_PASSWORD_VALID_1); - + assertSinglePasswordNotification(null, USER_RAPP_USERNAME, USER_PASSWORD_VALID_1); } - + /** * Make sure recompute does not destroy the situation. */ @@ -1782,7 +1782,7 @@ public void test401UserRappRecompute() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_RAPP_OID, task, result); @@ -1794,23 +1794,23 @@ public void test401UserRappRecompute() throws Exception { PrismObject userAfter = getUser(USER_RAPP_OID); display("User after", userAfter); String accountOid = getSingleLinkOid(userAfter); - + PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountOid, USER_RAPP_USERNAME); assertShadowLifecycle(accountShadow, true); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountOid, USER_RAPP_USERNAME, USER_RAPP_FULLNAME); assertShadowLifecycle(accountModel, true); - + // Check account in dummy resource assertDefaultDummyAccount(USER_RAPP_USERNAME, USER_RAPP_FULLNAME, true); assertDummyPassword(null, USER_RAPP_USERNAME, USER_PASSWORD_VALID_1); - + assertNoPasswordNotifications(); } - + /** * add new assignment to the user, check that account is provisioned and has correct lifecycle */ @@ -1823,7 +1823,7 @@ public void test402AssignRappDummyRed() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + PrismObject userBefore = getUser(USER_RAPP_OID); display("User before", userBefore); @@ -1838,7 +1838,7 @@ public void test402AssignRappDummyRed() throws Exception { PrismObject userAfter = getUser(USER_RAPP_OID); display("User after", userAfter); assertLinks(userAfter, 2); - + String accountDefaultOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_OID); String accountRedOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_RED_OID); @@ -1851,7 +1851,7 @@ public void test402AssignRappDummyRed() throws Exception { display("Repo shadow RED", accountShadowRed); assertAccountShadowRepo(accountShadowRed, accountRedOid, USER_RAPP_USERNAME, getDummyResourceType(RESOURCE_DUMMY_RED_NAME)); assertShadowLifecycle(accountShadowRed, false); - + PrismObject accountModelRed = modelService.getObject(ShadowType.class, accountRedOid, null, task, result); display("Model shadow RED", accountModelRed); assertAccountShadowModel(accountModelRed, accountRedOid, USER_RAPP_USERNAME, getDummyResourceType(RESOURCE_DUMMY_RED_NAME)); @@ -1861,20 +1861,20 @@ public void test402AssignRappDummyRed() throws Exception { PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountDefaultOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountDefaultOid, USER_RAPP_USERNAME); assertShadowLifecycle(accountShadow, null); - + PrismObject accountModel = modelService.getObject(ShadowType.class, accountDefaultOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountDefaultOid, USER_RAPP_USERNAME, USER_RAPP_FULLNAME); assertShadowLifecycle(accountModel, null); - + assertUserPassword(userAfter, USER_PASSWORD_VALID_1); assertDefaultDummyAccount(USER_RAPP_USERNAME, USER_RAPP_FULLNAME, true); assertDummyPassword(null, USER_RAPP_USERNAME, USER_PASSWORD_VALID_1); - + displayAllNotifications(); assertSinglePasswordNotificationConditional(RESOURCE_DUMMY_RED_NAME, USER_RAPP_USERNAME, USER_PASSWORD_VALID_1); assertAccountActivationNotification(RESOURCE_DUMMY_RED_NAME, USER_RAPP_USERNAME); } - + /** * Make sure recompute does not destroy the situation. */ @@ -1887,7 +1887,7 @@ public void test403UserRappRecompute() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + PrismObject userBefore = getUser(USER_RAPP_OID); display("User before", userBefore); @@ -1902,7 +1902,7 @@ public void test403UserRappRecompute() throws Exception { PrismObject userAfter = getUser(USER_RAPP_OID); display("User after", userAfter); assertLinks(userAfter, 2); - + String accountDefaultOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_OID); String accountRedOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_RED_OID); @@ -1915,7 +1915,7 @@ public void test403UserRappRecompute() throws Exception { display("Repo shadow RED", accountShadowRed); assertAccountShadowRepo(accountShadowRed, accountRedOid, USER_RAPP_USERNAME, getDummyResourceType(RESOURCE_DUMMY_RED_NAME)); assertShadowLifecycle(accountShadowRed, false); - + PrismObject accountModelRed = modelService.getObject(ShadowType.class, accountRedOid, null, task, result); display("Model shadow RED", accountModelRed); assertAccountShadowModel(accountModelRed, accountRedOid, USER_RAPP_USERNAME, getDummyResourceType(RESOURCE_DUMMY_RED_NAME)); @@ -1925,18 +1925,18 @@ public void test403UserRappRecompute() throws Exception { PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountDefaultOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountDefaultOid, USER_RAPP_USERNAME); assertShadowLifecycle(accountShadow, null); - + PrismObject accountModel = modelService.getObject(ShadowType.class, accountDefaultOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountDefaultOid, USER_RAPP_USERNAME, USER_RAPP_FULLNAME); assertShadowLifecycle(accountModel, null); - + assertUserPassword(userAfter, USER_PASSWORD_VALID_1); assertDefaultDummyAccount(USER_RAPP_USERNAME, USER_RAPP_FULLNAME, true); assertDummyPassword(null, USER_RAPP_USERNAME, USER_PASSWORD_VALID_1); - + assertNoPasswordNotifications(); } - + /** * initialize the account (password and lifecycle delta), check account password and lifecycle */ @@ -1949,7 +1949,7 @@ public void test404InitializeRappDummyRed() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + PrismObject userBefore = getUser(USER_RAPP_OID); display("User before", userBefore); String accountRedOid = getLinkRefOid(userBefore, RESOURCE_DUMMY_RED_OID); @@ -1959,7 +1959,7 @@ public void test404InitializeRappDummyRed() throws Exception { passwordPs.setClearValue(USER_PASSWORD_VALID_1); shadowDelta.addModificationReplaceProperty(SchemaConstants.PATH_PASSWORD_VALUE, passwordPs); shadowDelta.addModificationReplaceProperty(ObjectType.F_LIFECYCLE_STATE, SchemaConstants.LIFECYCLE_ACTIVE); - + // WHEN TestUtil.displayWhen(TEST_NAME); executeChanges(shadowDelta, null, task, result); @@ -1972,7 +1972,7 @@ public void test404InitializeRappDummyRed() throws Exception { PrismObject userAfter = getUser(USER_RAPP_OID); display("User after", userAfter); assertLinks(userAfter, 2); - + String accountDefaultOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_OID); getLinkRefOid(userAfter, RESOURCE_DUMMY_RED_OID); @@ -1985,7 +1985,7 @@ public void test404InitializeRappDummyRed() throws Exception { display("Repo shadow RED", accountShadowRed); assertAccountShadowRepo(accountShadowRed, accountRedOid, USER_RAPP_USERNAME, getDummyResourceType(RESOURCE_DUMMY_RED_NAME)); assertShadowLifecycle(accountShadowRed, SchemaConstants.LIFECYCLE_ACTIVE); - + PrismObject accountModelRed = modelService.getObject(ShadowType.class, accountRedOid, null, task, result); display("Model shadow RED", accountModelRed); assertAccountShadowModel(accountModelRed, accountRedOid, USER_RAPP_USERNAME, getDummyResourceType(RESOURCE_DUMMY_RED_NAME)); @@ -1995,15 +1995,15 @@ public void test404InitializeRappDummyRed() throws Exception { PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountDefaultOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountDefaultOid, USER_RAPP_USERNAME); assertShadowLifecycle(accountShadow, null); - + PrismObject accountModel = modelService.getObject(ShadowType.class, accountDefaultOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountDefaultOid, USER_RAPP_USERNAME, USER_RAPP_FULLNAME); assertShadowLifecycle(accountModel, null); - + assertUserPassword(userAfter, USER_PASSWORD_VALID_1); assertDefaultDummyAccount(USER_RAPP_USERNAME, USER_RAPP_FULLNAME, true); assertDummyPassword(null, USER_RAPP_USERNAME, USER_PASSWORD_VALID_1); - + assertSingleInitializationPasswordNotification(RESOURCE_DUMMY_RED_NAME, USER_RAPP_USERNAME, USER_PASSWORD_VALID_1); } @@ -2019,7 +2019,7 @@ public void test405UserRappRecompute() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + PrismObject userBefore = getUser(USER_RAPP_OID); display("User before", userBefore); @@ -2035,7 +2035,7 @@ public void test405UserRappRecompute() throws Exception { PrismObject userAfter = getUser(USER_RAPP_OID); display("User after", userAfter); assertLinks(userAfter, 2); - + String accountDefaultOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_OID); String accountRedOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_RED_OID); @@ -2048,7 +2048,7 @@ public void test405UserRappRecompute() throws Exception { display("Repo shadow RED", accountShadowRed); assertAccountShadowRepo(accountShadowRed, accountRedOid, USER_RAPP_USERNAME, getDummyResourceType(RESOURCE_DUMMY_RED_NAME)); assertShadowLifecycle(accountShadowRed, SchemaConstants.LIFECYCLE_ACTIVE); - + PrismObject accountModelRed = modelService.getObject(ShadowType.class, accountRedOid, null, task, result); display("Model shadow RED", accountModelRed); assertAccountShadowModel(accountModelRed, accountRedOid, USER_RAPP_USERNAME, getDummyResourceType(RESOURCE_DUMMY_RED_NAME)); @@ -2058,18 +2058,18 @@ public void test405UserRappRecompute() throws Exception { PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountDefaultOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountDefaultOid, USER_RAPP_USERNAME); assertShadowLifecycle(accountShadow, null); - + PrismObject accountModel = modelService.getObject(ShadowType.class, accountDefaultOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountDefaultOid, USER_RAPP_USERNAME, USER_RAPP_FULLNAME); assertShadowLifecycle(accountModel, null); - + assertUserPassword(userAfter, USER_PASSWORD_VALID_1); assertDefaultDummyAccount(USER_RAPP_USERNAME, USER_RAPP_FULLNAME, true); assertDummyPassword(null, USER_RAPP_USERNAME, USER_PASSWORD_VALID_1); - + assertNoPasswordNotifications(); } - + /** * add new assignment to the user. This resource has explicit lifecycle mapping. */ @@ -2082,7 +2082,7 @@ public void test410AssignRappDummyLifecycle() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + PrismObject userBefore = getUser(USER_RAPP_OID); display("User before", userBefore); @@ -2098,9 +2098,9 @@ public void test410AssignRappDummyLifecycle() throws Exception { PrismObject userAfter = getUser(USER_RAPP_OID); display("User after", userAfter); assertLinks(userAfter, 3); - + String accountLifecycleOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_LIFECYCLE_OID); - + assertDummyAccount(RESOURCE_DUMMY_LIFECYCLE_NAME, USER_RAPP_USERNAME, USER_RAPP_FULLNAME, true); assertDummyPasswordConditional(RESOURCE_DUMMY_LIFECYCLE_NAME, USER_RAPP_USERNAME, USER_PASSWORD_VALID_1); @@ -2110,16 +2110,16 @@ public void test410AssignRappDummyLifecycle() throws Exception { assertShadowLifecycle(accountShadowLifecycle, false); // assertShadowLifecycle(accountShadowLifecycle, SchemaConstants.LIFECYCLE_ACTIVE); - + assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_RAPP_USERNAME, USER_RAPP_FULLNAME, true); assertDummyPassword(RESOURCE_DUMMY_RED_NAME, USER_RAPP_USERNAME, USER_PASSWORD_VALID_1); assertUserPassword(userAfter, USER_PASSWORD_VALID_1); assertDefaultDummyAccount(USER_RAPP_USERNAME, USER_RAPP_FULLNAME, true); assertDummyPassword(null, USER_RAPP_USERNAME, USER_PASSWORD_VALID_1); - + assertSinglePasswordNotificationConditional(RESOURCE_DUMMY_LIFECYCLE_NAME, USER_RAPP_USERNAME, USER_PASSWORD_VALID_1); } - + @Test public void test412InitializeRappDummyLifecycle() throws Exception { final String TEST_NAME = "test412InitializeRappDummyLifecycle"; @@ -2129,7 +2129,7 @@ public void test412InitializeRappDummyLifecycle() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + PrismObject userBefore = getUser(USER_RAPP_OID); display("User before", userBefore); String accountLifecycleOid = getLinkRefOid(userBefore, RESOURCE_DUMMY_LIFECYCLE_OID); @@ -2139,7 +2139,7 @@ public void test412InitializeRappDummyLifecycle() throws Exception { passwordPs.setClearValue(USER_PASSWORD_VALID_1); shadowDelta.addModificationReplaceProperty(SchemaConstants.PATH_PASSWORD_VALUE, passwordPs); shadowDelta.addModificationReplaceProperty(ObjectType.F_LIFECYCLE_STATE, SchemaConstants.LIFECYCLE_ACTIVE); - + // WHEN TestUtil.displayWhen(TEST_NAME); executeChanges(shadowDelta, null, task, result); @@ -2152,9 +2152,9 @@ public void test412InitializeRappDummyLifecycle() throws Exception { PrismObject userAfter = getUser(USER_RAPP_OID); display("User after", userAfter); assertLinks(userAfter, 3); - + accountLifecycleOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_LIFECYCLE_OID); - + assertDummyAccount(RESOURCE_DUMMY_LIFECYCLE_NAME, USER_RAPP_USERNAME, USER_RAPP_FULLNAME, true); assertDummyPassword(RESOURCE_DUMMY_LIFECYCLE_NAME, USER_RAPP_USERNAME, USER_PASSWORD_VALID_1); @@ -2168,15 +2168,15 @@ public void test412InitializeRappDummyLifecycle() throws Exception { assertUserPassword(userAfter, USER_PASSWORD_VALID_1); assertDefaultDummyAccount(USER_RAPP_USERNAME, USER_RAPP_FULLNAME, true); assertDummyPassword(null, USER_RAPP_USERNAME, USER_PASSWORD_VALID_1); - + // RED shadows String accountRedOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_RED_OID); - + PrismObject accountShadowRed = repositoryService.getObject(ShadowType.class, accountRedOid, null, result); display("Repo shadow RED", accountShadowRed); assertAccountShadowRepo(accountShadowRed, accountRedOid, USER_RAPP_USERNAME, getDummyResourceType(RESOURCE_DUMMY_RED_NAME)); assertShadowLifecycle(accountShadowRed, SchemaConstants.LIFECYCLE_ACTIVE); - + PrismObject accountModelRed = modelService.getObject(ShadowType.class, accountRedOid, null, task, result); display("Model shadow RED", accountModelRed); assertAccountShadowModel(accountModelRed, accountRedOid, USER_RAPP_USERNAME, getDummyResourceType(RESOURCE_DUMMY_RED_NAME)); @@ -2184,7 +2184,7 @@ public void test412InitializeRappDummyLifecycle() throws Exception { // DEFAULT shadows String accountDefaultOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_OID); - + PrismObject accountModel = modelService.getObject(ShadowType.class, accountDefaultOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountDefaultOid, USER_RAPP_USERNAME, USER_RAPP_FULLNAME); assertShadowLifecycle(accountModel, null); @@ -2192,7 +2192,7 @@ public void test412InitializeRappDummyLifecycle() throws Exception { PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountDefaultOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountDefaultOid, USER_RAPP_USERNAME); assertShadowLifecycle(accountShadow, null); - + assertSingleInitializationPasswordNotification(RESOURCE_DUMMY_LIFECYCLE_NAME, USER_RAPP_USERNAME, USER_PASSWORD_VALID_1); } @@ -2206,7 +2206,7 @@ public void test414UserRappRecompute() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + PrismObject userBefore = getUser(USER_RAPP_OID); display("User before", userBefore); @@ -2221,7 +2221,7 @@ public void test414UserRappRecompute() throws Exception { PrismObject userAfter = getUser(USER_RAPP_OID); display("User after", userAfter); assertLinks(userAfter, 3); - + assertDummyAccount(RESOURCE_DUMMY_LIFECYCLE_NAME, USER_RAPP_USERNAME, USER_RAPP_FULLNAME, true); assertDummyPassword(RESOURCE_DUMMY_LIFECYCLE_NAME, USER_RAPP_USERNAME, USER_PASSWORD_VALID_1); @@ -2230,24 +2230,24 @@ public void test414UserRappRecompute() throws Exception { assertUserPassword(userAfter, USER_PASSWORD_VALID_1); assertDefaultDummyAccount(USER_RAPP_USERNAME, USER_RAPP_FULLNAME, true); assertDummyPassword(null, USER_RAPP_USERNAME, USER_PASSWORD_VALID_1); - + // LIFECYCLE shadows - + String accountLifecycleOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_LIFECYCLE_OID); PrismObject accountShadowLifecycle = repositoryService.getObject(ShadowType.class, accountLifecycleOid, null, result); display("Repo shadow LIFECYCLE", accountShadowLifecycle); assertAccountShadowRepo(accountShadowLifecycle, accountLifecycleOid, USER_RAPP_USERNAME, getDummyResourceType(RESOURCE_DUMMY_LIFECYCLE_NAME)); assertShadowLifecycle(accountShadowLifecycle, SchemaConstants.LIFECYCLE_ACTIVE); - + // RED shadows String accountRedOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_RED_OID); - + PrismObject accountShadowRed = repositoryService.getObject(ShadowType.class, accountRedOid, null, result); display("Repo shadow RED", accountShadowRed); assertAccountShadowRepo(accountShadowRed, accountRedOid, USER_RAPP_USERNAME, getDummyResourceType(RESOURCE_DUMMY_RED_NAME)); assertShadowLifecycle(accountShadowRed, SchemaConstants.LIFECYCLE_ACTIVE); - + PrismObject accountModelRed = modelService.getObject(ShadowType.class, accountRedOid, null, task, result); display("Model shadow RED", accountModelRed); assertAccountShadowModel(accountModelRed, accountRedOid, USER_RAPP_USERNAME, getDummyResourceType(RESOURCE_DUMMY_RED_NAME)); @@ -2255,7 +2255,7 @@ public void test414UserRappRecompute() throws Exception { // DEFAULT shadows String accountDefaultOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_OID); - + PrismObject accountModel = modelService.getObject(ShadowType.class, accountDefaultOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountDefaultOid, USER_RAPP_USERNAME, USER_RAPP_FULLNAME); assertShadowLifecycle(accountModel, null); @@ -2276,7 +2276,7 @@ public void test416UserRappEmployeeTypeWreck() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + PrismObject userBefore = getUser(USER_RAPP_OID); display("User before", userBefore); @@ -2291,7 +2291,7 @@ public void test416UserRappEmployeeTypeWreck() throws Exception { PrismObject userAfter = getUser(USER_RAPP_OID); display("User after", userAfter); assertLinks(userAfter, 3); - + assertDummyAccount(RESOURCE_DUMMY_LIFECYCLE_NAME, USER_RAPP_USERNAME, USER_RAPP_FULLNAME, true); assertDummyPassword(RESOURCE_DUMMY_LIFECYCLE_NAME, USER_RAPP_USERNAME, USER_PASSWORD_VALID_1); @@ -2300,24 +2300,24 @@ public void test416UserRappEmployeeTypeWreck() throws Exception { assertUserPassword(userAfter, USER_PASSWORD_VALID_1); assertDefaultDummyAccount(USER_RAPP_USERNAME, USER_RAPP_FULLNAME, true); assertDummyPassword(null, USER_RAPP_USERNAME, USER_PASSWORD_VALID_1); - + // LIFECYCLE shadows - + String accountLifecycleOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_LIFECYCLE_OID); PrismObject accountShadowLifecycle = repositoryService.getObject(ShadowType.class, accountLifecycleOid, null, result); display("Repo shadow LIFECYCLE", accountShadowLifecycle); assertAccountShadowRepo(accountShadowLifecycle, accountLifecycleOid, USER_RAPP_USERNAME, getDummyResourceType(RESOURCE_DUMMY_LIFECYCLE_NAME)); assertShadowLifecycle(accountShadowLifecycle, SchemaConstants.LIFECYCLE_ARCHIVED); - + // RED shadows String accountRedOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_RED_OID); - + PrismObject accountShadowRed = repositoryService.getObject(ShadowType.class, accountRedOid, null, result); display("Repo shadow RED", accountShadowRed); assertAccountShadowRepo(accountShadowRed, accountRedOid, USER_RAPP_USERNAME, getDummyResourceType(RESOURCE_DUMMY_RED_NAME)); assertShadowLifecycle(accountShadowRed, SchemaConstants.LIFECYCLE_ACTIVE); - + PrismObject accountModelRed = modelService.getObject(ShadowType.class, accountRedOid, null, task, result); display("Model shadow RED", accountModelRed); assertAccountShadowModel(accountModelRed, accountRedOid, USER_RAPP_USERNAME, getDummyResourceType(RESOURCE_DUMMY_RED_NAME)); @@ -2325,7 +2325,7 @@ public void test416UserRappEmployeeTypeWreck() throws Exception { // DEFAULT shadows String accountDefaultOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_OID); - + PrismObject accountModel = modelService.getObject(ShadowType.class, accountDefaultOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountDefaultOid, USER_RAPP_USERNAME, USER_RAPP_FULLNAME); assertShadowLifecycle(accountModel, null); @@ -2333,7 +2333,7 @@ public void test416UserRappEmployeeTypeWreck() throws Exception { PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountDefaultOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountDefaultOid, USER_RAPP_USERNAME); assertShadowLifecycle(accountShadow, null); - + assertNoPasswordNotifications(); } @@ -2342,19 +2342,19 @@ public void test416UserRappEmployeeTypeWreck() throws Exception { protected void assertDummyPassword(String userId, String expectedClearPassword) throws SchemaViolationException, ConflictException { assertDummyPassword(null, userId, expectedClearPassword); } - + protected void assertDummyPasswordConditional(String userId, String expectedClearPassword) throws SchemaViolationException, ConflictException { if (isPasswordEncryption()) { assertDummyPassword(null, userId, expectedClearPassword); } } - + protected void assertDummyPasswordConditional(String instance, String userId, String expectedClearPassword) throws SchemaViolationException, ConflictException { if (isPasswordEncryption()) { super.assertDummyPassword(instance, userId, expectedClearPassword); } } - + protected void assertDummyPasswordConditionalGenerated(String instance, String userId, String expectedClearPassword) throws SchemaViolationException, ConflictException { if (isPasswordEncryption()) { super.assertDummyPassword(instance, userId, expectedClearPassword); @@ -2362,13 +2362,13 @@ protected void assertDummyPasswordConditionalGenerated(String instance, String u assertDummyPasswordNotEmpty(instance, userId); } } - + protected void assertSinglePasswordNotificationConditional(String dummyResourceName, String username, String password) { if (isPasswordEncryption()) { assertSinglePasswordNotification(dummyResourceName, username, password); } } - + protected void assertSinglePasswordNotificationConditionalGenerated(String dummyResourceName, String username, String password) { if (isPasswordEncryption()) { assertSinglePasswordNotification(dummyResourceName, username, password); @@ -2376,15 +2376,15 @@ protected void assertSinglePasswordNotificationConditionalGenerated(String dummy assertSinglePasswordNotificationGenerated(dummyResourceName, username); } } - + private void assertSingleInitializationPasswordNotification(String dummyResourceName, String username, String password) { assertSinglePasswordNotification(dummyResourceName, username, password); } - + protected abstract void assertAccountActivationNotification(String dummyResourceName, String username); - + protected abstract void assertShadowLifecycle(PrismObject shadow, boolean focusCreated); - + protected void assertShadowLifecycle(PrismObject shadow, String expectedLifecycle) { if (expectedLifecycle == null) { String actualLifecycle = shadow.asObjectable().getLifecycleState(); @@ -2395,7 +2395,7 @@ protected void assertShadowLifecycle(PrismObject shadow, String expe PrismAsserts.assertPropertyValue(shadow, ObjectType.F_LIFECYCLE_STATE, expectedLifecycle); } } - + private void assertShadowPasswordMetadata(PrismObject shadow, XMLGregorianCalendar startCal, XMLGregorianCalendar endCal, boolean clearPasswordAvailable, boolean passwordCreated) { if (!clearPasswordAvailable && getPasswordStorageType() == CredentialsStorageTypeType.HASHING) { @@ -2403,7 +2403,7 @@ private void assertShadowPasswordMetadata(PrismObject shadow, } assertShadowPasswordMetadata(shadow, passwordCreated, startCal, endCal, USER_ADMINISTRATOR_OID, SchemaConstants.CHANNEL_GUI_USER_URI); } - + /** * Let's have a baseline for other 90x tests. */ @@ -2416,30 +2416,30 @@ public void test900ModifyUserElainePassword() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + lastPasswordChangeStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modifyUserChangePassword(USER_ELAINE_OID, USER_PASSWORD_VALID_1, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + lastPasswordChangeEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userAfter = getUser(USER_ELAINE_OID); display("User after", userAfter); - + assertUserPassword(userAfter, USER_PASSWORD_VALID_1); - + displayPasswordNotifications(); assertPasswordNotifications(3); assertHasPasswordNotification(null, USER_ELAINE_USERNAME, USER_PASSWORD_VALID_1); assertHasPasswordNotification(RESOURCE_DUMMY_RED_NAME, USER_ELAINE_USERNAME, USER_PASSWORD_VALID_1); assertHasPasswordNotification(RESOURCE_DUMMY_BLUE_NAME, USER_ELAINE_USERNAME, USER_PASSWORD_VALID_1); } - + @Test public void test902SetPasswordMinAge() throws Exception { final String TEST_NAME = "test900SetPasswordMinAge"; @@ -2449,25 +2449,25 @@ public void test902SetPasswordMinAge() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + // WHEN modifyObjectReplaceProperty(SecurityPolicyType.class, getSecurityPolicyOid(), new ItemPath(SecurityPolicyType.F_CREDENTIALS, CredentialsPolicyType.F_PASSWORD, PasswordCredentialsPolicyType.F_MIN_AGE), task, result, XmlTypeConverter.createDuration("PT10M")); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject securityPolicy = getObject(SecurityPolicyType.class, getSecurityPolicyOid()); display("Security policy after", securityPolicy); - PrismAsserts.assertPropertyValue(securityPolicy, - new ItemPath(SecurityPolicyType.F_CREDENTIALS, CredentialsPolicyType.F_PASSWORD, PasswordCredentialsPolicyType.F_MIN_AGE), + PrismAsserts.assertPropertyValue(securityPolicy, + new ItemPath(SecurityPolicyType.F_CREDENTIALS, CredentialsPolicyType.F_PASSWORD, PasswordCredentialsPolicyType.F_MIN_AGE), XmlTypeConverter.createDuration("PT10M")); - + assertNoPasswordNotifications(); } - + /** * Password modification is obviously before the password minAge has passed. * Therefore this should fail. @@ -2481,30 +2481,30 @@ public void test904ModifyUserElainePasswordAgain() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + try { - + // WHEN modifyUserChangePassword(USER_ELAINE_OID, USER_PASSWORD_VALID_2, task, result); - + assertNotReached(); - + } catch (PolicyViolationException e) { - + } - + // THEN result.computeStatus(); TestUtil.assertFailure(result); - + PrismObject userAfter = getUser(USER_ELAINE_OID); display("User after", userAfter); - + assertUserPassword(userAfter, USER_PASSWORD_VALID_1); - + assertNoPasswordNotifications(); } - + @Test public void test906ModifyUserElainePasswordLater() throws Exception { final String TEST_NAME = "test906ModifyUserElainePasswordLater"; @@ -2514,24 +2514,24 @@ public void test906ModifyUserElainePasswordLater() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); prepareTest(); - + clock.overrideDuration("PT15M"); - + lastPasswordChangeStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modifyUserChangePassword(USER_ELAINE_OID, USER_PASSWORD_VALID_3, task, result); - + // THEN assertSuccess(result); - + lastPasswordChangeEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userAfter = getUser(USER_ELAINE_OID); display("User after", userAfter); - + assertUserPassword(userAfter, USER_PASSWORD_VALID_3); - + displayPasswordNotifications(); assertPasswordNotifications(2); assertHasPasswordNotification(null, USER_ELAINE_USERNAME, USER_PASSWORD_VALID_3); @@ -2539,12 +2539,12 @@ public void test906ModifyUserElainePasswordLater() throws Exception { // BLUE resource already has a password } - + protected void prepareTest() throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); prepareNotifications(); } - + protected PrismObject getBlueShadow(PrismObject userAfter) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { String accountBlueOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_BLUE_OID); Task task = taskManager.createTaskInstance(AbstractPasswordTest.class.getName() + ".getBlueShadow"); @@ -2557,7 +2557,7 @@ protected PrismObject getBlueShadow(PrismObject userAfter) display("Blue shadow", shadow); return shadow; } - + protected boolean isPasswordEncryption() { return getPasswordStorageType() == CredentialsStorageTypeType.ENCRYPTION; } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/TestPasswordDefault.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/TestPasswordDefault.java index 5f6f75d1b83..516e5f98806 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/TestPasswordDefault.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/TestPasswordDefault.java @@ -41,7 +41,7 @@ /** * Password test with DEFAULT configuration of password storage. - * + * * @author semancik * */ @@ -49,11 +49,11 @@ @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class TestPasswordDefault extends AbstractPasswordTest { - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + } @Override @@ -65,7 +65,7 @@ protected String getSecurityPolicyOid() { protected void assertShadowLifecycle(PrismObject shadow, boolean focusCreated) { assertShadowLifecycle(shadow, null); } - + /** * Reconcile user after password policy change. There is a RED account with a strong password * mapping. The reconcile and the strong mapping will try to set the short password to RED account. @@ -79,25 +79,25 @@ public void test202ReconcileUserJack() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(AbstractPasswordTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User before", userBefore); assertLinks(userBefore, 4); - + try { // WHEN reconcileUser(USER_JACK_OID, task, result); - + assertNotReached(); - + } catch (PolicyViolationException e) { display("Expected exception", e); } - + // THEN result.computeStatus(); TestUtil.assertFailure(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", userAfter); assertLinks(userAfter, 4); @@ -106,28 +106,28 @@ public void test202ReconcileUserJack() throws Exception { // Check account in dummy resource (yellow): password is too short for this, original password should remain there assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyPasswordConditional(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_1_CLEAR); - + // Check account in dummy resource (red) assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyPassword(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_AA_CLEAR); - + // User and default dummy account should have unchanged passwords assertUserPassword(userAfter, USER_PASSWORD_AA_CLEAR); assertDummyPassword(ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_AA_CLEAR); // this one is not changed assertDummyPassword(RESOURCE_DUMMY_UGLY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_EMPLOYEE_NUMBER_NEW_GOOD); - + assertPasswordHistoryEntries(userAfter); } - + @Override protected void assert31xBluePasswordAfterAssignment(PrismObject userAfter) throws Exception { assertDummyPassword(RESOURCE_DUMMY_BLUE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_VALID_1); PrismObject shadow = getBlueShadow(userAfter); assertIncompleteShadowPassword(shadow); } - + @Override protected void assert31xBluePasswordAfterPasswordChange(PrismObject userAfter) throws Exception { // Password is set during the assign operation. As password mapping is weak it is never changed. @@ -141,5 +141,5 @@ protected void assertAccountActivationNotification(String dummyResourceName, Str // We have passwords here. We are not doing initialization. checkDummyTransportMessages(NOTIFIER_ACCOUNT_ACTIVATION_NAME, 0); } - + } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/TestPasswordDefaultHashing.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/TestPasswordDefaultHashing.java index 5b47ffebcae..2ce1f735457 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/TestPasswordDefaultHashing.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/TestPasswordDefaultHashing.java @@ -37,7 +37,7 @@ /** * Password test with HASHING storage for all credential types. - * + * * @author semancik * */ @@ -45,7 +45,7 @@ @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class TestPasswordDefaultHashing extends AbstractPasswordTest { - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -55,7 +55,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti protected String getSecurityPolicyOid() { return SECURITY_POLICY_DEFAULT_STORAGE_HASHING_OID; } - + @Override protected CredentialsStorageTypeType getPasswordStorageType() { return CredentialsStorageTypeType.HASHING; @@ -69,10 +69,10 @@ protected void assertShadowLifecycle(PrismObject shadow, boolean foc assertShadowLifecycle(shadow, SchemaConstants.LIFECYCLE_PROPOSED); } } - + /** * There is a RED account with a strong password - * mapping. The reconcile and the strong mapping would normally try to set the short + * mapping. The reconcile and the strong mapping would normally try to set the short * password to RED account which would fail on RED account password policy. But not today. * As we do not have password cleartexct in the user then no password change should happen. * And everything should go smoothly. @@ -85,18 +85,18 @@ public void test202ReconcileUserJack() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(AbstractPasswordTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User before", userBefore); assertLinks(userBefore, 4); - + // WHEN reconcileUser(USER_JACK_OID, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", userAfter); assertLinks(userAfter, 4); @@ -105,28 +105,28 @@ public void test202ReconcileUserJack() throws Exception { // Check account in dummy resource (yellow): password is too short for this, original password should remain there assertDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyPasswordConditional(RESOURCE_DUMMY_YELLOW_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_1_CLEAR); - + // Check account in dummy resource (red) assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyPassword(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_AA_CLEAR); - + // User and default dummy account should have unchanged passwords assertUserPassword(userAfter, USER_PASSWORD_AA_CLEAR); assertDummyPassword(ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_AA_CLEAR); // this one is not changed assertDummyPassword(RESOURCE_DUMMY_UGLY_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_JACK_EMPLOYEE_NUMBER_NEW_GOOD); - + assertPasswordHistoryEntries(userAfter); } - + @Override protected void assert31xBluePasswordAfterAssignment(PrismObject userAfter) throws Exception { assertDummyPassword(RESOURCE_DUMMY_BLUE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, null); PrismObject shadow = getBlueShadow(userAfter); assertNoShadowPassword(shadow); } - + @Override protected void assert31xBluePasswordAfterPasswordChange(PrismObject userAfter) throws Exception { // Password is set during the assign operation. As password mapping is weak it is never changed. @@ -147,5 +147,5 @@ protected void assertAccountActivationNotification(String dummyResourceName, Str fail("Link seems to be missing in "+dummyResourceName+" dummy account activation notification message : "+body); } } - + } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/TestPasswordDeprecated.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/TestPasswordDeprecated.java index fe99bdef348..11aa4d474da 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/TestPasswordDeprecated.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/TestPasswordDeprecated.java @@ -60,13 +60,13 @@ * Modified subset of AbstractPasswordTest. Just makes sure that the * password policy configured in a deprecated way is applied and that it * roughly works. It is not meant to be comprehensive. - * + * * @author semancik */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestPasswordDeprecated extends AbstractInitializedModelIntegrationTest { - + protected static final String USER_PASSWORD_0_CLEAR = "d3adM3nT3llN0Tal3s"; protected static final String USER_PASSWORD_JACK_CLEAR = "12jAcK34"; // contains username protected static final String USER_PASSWORD_SPARROW_CLEAR = "saRRow123"; // contains familyName @@ -79,19 +79,19 @@ public class TestPasswordDeprecated extends AbstractInitializedModelIntegrationT protected static final File PASSWORD_POLICY_DEPRECATED_FILE = new File(TEST_DIR, "password-policy-deprecated.xml"); protected static final String PASSWORD_POLICY_DEPRECATED_OID = "44bb6516-0d61-11e7-af71-73b639b25b04"; - + protected String accountJackOid; protected XMLGregorianCalendar lastPasswordChangeStart; protected XMLGregorianCalendar lastPasswordChangeEnd; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + importObjectFromFile(PASSWORD_POLICY_DEPRECATED_FILE); - + setGlobalSecurityPolicy(null, initResult); - + login(USER_ADMINISTRATOR_USERNAME); } @@ -104,30 +104,30 @@ public void test051ModifyUserJackPassword() throws Exception { Task task = createTask(AbstractPasswordTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserChangePassword(USER_JACK_OID, USER_PASSWORD_0_CLEAR, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - + XMLGregorianCalendar endCal = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack, "Jack Sparrow"); - + assertUserPassword(userJack, USER_PASSWORD_0_CLEAR); assertPasswordMetadata(userJack, false, startCal, endCal); // Password policy is not active yet. No history should be kept. assertPasswordHistoryEntries(userJack); } - + @Test public void test100ModifyUserJackAssignAccount() throws Exception { final String TEST_NAME = "test100ModifyUserJackAssignAccount"; @@ -137,32 +137,32 @@ public void test100ModifyUserJackAssignAccount() throws Exception { Task task = taskManager.createTaskInstance(AbstractPasswordTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + // WHEN assignAccount(USER_JACK_OID, RESOURCE_DUMMY_OID, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); accountJackOid = getSingleLinkOid(userJack); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, "jack", "Jack Sparrow"); - + // Check account in dummy resource assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); assertDummyPassword(null, ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_0_CLEAR); } - + @Test public void test200ApplyPasswordPolicy() throws Exception { final String TEST_NAME = "test200ApplyPasswordPolicy"; @@ -172,20 +172,20 @@ public void test200ApplyPasswordPolicy() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + PrismReferenceValue passPolicyRef = new PrismReferenceValue(PASSWORD_POLICY_DEPRECATED_OID, ValuePolicyType.COMPLEX_TYPE); - + // WHEN modifyObjectReplaceReference(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), new ItemPath(SystemConfigurationType.F_GLOBAL_PASSWORD_POLICY_REF), task, result, passPolicyRef); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); } - - + + /** * Change to password that complies with password policy. */ @@ -194,7 +194,7 @@ public void test210ModifyUserJackPasswordGood() throws Exception { doTestModifyUserJackPasswordSuccessWithHistory("test210ModifyUserJackPasswordGood", USER_PASSWORD_VALID_1, USER_PASSWORD_0_CLEAR); } - + /** * Reconcile user. Nothing should be changed. * MID-3567 @@ -207,17 +207,17 @@ public void test212ReconcileUserJack() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN reconcileUser(USER_JACK_OID, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + assertJackPasswordsWithHistory(USER_PASSWORD_VALID_1, USER_PASSWORD_0_CLEAR); } - + /** * Recompute user. Nothing should be changed. * MID-3567 @@ -230,17 +230,17 @@ public void test214RecomputeUserJack() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN recomputeUser(USER_JACK_OID, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + assertJackPasswordsWithHistory(USER_PASSWORD_VALID_1, USER_PASSWORD_0_CLEAR); } - + /** * Change to password that violates the password policy (but is still OK for yellow resource). */ @@ -249,7 +249,7 @@ public void test220ModifyUserJackPasswordBadA() throws Exception { doTestModifyUserJackPasswordFailureWithHistory("test220ModifyUserJackPasswordBadA", USER_PASSWORD_0_CLEAR, USER_PASSWORD_VALID_1, USER_PASSWORD_0_CLEAR); } - + /** * Change to password that violates the password policy (contains username) * MID-1657 @@ -259,9 +259,9 @@ public void test224ModifyUserJackPasswordBadJack() throws Exception { doTestModifyUserJackPasswordFailureWithHistory("test224ModifyUserJackPasswordBadJack", USER_PASSWORD_JACK_CLEAR, USER_PASSWORD_VALID_1, USER_PASSWORD_0_CLEAR); } - + /** - * Change to password that complies with password policy. Again. See that + * Change to password that complies with password policy. Again. See that * the change is applied correctly and that it is included in the history. */ @Test @@ -269,7 +269,7 @@ public void test230ModifyUserJackPasswordGoodAgain() throws Exception { doTestModifyUserJackPasswordSuccessWithHistory("test230ModifyUserJackPasswordGoodAgain", USER_PASSWORD_VALID_2, USER_PASSWORD_0_CLEAR, USER_PASSWORD_VALID_1); } - + /** * Change to password that complies with password policy. Again. * This time there are enough passwords in the history. So the history should @@ -280,7 +280,7 @@ public void test240ModifyUserJackPasswordGoodAgainOverHistory() throws Exception doTestModifyUserJackPasswordSuccessWithHistory("test240ModifyUserJackPasswordGoodAgainOverHistory", USER_PASSWORD_VALID_3, USER_PASSWORD_VALID_1, USER_PASSWORD_VALID_2); } - + /** * Change to password that complies with password policy. Again. * This time there are enough passwords in the history. So the history should @@ -291,7 +291,7 @@ public void test241ModifyUserJackPasswordGoodAgainOverHistoryAgain() throws Exce doTestModifyUserJackPasswordSuccessWithHistory("test241ModifyUserJackPasswordGoodAgainOverHistoryAgain", USER_PASSWORD_VALID_4, USER_PASSWORD_VALID_2, USER_PASSWORD_VALID_3); } - + /** * Reuse old password. Now the password should be out of the history, so * the system should allow its reuse. @@ -301,8 +301,8 @@ public void test248ModifyUserJackPasswordGoodReuse() throws Exception { doTestModifyUserJackPasswordSuccessWithHistory("test248ModifyUserJackPasswordGoodReuse", USER_PASSWORD_VALID_1, USER_PASSWORD_VALID_3, USER_PASSWORD_VALID_4); } - - private void doTestModifyUserJackPasswordSuccessWithHistory(final String TEST_NAME, + + private void doTestModifyUserJackPasswordSuccessWithHistory(final String TEST_NAME, String newPassword, String... expectedPasswordHistory) throws Exception { TestUtil.displayTestTitle(this, TEST_NAME); @@ -310,22 +310,22 @@ private void doTestModifyUserJackPasswordSuccessWithHistory(final String TEST_NA Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + lastPasswordChangeStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN modifyUserChangePassword(USER_JACK_OID, newPassword, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + lastPasswordChangeEnd = clock.currentTimeXMLGregorianCalendar(); - + assertJackPasswordsWithHistory(newPassword, expectedPasswordHistory); } - - private void doTestModifyUserJackPasswordFailureWithHistory(final String TEST_NAME, + + private void doTestModifyUserJackPasswordFailureWithHistory(final String TEST_NAME, String newPassword, String oldPassword, String... expectedPasswordHistory) throws Exception { TestUtil.displayTestTitle(this, TEST_NAME); @@ -333,25 +333,25 @@ private void doTestModifyUserJackPasswordFailureWithHistory(final String TEST_NA Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + try { // WHEN modifyUserChangePassword(USER_JACK_OID, newPassword, task, result); - + AssertJUnit.fail("Unexpected success"); - + } catch (PolicyViolationException e) { // This is expected display("Exected exception", e); } - + // THEN result.computeStatus(); TestUtil.assertFailure(result); - + assertJackPasswordsWithHistory(oldPassword, expectedPasswordHistory); } - + private void assertJackPasswordsWithHistory(String expectedCurrentPassword, String... expectedPasswordHistory) throws Exception { PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); @@ -359,10 +359,10 @@ private void assertJackPasswordsWithHistory(String expectedCurrentPassword, Stri assertUserPassword(userJack, expectedCurrentPassword); assertPasswordMetadata(userJack, false, lastPasswordChangeStart, lastPasswordChangeEnd); - + assertDummyPassword(null, ACCOUNT_JACK_DUMMY_USERNAME, expectedCurrentPassword); - + assertPasswordHistoryEntries(userJack, expectedPasswordHistory); } - + } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/TestPasswordNone.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/TestPasswordNone.java index f6d9f2f9b5b..3e54fe41fea 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/TestPasswordNone.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/TestPasswordNone.java @@ -35,13 +35,13 @@ /** * Password test with NONE password storage (default storage for other types) - * + * * This test is only partially working. * IT IS NOT PART OF THE TEST SUITE. It is NOT executed automatically. - * + * * E.g. new password will be generated on every recompute because the * weak inbound mapping is activated. - * + * * @author semancik * */ @@ -49,7 +49,7 @@ @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class TestPasswordNone extends AbstractPasswordTest { - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -59,12 +59,12 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti protected String getSecurityPolicyOid() { return SECURITY_POLICY_PASSWORD_STORAGE_NONE_OID; } - + @Override protected CredentialsStorageTypeType getPasswordStorageType() { return CredentialsStorageTypeType.NONE; } - + @Override protected void assertShadowLifecycle(PrismObject shadow, boolean focusCreated) { if (focusCreated) { @@ -73,14 +73,14 @@ protected void assertShadowLifecycle(PrismObject shadow, boolean foc assertShadowLifecycle(shadow, SchemaConstants.LIFECYCLE_PROPOSED); } } - + @Override protected void assert31xBluePasswordAfterAssignment(PrismObject userAfter) throws Exception { assertDummyPassword(RESOURCE_DUMMY_BLUE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, null); PrismObject shadow = getBlueShadow(userAfter); assertNoShadowPassword(shadow); } - + @Override protected void assert31xBluePasswordAfterPasswordChange(PrismObject userAfter) throws Exception { assertDummyPassword(RESOURCE_DUMMY_BLUE_NAME, ACCOUNT_JACK_DUMMY_USERNAME, USER_PASSWORD_VALID_2); @@ -91,7 +91,7 @@ protected void assert31xBluePasswordAfterPasswordChange(PrismObject us @Override protected void assertAccountActivationNotification(String dummyResourceName, String username) { // TODO Auto-generated method stub - + } } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/AbstractRbacTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/AbstractRbacTest.java index f57c7714dda..2f1ff66ee2d 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/AbstractRbacTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/AbstractRbacTest.java @@ -77,39 +77,39 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public abstract class AbstractRbacTest extends AbstractInitializedModelIntegrationTest { - + protected static final File TEST_DIR = new File("src/test/resources", "rbac"); - + protected static final File ROLE_ADRIATIC_PIRATE_FILE = new File(TEST_DIR, "role-adriatic-pirate.xml"); protected static final String ROLE_ADRIATIC_PIRATE_OID = "12345678-d34d-b33f-f00d-5555555566aa"; protected static final File ROLE_BLACK_SEA_PIRATE_FILE = new File(TEST_DIR, "role-black-sea-pirate.xml"); protected static final String ROLE_BLACK_SEA_PIRATE_OID = "12345678-d34d-b33f-f00d-5555555566bb"; - + protected static final File ROLE_INDIAN_OCEAN_PIRATE_FILE = new File(TEST_DIR, "role-indian-ocean-pirate.xml"); protected static final String ROLE_INDIAN_OCEAN_PIRATE_OID = "12345678-d34d-b33f-f00d-555555556610"; - + protected static final File ROLE_HONORABILITY_FILE = new File(TEST_DIR, "role-honorability.xml"); protected static final String ROLE_HONORABILITY_OID = "12345678-d34d-b33f-f00d-555555557701"; - + protected static final File ROLE_CLERIC_FILE = new File(TEST_DIR, "role-cleric.xml"); protected static final String ROLE_CLERIC_OID = "12345678-d34d-b33f-f00d-555555557702"; - + protected static final File ROLE_WANNABE_FILE = new File(TEST_DIR, "role-wannabe.xml"); protected static final String ROLE_WANNABE_OID = "12345678-d34d-b33f-f00d-555555557703"; - + protected static final File ROLE_HONORABLE_WANNABE_FILE = new File(TEST_DIR, "role-honorable-wannabe.xml"); protected static final String ROLE_HONORABLE_WANNABE_OID = "12345678-d34d-b33f-f00d-555555557704"; protected static final File ROLE_GOVERNOR_FILE = new File(TEST_DIR, "role-governor.xml"); protected static final String ROLE_GOVERNOR_OID = "12345678-d34d-b33f-f00d-555555557705"; - + protected static final File ROLE_CANNIBAL_FILE = new File(TEST_DIR, "role-cannibal.xml"); protected static final String ROLE_CANNIBAL_OID = "12345678-d34d-b33f-f00d-555555557706"; - + protected static final File ROLE_PROJECT_OMNINAMAGER_FILE = new File(TEST_DIR, "role-project-omnimanager.xml"); protected static final String ROLE_PROJECT_OMNINAMAGER_OID = "f23ab26c-69df-11e6-8330-979c643ea51c"; - + protected static final File ROLE_WEAK_GOSSIPER_FILE = new File(TEST_DIR, "role-weak-gossiper.xml"); protected static final String ROLE_WEAK_GOSSIPER_OID = "e8fb2226-7f48-11e6-8cf1-630ce5c3f80b"; @@ -125,7 +125,7 @@ public abstract class AbstractRbacTest extends AbstractInitializedModelIntegrati protected static final String ROLE_IMMUTABLE_GLOBAL_OID = "e7ba8884-b2f6-11e6-a0b9-d3540dd687d6"; protected static final String ROLE_IMMUTABLE_GLOBAL_DESCRIPTION = "Thou shalt not modify this role!"; protected static final String ROLE_IMMUTABLE_GLOBAL_IDENTIFIER = "GIG001"; - + protected static final File ROLE_IMMUTABLE_DESCRIPTION_GLOBAL_FILE = new File(TEST_DIR, "role-immutable-description-global.xml"); protected static final String ROLE_IMMUTABLE_DESCRIPTION_GLOBAL_OID = "b7ea1c0c-31d6-445e-8949-9f8f4a665b3b"; protected static final String ROLE_IMMUTABLE_DESCRIPTION_GLOBAL_DESCRIPTION = "Thou shalt not modify description of this role!"; @@ -139,7 +139,7 @@ public abstract class AbstractRbacTest extends AbstractInitializedModelIntegrati protected static final File ROLE_NON_CREATEABLE_FILE = new File(TEST_DIR, "role-non-createable.xml"); protected static final String ROLE_NON_CREATEABLE_OID = "c45a25ce-b2e8-11e6-923e-938d2c54d334"; - + protected static final File ROLE_IMMUTABLE_ASSIGN_FILE = new File(TEST_DIR, "role-immutable-assign.xml"); protected static final String ROLE_IMMUTABLE_ASSIGN_OID = "a6b10a7c-b57e-11e6-bcb3-1ba47cb07e2e"; @@ -151,7 +151,7 @@ public abstract class AbstractRbacTest extends AbstractInitializedModelIntegrati protected static final File ROLE_BLOODY_FOOL_FILE = new File(TEST_DIR, "role-bloody-fool.xml"); protected static final String ROLE_BLOODY_FOOL_OID = "0a0ac150-af3d-11e6-9901-67fbcbd5bb25"; - + protected static final File ROLE_TREASURE_GOLD_FILE = new File(TEST_DIR, "role-treasure-gold.xml"); protected static final String ROLE_TREASURE_GOLD_OID = "00a1db70-5817-11e7-93eb-9305bec579fe"; @@ -163,22 +163,22 @@ public abstract class AbstractRbacTest extends AbstractInitializedModelIntegrati protected static final File ROLE_ALL_TREASURE_FILE = new File(TEST_DIR, "role-all-treasure.xml"); protected static final String ROLE_ALL_TREASURE_OID = "7fda5d86-5817-11e7-ac85-3b1cba81d3ef"; - + protected static final File ROLE_LOOT_DIAMONDS_FILE = new File(TEST_DIR, "role-loot-diamonds.xml"); protected static final String ROLE_LOOT_DIAMONDS_OID = "974d7156-581c-11e7-916d-03ed3d47d102"; - + protected static final File ROLE_ALL_LOOT_FILE = new File(TEST_DIR, "role-all-loot.xml"); protected static final String ROLE_ALL_LOOT_OID = "aaede614-581c-11e7-91bf-db837eb406b7"; - + protected static final File ROLE_ALL_YOU_CAN_GET_FILE = new File(TEST_DIR, "role-all-you-can-get.xml"); protected static final String ROLE_ALL_YOU_CAN_GET_OID = "4671874e-5822-11e7-a571-8b43dc7d2876"; - + protected static final File ORG_PROJECT_RECLAIM_BLACK_PEARL_FILE = new File(TEST_DIR, "org-project-reclaim-black-pearl.xml"); protected static final String ORG_PROJECT_RECLAIM_BLACK_PEARL_OID = "00000000-8888-6666-0000-200000005000"; protected static final String USER_LEMONHEAD_NAME = "lemonhead"; protected static final String USER_LEMONHEAD_FULLNAME = "Cannibal Lemonhead"; - + protected static final String USER_SHARPTOOTH_NAME = "sharptooth"; protected static final String USER_SHARPTOOTH_FULLNAME = "Cannibal Sharptooth"; @@ -195,21 +195,21 @@ public abstract class AbstractRbacTest extends AbstractInitializedModelIntegrati * Undefined relation. It is not standard relation not a relation that is in any way configured. */ protected static final QName RELATION_COMPLICATED_QNAME = new QName("http://exmple.com/relation", "complicated"); - + protected File getRoleGovernorFile() { return ROLE_GOVERNOR_FILE; } - + protected File getRoleCannibalFile() { return ROLE_CANNIBAL_FILE; } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + repoAddObjectFromFile(ROLE_ADRIATIC_PIRATE_FILE, RoleType.class, initResult); repoAddObjectFromFile(ROLE_BLACK_SEA_PIRATE_FILE, RoleType.class, initResult); repoAddObjectFromFile(ROLE_INDIAN_OCEAN_PIRATE_FILE, RoleType.class, initResult); @@ -241,5 +241,5 @@ public void initSystem(Task initTask, OperationResult initResult) dummyResourceCtl.addGroup(GROUP_SIMPLETONS_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 b1bba7b433f..e502df05bc5 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 @@ -47,16 +47,16 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestAssignmentValidity extends AbstractRbacTest { - + private XMLGregorianCalendar jackPirateValidTo; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); // InternalsConfig.setTestingPaths(TestingPaths.REVERSED); } - + /** * MID-4110 */ @@ -67,24 +67,24 @@ public void test100JackAssignRolePirateValidTo() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + ActivationType activationType = new ActivationType(); jackPirateValidTo = getTimestamp("PT10M"); activationType.setValidTo(jackPirateValidTo); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_PIRATE_OID, activationType, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); @@ -94,7 +94,7 @@ public void test100JackAssignRolePirateValidTo() throws Exception { assertEffectiveActivation(assignmentTypeAfter, ActivationStatusType.ENABLED); assertRoleMembershipRef(userAfter, ROLE_PIRATE_OID); assertDelegatedRef(userAfter); - + assertJackDummyPirateAccount(); } @@ -109,17 +109,17 @@ public void test102Forward15min() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + clockForward("PT15M"); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 1); @@ -129,7 +129,7 @@ public void test102Forward15min() throws Exception { assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * New assignment. No time validity. * MID-4110 @@ -141,20 +141,20 @@ public void test104JackAssignRolePirateAgain() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); @@ -162,10 +162,10 @@ public void test104JackAssignRolePirateAgain() throws Exception { assertAssignments(userAfter, 2); assertRoleMembershipRef(userAfter, ROLE_PIRATE_OID); assertDelegatedRef(userAfter); - + assertJackDummyPirateAccount(); } - + /** * Unassign valid assignment. Only invalid assignment remains. * MID-4110 @@ -177,15 +177,15 @@ public void test106JackUnassignRolePirateValid() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 1); @@ -195,7 +195,7 @@ public void test106JackUnassignRolePirateValid() throws Exception { assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * MID-4110 */ @@ -203,7 +203,7 @@ public void test106JackUnassignRolePirateValid() throws Exception { public void test109JackUnassignAll() throws Exception { unassignAll("test109JackUnassignAll"); } - + /** * Raw modification of assignment. The assignment is not effective immediately, * as this is raw operation. So, nothing much happens. Yet. @@ -216,25 +216,25 @@ public void test110JackAssignRolePirateValidToRaw() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + ActivationType activationType = new ActivationType(); jackPirateValidTo = getTimestamp("PT10M"); activationType.setValidTo(jackPirateValidTo); - + ModelExecuteOptions options = ModelExecuteOptions.createRaw(); - + // WHEN displayWhen(TEST_NAME); - modifyUserAssignment(USER_JACK_OID, ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, + modifyUserAssignment(USER_JACK_OID, ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, task, null, activationType, true, options, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 1); @@ -242,7 +242,7 @@ public void test110JackAssignRolePirateValidToRaw() throws Exception { assertEffectiveActivation(assignmentTypeAfter, null); assertRoleMembershipRef(userAfter); assertDelegatedRef(userAfter); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } @@ -256,7 +256,7 @@ public void test111RecomputeJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); @@ -267,7 +267,7 @@ public void test111RecomputeJack() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 1); @@ -275,7 +275,7 @@ public void test111RecomputeJack() throws Exception { assertEffectiveActivation(assignmentTypeAfter, ActivationStatusType.ENABLED); assertRoleMembershipRef(userAfter, ROLE_PIRATE_OID); assertDelegatedRef(userAfter); - + assertJackDummyPirateAccount(); } @@ -290,17 +290,17 @@ public void test112Forward15min() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + clockForward("PT15M"); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 1); @@ -310,7 +310,7 @@ public void test112Forward15min() throws Exception { assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * New assignment. No time validity. * MID-4110 @@ -322,20 +322,20 @@ public void test114JackAssignRolePirateAgain() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); @@ -343,10 +343,10 @@ public void test114JackAssignRolePirateAgain() throws Exception { assertAssignments(userAfter, 2); assertRoleMembershipRef(userAfter, ROLE_PIRATE_OID); assertDelegatedRef(userAfter); - + assertJackDummyPirateAccount(); } - + /** * MID-4110 */ @@ -366,24 +366,24 @@ public void test120JackAssignRoleSailorValidTo() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + ActivationType activationType = new ActivationType(); jackPirateValidTo = getTimestamp("PT10M"); activationType.setValidTo(jackPirateValidTo); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_STRONG_SAILOR_OID, activationType, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); @@ -393,10 +393,10 @@ public void test120JackAssignRoleSailorValidTo() throws Exception { assertEffectiveActivation(assignmentTypeAfter, ActivationStatusType.ENABLED); assertRoleMembershipRef(userAfter, ROLE_STRONG_SAILOR_OID); assertDelegatedRef(userAfter); - + assertJackDummySailorAccount(); } - + /** * Assignment expires. * MID-4110, MID-4114 @@ -408,17 +408,17 @@ public void test122Forward15min() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + clockForward("PT15M"); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 1); @@ -428,7 +428,7 @@ public void test122Forward15min() throws Exception { assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * New assignment. No time validity. * MID-4110 @@ -440,20 +440,20 @@ public void test124JackAssignRoleSailorAgain() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_STRONG_SAILOR_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); @@ -461,10 +461,10 @@ public void test124JackAssignRoleSailorAgain() throws Exception { assertAssignments(userAfter, 2); assertRoleMembershipRef(userAfter, ROLE_STRONG_SAILOR_OID); assertDelegatedRef(userAfter); - + assertJackDummySailorAccount(); } - + /** * MID-4110 */ @@ -472,7 +472,7 @@ public void test124JackAssignRoleSailorAgain() throws Exception { public void test129JackUnassignAll() throws Exception { unassignAll("test129JackUnassignAll"); } - + /** * Raw modification of assignment. The assignment is not effective immediately, * as this is raw operation. So, nothing much happens. Yet. @@ -485,25 +485,25 @@ public void test130JackAssignRoleSailorValidToRaw() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + ActivationType activationType = new ActivationType(); jackPirateValidTo = getTimestamp("PT10M"); activationType.setValidTo(jackPirateValidTo); - + ModelExecuteOptions options = ModelExecuteOptions.createRaw(); - + // WHEN displayWhen(TEST_NAME); - modifyUserAssignment(USER_JACK_OID, ROLE_STRONG_SAILOR_OID, RoleType.COMPLEX_TYPE, null, + modifyUserAssignment(USER_JACK_OID, ROLE_STRONG_SAILOR_OID, RoleType.COMPLEX_TYPE, null, task, null, activationType, true, options, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 1); @@ -511,10 +511,10 @@ public void test130JackAssignRoleSailorValidToRaw() throws Exception { assertEffectiveActivation(assignmentTypeAfter, null); assertRoleMembershipRef(userAfter); assertDelegatedRef(userAfter); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * MID-4110, MID-4114 */ @@ -525,7 +525,7 @@ public void test131RecomputeJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); @@ -536,7 +536,7 @@ public void test131RecomputeJack() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 1); @@ -544,10 +544,10 @@ public void test131RecomputeJack() throws Exception { assertEffectiveActivation(assignmentTypeAfter, ActivationStatusType.ENABLED); assertRoleMembershipRef(userAfter, ROLE_STRONG_SAILOR_OID); assertDelegatedRef(userAfter); - + assertJackDummySailorAccount(); } - + /** * Assignment expires. * MID-4110, MID-4114 @@ -559,17 +559,17 @@ public void test132Forward15min() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + clockForward("PT15M"); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 1); @@ -579,7 +579,7 @@ public void test132Forward15min() throws Exception { assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * New assignment. No time validity. * MID-4110 @@ -591,20 +591,20 @@ public void test134JackAssignRoleSailorAgain() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_STRONG_SAILOR_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); @@ -612,10 +612,10 @@ public void test134JackAssignRoleSailorAgain() throws Exception { assertAssignments(userAfter, 2); assertRoleMembershipRef(userAfter, ROLE_STRONG_SAILOR_OID); assertDelegatedRef(userAfter); - + assertJackDummySailorAccount(); } - + /** * MID-4110 */ @@ -623,7 +623,7 @@ public void test134JackAssignRoleSailorAgain() throws Exception { public void test139JackUnassignAll() throws Exception { unassignAll("test139JackUnassignAll"); } - + /** * This time do not recompute. Just set everything up, let the assignment expire * and assign the role again. @@ -636,25 +636,25 @@ public void test140JackAssignRoleSailorValidToRaw() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + ActivationType activationType = new ActivationType(); jackPirateValidTo = getTimestamp("PT10M"); activationType.setValidTo(jackPirateValidTo); - + ModelExecuteOptions options = ModelExecuteOptions.createRaw(); - + // WHEN displayWhen(TEST_NAME); - modifyUserAssignment(USER_JACK_OID, ROLE_STRONG_SAILOR_OID, RoleType.COMPLEX_TYPE, null, + modifyUserAssignment(USER_JACK_OID, ROLE_STRONG_SAILOR_OID, RoleType.COMPLEX_TYPE, null, task, null, activationType, true, options, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 1); @@ -662,10 +662,10 @@ public void test140JackAssignRoleSailorValidToRaw() throws Exception { assertEffectiveActivation(assignmentTypeAfter, null); assertRoleMembershipRef(userAfter); assertDelegatedRef(userAfter); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * Assignment expires. BUt do NOT recompute. * MID-4110 @@ -676,15 +676,15 @@ public void test142Forward15min() throws Exception { displayTestTitle(TEST_NAME); Task task = createTask(TEST_NAME); - + // WHEN displayWhen(TEST_NAME); clockForward("PT15M"); // do NOT recompute - + // THEN displayThen(TEST_NAME); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 1); @@ -694,7 +694,7 @@ public void test142Forward15min() throws Exception { assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * New assignment. No time validity. * MID-4110 @@ -706,20 +706,20 @@ public void test144JackAssignRoleSailorAgain() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_STRONG_SAILOR_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); @@ -727,10 +727,10 @@ public void test144JackAssignRoleSailorAgain() throws Exception { assertAssignments(userAfter, 2); assertRoleMembershipRef(userAfter, ROLE_STRONG_SAILOR_OID); assertDelegatedRef(userAfter); - + assertJackDummySailorAccount(); } - + /** * MID-4110 */ @@ -738,7 +738,7 @@ public void test144JackAssignRoleSailorAgain() throws Exception { public void test149JackUnassignAll() throws Exception { unassignAll("test149JackUnassignAll"); } - + /** * MID-4110 */ @@ -749,31 +749,31 @@ public void test150JackAssignRolePirate() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignments(userAfter, 1); AssignmentType assignmentPirateTypeAfter = assertAssignedRole(userAfter, ROLE_PIRATE_OID); assertEffectiveActivation(assignmentPirateTypeAfter, ActivationStatusType.ENABLED); - + assertRoleMembershipRef(userAfter, ROLE_PIRATE_OID); assertDelegatedRef(userAfter); - + assertJackDummyPirateAccount(); } - + /** * Sailor is an idempotent(conservative) role. * MID-4110 @@ -785,37 +785,37 @@ public void test151JackAssignRoleSailorValidTo() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + ActivationType activationType = new ActivationType(); jackPirateValidTo = getTimestamp("PT10M"); activationType.setValidTo(jackPirateValidTo); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_STRONG_SAILOR_OID, activationType, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignments(userAfter, 2); AssignmentType assignmentSailorTypeAfter = assertAssignedRole(userAfter, ROLE_STRONG_SAILOR_OID); assertEffectiveActivation(assignmentSailorTypeAfter, ActivationStatusType.ENABLED); AssignmentType assignmentPirateTypeAfter = assertAssignedRole(userAfter, ROLE_PIRATE_OID); assertEffectiveActivation(assignmentPirateTypeAfter, ActivationStatusType.ENABLED); - + assertRoleMembershipRef(userAfter, ROLE_PIRATE_OID, ROLE_STRONG_SAILOR_OID); assertDelegatedRef(userAfter); - + assertJackDummyPirateSailorAccount(); } - + /** * Assignment expires. * MID-4110, MID-4114 @@ -827,17 +827,17 @@ public void test153Forward15min() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + clockForward("PT15M"); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 2); @@ -849,7 +849,7 @@ public void test153Forward15min() throws Exception { assertJackDummyPirateAccount(); } - + /** * New assignment. No time validity. * MID-4110 @@ -861,27 +861,27 @@ public void test154JackAssignRoleSailorAgain() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_STRONG_SAILOR_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 3); assertRoleMembershipRef(userAfter, ROLE_PIRATE_OID, ROLE_STRONG_SAILOR_OID); assertDelegatedRef(userAfter); - + assertJackDummyPirateSailorAccount(); } - + /** * MID-4110 */ @@ -889,7 +889,7 @@ public void test154JackAssignRoleSailorAgain() throws Exception { public void test159JackUnassignAll() throws Exception { unassignAll("test159JackUnassignAll"); } - + /** * MID-4110 */ @@ -900,31 +900,31 @@ public void test160JackAssignRolePirate() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignments(userAfter, 1); AssignmentType assignmentPirateTypeAfter = assertAssignedRole(userAfter, ROLE_PIRATE_OID); assertEffectiveActivation(assignmentPirateTypeAfter, ActivationStatusType.ENABLED); - + assertRoleMembershipRef(userAfter, ROLE_PIRATE_OID); assertDelegatedRef(userAfter); - + assertJackDummyPirateAccount(); } - + /** * MID-4110 */ @@ -935,41 +935,41 @@ public void test161JackAssignRoleSailorValidToRaw() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + ActivationType activationType = new ActivationType(); jackPirateValidTo = getTimestamp("PT10M"); activationType.setValidTo(jackPirateValidTo); - + ModelExecuteOptions options = ModelExecuteOptions.createRaw(); - + // WHEN displayWhen(TEST_NAME); - modifyUserAssignment(USER_JACK_OID, ROLE_STRONG_SAILOR_OID, RoleType.COMPLEX_TYPE, null, + modifyUserAssignment(USER_JACK_OID, ROLE_STRONG_SAILOR_OID, RoleType.COMPLEX_TYPE, null, task, null, activationType, true, options, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignments(userAfter, 2); AssignmentType assignmentSailorTypeAfter = assertAssignedRole(userAfter, ROLE_STRONG_SAILOR_OID); assertEffectiveActivation(assignmentSailorTypeAfter, null); AssignmentType assignmentPirateTypeAfter = assertAssignedRole(userAfter, ROLE_PIRATE_OID); assertEffectiveActivation(assignmentPirateTypeAfter, ActivationStatusType.ENABLED); - + assertRoleMembershipRef(userAfter, ROLE_PIRATE_OID); // SAILOR is not here, we are raw assertDelegatedRef(userAfter); - + assertJackDummyPirateAccount(); } - + /** * Recompute should fix it all. * MID-4110 @@ -981,37 +981,37 @@ public void test162RecomputeJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + ActivationType activationType = new ActivationType(); jackPirateValidTo = getTimestamp("PT10M"); activationType.setValidTo(jackPirateValidTo); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignments(userAfter, 2); AssignmentType assignmentSailorTypeAfter = assertAssignedRole(userAfter, ROLE_STRONG_SAILOR_OID); assertEffectiveActivation(assignmentSailorTypeAfter, ActivationStatusType.ENABLED); AssignmentType assignmentPirateTypeAfter = assertAssignedRole(userAfter, ROLE_PIRATE_OID); assertEffectiveActivation(assignmentPirateTypeAfter, ActivationStatusType.ENABLED); - + assertRoleMembershipRef(userAfter, ROLE_PIRATE_OID, ROLE_STRONG_SAILOR_OID); assertDelegatedRef(userAfter); - + assertJackDummyPirateSailorAccount(); } - + /** * Assignment expires. * MID-4110, MID-4114 @@ -1023,17 +1023,17 @@ public void test163Forward15min() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + clockForward("PT15M"); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 2); @@ -1045,7 +1045,7 @@ public void test163Forward15min() throws Exception { assertJackDummyPirateAccount(); } - + /** * New assignment. No time validity. * MID-4110 @@ -1057,27 +1057,27 @@ public void test164JackAssignRoleSailorAgain() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_STRONG_SAILOR_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 3); assertRoleMembershipRef(userAfter, ROLE_PIRATE_OID, ROLE_STRONG_SAILOR_OID); assertDelegatedRef(userAfter); - + assertJackDummyPirateSailorAccount(); } - + /** * MID-4110 */ @@ -1085,7 +1085,7 @@ public void test164JackAssignRoleSailorAgain() throws Exception { public void test169JackUnassignAll() throws Exception { unassignAll("test169JackUnassignAll"); } - + /** * MID-4110 */ @@ -1096,31 +1096,31 @@ public void test170JackAssignRolePirate() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignments(userAfter, 1); AssignmentType assignmentPirateTypeAfter = assertAssignedRole(userAfter, ROLE_PIRATE_OID); assertEffectiveActivation(assignmentPirateTypeAfter, ActivationStatusType.ENABLED); - + assertRoleMembershipRef(userAfter, ROLE_PIRATE_OID); assertDelegatedRef(userAfter); - + assertJackDummyPirateAccount(); } - + /** * MID-4110 */ @@ -1131,37 +1131,37 @@ public void test171JackAssignRoleWeakSingerValidTo() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + ActivationType activationType = new ActivationType(); jackPirateValidTo = getTimestamp("PT10M"); activationType.setValidTo(jackPirateValidTo); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_WEAK_SINGER_OID, activationType, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignments(userAfter, 2); AssignmentType assignmentSingerTypeAfter = assertAssignedRole(userAfter, ROLE_WEAK_SINGER_OID); assertEffectiveActivation(assignmentSingerTypeAfter, ActivationStatusType.ENABLED); AssignmentType assignmentPirateTypeAfter = assertAssignedRole(userAfter, ROLE_PIRATE_OID); assertEffectiveActivation(assignmentPirateTypeAfter, ActivationStatusType.ENABLED); - + assertRoleMembershipRef(userAfter, ROLE_PIRATE_OID, ROLE_WEAK_SINGER_OID); assertDelegatedRef(userAfter); - + assertJackDummyPirateSingerAccount(); } - + /** * Assignment expires. * MID-4110, MID-4114 @@ -1173,17 +1173,17 @@ public void test173Forward15min() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + clockForward("PT15M"); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 2); @@ -1196,7 +1196,7 @@ public void test173Forward15min() throws Exception { // Dummy attribute "title" is tolerant, so the singer value remains assertJackDummyPirateSingerAccount(); } - + /** * New assignment. No time validity. * MID-4110 @@ -1208,27 +1208,27 @@ public void test174JackAssignRoleSingerAgain() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_WEAK_SINGER_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 3); assertRoleMembershipRef(userAfter, ROLE_PIRATE_OID, ROLE_WEAK_SINGER_OID); assertDelegatedRef(userAfter); - + assertJackDummyPirateSingerAccount(); } - + /** * MID-4110 */ @@ -1236,7 +1236,7 @@ public void test174JackAssignRoleSingerAgain() throws Exception { public void test179JackUnassignAll() throws Exception { unassignAll("test179JackUnassignAll"); } - + /** * This time do both assigns as raw. And do NOT recompute until everything is set up. * MID-4110 @@ -1248,23 +1248,23 @@ public void test180JackAssignRoleSailorValidToRaw() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + ActivationType activationType = new ActivationType(); jackPirateValidTo = getTimestamp("PT10M"); activationType.setValidTo(jackPirateValidTo); - + // WHEN displayWhen(TEST_NAME); - modifyUserAssignment(USER_JACK_OID, ROLE_STRONG_SAILOR_OID, RoleType.COMPLEX_TYPE, null, + modifyUserAssignment(USER_JACK_OID, ROLE_STRONG_SAILOR_OID, RoleType.COMPLEX_TYPE, null, task, null, activationType, true, ModelExecuteOptions.createRaw(), result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 1); @@ -1272,10 +1272,10 @@ public void test180JackAssignRoleSailorValidToRaw() throws Exception { assertEffectiveActivation(assignmentTypeAfter, null); assertRoleMembershipRef(userAfter); assertDelegatedRef(userAfter); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * MID-4110 */ @@ -1286,17 +1286,17 @@ public void test182Forward15minAndAssignRaw() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + clockForward("PT15M"); - + // WHEN displayWhen(TEST_NAME); - modifyUserAssignment(USER_JACK_OID, ROLE_STRONG_SAILOR_OID, RoleType.COMPLEX_TYPE, null, + modifyUserAssignment(USER_JACK_OID, ROLE_STRONG_SAILOR_OID, RoleType.COMPLEX_TYPE, null, task, null, null, true, ModelExecuteOptions.createRaw(), result); - + // THEN displayThen(TEST_NAME); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 2); @@ -1304,7 +1304,7 @@ public void test182Forward15minAndAssignRaw() throws Exception { assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * MID-4110, MID-4114 */ @@ -1315,27 +1315,27 @@ public void test184RecomputeJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 2); assertRoleMembershipRef(userAfter, ROLE_STRONG_SAILOR_OID); assertDelegatedRef(userAfter); - + assertJackDummySailorAccount(); } - + /** * MID-4110 */ @@ -1344,78 +1344,78 @@ public void test189JackUnassignAll() throws Exception { unassignAll("test189JackUnassignAll"); } - + private void assertJackDummyPirateAccount() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, ROLE_PIRATE_TITLE); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, USER_JACK_LOCALITY); - // Outbound mapping for weapon is weak, therefore the mapping in role should override it - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, + // Outbound mapping for weapon is weak, therefore the mapping in role should override it + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, ROLE_PIRATE_WEAPON); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow is the best pirate Caribbean has ever seen"); } - + private void assertJackDummySailorAccount() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_SAILOR_DRINK); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, USER_JACK_LOCALITY); } - + private void assertJackDummyPirateSailorAccount() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, ROLE_PIRATE_TITLE); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_SAILOR_DRINK); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, USER_JACK_LOCALITY); - // Outbound mapping for weapon is weak, therefore the mapping in role should override it - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, + // Outbound mapping for weapon is weak, therefore the mapping in role should override it + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, ROLE_PIRATE_WEAPON); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow is the best pirate Caribbean has ever seen"); } - + private void assertJackDummyPirateSingerAccount() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, ROLE_PIRATE_TITLE, ROLE_WEAK_SINGER_TITLE); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, USER_JACK_LOCALITY); - // Outbound mapping for weapon is weak, therefore the mapping in role should override it - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, + // Outbound mapping for weapon is weak, therefore the mapping in role should override it + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, ROLE_PIRATE_WEAPON); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow is the best pirate Caribbean has ever seen"); } - + private void unassignAll(final String TEST_NAME) throws Exception { displayTestTitle(TEST_NAME); Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); unassignAll(userBefore, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 0); @@ -1423,6 +1423,6 @@ 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/TestRbac.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestRbac.java index 578d67c29de..f46d65b2c44 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 @@ -77,22 +77,22 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestRbac extends AbstractRbacTest { - + private static final String LOCALITY_TORTUGA = "Tortuga"; - + private String userLemonheadOid; private String userSharptoothOid; private String userRedskullOid; private String userBignoseOid; - - private final String EXISTING_GOSSIP = "Black spot!"; - + + private final String EXISTING_GOSSIP = "Black spot!"; + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); } - + @Test public void test000SanityRolePirate() throws Exception { final String TEST_NAME = "test000SanityRolePirate"; @@ -100,18 +100,18 @@ public void test000SanityRolePirate() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN PrismObject rolePirate = modelService.getObject(RoleType.class, ROLE_PIRATE_OID, null, task, result); - + // THEN display("Role pirate", rolePirate); IntegrationTestTools.displayXml("Role pirate", rolePirate); assertNotNull("No pirate", rolePirate); - + PrismAsserts.assertEquivalent(ROLE_PIRATE_FILE, rolePirate); } - + @Test public void test001SanityRoleProjectOmnimanager() throws Exception { final String TEST_NAME = "test001SanityRoleProjectOmnimanager"; @@ -119,20 +119,20 @@ public void test001SanityRoleProjectOmnimanager() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN PrismObject roleOmnimanager = modelService.getObject(RoleType.class, ROLE_PROJECT_OMNINAMAGER_OID, null, task, result); - + // THEN display("Role omnimanager", roleOmnimanager); IntegrationTestTools.displayXml("Role omnimanager", roleOmnimanager); assertNotNull("No omnimanager", roleOmnimanager); - + ObjectReferenceType targetRef = roleOmnimanager.asObjectable().getInducement().get(0).getTargetRef(); assertEquals("Wrong targetRef resolutionTime", EvaluationTimeType.RUN, targetRef.getResolutionTime()); assertNull("targetRef is resolved", targetRef.getOid()); } - + @Test public void test010SearchRequestableRoles() throws Exception { final String TEST_NAME = "test010SearchRequestableRoles"; @@ -140,17 +140,17 @@ public void test010SearchRequestableRoles() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = QueryBuilder.queryFor(RoleType.class, prismContext) .item(RoleType.F_REQUESTABLE).eq(true) .build(); // WHEN List> requestableRoles = modelService.searchObjects(RoleType.class, query, null, task, result); - + // THEN display("Requestable roles", requestableRoles); - + assertEquals("Unexpected number of requestable roles", 3, requestableRoles.size()); } @@ -161,19 +161,19 @@ public void test101JackAssignRolePirate() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); // WHEN assignRole(USER_JACK_OID, ROLE_PIRATE_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); @@ -187,13 +187,13 @@ public void test101JackAssignRolePirate() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, ROLE_PIRATE_TITLE); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, USER_JACK_LOCALITY); - // Outbound mapping for weapon is weak, therefore the mapping in role should override it - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, + // Outbound mapping for weapon is weak, therefore the mapping in role should override it + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, ROLE_PIRATE_WEAPON); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow is the best pirate Caribbean has ever seen"); } @@ -203,7 +203,7 @@ protected ModelExecuteOptions getDefaultOptions() { /** * We modify Jack's "locality". As this is assigned by expression in the role to the dummy account, the account should - * be updated as well. + * be updated as well. */ @Test public void test102JackModifyUserLocality() throws Exception { @@ -212,22 +212,22 @@ public void test102JackModifyUserLocality() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // gossip is a tolerant attribute. Make sure there there is something to tolerate DummyAccount jackDummyAccount = getDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME); - jackDummyAccount.addAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + 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, + modifyUserReplace(USER_JACK_OID, UserType.F_LOCALITY, getDefaultOptions(), task, result, createPolyString(LOCALITY_TORTUGA)); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); PrismObject userAfter = getUser(USER_JACK_OID); @@ -238,15 +238,15 @@ public void test102JackModifyUserLocality() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, ROLE_PIRATE_TITLE); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, LOCALITY_TORTUGA); - // Outbound mapping for weapon is weak, therefore the mapping in role should override it - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, + // Outbound mapping for weapon is weak, therefore the mapping in role should override it + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, ROLE_PIRATE_WEAPON); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow is the best pirate Tortuga has ever seen", EXISTING_GOSSIP); } - + @Test public void test110UnAssignRolePirate() throws Exception { final String TEST_NAME = "test110UnAssignRolePirate"; @@ -254,14 +254,14 @@ public void test110UnAssignRolePirate() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignedNoRole(userAfter, task, result); @@ -278,46 +278,46 @@ public void test120JackAssignRolePirateWhileAlreadyHasAccount() throws Exception // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); - + // Make sure that the account has explicit intent account.asObjectable().setIntent(SchemaConstants.INTENT_DEFAULT); - + // Make sure that the existing account has the same value as is set by the role // This causes problems if the resource does not tolerate duplicate values in deltas. But provisioning // should work around that. - TestUtil.setAttribute(account, + TestUtil.setAttribute(account, getDummyResourceController().getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME), DOMUtil.XSD_STRING, prismContext, ROLE_PIRATE_TITLE); - - ObjectDelta delta = ObjectDelta.createModificationAddReference(UserType.class, USER_JACK_OID, + + ObjectDelta delta = ObjectDelta.createModificationAddReference(UserType.class, USER_JACK_OID, UserType.F_LINK_REF, prismContext, account); Collection> deltas = MiscSchemaUtil.createCollection(delta); - + // We need to switch off the enforcement for this operation. Otherwise we won't be able to create the account assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); modelService.executeChanges(deltas, getDefaultOptions(), task, result); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - + // Precondition (simplified) assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "weapon", "rum"); - + // gossip is a tolerant attribute. Make sure there there is something to tolerate DummyAccount jackDummyAccount = getDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME); - jackDummyAccount.addAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + jackDummyAccount.addAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, EXISTING_GOSSIP); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_PIRATE_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after", userJack); assertAssignments(userJack, 1); @@ -330,13 +330,13 @@ public void test120JackAssignRolePirateWhileAlreadyHasAccount() throws Exception assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "location", LOCALITY_TORTUGA); // The account already has a value for 'weapon', it should be unchanged. assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "weapon", "rum"); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow is the best pirate Tortuga has ever seen", EXISTING_GOSSIP); - + } - - - + + + @Test public void test121JackAssignAccountImplicitIntent() throws Exception { final String TEST_NAME = "test121JackAssignAccountImplicitIntent"; @@ -345,17 +345,17 @@ public void test121JackAssignAccountImplicitIntent() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // Precondition (simplified) assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - + // WHEN assignAccount(USER_JACK_OID, RESOURCE_DUMMY_OID, null, task, result); // TODO options? - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after", userJack); assertAssignments(userJack, 2); @@ -366,11 +366,11 @@ public void test121JackAssignAccountImplicitIntent() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", ROLE_PIRATE_TITLE); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "location", LOCALITY_TORTUGA); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow is the best pirate Tortuga has ever seen", EXISTING_GOSSIP); - + } - + @Test public void test122JackAssignAccountExplicitIntent() throws Exception { final String TEST_NAME = "test122JackAssignAccountExplicitIntent"; @@ -379,17 +379,17 @@ public void test122JackAssignAccountExplicitIntent() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // Precondition (simplified) assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - + // WHEN assignAccount(USER_JACK_OID, RESOURCE_DUMMY_OID, SchemaConstants.INTENT_DEFAULT, task, result); // TODO options? - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after", userJack); assertAssignments(userJack, 3); @@ -400,26 +400,26 @@ public void test122JackAssignAccountExplicitIntent() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", ROLE_PIRATE_TITLE); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "location", LOCALITY_TORTUGA); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow is the best pirate Tortuga has ever seen", EXISTING_GOSSIP); - + } - + @Test public void test127UnAssignAccountImplicitIntent() throws Exception { final String TEST_NAME = "test127UnAssignAccountImplicitIntent"; displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignAccount(USER_JACK_OID, RESOURCE_DUMMY_OID, null, task, result); // TODO options? - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after", userJack); assertAssignments(userJack, 2); @@ -430,25 +430,25 @@ public void test127UnAssignAccountImplicitIntent() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", ROLE_PIRATE_TITLE); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "location", LOCALITY_TORTUGA); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow is the best pirate Tortuga has ever seen", EXISTING_GOSSIP); } - + @Test public void test128UnAssignAccountExplicitIntent() throws Exception { final String TEST_NAME = "test128UnAssignAccountExplicitIntent"; displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignAccount(USER_JACK_OID, RESOURCE_DUMMY_OID, SchemaConstants.INTENT_DEFAULT, task, result); // TODO options? - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after", userJack); assertAssignments(userJack, 1); @@ -459,25 +459,25 @@ public void test128UnAssignAccountExplicitIntent() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", ROLE_PIRATE_TITLE); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "location", LOCALITY_TORTUGA); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow is the best pirate Tortuga has ever seen", EXISTING_GOSSIP); } - + @Test public void test129UnAssignRolePirate() throws Exception { final String TEST_NAME = "test129UnAssignRolePirate"; displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, getDefaultOptions(), task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after", userJack); assertAssignments(userJack, 0); @@ -485,7 +485,7 @@ public void test129UnAssignRolePirate() throws Exception { assertDelegatedRef(userJack); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + @Test public void test130JackAssignRolePirateWithSeaInAssignment() throws Exception { final String TEST_NAME = "test130JackAssignRolePirateWithSeaInAssignment"; @@ -493,17 +493,17 @@ public void test130JackAssignRolePirateWithSeaInAssignment() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismContainer extension = getAssignmentExtensionInstance(); PrismSchema piracySchema = getPiracySchema(); PrismPropertyDefinition seaPropDef = piracySchema.findPropertyDefinitionByElementName(PIRACY_SEA_QNAME); PrismProperty seaProp = seaPropDef.instantiate(); seaProp.setRealValue("Caribbean"); extension.add(seaProp); - + // WHEN assignRole(USER_JACK_OID, ROLE_PIRATE_OID, extension, getDefaultOptions(), task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); @@ -516,14 +516,14 @@ public void test130JackAssignRolePirateWithSeaInAssignment() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", ROLE_PIRATE_TITLE); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "location", LOCALITY_TORTUGA); - // Outbound mapping for weapon is weak, therefore the mapping in role should override it + // Outbound mapping for weapon is weak, therefore the mapping in role should override it assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "weapon", ROLE_PIRATE_WEAPON); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow is the best pirate Tortuga has ever seen"); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_SEA_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_SEA_NAME, "jack sailed Caribbean, immediately Caribbean, role , with this The Seven Seas while focused on Caribbean (in Pirate)"); } - + @Test public void test132JackUnAssignRolePirateWithSeaInAssignment() throws Exception { final String TEST_NAME = "test132JackUnAssignRolePirateWithSeaInAssignment"; @@ -531,21 +531,21 @@ public void test132JackUnAssignRolePirateWithSeaInAssignment() throws Exception Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismContainer extension = getAssignmentExtensionInstance(); PrismSchema piracySchema = getPiracySchema(); PrismPropertyDefinition seaPropDef = piracySchema.findPropertyDefinitionByElementName(PIRACY_SEA_QNAME); PrismProperty seaProp = seaPropDef.instantiate(); seaProp.setRealValue("Caribbean"); extension.add(seaProp); - + // WHEN unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, extension, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after", userJack); assertAssignments(userJack, 0); @@ -553,7 +553,7 @@ public void test132JackUnAssignRolePirateWithSeaInAssignment() throws Exception assertDelegatedRef(userJack); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * The value for sea is set in Adriatic Pirate role extension. */ @@ -564,14 +564,14 @@ public void test134JackAssignRoleAdriaticPirate() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignRole(USER_JACK_OID, ROLE_ADRIATIC_PIRATE_OID, getDefaultOptions(), task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignedRole(userAfter, ROLE_ADRIATIC_PIRATE_OID, task, result); @@ -580,14 +580,14 @@ public void test134JackAssignRoleAdriaticPirate() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", ROLE_PIRATE_TITLE); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "location", LOCALITY_TORTUGA); - // Outbound mapping for weapon is weak, therefore the mapping in role should override it + // Outbound mapping for weapon is weak, therefore the mapping in role should override it assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "weapon", ROLE_PIRATE_WEAPON); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow is the best pirate Tortuga has ever seen"); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_SEA_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_SEA_NAME, "jack sailed Adriatic, immediately Adriatic, role , with this The Seven Seas while focused on (in Pirate)"); } - + /** * Check if all the roles are visible in preview changes */ @@ -600,14 +600,14 @@ public void test135PreviewChangesEmptyDelta() throws Exception { OperationResult result = task.getResult(); PrismObject user = getUser(USER_JACK_OID); ObjectDelta delta = user.createModifyDelta(); - + // WHEN ModelContext modelContext = modelInteractionService.previewChanges(MiscSchemaUtil.createCollection(delta), getDefaultOptions(), task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + DeltaSetTriple evaluatedAssignmentTriple = modelContext.getEvaluatedAssignmentTriple(); PrismAsserts.assertTripleNoPlus(evaluatedAssignmentTriple); PrismAsserts.assertTripleNoMinus(evaluatedAssignmentTriple); @@ -621,7 +621,7 @@ 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 @@ -631,14 +631,14 @@ public void test136JackUnAssignRoleAdriaticPirate() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignRole(USER_JACK_OID, ROLE_ADRIATIC_PIRATE_OID, getDefaultOptions(), task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after", userJack); assertAssignments(userJack, 0); @@ -646,7 +646,7 @@ public void test136JackUnAssignRoleAdriaticPirate() throws Exception { assertDelegatedRef(userJack); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * Even though we assign Adriatic Pirate role which has a sea set in its extension the * sea set in user's extension should override it. @@ -658,21 +658,21 @@ public void test137JackAssignRoleAdriaticPirateWithSeaInAssignment() throws Exce Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismContainer extension = getAssignmentExtensionInstance(); PrismSchema piracySchema = getPiracySchema(); PrismPropertyDefinition seaPropDef = piracySchema.findPropertyDefinitionByElementName(PIRACY_SEA_QNAME); PrismProperty seaProp = seaPropDef.instantiate(); seaProp.setRealValue("Caribbean"); extension.add(seaProp); - + // WHEN assignRole(USER_JACK_OID, ROLE_ADRIATIC_PIRATE_OID, extension, getDefaultOptions(), task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignedRole(userAfter, ROLE_ADRIATIC_PIRATE_OID, task, result); @@ -681,14 +681,14 @@ public void test137JackAssignRoleAdriaticPirateWithSeaInAssignment() throws Exce assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", ROLE_PIRATE_TITLE); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "location", LOCALITY_TORTUGA); - // Outbound mapping for weapon is weak, therefore the mapping in role should override it + // Outbound mapping for weapon is weak, therefore the mapping in role should override it assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "weapon", ROLE_PIRATE_WEAPON); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow is the best pirate Tortuga has ever seen"); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_SEA_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_SEA_NAME, "jack sailed Caribbean, immediately Adriatic, role , with this The Seven Seas while focused on Caribbean (in Pirate)"); } - + @Test public void test139JackUnAssignRoleAdriaticPirateWithSeaInAssignment() throws Exception { final String TEST_NAME = "test139JackUnAssignRoleAdriaticPirateWithSeaInAssignment"; @@ -696,21 +696,21 @@ public void test139JackUnAssignRoleAdriaticPirateWithSeaInAssignment() throws Ex Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismContainer extension = getAssignmentExtensionInstance(); PrismSchema piracySchema = getPiracySchema(); PrismPropertyDefinition seaPropDef = piracySchema.findPropertyDefinitionByElementName(PIRACY_SEA_QNAME); PrismProperty seaProp = seaPropDef.instantiate(); seaProp.setRealValue("Caribbean"); extension.add(seaProp); - + // WHEN unassignRole(USER_JACK_OID, ROLE_ADRIATIC_PIRATE_OID, extension, getDefaultOptions(), task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after", userJack); assertAssignments(userJack, 0); @@ -718,7 +718,7 @@ public void test139JackUnAssignRoleAdriaticPirateWithSeaInAssignment() throws Ex assertDelegatedRef(userJack); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + @Test public void test144JackAssignRoleBlackSeaPirate() throws Exception { final String TEST_NAME = "test144JackAssignRoleBlackSeaPirate"; @@ -726,13 +726,13 @@ public void test144JackAssignRoleBlackSeaPirate() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignRole(USER_JACK_OID, ROLE_BLACK_SEA_PIRATE_OID, getDefaultOptions(), task, result); - + // THEN assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignedRole(userAfter, ROLE_BLACK_SEA_PIRATE_OID, task, result); @@ -742,14 +742,14 @@ public void test144JackAssignRoleBlackSeaPirate() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", ROLE_PIRATE_TITLE); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "location", LOCALITY_TORTUGA); - // Outbound mapping for weapon is weak, therefore the mapping in role should override it + // Outbound mapping for weapon is weak, therefore the mapping in role should override it assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "weapon", ROLE_PIRATE_WEAPON); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow is the best pirate Tortuga has ever seen"); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_SEA_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_SEA_NAME, "jack sailed Marmara Sea, immediately Marmara Sea, role Black Sea, with this The Seven Seas while focused on (in Pirate)"); } - + @Test public void test146JackUnAssignRoleBlackSeaPirate() throws Exception { final String TEST_NAME = "test146JackUnAssignRoleBlackSeaPirate"; @@ -757,14 +757,14 @@ public void test146JackUnAssignRoleBlackSeaPirate() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignRole(USER_JACK_OID, ROLE_BLACK_SEA_PIRATE_OID, getDefaultOptions(), task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after", userJack); assertAssignments(userJack, 0); @@ -772,7 +772,7 @@ public void test146JackUnAssignRoleBlackSeaPirate() throws Exception { assertDelegatedRef(userJack); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + @Test public void test147JackAssignRoleBlackSeaPirateWithSeaInAssignment() throws Exception { final String TEST_NAME = "test147JackAssignRoleBlackSeaPirateWithSeaInAssignment"; @@ -780,21 +780,21 @@ public void test147JackAssignRoleBlackSeaPirateWithSeaInAssignment() throws Exce Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismContainer extension = getAssignmentExtensionInstance(); PrismSchema piracySchema = getPiracySchema(); PrismPropertyDefinition seaPropDef = piracySchema.findPropertyDefinitionByElementName(PIRACY_SEA_QNAME); PrismProperty seaProp = seaPropDef.instantiate(); seaProp.setRealValue("Caribbean"); extension.add(seaProp); - + // WHEN assignRole(USER_JACK_OID, ROLE_BLACK_SEA_PIRATE_OID, extension, getDefaultOptions(), task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignedRole(userAfter, ROLE_BLACK_SEA_PIRATE_OID, task, result); @@ -804,14 +804,14 @@ public void test147JackAssignRoleBlackSeaPirateWithSeaInAssignment() throws Exce assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", ROLE_PIRATE_TITLE); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "location", LOCALITY_TORTUGA); - // Outbound mapping for weapon is weak, therefore the mapping in role should override it + // Outbound mapping for weapon is weak, therefore the mapping in role should override it assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "weapon", ROLE_PIRATE_WEAPON); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow is the best pirate Tortuga has ever seen"); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_SEA_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_SEA_NAME, "jack sailed Caribbean, immediately Marmara Sea, role Black Sea, with this The Seven Seas while focused on Caribbean (in Pirate)"); } - + @Test public void test149JackUnAssignRoleBlackSeaPirateWithSeaInAssignment() throws Exception { final String TEST_NAME = "test149JackUnAssignRoleBlackSeaPirateWithSeaInAssignment"; @@ -819,21 +819,21 @@ public void test149JackUnAssignRoleBlackSeaPirateWithSeaInAssignment() throws Ex Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismContainer extension = getAssignmentExtensionInstance(); PrismSchema piracySchema = getPiracySchema(); PrismPropertyDefinition seaPropDef = piracySchema.findPropertyDefinitionByElementName(PIRACY_SEA_QNAME); PrismProperty seaProp = seaPropDef.instantiate(); seaProp.setRealValue("Caribbean"); extension.add(seaProp); - + // WHEN unassignRole(USER_JACK_OID, ROLE_BLACK_SEA_PIRATE_OID, extension, getDefaultOptions(), task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after", userJack); assertAssignments(userJack, 0); @@ -841,7 +841,7 @@ public void test149JackUnAssignRoleBlackSeaPirateWithSeaInAssignment() throws Ex assertDelegatedRef(userJack); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + @Test public void test154JackAssignRoleIndianOceanPirate() throws Exception { final String TEST_NAME = "test154JackAssignRoleIndianOceanPirate"; @@ -849,17 +849,17 @@ public void test154JackAssignRoleIndianOceanPirate() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_INDIAN_OCEAN_PIRATE_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); display("Result", result); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignedRole(userAfter, ROLE_INDIAN_OCEAN_PIRATE_OID, task, result); @@ -869,14 +869,14 @@ public void test154JackAssignRoleIndianOceanPirate() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", ROLE_PIRATE_TITLE); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "location", LOCALITY_TORTUGA); - // Outbound mapping for weapon is weak, therefore the mapping in role should override it + // Outbound mapping for weapon is weak, therefore the mapping in role should override it assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "weapon", ROLE_PIRATE_WEAPON); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow is the best pirate Tortuga has ever seen"); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_SEA_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_SEA_NAME, "jack sailed Indian Ocean, immediately , role Indian Ocean, with this The Seven Seas while focused on (in Pirate)"); } - + @Test public void test156JackUnAssignRoleIndianOceanPirate() throws Exception { final String TEST_NAME = "test156JackUnAssignRoleIndianOceanPirate"; @@ -884,14 +884,14 @@ public void test156JackUnAssignRoleIndianOceanPirate() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignRole(USER_JACK_OID, ROLE_INDIAN_OCEAN_PIRATE_OID, getDefaultOptions(), task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after", userJack); assertAssignments(userJack, 0); @@ -899,8 +899,8 @@ public void test156JackUnAssignRoleIndianOceanPirate() throws Exception { assertDelegatedRef(userJack); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - - + + /** * Approver relation is not supposed to give any role privileges. * MID-3580 @@ -909,14 +909,14 @@ public void test156JackUnAssignRoleIndianOceanPirate() throws Exception { public void test160JackAssignRolePirateApprover() throws Exception { testJackAssignRolePirateRelationNoPrivs("test160JackAssignRolePirateApprover", SchemaConstants.ORG_APPROVER); } - + /** * MID-3580 */ @Test public void test162JackUnassignRolePirateApprover() throws Exception { testJackUnassignRolePirateRelationNoPrivs("test160JackAssignRolePirateApprover", SchemaConstants.ORG_APPROVER); - + } /** @@ -927,13 +927,13 @@ public void test162JackUnassignRolePirateApprover() throws Exception { public void test164JackAssignRolePirateOwner() throws Exception { testJackAssignRolePirateRelationNoPrivs("test164JackAssignRolePirateOwner", SchemaConstants.ORG_OWNER); } - + /** * MID-3580 */ @Test public void test166JackUnassignRolePirateOwner() throws Exception { - testJackUnassignRolePirateRelationNoPrivs("test166JackUnassignRolePirateOwner", SchemaConstants.ORG_OWNER); + testJackUnassignRolePirateRelationNoPrivs("test166JackUnassignRolePirateOwner", SchemaConstants.ORG_OWNER); } /** @@ -944,13 +944,13 @@ public void test166JackUnassignRolePirateOwner() throws Exception { public void test168JackAssignRolePirateComplicated() throws Exception { testJackAssignRolePirateRelationNoPrivs("test168JackAssignRolePirateComplicated", RELATION_COMPLICATED_QNAME); } - + /** * MID-3580 */ @Test public void test169JackUnassignRolePirateComplicated() throws Exception { - testJackUnassignRolePirateRelationNoPrivs("test169JackUnassignRolePirateComplicated", RELATION_COMPLICATED_QNAME); + testJackUnassignRolePirateRelationNoPrivs("test169JackUnassignRolePirateComplicated", RELATION_COMPLICATED_QNAME); } public void testJackAssignRolePirateRelationNoPrivs(final String TEST_NAME, QName relation) throws Exception { @@ -958,34 +958,34 @@ public void testJackAssignRolePirateRelationNoPrivs(final String TEST_NAME, QNam Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); assertNoAssignments(userBefore); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); - + // WHEN (1) displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_PIRATE_OID, relation, getDefaultOptions(), task, result); - + // THEN (1) displayThen(TEST_NAME); assertSuccess(result); assertJackAssignRolePirateRelationNoPrivs(relation); - + // WHEN (2) displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, getDefaultOptions(), task, result); - + // THEN (2) displayThen(TEST_NAME); assertSuccess(result); assertJackAssignRolePirateRelationNoPrivs(relation); } - + private void assertJackAssignRolePirateRelationNoPrivs(QName relation) throws Exception { PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); @@ -995,25 +995,25 @@ private void assertJackAssignRolePirateRelationNoPrivs(QName relation) throws Ex assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + public void testJackUnassignRolePirateRelationNoPrivs(final String TEST_NAME, QName relation) throws Exception { displayTestTitle(TEST_NAME); Task task = createTask(TEST_NAME); 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); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); @@ -1024,7 +1024,7 @@ public void testJackUnassignRolePirateRelationNoPrivs(final String TEST_NAME, QN // TODO: assign with owner relation // TODO: assign with custom(unknown) relation - + /** * Import role with dynamic target resolution. * Make sure that the reference is NOT resolved at import time. @@ -1036,10 +1036,10 @@ public void test200ImportRoleAllTreasure() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN importObjectFromFile(ROLE_ALL_TREASURE_FILE, task, result); - + // THEN assertSuccess(result); @@ -1048,7 +1048,7 @@ public void test200ImportRoleAllTreasure() throws Exception { ObjectReferenceType targetRef = roleAfter.asObjectable().getInducement().get(0).getTargetRef(); assertNull("Unexpected OID in targetRef", targetRef.getOid()); } - + /** * General simple test for roles with dynamic target resolution. */ @@ -1059,29 +1059,29 @@ public void test202JackAssignRoleAllTreasure() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); assertAssignments(userBefore, 0); - + // WHEN assignRole(USER_JACK_OID, ROLE_ALL_TREASURE_OID, getDefaultOptions(), task, result); - + // THEN assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignedRole(userAfter, ROLE_ALL_TREASURE_OID, task, result); - assertRoleMembershipRef(userAfter, ROLE_ALL_TREASURE_OID, + assertRoleMembershipRef(userAfter, ROLE_ALL_TREASURE_OID, ROLE_TREASURE_BRONZE_OID, ROLE_TREASURE_SILVER_OID); assertDelegatedRef(userAfter); assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", "Silver treasure", "Bronze treasure"); } - + /** * Add gold treasure role. This should be picked up by the dynamic * "all treasure" role. @@ -1093,27 +1093,27 @@ public void test204AddGoldTreasureAndRecomputeJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + addObject(ROLE_TREASURE_GOLD_FILE); - + // WHEN recomputeUser(USER_JACK_OID, getDefaultOptions(), task, result); - + // THEN assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignedRole(userAfter, ROLE_ALL_TREASURE_OID, task, result); - assertRoleMembershipRef(userAfter, ROLE_ALL_TREASURE_OID, + assertRoleMembershipRef(userAfter, ROLE_ALL_TREASURE_OID, ROLE_TREASURE_BRONZE_OID, ROLE_TREASURE_SILVER_OID, ROLE_TREASURE_GOLD_OID); assertDelegatedRef(userAfter); assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", "Silver treasure", "Bronze treasure", "Golden treasure"); } - + /** * MID-3966 */ @@ -1124,26 +1124,26 @@ public void test206JackAssignRoleAllLoot() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignRole(USER_JACK_OID, ROLE_ALL_LOOT_OID, getDefaultOptions(), task, result); - + // THEN assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignedRole(userAfter, ROLE_ALL_TREASURE_OID, task, result); - assertRoleMembershipRef(userAfter, ROLE_ALL_TREASURE_OID, + assertRoleMembershipRef(userAfter, ROLE_ALL_TREASURE_OID, ROLE_TREASURE_BRONZE_OID, ROLE_TREASURE_SILVER_OID, ROLE_TREASURE_GOLD_OID, ROLE_ALL_LOOT_OID, ROLE_LOOT_DIAMONDS_OID); assertDelegatedRef(userAfter); assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", "Silver treasure", "Bronze treasure", "Golden treasure", "Diamond loot"); } - + @Test public void test208JackUnassignRoleAllLoot() throws Exception { final String TEST_NAME = "test208JackUnassignRoleAllLoot"; @@ -1151,25 +1151,25 @@ public void test208JackUnassignRoleAllLoot() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignRole(USER_JACK_OID, ROLE_ALL_LOOT_OID, getDefaultOptions(), task, result); - + // THEN assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignedRole(userAfter, ROLE_ALL_TREASURE_OID, task, result); - assertRoleMembershipRef(userAfter, ROLE_ALL_TREASURE_OID, + assertRoleMembershipRef(userAfter, ROLE_ALL_TREASURE_OID, ROLE_TREASURE_BRONZE_OID, ROLE_TREASURE_SILVER_OID, ROLE_TREASURE_GOLD_OID); assertDelegatedRef(userAfter); assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", "Silver treasure", "Bronze treasure", "Golden treasure"); } - + @Test public void test209JackUnassignRoleAllTreasure() throws Exception { final String TEST_NAME = "test209JackUnassignRoleAllTreasure"; @@ -1177,20 +1177,20 @@ public void test209JackUnassignRoleAllTreasure() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignRole(USER_JACK_OID, ROLE_ALL_TREASURE_OID, getDefaultOptions(), task, result); - + // THEN assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 0); assertNoDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * MID-3966 */ @@ -1201,26 +1201,26 @@ public void test210JackAssignRoleAllYouCanGet() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignRole(USER_JACK_OID, ROLE_ALL_YOU_CAN_GET_OID, getDefaultOptions(), task, result); - + // THEN assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignedRole(userAfter, ROLE_ALL_YOU_CAN_GET_OID, task, result); - assertRoleMembershipRef(userAfter, ROLE_ALL_YOU_CAN_GET_OID, + assertRoleMembershipRef(userAfter, ROLE_ALL_YOU_CAN_GET_OID, ROLE_TREASURE_BRONZE_OID, ROLE_TREASURE_SILVER_OID, ROLE_TREASURE_GOLD_OID, ROLE_LOOT_DIAMONDS_OID); assertDelegatedRef(userAfter); assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", "Silver treasure", "Bronze treasure", "Golden treasure", "Diamond loot"); } - + @Test(enabled=false) // MID-3966 public void test219JackUnassignRoleAllYouCanGet() throws Exception { final String TEST_NAME = "test219JackUnassignRoleAllYouCanGet"; @@ -1228,42 +1228,42 @@ public void test219JackUnassignRoleAllYouCanGet() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignRole(USER_JACK_OID, ROLE_ALL_YOU_CAN_GET_OID, getDefaultOptions(), task, result); - + // THEN assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignments(userAfter, 0); assertNoDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME); } - + ////////////////////// // Following tests use POSITIVE enforcement mode ///////////////////// - + @Test public void test501JackAssignRolePirate() throws Exception { final String TEST_NAME = "test501JackAssignRolePirate"; displayTestTitle(TEST_NAME); - + // IMPORTANT: Changing the assignment policy assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignRole(USER_JACK_OID, ROLE_PIRATE_OID, getDefaultOptions(), task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignedRole(userAfter, ROLE_PIRATE_OID, task, result); @@ -1273,15 +1273,15 @@ public void test501JackAssignRolePirate() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", ROLE_PIRATE_TITLE); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "location", LOCALITY_TORTUGA); - // Outbound mapping for weapon is weak, therefore the mapping in role should override it + // Outbound mapping for weapon is weak, therefore the mapping in role should override it assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "weapon", ROLE_PIRATE_WEAPON); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow is the best pirate Tortuga has ever seen"); } - + /** * We modify Jack's "locality". As this is assigned by expression in the role to the dummy account, the account should - * be updated as well. + * be updated as well. */ @Test public void test502JackModifyUserLocality() throws Exception { @@ -1290,20 +1290,20 @@ public void test502JackModifyUserLocality() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // gossip is a tolerant attribute. Make sure there there is something to tolerate DummyAccount jackDummyAccount = getDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME); - jackDummyAccount.addAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + jackDummyAccount.addAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, EXISTING_GOSSIP); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, UserType.F_LOCALITY, getDefaultOptions(), task, result, createPolyString("Isla de Muerta")); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignedRole(userAfter, ROLE_PIRATE_OID, task, result); @@ -1314,12 +1314,12 @@ public void test502JackModifyUserLocality() throws Exception { assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", ROLE_PIRATE_TITLE); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "location", "Isla de Muerta"); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "weapon", ROLE_PIRATE_WEAPON); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow is the best pirate Isla de Muerta has ever seen", "Jack Sparrow is the best pirate Tortuga has ever seen", // Positive enforcement. This vales are not removed. EXISTING_GOSSIP); } - + /** * Assignment policy is POSITIVE, therefore the account should remain. */ @@ -1330,10 +1330,10 @@ public void test510UnAssignRolePirate() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, getDefaultOptions(), task, result); - + // THEN PrismObject userJack = getUser(USER_JACK_OID); display("User after", userJack); @@ -1343,12 +1343,12 @@ public void test510UnAssignRolePirate() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "location", "Isla de Muerta"); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow is the best pirate Isla de Muerta has ever seen", // Positive enforcement. This vales are not removed. "Jack Sparrow is the best pirate Tortuga has ever seen", // Positive enforcement. This vales are not removed. EXISTING_GOSSIP); } - + /** * This should go fine without any policy violation error. */ @@ -1359,18 +1359,18 @@ public void test511DeleteAccount() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userJack = getUser(USER_JACK_OID); String accountOid = userJack.asObjectable().getLinkRef().iterator().next().getOid(); - + ObjectDelta accountDelta = ObjectDelta.createDeleteDelta(ShadowType.class, accountOid, prismContext); // Use modification of user to delete account. Deleting account directly is tested later. ObjectDelta userDelta = ObjectDelta.createModificationDeleteReference(UserType.class, USER_JACK_OID, UserType.F_LINK_REF, prismContext, accountOid); Collection> deltas = MiscSchemaUtil.createCollection(userDelta, accountDelta); - + // WHEN modelService.executeChanges(deltas, getDefaultOptions(), task, result); - + // THEN userJack = getUser(USER_JACK_OID); display("User after", userJack); @@ -1380,25 +1380,25 @@ public void test511DeleteAccount() throws Exception { assertNoLinkedAccount(userJack); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + @Test public void test520JackAssignRolePirate() throws Exception { final String TEST_NAME = "test520JackAssignRolePirate"; displayTestTitle(TEST_NAME); - + // IMPORTANT: Changing the assignment policy assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignRole(USER_JACK_OID, ROLE_PIRATE_OID, getDefaultOptions(), task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignedRole(userAfter, ROLE_PIRATE_OID, task, result); @@ -1408,36 +1408,36 @@ public void test520JackAssignRolePirate() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", ROLE_PIRATE_TITLE); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "location", "Isla de Muerta"); - // Outbound mapping for weapon is weak, therefore the mapping in role should override it + // Outbound mapping for weapon is weak, therefore the mapping in role should override it assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "weapon", ROLE_PIRATE_WEAPON); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow is the best pirate Isla de Muerta has ever seen"); } - + @Test public void test521JackUnassignRolePirateDeleteAccount() throws Exception { final String TEST_NAME = "test521JackUnassignRolePirateDeleteAccount"; displayTestTitle(TEST_NAME); - + // IMPORTANT: Changing the assignment policy assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + Collection> modifications = new ArrayList<>(); modifications.add(createAssignmentModification(ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, null, null, false)); ObjectDelta userDelta = ObjectDelta.createModifyDelta(USER_JACK_OID, modifications, UserType.class, prismContext); - + PrismObject userJack = getUser(USER_JACK_OID); - String accountOid = userJack.asObjectable().getLinkRef().iterator().next().getOid(); + String accountOid = userJack.asObjectable().getLinkRef().iterator().next().getOid(); ObjectDelta accountDelta = ObjectDelta.createDeleteDelta(ShadowType.class, accountOid, prismContext); // This all goes in the same context with user, explicit unlink should not be necessary Collection> deltas = MiscSchemaUtil.createCollection(userDelta, accountDelta); - + // WHEN modelService.executeChanges(deltas, getDefaultOptions(), task, result); - + // THEN userJack = getUser(USER_JACK_OID); display("User after", userJack); @@ -1447,7 +1447,7 @@ public void test521JackUnassignRolePirateDeleteAccount() throws Exception { assertNoLinkedAccount(userJack); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + @Test public void test530JackAssignRoleCleric() throws Exception { final String TEST_NAME = "test530JackAssignRoleCleric"; @@ -1456,16 +1456,16 @@ public void test530JackAssignRoleCleric() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignRole(USER_JACK_OID, ROLE_CLERIC_OID, getDefaultOptions(), task, result); - + // THEN assertAssignedRole(USER_JACK_OID, ROLE_CLERIC_OID, task, result); assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", "Holy man"); } - + @Test public void test532JackModifyAssignmentRoleCleric() throws Exception { final String TEST_NAME = "test532JackModifyAssignmentRoleCleric"; @@ -1474,25 +1474,25 @@ public void test532JackModifyAssignmentRoleCleric() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject user = getObject(UserType.class, USER_JACK_OID); - + ItemPath itemPath = new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(user.asObjectable().getAssignment().get(0).getId()), new NameItemPathSegment(AssignmentType.F_DESCRIPTION)); ObjectDelta assignmentDelta = ObjectDelta.createModificationReplaceProperty( UserType.class, USER_JACK_OID, itemPath, prismContext, "soul"); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(assignmentDelta), getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignedRole(userAfter, ROLE_CLERIC_OID, task, result); @@ -1502,7 +1502,7 @@ public void test532JackModifyAssignmentRoleCleric() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", "Holy soul"); } - + @Test public void test539JackUnAssignRoleCleric() throws Exception { final String TEST_NAME = "test539JackUnAssignRoleCleric"; @@ -1511,23 +1511,23 @@ public void test539JackUnAssignRoleCleric() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject user = getObject(UserType.class, USER_JACK_OID); - + AssignmentType assignmentType = new AssignmentType(); assignmentType.setId(user.asObjectable().getAssignment().get(0).getId()); ObjectDelta assignmentDelta = ObjectDelta.createModificationDeleteContainer( UserType.class, USER_JACK_OID, UserType.F_ASSIGNMENT, prismContext, assignmentType); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(assignmentDelta), getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after", userJack); assertAssignedNoRole(userJack); @@ -1536,7 +1536,7 @@ public void test539JackUnAssignRoleCleric() throws Exception { assertNoLinkedAccount(userJack); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * Wannabe role is conditional. All conditions should be false now. So no provisioning should happen. */ @@ -1548,15 +1548,15 @@ public void test540JackAssignRoleWannabe() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_WANNABE_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignedRole(userAfter, ROLE_WANNABE_OID, task, result); @@ -1565,7 +1565,7 @@ public void test540JackAssignRoleWannabe() throws Exception { assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * Remove honorificSuffix. This triggers a condition in Wannabe role inducement. * But as the whole role has false condition nothing should happen. @@ -1578,11 +1578,11 @@ public void test541JackRemoveHonorificSuffixWannabe() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, UserType.F_HONORIFIC_SUFFIX, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); @@ -1607,15 +1607,15 @@ public void test542JackModifyEmployeeTypeWannabe() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, UserType.F_EMPLOYEE_TYPE, getDefaultOptions(), task, result, "wannabe"); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignedRole(userAfter, ROLE_WANNABE_OID, task, result); @@ -1625,7 +1625,7 @@ public void test542JackModifyEmployeeTypeWannabe() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", "Wannabe Cpt. Where's the rum?"); } - + /** * Remove honorificPrefix. This triggers a condition in Wannabe role and should remove an account. */ @@ -1637,11 +1637,11 @@ public void test543JackRemoveHonorificPrefixWannabe() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, UserType.F_HONORIFIC_PREFIX, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); @@ -1654,7 +1654,7 @@ public void test543JackRemoveHonorificPrefixWannabe() throws Exception { assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * Set honorificSuffix. This triggers conditions and adds a sub-role Honorable Wannabe. */ @@ -1666,16 +1666,16 @@ public void test544JackSetHonorificSuffixWannabe() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, UserType.F_HONORIFIC_SUFFIX, getDefaultOptions(), task, result, PrismTestUtil.createPolyString("PhD.")); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignedRole(userAfter, ROLE_WANNABE_OID, task, result); @@ -1683,10 +1683,10 @@ public void test544JackSetHonorificSuffixWannabe() throws Exception { assertDelegatedRef(userAfter); assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "Arr!", "Whatever. -- jack"); } - + /** * Restore honorificPrefix. The title should be replaced again. */ @@ -1698,12 +1698,12 @@ public void test545JackRestoreHonorificPrefixWannabe() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(USER_JACK_OID, UserType.F_HONORIFIC_PREFIX, getDefaultOptions(), task, result, PrismTestUtil.createPolyString("captain")); - + // THEN displayThen(TEST_NAME); assertSuccess(result); @@ -1717,7 +1717,7 @@ public void test545JackRestoreHonorificPrefixWannabe() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", "Wannabe captain Where's the rum?"); } - + /** * The account should be gone - regardless of the condition state. */ @@ -1729,15 +1729,15 @@ public void test549JackUnassignRoleWannabe() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_WANNABE_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertNotAssignedRole(userAfter, ROLE_WANNABE_OID, task, result); @@ -1746,7 +1746,7 @@ public void test549JackUnassignRoleWannabe() throws Exception { assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + @Test public void test600JackAssignRoleJudge() throws Exception { final String TEST_NAME = "test600JackAssignRoleJudge"; @@ -1755,13 +1755,13 @@ public void test600JackAssignRoleJudge() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN assignRole(USER_JACK_OID, ROLE_JUDGE_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1777,10 +1777,10 @@ public void test600JackAssignRoleJudge() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", "Honorable Justice"); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "weapon", "mouth", "pistol"); -// assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, +// assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, // "Jack Sparrow is the best pirate Caribbean has ever seen"); } - + /** * Judge and pirate are excluded roles. This should fail. */ @@ -1792,22 +1792,22 @@ public void test602JackAssignRolePirate() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + try { // WHEN assignRole(USER_JACK_OID, ROLE_PIRATE_OID, getDefaultOptions(), task, result); - + AssertJUnit.fail("Unexpected success"); } catch (PolicyViolationException e) { // this is expected display("Expected exception", e); } - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertFailure(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignedRole(userAfter, ROLE_JUDGE_OID, task, result); @@ -1818,7 +1818,7 @@ public void test602JackAssignRolePirate() throws Exception { assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", "Honorable Justice"); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "weapon", "mouth", "pistol"); } - + @Test public void test605JackUnAssignRoleJudgeAssignRolePirate() throws Exception { final String TEST_NAME = "test605JackUnAssignRoleJudgeAssignRolePirate"; @@ -1827,19 +1827,19 @@ public void test605JackUnAssignRoleJudgeAssignRolePirate() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta userDelta = createAssignmentUserDelta(USER_JACK_OID, ROLE_JUDGE_OID, RoleType.COMPLEX_TYPE, null, null, false); userDelta.addModification(createAssignmentModification(ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, null, null, true)); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignedRole(userAfter, ROLE_PIRATE_OID, task, result); @@ -1853,10 +1853,10 @@ public void test605JackUnAssignRoleJudgeAssignRolePirate() throws Exception { // the mapping is weak and the account already has a value for weapon from the times // Jack was a judge. So it is unchanged assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "weapon", "mouth", "pistol"); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Jack Sparrow is the best pirate Isla de Muerta has ever seen"); } - + @Test public void test609JackUnAssignRolePirate() throws Exception { final String TEST_NAME = "test609JackUnAssignRolePirate"; @@ -1865,19 +1865,19 @@ public void test609JackUnAssignRolePirate() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + @Test public void test610ElaineAssignRoleGovernor() throws Exception { final String TEST_NAME = "test610ElaineAssignRoleGovernor"; @@ -1886,15 +1886,15 @@ public void test610ElaineAssignRoleGovernor() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_ELAINE_OID); display("User before", userBefore); - + assertAssignees(ROLE_GOVERNOR_OID, 0); - + // WHEN assignRole(USER_ELAINE_OID, ROLE_GOVERNOR_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1909,10 +1909,10 @@ public void test610ElaineAssignRoleGovernor() throws Exception { assertAssignedRole(USER_ELAINE_OID, ROLE_GOVERNOR_OID, task, result); assertDefaultDummyAccount(ACCOUNT_ELAINE_DUMMY_USERNAME, ACCOUNT_ELAINE_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_ELAINE_DUMMY_USERNAME, "title", "Her Excellency Governor"); - + assertAssignees(ROLE_GOVERNOR_OID, 1); } - + /** * Governor has maxAssignees=1 */ @@ -1924,27 +1924,27 @@ public void test612JackAssignRoleGovernor() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + try { // WHEN assignRole(USER_JACK_OID, ROLE_GOVERNOR_OID, getDefaultOptions(), task, result); - + AssertJUnit.fail("Unexpected success"); } catch (PolicyViolationException e) { // this is expected display("Expected exception", e); } - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertFailure(result); - + assertNoAssignments(USER_JACK_OID); - + assertAssignees(ROLE_GOVERNOR_OID, 1); } - + /** * Governor has maxAssignees=0 for 'approver' */ @@ -1995,30 +1995,30 @@ public void test620LemonheadAssignRoleCanibal() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject user = createUser(USER_LEMONHEAD_NAME, USER_LEMONHEAD_FULLNAME, true); addObject(user); userLemonheadOid = user.getOid(); - + assertAssignees(ROLE_CANNIBAL_OID, 0); - + // WHEN displayWhen(TEST_NAME); assignRole(user.getOid(), ROLE_CANNIBAL_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertAssignedRole(user.getOid(), ROLE_CANNIBAL_OID, task, result); assertDefaultDummyAccount(USER_LEMONHEAD_NAME, USER_LEMONHEAD_FULLNAME, true); assertDefaultDummyAccountAttribute(USER_LEMONHEAD_NAME, "title", "Voracious Cannibal"); - + assertAssignees(ROLE_CANNIBAL_OID, 1); assertAssignees(ROLE_GOVERNOR_OID, 1); } - + @Test public void test622SharptoothAssignRoleCanibal() throws Exception { final String TEST_NAME = "test622SharptoothAssignRoleCanibal"; @@ -2027,30 +2027,30 @@ public void test622SharptoothAssignRoleCanibal() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject user = createUser(USER_SHARPTOOTH_NAME, USER_SHARPTOOTH_FULLNAME, true); addObject(user); userSharptoothOid = user.getOid(); - + assertAssignees(ROLE_CANNIBAL_OID, 1); - + // WHEN displayWhen(TEST_NAME); assignRole(user.getOid(), ROLE_CANNIBAL_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertAssignedRole(user.getOid(), ROLE_CANNIBAL_OID, task, result); assertDefaultDummyAccount(USER_SHARPTOOTH_NAME, USER_SHARPTOOTH_FULLNAME, true); assertDefaultDummyAccountAttribute(USER_SHARPTOOTH_NAME, "title", "Voracious Cannibal"); - + assertAssignees(ROLE_CANNIBAL_OID, 2); assertAssignees(ROLE_GOVERNOR_OID, 1); } - + @Test public void test624RedskullAssignRoleCanibal() throws Exception { final String TEST_NAME = "test624RedskullAssignRoleCanibal"; @@ -2059,26 +2059,26 @@ public void test624RedskullAssignRoleCanibal() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject user = createUser(USER_REDSKULL_NAME, USER_REDSKULL_FULLNAME, true); addObject(user); userRedskullOid = user.getOid(); - + assertAssignees(ROLE_CANNIBAL_OID, 2); - + // WHEN displayWhen(TEST_NAME); assignRole(user.getOid(), ROLE_CANNIBAL_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertAssignedRole(user.getOid(), ROLE_CANNIBAL_OID, task, result); assertDefaultDummyAccount(USER_REDSKULL_NAME, USER_REDSKULL_FULLNAME, true); assertDefaultDummyAccountAttribute(USER_REDSKULL_NAME, "title", "Voracious Cannibal"); - + assertAssignees(ROLE_CANNIBAL_OID, 3); assertAssignees(ROLE_GOVERNOR_OID, 1); } @@ -2091,35 +2091,35 @@ public void test625BignoseAssignRoleCanibal() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject user = createUser(USER_BIGNOSE_NAME, USER_BIGNOSE_FULLNAME, true); addObject(user); userBignoseOid = user.getOid(); - + assertAssignees(ROLE_CANNIBAL_OID, 3); - + try { // WHEN displayWhen(TEST_NAME); assignRole(user.getOid(), ROLE_CANNIBAL_OID, getDefaultOptions(), task, result); - + AssertJUnit.fail("Unexpected success"); } catch (PolicyViolationException e) { // this is expected display("Expected exception", e); } - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertFailure(result); - + assertNoAssignments(user.getOid()); - + assertAssignees(ROLE_CANNIBAL_OID, 3); assertAssignees(ROLE_GOVERNOR_OID, 1); } - + @Test public void test627SharptoothUnassignRoleCanibal() throws Exception { final String TEST_NAME = "test627SharptoothUnassignRoleCanibal"; @@ -2128,25 +2128,25 @@ public void test627SharptoothUnassignRoleCanibal() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assertAssignees(ROLE_CANNIBAL_OID, 3); - + // WHEN displayWhen(TEST_NAME); unassignRole(userSharptoothOid, ROLE_CANNIBAL_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertNoAssignments(userSharptoothOid); assertNoDummyAccount(USER_SHARPTOOTH_NAME); - + assertAssignees(ROLE_CANNIBAL_OID, 2); assertAssignees(ROLE_GOVERNOR_OID, 1); } - + @Test public void test628RedskullUnassignRoleCanibal() throws Exception { final String TEST_NAME = "test628RedskullUnassignRoleCanibal"; @@ -2155,29 +2155,29 @@ public void test628RedskullUnassignRoleCanibal() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assertAssignees(ROLE_CANNIBAL_OID, 2); - + try { // WHEN displayWhen(TEST_NAME); unassignRole(userRedskullOid, ROLE_CANNIBAL_OID, getDefaultOptions(), task, result); - + AssertJUnit.fail("Unexpected success"); } catch (PolicyViolationException e) { // this is expected display("Expected exception", e); } - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertFailure(result); - + assertAssignedRole(userRedskullOid, ROLE_CANNIBAL_OID, task, result); assertDefaultDummyAccount(USER_REDSKULL_NAME, USER_REDSKULL_FULLNAME, true); assertDefaultDummyAccountAttribute(USER_REDSKULL_NAME, "title", "Voracious Cannibal"); - + assertAssignees(ROLE_CANNIBAL_OID, 2); assertAssignees(ROLE_GOVERNOR_OID, 1); } @@ -2323,16 +2323,16 @@ public void test649ElaineUnassignRoleGovernor() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_ELAINE_OID); display("User before", userBefore); - + assertAssignees(ROLE_GOVERNOR_OID, 1); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_ELAINE_OID, ROLE_GOVERNOR_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -2341,7 +2341,7 @@ public void test649ElaineUnassignRoleGovernor() throws Exception { PrismObject userAfter = getUser(USER_ELAINE_OID); display("User after", userAfter); assertAssignedNoRole(userAfter); - + assertAssignees(ROLE_GOVERNOR_OID, 0); } @@ -2353,25 +2353,25 @@ public void test700JackAssignRoleJudge() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_JUDGE_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertAssignedRole(USER_JACK_OID, ROLE_JUDGE_OID, task, result); assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", "Honorable Justice"); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "weapon", "mouth", "pistol"); } - + @Test public void test701JackModifyJudgeDeleteConstructionRecompute() throws Exception { final String TEST_NAME = "test701JackModifyJudgeDeleteConstructionRecompute"; @@ -2381,10 +2381,10 @@ public void test701JackModifyJudgeDeleteConstructionRecompute() throws Exception Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); modifyRoleDeleteInducement(ROLE_JUDGE_OID, 1111L, true, getDefaultOptions(), task); @@ -2395,14 +2395,14 @@ public void test701JackModifyJudgeDeleteConstructionRecompute() throws Exception TestUtil.assertInProgressOrSuccess(result); assertTrue("task is not persistent", task.isPersistent()); - + assertAssignedRole(USER_JACK_OID, ROLE_JUDGE_OID, task, result); waitForTaskFinish(task.getOid(), true); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + @Test public void test702JackModifyJudgeAddInducementHonorabilityRecompute() throws Exception { final String TEST_NAME = "test702JackModifyJudgeAddInducementHonorabilityRecompute"; @@ -2412,10 +2412,10 @@ public void test702JackModifyJudgeAddInducementHonorabilityRecompute() throws Ex Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); modifyRoleAddInducementTarget(ROLE_JUDGE_OID, ROLE_HONORABILITY_OID, true, getDefaultOptions(), task); @@ -2434,11 +2434,11 @@ public void test702JackModifyJudgeAddInducementHonorabilityRecompute() throws Ex assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", "Honorable"); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "weapon", "mouth", "pistol"); - + assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "title", "Bloody Honorable"); } - + @Test public void test703JackModifyJudgeDeleteInducementHonorabilityRecompute() throws Exception { final String TEST_NAME = "test703JackModifyJudgeDeleteInducementHonorabilityRecompute"; @@ -2447,31 +2447,31 @@ public void test703JackModifyJudgeDeleteInducementHonorabilityRecompute() throws Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + modifyRoleDeleteInducementTarget(ROLE_JUDGE_OID, ROLE_HONORABILITY_OID, getDefaultOptions()); PrismObject roleJudge = modelService.getObject(RoleType.class, ROLE_JUDGE_OID, null, task, result); display("Role judge", roleJudge); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, ModelExecuteOptions.createReconcile(getDefaultOptions()), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertAssignedRole(USER_JACK_OID, ROLE_JUDGE_OID, task, result); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); - + assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, false); assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "title", "Bloody Honorable"); } - + @Test public void test709JackUnAssignRoleJudge() throws Exception { final String TEST_NAME = "test709JackUnAssignRoleJudge"; @@ -2480,14 +2480,14 @@ public void test709JackUnAssignRoleJudge() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_JUDGE_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -2496,7 +2496,7 @@ public void test709JackUnAssignRoleJudge() throws Exception { assertAssignedNoRole(USER_JACK_OID, task, result); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + @Test public void test710JackAssignRoleEmpty() throws Exception { final String TEST_NAME = "test710JackAssignRoleEmpty"; @@ -2506,23 +2506,23 @@ public void test710JackAssignRoleEmpty() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_EMPTY_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertAssignedRole(USER_JACK_OID, ROLE_EMPTY_OID, task, result); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + @Test public void test712JackModifyEmptyRoleAddInducementPirateRecompute() throws Exception { final String TEST_NAME = "test712JackModifyEmptyRoleAddInducementPirateRecompute"; @@ -2532,10 +2532,10 @@ public void test712JackModifyEmptyRoleAddInducementPirateRecompute() throws Exce Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); modifyRoleAddInducementTarget(ROLE_EMPTY_OID, ROLE_PIRATE_OID, true, getDefaultOptions(), task); @@ -2550,12 +2550,12 @@ public void test712JackModifyEmptyRoleAddInducementPirateRecompute() throws Exce assertAssignedRole(USER_JACK_OID, ROLE_EMPTY_OID, task, result); waitForTaskFinish(task.getOid(), true); - + assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "title", ROLE_PIRATE_TITLE); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, "weapon", ROLE_PIRATE_WEAPON); } - + @Test public void test714JackModifyEmptyRoleDeleteInducementPirateRecompute() throws Exception { final String TEST_NAME = "test714JackModifyEmptyRoleDeleteInducementPirateRecompute"; @@ -2564,26 +2564,26 @@ public void test714JackModifyEmptyRoleDeleteInducementPirateRecompute() throws E Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + modifyRoleDeleteInducementTarget(ROLE_EMPTY_OID, ROLE_PIRATE_OID, getDefaultOptions()); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertAssignedRole(USER_JACK_OID, ROLE_EMPTY_OID, task, result); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + @Test public void test719JackUnAssignRoleEmpty() throws Exception { final String TEST_NAME = "test719JackUnAssignRoleEmpty"; @@ -2592,19 +2592,19 @@ public void test719JackUnAssignRoleEmpty() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_EMPTY_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertAssignedNoRole(USER_JACK_OID, task, result); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } @@ -2618,29 +2618,29 @@ public void test720JackAssignRoleGovernorTenantRef() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + assertAssignees(ROLE_GOVERNOR_OID, 0); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); assignParametricRole(USER_JACK_OID, ROLE_GOVERNOR_OID, null, ORG_SCUMM_BAR_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertAssignedRole(USER_JACK_OID, ROLE_GOVERNOR_OID, task, result); assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, + assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Her Excellency Governor of Scumm Bar"); - + assertAssignees(ROLE_GOVERNOR_OID, 1); } - + @Test public void test729JackUnassignRoleGovernorTenantRef() throws Exception { final String TEST_NAME = "test729JackUnassignRoleGovernorTenantRef"; @@ -2650,27 +2650,27 @@ public void test729JackUnassignRoleGovernorTenantRef() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + assertAssignees(ROLE_GOVERNOR_OID, 1); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); unassignParametricRole(USER_JACK_OID, ROLE_GOVERNOR_OID, null, ORG_SCUMM_BAR_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertAssignedNoRole(USER_JACK_OID, task, result); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); - + assertAssignees(ROLE_GOVERNOR_OID, 0); } - + /** * MID-3365 */ @@ -2683,28 +2683,28 @@ public void test750JackAssignRoleOmnimanager() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_PROJECT_OMNINAMAGER_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRole(userAfter, ROLE_PROJECT_OMNINAMAGER_OID, task, result); - + assertHasOrg(userAfter, ORG_SAVE_ELAINE_OID, SchemaConstants.ORG_MANAGER); assertHasOrg(userAfter, ORG_KIDNAP_AND_MARRY_ELAINE_OID, SchemaConstants.ORG_MANAGER); } - + /** * MID-3365 */ @@ -2721,22 +2721,22 @@ public void test755AddProjectAndRecomputeJack() throws Exception { PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); assertAssignedRole(userBefore, ROLE_PROJECT_OMNINAMAGER_OID, task, result); - + addObject(ORG_PROJECT_RECLAIM_BLACK_PEARL_FILE); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, ModelExecuteOptions.createReconcile(getDefaultOptions()), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertAssignedRole(userAfter, ROLE_PROJECT_OMNINAMAGER_OID, task, result); - + assertHasOrg(userAfter, ORG_SAVE_ELAINE_OID, SchemaConstants.ORG_MANAGER); assertHasOrg(userAfter, ORG_KIDNAP_AND_MARRY_ELAINE_OID, SchemaConstants.ORG_MANAGER); assertHasOrg(userAfter, ORG_PROJECT_RECLAIM_BLACK_PEARL_OID, SchemaConstants.ORG_MANAGER); @@ -2754,27 +2754,27 @@ public void test759JackUnassignRoleOmnimanager() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_PROJECT_OMNINAMAGER_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertNotAssignedRole(userAfter, ROLE_PROJECT_OMNINAMAGER_OID, task, result); - + assertHasNoOrg(userAfter); } - + /** * Assign role with weak construction. Nothing should happen (no account). * MID-2850 @@ -2788,30 +2788,30 @@ public void test760JackAssignRoleWeakGossiper() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); assertAssignedNoRole(userBefore); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_WEAK_GOSSIPER_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRole(userAfter, ROLE_WEAK_GOSSIPER_OID); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * MID-2850 */ @@ -2824,27 +2824,27 @@ public void test762JackRecompute() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); assertAssignedRole(userBefore, ROLE_WEAK_GOSSIPER_OID); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRole(userAfter, ROLE_WEAK_GOSSIPER_OID); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } @@ -2860,27 +2860,27 @@ public void test763JackReconcile() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); assertAssignedRole(userBefore, ROLE_WEAK_GOSSIPER_OID); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_JACK_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRole(userAfter, ROLE_WEAK_GOSSIPER_OID); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } @@ -2898,34 +2898,34 @@ public void test764JackAssignRoleSailor() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); assertAssignedRole(userBefore, ROLE_WEAK_GOSSIPER_OID); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_SAILOR_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRole(userAfter, ROLE_WEAK_GOSSIPER_OID); assertAssignedRole(userAfter, ROLE_SAILOR_OID); - + assertDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_SAILOR_DRINK); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Pssst! hear this: dead men tell no tales"); } - + /** * MID-2850 */ @@ -2938,33 +2938,33 @@ public void test765JackRecompute() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRole(userAfter, ROLE_WEAK_GOSSIPER_OID); assertAssignedRole(userAfter, ROLE_SAILOR_OID); - + assertDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_SAILOR_DRINK); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Pssst! hear this: dead men tell no tales"); } - + /** * MID-2850 */ @@ -2977,33 +2977,33 @@ public void test766JackReconcile() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_JACK_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRole(userAfter, ROLE_WEAK_GOSSIPER_OID); assertAssignedRole(userAfter, ROLE_SAILOR_OID); - + assertDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_SAILOR_DRINK); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Pssst! hear this: dead men tell no tales"); } - + /** * Unassign role with weak construction. The values given by this construction * should be removed, but the other values should remain. @@ -3018,32 +3018,32 @@ public void test767JackUnAssignRoleWeakGossiper() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_WEAK_GOSSIPER_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRole(userAfter, ROLE_SAILOR_OID); - + assertDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_SAILOR_DRINK); - assertNoDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertNoDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME); } - + /** * MID-2850 */ @@ -3056,32 +3056,32 @@ public void test768JackRecompute() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRole(userAfter, ROLE_SAILOR_OID); - + assertDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_SAILOR_DRINK); - assertNoDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertNoDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME); } - + /** * MID-2850 */ @@ -3094,28 +3094,28 @@ public void test769JackUnAssignRoleSailor() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_SAILOR_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedNoRole(userAfter); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * Now assign the normal role first. * MID-2850 @@ -3129,32 +3129,32 @@ public void test770JackAssignRoleSailor() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_SAILOR_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRole(userAfter, ROLE_SAILOR_OID); - + assertDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_SAILOR_DRINK); - assertNoDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertNoDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME); } - + /** * Assign role with weak construction. It should be activated in a * usual way. @@ -3169,33 +3169,33 @@ public void test772JackAssignRoleGossiper() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_WEAK_GOSSIPER_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRole(userAfter, ROLE_WEAK_GOSSIPER_OID); assertAssignedRole(userAfter, ROLE_SAILOR_OID); - + assertDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_SAILOR_DRINK); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Pssst! hear this: dead men tell no tales"); } - + /** * Unassign normal role. Even though the role with weak construction remains, * it should not be applied. The account should be gone. @@ -3210,28 +3210,28 @@ public void test774JackUnAssignRoleSailor() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_SAILOR_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRole(userAfter, ROLE_WEAK_GOSSIPER_OID); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * Unassign role with weak construction. Nothing should really happen. * MID-2850 @@ -3245,29 +3245,29 @@ public void test775JackUnAssignRoleGossiper() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_WEAK_GOSSIPER_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedNoRole(userAfter); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - - + + /** * Assign both roles together (weak and normal). * MID-2850 @@ -3281,40 +3281,40 @@ public void test778JackAssignRoleGossiperAndSailor() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - - + + ObjectDelta userDelta = createAssignmentUserDelta(USER_JACK_OID, ROLE_WEAK_GOSSIPER_OID, RoleType.COMPLEX_TYPE, null, null, null, true); userDelta.addModification(createAssignmentModification(ROLE_SAILOR_OID, RoleType.COMPLEX_TYPE, null, null, null, true)); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(deltas, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRole(userAfter, ROLE_WEAK_GOSSIPER_OID); assertAssignedRole(userAfter, ROLE_SAILOR_OID); - + assertDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_SAILOR_DRINK); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Pssst! hear this: dead men tell no tales"); } - + /** * Unassign both roles together (weak and normal). * MID-2850 @@ -3328,34 +3328,34 @@ public void test779JackUnassignRoleGossiperAndSailor() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - - + + ObjectDelta userDelta = createAssignmentUserDelta(USER_JACK_OID, ROLE_WEAK_GOSSIPER_OID, RoleType.COMPLEX_TYPE, null, null, null, false); userDelta.addModification(createAssignmentModification(ROLE_SAILOR_OID, RoleType.COMPLEX_TYPE, null, null, null, false)); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(deltas, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedNoRole(userAfter); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * Assign role with weak construction. Nothing should happen (no account). * MID-2850, MID-3662 @@ -3369,32 +3369,32 @@ public void test780JackAssignRoleWeakSinger() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); assertAssignedNoRole(userBefore); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_WEAK_SINGER_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRole(userAfter, ROLE_WEAK_SINGER_OID); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } /** - * Assign another role with weak construction. Still nothing + * Assign another role with weak construction. Still nothing * should happen (no account). * MID-2850, MID-3662 */ @@ -3407,30 +3407,30 @@ public void test781JackAssignRoleWeakGossiper() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); assertAssignedRole(userBefore, ROLE_WEAK_SINGER_OID); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_WEAK_GOSSIPER_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRoles(userAfter, ROLE_WEAK_GOSSIPER_OID, ROLE_WEAK_SINGER_OID); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * Assign role with normal construction. Account should be created. * Both the normal and both weak constructions should be applied. @@ -3445,38 +3445,38 @@ public void test782JackAssignRoleSailor() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); assertAssignedRole(userBefore, ROLE_WEAK_GOSSIPER_OID); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_SAILOR_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRoles(userAfter, ROLE_WEAK_GOSSIPER_OID, ROLE_WEAK_SINGER_OID, ROLE_SAILOR_OID); - + assertDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_SAILOR_DRINK); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Pssst! hear this: dead men tell no tales"); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, ROLE_WEAK_SINGER_TITLE); } - + /** * Unassign role with normal construction. The account should be gone, - * the two weak roles should not be applied. + * the two weak roles should not be applied. * MID-2850, MID-3662 */ @Test @@ -3488,29 +3488,29 @@ public void test783JackUnassignRoleSailor() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); assertAssignedRole(userBefore, ROLE_WEAK_SINGER_OID); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_SAILOR_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRoles(userAfter, ROLE_WEAK_GOSSIPER_OID, ROLE_WEAK_SINGER_OID); assertNotAssignedRole(userAfter, ROLE_SAILOR_OID); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * MID-2850, MID-3662 */ @@ -3523,31 +3523,31 @@ public void test784JackUnAssignRoleWeakSinger() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_WEAK_SINGER_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRoles(userAfter, ROLE_WEAK_GOSSIPER_OID); assertNotAssignedRole(userAfter, ROLE_SAILOR_OID); assertNotAssignedRole(userAfter, ROLE_WEAK_SINGER_OID); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * MID-2850, MID-3662 */ @@ -3560,28 +3560,28 @@ public void test785JackUnAssignRoleGossiper() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, ROLE_WEAK_GOSSIPER_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedNoRole(userAfter); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * Assign both roles with weak construction together. Nothing should happen. * MID-2850, MID-3662 @@ -3595,35 +3595,35 @@ public void test786JackAssignRoleGossiperAndSinger() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - - + + ObjectDelta userDelta = createAssignmentUserDelta(USER_JACK_OID, ROLE_WEAK_GOSSIPER_OID, RoleType.COMPLEX_TYPE, null, null, null, true); userDelta.addModification(createAssignmentModification(ROLE_WEAK_SINGER_OID, RoleType.COMPLEX_TYPE, null, null, null, true)); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(deltas, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRoles(userAfter, ROLE_WEAK_GOSSIPER_OID, ROLE_WEAK_SINGER_OID); assertNotAssignedRole(userAfter, ROLE_SAILOR_OID); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * Unassign both roles with weak construction together. Nothing should happen. * MID-2850, MID-3662 @@ -3637,34 +3637,34 @@ public void test788JackUnassignRoleGossiperAndSinger() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - - + + ObjectDelta userDelta = createAssignmentUserDelta(USER_JACK_OID, ROLE_WEAK_GOSSIPER_OID, RoleType.COMPLEX_TYPE, null, null, null, false); userDelta.addModification(createAssignmentModification(ROLE_WEAK_SINGER_OID, RoleType.COMPLEX_TYPE, null, null, null, false)); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(deltas, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedNoRole(userAfter); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * Assign role with weak construction. Nothing should happen (no account). * Preparation for following tests. @@ -3679,30 +3679,30 @@ public void test790JackAssignRoleWeakSinger() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); assertAssignedNoRole(userBefore); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_WEAK_SINGER_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRole(userAfter, ROLE_WEAK_SINGER_OID); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * Switch: weak -> weak (strong absent) * Switch one role with weak construction for another role with weak @@ -3719,37 +3719,37 @@ public void test791JackSwitchRolesGossiperAndSinger() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); - + ObjectDelta userDelta = createAssignmentUserDelta(USER_JACK_OID, ROLE_WEAK_GOSSIPER_OID, RoleType.COMPLEX_TYPE, null, null, null, true); userDelta.addModification(createAssignmentModification(ROLE_WEAK_SINGER_OID, RoleType.COMPLEX_TYPE, null, null, null, false)); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(deltas, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRoles(userAfter, ROLE_WEAK_GOSSIPER_OID); assertNotAssignedRole(userAfter, ROLE_SAILOR_OID); assertNotAssignedRole(userAfter, ROLE_WEAK_SINGER_OID); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * MID-2850, MID-3662 */ @@ -3762,34 +3762,34 @@ public void test792JackAssignRoleSailor() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); assertAssignedRole(userBefore, ROLE_WEAK_GOSSIPER_OID); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_SAILOR_OID, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRoles(userAfter, ROLE_WEAK_GOSSIPER_OID, ROLE_SAILOR_OID); assertNotAssignedRole(userAfter, ROLE_WEAK_SINGER_OID); - + assertDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_SAILOR_DRINK); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Pssst! hear this: dead men tell no tales"); } - + /** * Switch: weak -> weak (strong present) * Switch one role with weak construction for another role with weak @@ -3807,40 +3807,40 @@ public void test793JackSwitchRolesSingerAndGossiper() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + ObjectDelta userDelta = createAssignmentUserDelta(USER_JACK_OID, ROLE_WEAK_GOSSIPER_OID, RoleType.COMPLEX_TYPE, null, null, null, false); userDelta.addModification(createAssignmentModification(ROLE_WEAK_SINGER_OID, RoleType.COMPLEX_TYPE, null, null, null, true)); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(deltas, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRoles(userAfter, ROLE_WEAK_SINGER_OID, ROLE_SAILOR_OID); assertNotAssignedRole(userAfter, ROLE_WEAK_GOSSIPER_OID); - + assertDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_SAILOR_DRINK); - assertNoDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertNoDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, ROLE_WEAK_SINGER_TITLE); } - + /** * Switch: strong -> weak * MID-2850, MID-3662 @@ -3854,34 +3854,34 @@ public void test794JackSwitchRolesSailorAndGossiper() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + ObjectDelta userDelta = createAssignmentUserDelta(USER_JACK_OID, ROLE_WEAK_GOSSIPER_OID, RoleType.COMPLEX_TYPE, null, null, null, true); userDelta.addModification(createAssignmentModification(ROLE_SAILOR_OID, RoleType.COMPLEX_TYPE, null, null, null, false)); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(deltas, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRoles(userAfter, ROLE_WEAK_SINGER_OID, ROLE_WEAK_GOSSIPER_OID); assertNotAssignedRole(userAfter, ROLE_SAILOR_OID); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - + /** * Switch: weak -> strong * MID-2850, MID-3662 @@ -3895,40 +3895,40 @@ public void test795JackSwitchRolesSingerAndSailor() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + ObjectDelta userDelta = createAssignmentUserDelta(USER_JACK_OID, ROLE_WEAK_SINGER_OID, RoleType.COMPLEX_TYPE, null, null, null, false); userDelta.addModification(createAssignmentModification(ROLE_SAILOR_OID, RoleType.COMPLEX_TYPE, null, null, null, true)); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(deltas, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRoles(userAfter, ROLE_WEAK_GOSSIPER_OID, ROLE_SAILOR_OID); assertNotAssignedRole(userAfter, ROLE_WEAK_SINGER_OID); - + assertDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_SAILOR_DRINK); - assertNoDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertNoDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Pssst! hear this: dead men tell no tales"); } - + /** * Switch: strong -> strong (weak present) * MID-2850, MID-3662 @@ -3942,41 +3942,41 @@ public void test796JackSwitchRolesSailorAndGovernor() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + ObjectDelta userDelta = createAssignmentUserDelta(USER_JACK_OID, ROLE_SAILOR_OID, RoleType.COMPLEX_TYPE, null, null, null, false); userDelta.addModification(createAssignmentModification(ROLE_GOVERNOR_OID, RoleType.COMPLEX_TYPE, null, null, null, true)); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(deltas, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedRoles(userAfter, ROLE_WEAK_GOSSIPER_OID, ROLE_GOVERNOR_OID); assertNotAssignedRole(userAfter, ROLE_WEAK_SINGER_OID); assertNotAssignedRole(userAfter, ROLE_SAILOR_OID); - + assertDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Her Excellency Governor"); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Pssst! hear this: dead men tell no tales"); } - + /** * Cleanup * MID-2850, MID-3662 @@ -3990,30 +3990,30 @@ public void test799JackUnassignGovernorAndWeakGossiper() throws Exception { Task task = createTask(TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - + ObjectDelta userDelta = createAssignmentUserDelta(USER_JACK_OID, ROLE_WEAK_GOSSIPER_OID, RoleType.COMPLEX_TYPE, null, null, null, false); userDelta.addModification(createAssignmentModification(ROLE_GOVERNOR_OID, RoleType.COMPLEX_TYPE, null, null, null, false)); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(deltas, getDefaultOptions(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - + assertAssignedNoRole(userAfter); - + assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } @@ -4025,13 +4025,13 @@ public void test800ModifyRoleImmutable() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + try { // WHEN displayWhen(TEST_NAME); modifyObjectReplaceProperty(RoleType.class, ROLE_IMMUTABLE_OID, RoleType.F_DESCRIPTION, getDefaultOptions(), task, result, "whatever"); - + AssertJUnit.fail("Unexpected success"); } catch (PolicyViolationException e) { // THEN @@ -4043,7 +4043,7 @@ public void test800ModifyRoleImmutable() throws Exception { PrismObject roleAfter = getObject(RoleType.class, ROLE_IMMUTABLE_OID); PrismAsserts.assertPropertyValue(roleAfter, RoleType.F_DESCRIPTION, ROLE_IMMUTABLE_DESCRIPTION); } - + /** * This should go well. The global immutable role has enforced modification, * but not addition. @@ -4056,10 +4056,10 @@ public void test802AddGlobalImmutableRole() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject role = PrismTestUtil.parseObject(ROLE_IMMUTABLE_GLOBAL_FILE); display("Role before", role); - + // WHEN displayWhen(TEST_NAME); addObject(role, getDefaultOptions(), task, result); @@ -4073,7 +4073,7 @@ public void test802AddGlobalImmutableRole() throws Exception { display("Role before", roleAfter); assertNotNull("No role added", roleAfter); } - + @Test public void test804ModifyRoleImmutableGlobalIdentifier() throws Exception { final String TEST_NAME = "test804ModifyRoleImmutableGlobalIdentifier"; @@ -4082,13 +4082,13 @@ public void test804ModifyRoleImmutableGlobalIdentifier() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + try { // WHEN displayWhen(TEST_NAME); modifyObjectReplaceProperty(RoleType.class, ROLE_IMMUTABLE_GLOBAL_OID, RoleType.F_IDENTIFIER, getDefaultOptions(), task, result, "whatever"); - + AssertJUnit.fail("Unexpected success"); } catch (PolicyViolationException e) { // THEN @@ -4101,7 +4101,7 @@ public void test804ModifyRoleImmutableGlobalIdentifier() throws Exception { PrismAsserts.assertPropertyValue(roleAfter, RoleType.F_DESCRIPTION, ROLE_IMMUTABLE_GLOBAL_DESCRIPTION); PrismAsserts.assertPropertyValue(roleAfter, RoleType.F_IDENTIFIER, ROLE_IMMUTABLE_GLOBAL_IDENTIFIER); } - + @Test public void test805ModifyRoleImmutableGlobalDescription() throws Exception { final String TEST_NAME = "test805ModifyRoleImmutableGlobalDescription"; @@ -4110,13 +4110,13 @@ public void test805ModifyRoleImmutableGlobalDescription() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + try { // WHEN displayWhen(TEST_NAME); modifyObjectReplaceProperty(RoleType.class, ROLE_IMMUTABLE_GLOBAL_OID, RoleType.F_DESCRIPTION, getDefaultOptions(), task, result, "whatever"); - + AssertJUnit.fail("Unexpected success"); } catch (PolicyViolationException e) { // THEN @@ -4214,7 +4214,7 @@ public void test815ModifyRoleImmutableGlobalDescription() throws Exception { PrismObject roleAfter = getObject(RoleType.class, ROLE_IMMUTABLE_DESCRIPTION_GLOBAL_OID); PrismAsserts.assertPropertyValue(roleAfter, RoleType.F_DESCRIPTION, ROLE_IMMUTABLE_DESCRIPTION_GLOBAL_DESCRIPTION); } - + @Test public void test826AddNonCreateableRole() throws Exception { final String TEST_NAME = "test826AddNonCreateableRole"; @@ -4223,15 +4223,15 @@ public void test826AddNonCreateableRole() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject role = PrismTestUtil.parseObject(ROLE_NON_CREATEABLE_FILE); display("Role before", role); - + try { // WHEN displayWhen(TEST_NAME); addObject(role, getDefaultOptions(), task, result); - + AssertJUnit.fail("Unexpected success"); } catch (PolicyViolationException e) { // THEN @@ -4255,15 +4255,15 @@ public void test827AddImmutableAssignRole() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject role = PrismTestUtil.parseObject(ROLE_IMMUTABLE_ASSIGN_FILE); display("Role before", role); - + try { // WHEN displayWhen(TEST_NAME); addObject(role, getDefaultOptions(), task, result); - + AssertJUnit.fail("Unexpected success"); } catch (PolicyViolationException e) { // THEN @@ -4274,7 +4274,7 @@ public void test827AddImmutableAssignRole() throws Exception { assertNoObject(RoleType.class, ROLE_IMMUTABLE_ASSIGN_OID); } - + /** * The untouchable metarole has immutable policy rule in the * inducement. So it will apply to member roles, but not to the @@ -4288,12 +4288,12 @@ public void test828ModifyUntouchableMetarole() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); modifyObjectReplaceProperty(RoleType.class, ROLE_META_UNTOUCHABLE_OID, RoleType.F_DESCRIPTION, getDefaultOptions(), task, result, "Touche!"); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -4311,12 +4311,12 @@ public void test830ModifyRoleJudge() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); modifyObjectReplaceProperty(RoleType.class, ROLE_JUDGE_OID, RoleType.F_DESCRIPTION, getDefaultOptions(), task, result, "whatever"); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -4325,7 +4325,7 @@ public void test830ModifyRoleJudge() throws Exception { PrismObject roleAfter = getObject(RoleType.class, ROLE_JUDGE_OID); PrismAsserts.assertPropertyValue(roleAfter, RoleType.F_DESCRIPTION, "whatever"); } - + @Test public void test840AssignRoleNonAssignable() throws Exception { final String TEST_NAME = "test840AssignRoleNonAssignable"; @@ -4334,16 +4334,16 @@ public void test840AssignRoleNonAssignable() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userJackBefore = getUser(USER_JACK_OID); display("user jack", userJackBefore); assertNoAssignments(userJackBefore); - + try { // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_NON_ASSIGNABLE_OID, getDefaultOptions(), task, result); - + AssertJUnit.fail("Unexpected success"); } catch (PolicyViolationException e) { // THEN diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestRbacDeprecated.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestRbacDeprecated.java index bb6ddd1864c..4a7a6093677 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestRbacDeprecated.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestRbacDeprecated.java @@ -28,10 +28,10 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestRbacDeprecated extends TestRbac { - + protected static final File ROLE_GOVERNOR_DEPRECATED_FILE = new File(TEST_DIR, "role-governor-deprecated.xml"); protected static final File ROLE_CANNIBAL_DEPRECATED_FILE = new File(TEST_DIR, "role-cannibal-deprecated.xml"); - + @Override protected File getRoleGovernorFile() { return ROLE_GOVERNOR_DEPRECATED_FILE; 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 6385e3b55f9..aed73a2b26e 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 @@ -71,63 +71,63 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestSegregationOfDuties extends AbstractInitializedModelIntegrationTest { - + protected static final File TEST_DIR = new File("src/test/resources/rbac/sod"); - + // Gold, silver and bronze: mutual exclusion (prune), directly in the roles - + protected static final File ROLE_PRIZE_GOLD_FILE = new File(TEST_DIR, "role-prize-gold.xml"); protected static final String ROLE_PRIZE_GOLD_OID = "bbc22f82-df21-11e6-aa6b-4b1408befd10"; protected static final String ROLE_PRIZE_GOLD_SHIP = "Gold"; - + protected static final File ROLE_PRIZE_SILVER_FILE = new File(TEST_DIR, "role-prize-silver.xml"); protected static final String ROLE_PRIZE_SILVER_OID = "dfb5fffe-df21-11e6-bb4f-ef02bdbc9d71"; protected static final String ROLE_PRIZE_SILVER_SHIP = "Silver"; - + protected static final File ROLE_PRIZE_BRONZE_FILE = new File(TEST_DIR, "role-prize-bronze.xml"); protected static final String ROLE_PRIZE_BRONZE_OID = "19f11686-df22-11e6-b0e9-835ed7ca08a5"; protected static final String ROLE_PRIZE_BRONZE_SHIP = "Bronze"; - + // 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"; protected static final String ROLE_COLOR_RED_SHIP = "Red"; - + protected static final File ROLE_COLOR_GREEN_FILE = new File(TEST_DIR, "role-color-green.xml"); protected static final String ROLE_COLOR_GREEN_OID = "2fd9e8f4-df29-11e6-9605-cfcedd703b9e"; protected static final String ROLE_COLOR_GREEN_SHIP = "Green"; - + protected static final File ROLE_COLOR_BLUE_FILE = new File(TEST_DIR, "role-color-blue.xml"); protected static final String ROLE_COLOR_BLUE_OID = "553e8df2-df29-11e6-a7ca-cb7c1f38d89f"; protected static final String ROLE_COLOR_BLUE_SHIP = "Blue"; - + protected static final File ROLE_COLOR_NONE_FILE = new File(TEST_DIR, "role-color-none.xml"); protected static final String ROLE_COLOR_NONE_OID = "662a997e-df2b-11e6-9bb3-5f235d1a8e60"; - + // 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"; - + protected static final File ROLE_EXECUTIVE_2_FILE = new File(TEST_DIR, "role-executive-2.xml"); 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"; - + protected static final File ROLE_CONTROLLING_2_FILE = new File(TEST_DIR, "role-controlling-2.xml"); protected static final String ROLE_CONTROLLING_2_OID = "d20aefe6-3ecf-11e7-8068-5f346db1cc02"; - + protected static final File ROLE_CITIZEN_SK_FILE = new File(TEST_DIR, "role-citizen-sk.xml"); protected static final String ROLE_CITIZEN_SK_OID = "88420574-5596-11e7-80e9-7f28005e6b39"; @@ -142,23 +142,23 @@ public class TestSegregationOfDuties extends AbstractInitializedModelIntegration private static final File CONFIG_WITH_GLOBAL_RULES_EXCLUSION_FILE = new File(TEST_DIR, "global-policy-rules-exclusion.xml"); private static final File CONFIG_WITH_GLOBAL_RULES_SOD_APPROVAL_FILE = new File(TEST_DIR, "global-policy-rules-sod-approval.xml"); - + private static final String GLOBAL_POLICY_RULE_SOD_APPROVAL_NAME = "exclusion-global-sod-approval"; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + repoAddObjectFromFile(ROLE_PRIZE_GOLD_FILE, initResult); repoAddObjectFromFile(ROLE_PRIZE_SILVER_FILE, initResult); repoAddObjectFromFile(ROLE_PRIZE_BRONZE_FILE, initResult); - + repoAddObjectFromFile(ROLE_META_COLOR_FILE, initResult); repoAddObjectFromFile(ROLE_COLOR_RED_FILE, initResult); repoAddObjectFromFile(ROLE_COLOR_GREEN_FILE, initResult); repoAddObjectFromFile(ROLE_COLOR_BLUE_FILE, initResult); repoAddObjectFromFile(ROLE_COLOR_NONE_FILE, initResult); - + repoAddObjectFromFile(ROLE_META_EXECUTIVE_FILE, initResult); repoAddObjectFromFile(ROLE_EXECUTIVE_1_FILE, initResult); repoAddObjectFromFile(ROLE_EXECUTIVE_2_FILE, initResult); @@ -170,7 +170,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti repoAddObjectFromFile(ROLE_MINISTER_FILE, initResult); repoAddObjectFromFile(ROLE_CRIMINAL_FILE, initResult); } - + @Test public void test110SimpleExclusion1() throws Exception { final String TEST_NAME = "test110SimpleExclusion1"; @@ -178,28 +178,28 @@ public void test110SimpleExclusion1() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // This should go well assignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); - + assertSuccess(result); - + try { // This should die assignRole(USER_JACK_OID, ROLE_JUDGE_OID, task, result); - + fail("Expected policy violation after adding judge role, but it went well"); } catch (PolicyViolationException e) { // This is expected result.computeStatus(); assertFailure(result); } - + unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); - + assertAssignedNoRole(USER_JACK_OID, task, result); } - + @Test public void test112SimpleExclusion1Deprecated() throws Exception { final String TEST_NAME = "test112SimpleExclusion1Deprecated"; @@ -207,226 +207,226 @@ public void test112SimpleExclusion1Deprecated() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // This should go well assignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); - + try { // This should die assignRole(USER_JACK_OID, ROLE_JUDGE_DEPRECATED_OID, task, result); - + AssertJUnit.fail("Expected policy violation after adding judge role, but it went well"); } catch (PolicyViolationException e) { // This is expected } - + unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); - + assertAssignedNoRole(USER_JACK_OID, task, result); } - + /** - * Same thing as before but other way around + * Same thing as before but other way around */ @Test public void test120SimpleExclusion2() throws Exception { final String TEST_NAME = "test120SimpleExclusion2"; displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // This should go well assignRole(USER_JACK_OID, ROLE_JUDGE_OID, task, result); - + try { // This should die assignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); - + AssertJUnit.fail("Expected policy violation after adding pirate role, but it went well"); } catch (PolicyViolationException e) { // This is expected } - + unassignRole(USER_JACK_OID, ROLE_JUDGE_OID, task, result); assertAssignedNoRole(USER_JACK_OID, task, result); } - + /** - * Same thing as before but other way around + * Same thing as before but other way around */ @Test public void test122SimpleExclusion2Deprecated() throws Exception { final String TEST_NAME = "test122SimpleExclusion2Deprecated"; displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // This should go well assignRole(USER_JACK_OID, ROLE_JUDGE_DEPRECATED_OID, task, result); - + try { // This should die assignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); - + AssertJUnit.fail("Expected policy violation after adding pirate role, but it went well"); } catch (PolicyViolationException e) { // This is expected } - + unassignRole(USER_JACK_OID, ROLE_JUDGE_DEPRECATED_OID, task, result); assertAssignedNoRole(USER_JACK_OID, task, result); } - + @Test public void test130SimpleExclusionBoth1() throws Exception { final String TEST_NAME = "test130SimpleExclusionBoth1"; displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + 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 = ObjectDelta.createModifyDelta(USER_JACK_OID, modifications, UserType.class, prismContext); - - + + try { modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + AssertJUnit.fail("Expected policy violation, but it went well"); } catch (PolicyViolationException e) { // This is expected } - + assertAssignedNoRole(USER_JACK_OID, task, result); } - + @Test public void test132SimpleExclusionBoth1Deprecated() throws Exception { final String TEST_NAME = "test132SimpleExclusionBoth1Deprecated"; displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + Collection> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(ROLE_JUDGE_DEPRECATED_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); modifications.add((createAssignmentModification(ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); ObjectDelta userDelta = ObjectDelta.createModifyDelta(USER_JACK_OID, modifications, UserType.class, prismContext); - - + + try { modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + AssertJUnit.fail("Expected policy violation, but it went well"); } catch (PolicyViolationException e) { // This is expected } - + assertAssignedNoRole(USER_JACK_OID, task, result); } - + @Test public void test140SimpleExclusionBoth2() throws Exception { final String TEST_NAME = "test140SimpleExclusionBoth2"; displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + 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 = ObjectDelta.createModifyDelta(USER_JACK_OID, modifications, UserType.class, prismContext); - - + + try { modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + AssertJUnit.fail("Expected policy violation, but it went well"); } catch (PolicyViolationException e) { // This is expected } - + assertAssignedNoRole(USER_JACK_OID, task, result); } - + @Test public void test142SimpleExclusionBoth2Deprecated() throws Exception { final String TEST_NAME = "test142SimpleExclusionBoth2Deprecated"; displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + Collection> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); modifications.add((createAssignmentModification(ROLE_JUDGE_DEPRECATED_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); ObjectDelta userDelta = ObjectDelta.createModifyDelta(USER_JACK_OID, modifications, UserType.class, prismContext); - - + + try { modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + AssertJUnit.fail("Expected policy violation, but it went well"); } catch (PolicyViolationException e) { // This is expected } - + assertAssignedNoRole(USER_JACK_OID, task, result); } - + @Test public void test150SimpleExclusionBothBidirectional1() throws Exception { final String TEST_NAME = "test150SimpleExclusionBothBidirectional1"; displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + 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 = ObjectDelta.createModifyDelta(USER_JACK_OID, modifications, UserType.class, prismContext); - + try { modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + AssertJUnit.fail("Expected policy violation, but it went well"); } catch (PolicyViolationException e) { // This is expected } - + assertAssignedNoRole(USER_JACK_OID, task, result); } - + @Test public void test160SimpleExclusionBothBidirectional2() throws Exception { final String TEST_NAME = "test160SimpleExclusionBothBidirectional2"; displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + 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 = ObjectDelta.createModifyDelta(USER_JACK_OID, modifications, UserType.class, prismContext); - + try { modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); - + AssertJUnit.fail("Expected policy violation, but it went well"); } catch (PolicyViolationException e) { // This is expected } - + assertAssignedNoRole(USER_JACK_OID, task, result); } - + @Test public void test171SimpleExclusion1WithPolicyException() throws Exception { final String TEST_NAME = "test171SimpleExclusion1WithPolicyException"; @@ -434,21 +434,21 @@ public void test171SimpleExclusion1WithPolicyException() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assignRole(USER_JACK_OID, ROLE_JUDGE_OID, task, result); - + assignRole(USER_JACK_OID, ROLE_PIRATE_OID, null, getJudgeExceptionBlock(ROLE_PIRATE_NAME), task, result); - + PrismObject userJackIn = getUser(USER_JACK_OID); assertAssignedRoles(userJackIn, ROLE_JUDGE_OID, ROLE_PIRATE_OID); - + 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); } - + @Test public void test172SimpleExclusion2WithPolicyException() throws Exception { final String TEST_NAME = "test172SimpleExclusion2WithPolicyException"; @@ -456,21 +456,21 @@ public void test172SimpleExclusion2WithPolicyException() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assignRole(USER_JACK_OID, ROLE_PIRATE_OID, null, getJudgeExceptionBlock(ROLE_PIRATE_NAME), task, result); assignRole(USER_JACK_OID, ROLE_JUDGE_OID, task, result); - + PrismObject userJackIn = getUser(USER_JACK_OID); assertAssignedRoles(userJackIn, ROLE_JUDGE_OID, ROLE_PIRATE_OID); - + 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); } - + @Test public void test173SimpleExclusion3WithPolicyException() throws Exception { final String TEST_NAME = "test173SimpleExclusion3WithPolicyException"; @@ -478,18 +478,18 @@ public void test173SimpleExclusion3WithPolicyException() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); - + assignRole(USER_JACK_OID, ROLE_JUDGE_OID, null, getJudgeExceptionBlock(ROLE_PIRATE_NAME), task, result); - + PrismObject userJackIn = getUser(USER_JACK_OID); assertAssignedRoles(userJackIn, ROLE_JUDGE_OID, ROLE_PIRATE_OID); - + unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); - + unassignRole(USER_JACK_OID, ROLE_JUDGE_OID, null, getJudgeExceptionBlock(ROLE_PIRATE_NAME), task, result); - + assertAssignedNoRole(USER_JACK_OID, task, result); } @@ -500,21 +500,21 @@ public void test174SimpleExclusion4WithPolicyException() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assignRole(USER_JACK_OID, ROLE_JUDGE_OID, null, getJudgeExceptionBlock(ROLE_PIRATE_NAME), task, result); assignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); - + PrismObject userJackIn = getUser(USER_JACK_OID); assertAssignedRoles(userJackIn, ROLE_JUDGE_OID, ROLE_PIRATE_OID); - + unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); - + unassignRole(USER_JACK_OID, ROLE_JUDGE_OID, null, getJudgeExceptionBlock(ROLE_PIRATE_NAME), task, result); - + assertAssignedNoRole(USER_JACK_OID, task, result); } - + /** * Add pirate role to judge. But include policy exception in the pirate assignment, so it * should go OK. The assign thief (without exception). The exception in the pirate assignment @@ -527,28 +527,28 @@ public void test180JudgeExceptionalPirateAndThief() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + assignRole(USER_JACK_OID, ROLE_JUDGE_OID, task, result); - + assignRole(USER_JACK_OID, ROLE_PIRATE_OID, null, getJudgeExceptionBlock(ROLE_PIRATE_NAME), task, result); - + PrismObject userJackIn = getUser(USER_JACK_OID); assertAssignedRoles(userJackIn, ROLE_JUDGE_OID, ROLE_PIRATE_OID); - + try { // This should die assignRole(USER_JACK_OID, ROLE_THIEF_OID, task, result); - + AssertJUnit.fail("Expected policy violation after adding thief role, but it went well"); } catch (PolicyViolationException e) { // This is expected } - + // Cleanup - + 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); } @@ -559,7 +559,7 @@ Consumer getJudgeExceptionBlock(String excludedRoleName) { assignment.getPolicyException().add(policyException); }; } - + /** * MID-3685 */ @@ -571,26 +571,26 @@ public void test200GuybrushAssignRoleGold() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_PRIZE_GOLD_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignedRole(userAfter, ROLE_PRIZE_GOLD_OID); assertNotAssignedRole(userAfter, ROLE_PRIZE_SILVER_OID); assertNotAssignedRole(userAfter, ROLE_PRIZE_BRONZE_OID); - + assertDummyAccount(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, ROLE_PRIZE_GOLD_SHIP); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK); } @@ -605,29 +605,29 @@ public void test202GuybrushAssignRoleSilver() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_PRIZE_SILVER_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertNotAssignedRole(userAfter, ROLE_PRIZE_GOLD_OID); assertAssignedRole(userAfter, ROLE_PRIZE_SILVER_OID); assertNotAssignedRole(userAfter, ROLE_PRIZE_BRONZE_OID); - + assertDummyAccount(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, ROLE_PRIZE_SILVER_SHIP); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK); } - + /** * Mix in ordinary role to check for interferences. * MID-3685 @@ -640,31 +640,31 @@ public void test204GuybrushAssignRoleSailor() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_SAILOR_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertNotAssignedRole(userAfter, ROLE_PRIZE_GOLD_OID); assertAssignedRole(userAfter, ROLE_PRIZE_SILVER_OID); assertNotAssignedRole(userAfter, ROLE_PRIZE_BRONZE_OID); assertAssignedRole(userAfter, ROLE_SAILOR_OID); - + assertDummyAccount(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, ROLE_PRIZE_SILVER_SHIP); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_SAILOR_DRINK); } - - + + /** * MID-3685 */ @@ -676,30 +676,30 @@ public void test206GuybrushAssignRoleBronze() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_PRIZE_BRONZE_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertNotAssignedRole(userAfter, ROLE_PRIZE_GOLD_OID); assertNotAssignedRole(userAfter, ROLE_PRIZE_SILVER_OID); assertAssignedRole(userAfter, ROLE_PRIZE_BRONZE_OID); assertAssignedRole(userAfter, ROLE_SAILOR_OID); - + assertDummyAccount(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, ROLE_PRIZE_BRONZE_SHIP); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_SAILOR_DRINK); } - + /** * MID-3685 */ @@ -711,16 +711,16 @@ public void test208GuybrushUnassignRoleBronze() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); unassignRole(USER_GUYBRUSH_OID, ROLE_PRIZE_BRONZE_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertNotAssignedRole(userAfter, ROLE_PRIZE_GOLD_OID); @@ -729,7 +729,7 @@ public void test208GuybrushUnassignRoleBronze() throws Exception { assertAssignedRole(userAfter, ROLE_SAILOR_OID); assertDummyAccount(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_SAILOR_DRINK); } @@ -744,16 +744,16 @@ public void test209GuybrushUnassignRoleSailor() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); unassignRole(USER_GUYBRUSH_OID, ROLE_SAILOR_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignedNoRole(userAfter); @@ -772,27 +772,27 @@ public void test210GuybrushAssignRoleRed() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_COLOR_RED_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignedRole(userAfter, ROLE_COLOR_RED_OID); assertNotAssignedRole(userAfter, ROLE_COLOR_GREEN_OID); assertNotAssignedRole(userAfter, ROLE_COLOR_BLUE_OID); assertNotAssignedRole(userAfter, ROLE_COLOR_NONE_OID); - + assertDummyAccount(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, ROLE_COLOR_RED_SHIP); } - + /** * MID-3685 */ @@ -804,28 +804,28 @@ public void test212GuybrushAssignRoleGreen() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_COLOR_GREEN_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertNotAssignedRole(userAfter, ROLE_COLOR_RED_OID); assertAssignedRole(userAfter, ROLE_COLOR_GREEN_OID); assertNotAssignedRole(userAfter, ROLE_COLOR_BLUE_OID); assertNotAssignedRole(userAfter, ROLE_COLOR_NONE_OID); - + assertDummyAccount(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, ROLE_COLOR_GREEN_SHIP); } - + /** * MID-3685 */ @@ -837,26 +837,26 @@ public void test214GuybrushAssignRoleColorNone() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_COLOR_NONE_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertNotAssignedRole(userAfter, ROLE_COLOR_RED_OID); assertNotAssignedRole(userAfter, ROLE_COLOR_GREEN_OID); assertNotAssignedRole(userAfter, ROLE_COLOR_BLUE_OID); assertAssignedRole(userAfter, ROLE_COLOR_NONE_OID); - + assertNoDummyAccount(ACCOUNT_GUYBRUSH_DUMMY_USERNAME); } - + /** * MID-3685 */ @@ -868,25 +868,25 @@ public void test216GuybrushAssignRoleBlue() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_COLOR_BLUE_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertNotAssignedRole(userAfter, ROLE_COLOR_RED_OID); assertNotAssignedRole(userAfter, ROLE_COLOR_GREEN_OID); assertAssignedRole(userAfter, ROLE_COLOR_BLUE_OID); assertNotAssignedRole(userAfter, ROLE_COLOR_NONE_OID); - + assertDummyAccount(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, ROLE_COLOR_BLUE_SHIP); } @@ -898,15 +898,15 @@ public void test219GuybrushUnassignRoleBlue() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_GUYBRUSH_OID, ROLE_COLOR_BLUE_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertNotAssignedRole(userAfter, ROLE_COLOR_RED_OID); @@ -914,10 +914,10 @@ public void test219GuybrushUnassignRoleBlue() throws Exception { assertNotAssignedRole(userAfter, ROLE_COLOR_BLUE_OID); assertNotAssignedRole(userAfter, ROLE_COLOR_NONE_OID); assertAssignments(userAfter, 0); - + assertNoDummyAccount(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); } - + /** * MID-3694 */ @@ -929,20 +929,20 @@ public void test220GuybrushAssignRoleExecutiveOne() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_EXECUTIVE_1_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertAssignedRole(userAfter, ROLE_EXECUTIVE_1_OID); + assertAssignedRole(userAfter, ROLE_EXECUTIVE_1_OID); } - + /** * MID-3694 */ @@ -955,13 +955,13 @@ public void test222GuybrushAssignRoleControllingOne() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - // WHEN + // WHEN PrismObject userAfter = assignRolePolicyFailure(TEST_NAME, USER_GUYBRUSH_OID, ROLE_CONTROLLING_1_OID, task, result); - + // THEN - assertAssignedRole(userAfter, ROLE_EXECUTIVE_1_OID); + assertAssignedRole(userAfter, ROLE_EXECUTIVE_1_OID); } - + /** * MID-3694 */ @@ -973,21 +973,21 @@ public void test224GuybrushAssignRoleExecutiveTwo() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_EXECUTIVE_2_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignedRole(userAfter, ROLE_EXECUTIVE_1_OID); assertAssignedRole(userAfter, ROLE_EXECUTIVE_2_OID); } - + /** * MID-3694 */ @@ -1000,9 +1000,9 @@ public void test225GuybrushAssignRoleControllingTwo() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - // WHEN + // WHEN PrismObject userAfter = assignRolePolicyFailure(TEST_NAME, USER_GUYBRUSH_OID, ROLE_CONTROLLING_2_OID, task, result); - + // THEN assertAssignedRole(userAfter, ROLE_EXECUTIVE_1_OID); assertAssignedRole(userAfter, ROLE_EXECUTIVE_2_OID); @@ -1020,20 +1020,20 @@ public void test226GuybrushUnassignRoleExecutiveOne() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_GUYBRUSH_OID, ROLE_EXECUTIVE_1_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertAssignedRole(userAfter, ROLE_EXECUTIVE_2_OID); + assertAssignedRole(userAfter, ROLE_EXECUTIVE_2_OID); } - + /** * MID-3694 */ @@ -1045,16 +1045,16 @@ public void test227GuybrushAssignRoleControllingOne() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - - // WHEN + + // WHEN PrismObject userAfter = assignRolePolicyFailure(TEST_NAME, USER_GUYBRUSH_OID, ROLE_CONTROLLING_1_OID, task, result); - + // THEN assertNotAssignedRole(userAfter, ROLE_EXECUTIVE_1_OID); assertAssignedRole(userAfter, ROLE_EXECUTIVE_2_OID); assertNotAssignedRole(userAfter, ROLE_CONTROLLING_2_OID); } - + /** * MID-3694 */ @@ -1066,15 +1066,15 @@ public void test229GuybrushUnassignRoleExecutiveTwo() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_GUYBRUSH_OID, ROLE_EXECUTIVE_2_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertNotAssignedRole(userAfter, ROLE_EXECUTIVE_1_OID); @@ -1082,7 +1082,7 @@ public void test229GuybrushUnassignRoleExecutiveTwo() throws Exception { assertNotAssignedRole(userAfter, ROLE_CONTROLLING_1_OID); assertNotAssignedRole(userAfter, ROLE_CONTROLLING_2_OID); } - + /** * MID-3694 */ @@ -1094,20 +1094,20 @@ public void test230GuybrushAssignRoleControllingOne() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_CONTROLLING_1_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertAssignedRole(userAfter, ROLE_CONTROLLING_1_OID); + assertAssignedRole(userAfter, ROLE_CONTROLLING_1_OID); } - + /** * MID-3694 */ @@ -1119,14 +1119,14 @@ public void test232GuybrushAssignRoleExecutiveOne() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN PrismObject userAfter = assignRolePolicyFailure(TEST_NAME, USER_GUYBRUSH_OID, ROLE_EXECUTIVE_1_OID, task, result); - - // THEN - assertAssignedRole(userAfter, ROLE_CONTROLLING_1_OID); + + // THEN + assertAssignedRole(userAfter, ROLE_CONTROLLING_1_OID); } - + /** * MID-3694 */ @@ -1138,15 +1138,15 @@ public void test239GuybrushUnassignRoleControllingOne() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_GUYBRUSH_OID, ROLE_CONTROLLING_1_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertNotAssignedRole(userAfter, ROLE_EXECUTIVE_1_OID); @@ -1154,7 +1154,7 @@ public void test239GuybrushUnassignRoleControllingOne() throws Exception { assertNotAssignedRole(userAfter, ROLE_CONTROLLING_1_OID); assertNotAssignedRole(userAfter, ROLE_CONTROLLING_2_OID); } - + @Test public void test800ApplyGlobalPolicyRulesExclusion() throws Exception { final String TEST_NAME = "test800ApplyGlobalPolicyRulesExclusion"; @@ -1163,15 +1163,15 @@ public void test800ApplyGlobalPolicyRulesExclusion() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); transplantGlobalPolicyRulesAdd(CONFIG_WITH_GLOBAL_RULES_EXCLUSION_FILE, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + List globalPolicyRules = getSystemConfiguration().getGlobalPolicyRule(); display("Global policy rules", globalPolicyRules); assertEquals("Wrong number of global policy rules", NUMBER_OF_GLOBAL_POLICY_RULES + 1, globalPolicyRules.size()); @@ -1185,18 +1185,18 @@ public void test810GuybrushAssignRoleCitizenSk() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_CITIZEN_SK_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertAssignedRole(userAfter, ROLE_CITIZEN_SK_OID); + assertAssignedRole(userAfter, ROLE_CITIZEN_SK_OID); } @Test @@ -1207,14 +1207,14 @@ public void test812GuybrushAssignRoleCitizenUs() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN PrismObject userAfter = assignRolePolicyFailure(TEST_NAME, USER_GUYBRUSH_OID, ROLE_CITIZEN_US_OID, task, result); - + // THEN - assertAssignedRole(userAfter, ROLE_CITIZEN_SK_OID); + assertAssignedRole(userAfter, ROLE_CITIZEN_SK_OID); } - + /** * Assign non-citizen role. This should go smoothly. */ @@ -1226,21 +1226,21 @@ public void test814GuybrushAssignRoleEmpty() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_EMPTY_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignedRole(userAfter, ROLE_CITIZEN_SK_OID); assertAssignedRole(userAfter, ROLE_EMPTY_OID); } - + @Test public void test818GuybrushUnassignRoleCitizenSk() throws Exception { final String TEST_NAME = "test818GuybrushUnassignRoleCitizenSk"; @@ -1249,15 +1249,15 @@ public void test818GuybrushUnassignRoleCitizenSk() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_GUYBRUSH_OID, ROLE_CITIZEN_SK_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertNotAssignedRole(userAfter, ROLE_CITIZEN_SK_OID); @@ -1274,15 +1274,15 @@ public void test819GuybrushUnassignRoleEmpty() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_GUYBRUSH_OID, ROLE_EMPTY_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignments(userAfter, 0); @@ -1300,18 +1300,18 @@ public void test820GuybrushAssignRoleCriminal() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_CRIMINAL_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); - assertAssignedRole(userAfter, ROLE_CRIMINAL_OID); + assertAssignedRole(userAfter, ROLE_CRIMINAL_OID); } /** @@ -1326,20 +1326,20 @@ public void test822GuybrushAssignRoleMinister() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_MINISTER_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignedRole(userAfter, ROLE_CRIMINAL_OID); assertAssignedRole(userAfter, ROLE_MINISTER_OID); - + assertPolicySituation(userAfter, ROLE_MINISTER_OID, SchemaConstants.MODEL_POLICY_SITUATION_EXCLUSION_VIOLATION); } @@ -1351,19 +1351,19 @@ public void test826GuybrushUnassignRoleCriminal() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_GUYBRUSH_OID, ROLE_CRIMINAL_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertNotAssignedRole(userAfter, ROLE_CRIMINAL_OID); - assertAssignedRole(userAfter, ROLE_MINISTER_OID); + assertAssignedRole(userAfter, ROLE_MINISTER_OID); } @Test @@ -1374,21 +1374,21 @@ public void test829GuybrushUnassignRoleMinister() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_GUYBRUSH_OID, ROLE_MINISTER_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertNotAssignedRole(userAfter, ROLE_CRIMINAL_OID); - assertNotAssignedRole(userAfter, ROLE_MINISTER_OID); + assertNotAssignedRole(userAfter, ROLE_MINISTER_OID); } - + @Test public void test900ApplyGlobalPolicyRulesSoDApproval() throws Exception { final String TEST_NAME = "test900ApplyGlobalPolicyRulesSoDApproval"; @@ -1397,19 +1397,19 @@ public void test900ApplyGlobalPolicyRulesSoDApproval() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); transplantGlobalPolicyRulesAdd(CONFIG_WITH_GLOBAL_RULES_SOD_APPROVAL_FILE, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + List globalPolicyRules = getSystemConfiguration().getGlobalPolicyRule(); 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 @@ -1424,15 +1424,15 @@ public void test920GuybrushAssignRoleCriminal() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_CRIMINAL_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignedRole(userAfter, ROLE_CRIMINAL_OID); @@ -1455,26 +1455,26 @@ public void test922GuybrushPreviewAssignRoleMinister() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - ObjectDelta delta = createAssignmentFocusDelta(UserType.class, USER_GUYBRUSH_OID, + ObjectDelta delta = createAssignmentFocusDelta(UserType.class, USER_GUYBRUSH_OID, ROLE_MINISTER_OID, RoleType.COMPLEX_TYPE, null, null, null, true); - + // WHEN displayWhen(TEST_NAME); ModelContext modelContext = modelInteractionService.previewChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + display("Preview context", modelContext); - + DeltaSetTriple> evaluatedAssignmentTriple = modelContext.getEvaluatedAssignmentTriple(); - + Collection evaluatedAssignmentsZero = evaluatedAssignmentTriple.getZeroSet(); assertEquals("Wrong number of evaluated assignments (zero)", 1, evaluatedAssignmentsZero.size()); - + PrismAsserts.assertTripleNoMinus(evaluatedAssignmentTriple); - + Collection evaluatedAssignmentsPlus = evaluatedAssignmentTriple.getPlusSet(); assertEquals("Wrong number of evaluated assignments (plus)", 1, evaluatedAssignmentsPlus.size()); EvaluatedAssignment evaluatedAssignment = evaluatedAssignmentsPlus.iterator().next(); @@ -1513,7 +1513,7 @@ private EvaluatedPolicyRuleTrigger getSinglePolicyRuleTrigger(EvaluatedPolicy assertEvaluatedPolicyRuleTriggers(evaluatedPolicyRule, triggers, 1); return triggers.iterator().next(); } - + private EvaluatedPolicyRuleTrigger getEvaluatedPolicyRuleTrigger(EvaluatedPolicyRule evaluatedPolicyRule, Collection> triggers, PolicyConstraintKindType expectedConstraintType) { return triggers.stream().filter(trigger -> expectedConstraintType.equals(trigger.getConstraintKind())).findFirst().get(); @@ -1532,50 +1532,50 @@ public void test929GuybrushUnassignRoleCriminal() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_GUYBRUSH_OID, ROLE_CRIMINAL_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertNotAssignedRole(userAfter, ROLE_CRIMINAL_OID); assertNotAssignedRole(userAfter, ROLE_MINISTER_OID); } - + private PrismObject assignRolePolicyFailure(String TEST_NAME, String userOid, String roleOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, SecurityViolationException { try { // WHEN - + displayWhen(TEST_NAME); assignRole(userOid, roleOid, task, result); - + assertNotReached(); - + } catch (PolicyViolationException e) { - + // THEN displayThen(TEST_NAME); assertFailure(result); } - + PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); 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/scripting/TestScriptingBasic.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/scripting/TestScriptingBasic.java index 2f751efc5fb..46965781615 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 @@ -66,7 +66,7 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestScriptingBasic extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/scripting"); private static final String DOT_CLASS = TestScriptingBasic.class.getName() + "."; private static final File LOG_FILE = new File(TEST_DIR, "log.xml"); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/AbstractSecurityTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/AbstractSecurityTest.java index 312c73def2f..b0f21d75c90 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/AbstractSecurityTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/AbstractSecurityTest.java @@ -103,34 +103,34 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public abstract class AbstractSecurityTest extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/security"); - + protected static final File USER_LECHUCK_FILE = new File(TEST_DIR, "user-lechuck.xml"); protected static final String USER_LECHUCK_OID = "c0c010c0-d34d-b33f-f00d-1c1c11cc11c2"; protected static final String USER_LECHUCK_USERNAME = "lechuck"; - + // Persona of LeChuck protected static final File USER_CHARLES_FILE = new File(TEST_DIR, "user-charles.xml"); protected static final String USER_CHARLES_OID = "65e66ea2-30de-11e7-b852-4b46724fcdaa"; protected static final File USER_MANCOMB_FILE = new File(TEST_DIR, "user-mancomb.xml"); protected static final String USER_MANCOMB_OID = "00000000-0000-0000-0000-110000000011"; - + protected static final File USER_ESTEVAN_FILE = new File(TEST_DIR, "user-estevan.xml"); protected static final String USER_ESTEVAN_OID = "00000000-0000-0000-0000-110000000012"; - + protected static final File USER_ANGELICA_FILE = new File(TEST_DIR, "user-angelica.xml"); protected static final String USER_ANGELICA_NAME = "angelika"; protected static final String USER_RUM_ROGERS_NAME = "rum"; protected static final String USER_COBB_NAME = "cobb"; - + protected static final String USER_JACK_GIVEN_NAME_NEW = "Jackie"; protected static final File ROLE_READ_JACKS_CAMPAIGNS_FILE = new File(TEST_DIR, "role-read-jacks-campaigns.xml"); protected static final String ROLE_READ_JACKS_CAMPAIGNS_OID = "00000000-0000-0000-0000-00000001aa00"; - + protected static final File ROLE_READ_SOME_ROLES_FILE = new File(TEST_DIR, "role-read-some-roles.xml"); protected static final String ROLE_READ_SOME_ROLES_OID = "7b4a3880-e167-11e6-b38b-2b6a550a03e7"; @@ -142,33 +142,33 @@ public abstract class AbstractSecurityTest extends AbstractInitializedModelInteg protected static final String ROLE_READONLY_EXEC_OID = "00000000-0000-0000-0000-00000000ae01"; protected static final File ROLE_READONLY_REQ_EXEC_FILE = new File(TEST_DIR, "role-readonly-req-exec.xml"); protected static final String ROLE_READONLY_REQ_EXEC_OID = "00000000-0000-0000-0000-00000000ab01"; - + protected static final File ROLE_READONLY_DEEP_FILE = new File(TEST_DIR, "role-readonly-deep.xml"); protected static final String ROLE_READONLY_DEEP_OID = "00000000-0000-0000-0000-00000000aa02"; protected static final File ROLE_READONLY_DEEP_EXEC_FILE = new File(TEST_DIR, "role-readonly-deep-exec.xml"); protected static final String ROLE_READONLY_DEEP_EXEC_OID = "00000000-0000-0000-0000-00000000ae02"; - + protected static final File ROLE_READ_BASIC_ITEMS_FILE = new File(TEST_DIR, "role-read-basic-items.xml"); protected static final String ROLE_READ_BASIC_ITEMS_OID = "519e8bf4-3af3-11e7-bc89-cbcee62d4088"; - + protected static final File ROLE_SELF_FILE = new File(TEST_DIR, "role-self.xml"); protected static final String ROLE_SELF_OID = "00000000-0000-0000-0000-00000000aa03"; - + protected static final File ROLE_OBJECT_FILTER_MODIFY_CARIBBEAN_FILE = new File(TEST_DIR, "role-filter-object-modify-caribbean.xml"); protected static final String ROLE_OBJECT_FILTER_MODIFY_CARIBBEAN_OID = "00000000-0000-0000-0000-00000000aa04"; - + protected static final File ROLE_PROP_READ_ALL_MODIFY_SOME_FILE = new File(TEST_DIR, "role-prop-read-all-modify-some.xml"); protected static final String ROLE_PROP_READ_ALL_MODIFY_SOME_OID = "00000000-0000-0000-0000-00000000aa05"; - + protected static final File ROLE_PROP_READ_ALL_MODIFY_SOME_USER_FILE = new File(TEST_DIR, "role-prop-read-all-modify-some-user.xml"); protected static final String ROLE_PROP_READ_ALL_MODIFY_SOME_USER_OID = "00000000-0000-0000-0000-00000000ae05"; - + protected static final File ROLE_MASTER_MINISTRY_OF_RUM_FILE = new File(TEST_DIR, "role-org-master-ministry-of-rum.xml"); protected static final String ROLE_MASTER_MINISTRY_OF_RUM_OID = "00000000-0000-0000-0000-00000000aa06"; - + protected static final File ROLE_OBJECT_FILTER_CARIBBEAN_FILE = new File(TEST_DIR, "role-filter-object-caribbean.xml"); protected static final String ROLE_OBJECT_FILTER_CARIBBEAN_OID = "00000000-0000-0000-0000-00000000aa07"; - + protected static final File ROLE_PROP_READ_SOME_MODIFY_SOME_FILE = new File(TEST_DIR, "role-prop-read-some-modify-some.xml"); protected static final String ROLE_PROP_READ_SOME_MODIFY_SOME_OID = "00000000-0000-0000-0000-00000000aa08"; protected static final File ROLE_PROP_READ_SOME_MODIFY_SOME_REQ_EXEC_FILE = new File(TEST_DIR, "role-prop-read-some-modify-some-req-exec.xml"); @@ -179,16 +179,16 @@ public abstract class AbstractSecurityTest extends AbstractInitializedModelInteg protected static final File ROLE_PROP_READ_SOME_MODIFY_SOME_USER_FILE = new File(TEST_DIR, "role-prop-read-some-modify-some-user.xml"); protected static final String ROLE_PROP_READ_SOME_MODIFY_SOME_USER_OID = "00000000-0000-0000-0000-00000000ae08"; - + protected static final File ROLE_PROP_DENY_MODIFY_SOME_FILE = new File(TEST_DIR, "role-prop-deny-modify-some.xml"); protected static final String ROLE_PROP_DENY_MODIFY_SOME_OID = "d867ca80-b18a-11e6-826e-1b0f95ef9125"; - + protected static final File ROLE_SELF_ACCOUNTS_READ_FILE = new File(TEST_DIR, "role-self-accounts-read.xml"); protected static final String ROLE_SELF_ACCOUNTS_READ_OID = "00000000-0000-0000-0000-00000000aa09"; - + protected static final File ROLE_SELF_ACCOUNTS_READ_WRITE_FILE = new File(TEST_DIR, "role-self-accounts-read-write.xml"); protected static final String ROLE_SELF_ACCOUNTS_READ_WRITE_OID = "00000000-0000-0000-0000-00000000aa0a"; - + protected static final File ROLE_SELF_ACCOUNTS_PARTIAL_CONTROL_FILE = new File(TEST_DIR, "role-self-accounts-partial-control.xml"); protected static final String ROLE_SELF_ACCOUNTS_PARTIAL_CONTROL_OID = "00000000-0000-0000-0000-00000000aa0b"; @@ -197,34 +197,34 @@ public abstract class AbstractSecurityTest extends AbstractInitializedModelInteg protected static final File ROLE_ASSIGN_APPLICATION_ROLES_FILE = new File(TEST_DIR, "role-assign-application-roles.xml"); protected static final String ROLE_ASSIGN_APPLICATION_ROLES_OID = "00000000-0000-0000-0000-00000000aa0c"; - + protected static final File ROLE_ASSIGN_ANY_ROLES_FILE = new File(TEST_DIR, "role-assign-any-roles.xml"); protected static final String ROLE_ASSIGN_ANY_ROLES_OID = "00000000-0000-0000-0000-00000000ab0c"; protected static final File ROLE_ASSIGN_NON_APPLICATION_ROLES_FILE = new File(TEST_DIR, "role-assign-non-application-roles.xml"); protected static final String ROLE_ASSIGN_NON_APPLICATION_ROLES_OID = "00000000-0000-0000-0000-00000000ac0c"; - + protected static final File ROLE_ASSIGN_REQUESTABLE_ROLES_FILE = new File(TEST_DIR, "role-assign-requestable-roles.xml"); protected static final String ROLE_ASSIGN_REQUESTABLE_ROLES_OID = "00000000-0000-0000-0000-00000000ad0c"; - + protected static final File ROLE_ASSIGN_ORGRELATION_FILE = new File(TEST_DIR, "role-assign-orgrelation.xml"); protected static final String ROLE_ASSIGN_ORGRELATION_OID = "5856eb42-319f-11e7-8e26-a7c6d1a855fc"; - + protected static final File ROLE_DELEGATOR_FILE = new File(TEST_DIR, "role-delegator.xml"); protected static final String ROLE_DELEGATOR_OID = "00000000-0000-0000-0000-00000000d001"; - + protected static final File ROLE_ORG_READ_ORGS_MINISTRY_OF_RUM_FILE = new File(TEST_DIR, "role-org-read-orgs-ministry-of-rum.xml"); protected static final String ROLE_ORG_READ_ORGS_MINISTRY_OF_RUM_OID = "00000000-0000-0000-0000-00000000aa0d"; protected static final File ROLE_FILTER_OBJECT_USER_LOCATION_SHADOWS_FILE = new File(TEST_DIR, "role-filter-object-user-location-shadows.xml"); protected static final String ROLE_FILTER_OBJECT_USER_LOCATION_SHADOWS_OID = "00000000-0000-0000-0000-00000000aa0e"; - + protected static final File ROLE_FILTER_OBJECT_USER_TYPE_SHADOWS_FILE = new File(TEST_DIR, "role-filter-object-user-type-shadow.xml"); protected static final String ROLE_FILTER_OBJECT_USER_TYPE_SHADOWS_OID = "00000000-0000-0000-0000-00000000aa0h"; - + protected static final File ROLE_END_USER_FILE = new File(TEST_DIR, "role-end-user.xml"); protected static final String ROLE_END_USER_OID = "00000000-0000-0000-0000-00000000aa0f"; - + protected static final File ROLE_MODIFY_USER_FILE = new File(TEST_DIR, "role-modify-user.xml"); protected static final String ROLE_MODIFY_USER_OID = "00000000-0000-0000-0000-00000000aa0g"; @@ -239,7 +239,7 @@ public abstract class AbstractSecurityTest extends AbstractInitializedModelInteg protected static final File ROLE_BUSINESS_2_FILE = new File(TEST_DIR, "role-business-2.xml"); protected static final String ROLE_BUSINESS_2_OID = "00000000-0000-0000-0000-00000000aab2"; - + protected static final File ROLE_BUSINESS_3_FILE = new File(TEST_DIR, "role-business-3.xml"); protected static final String ROLE_BUSINESS_3_OID = "00000000-0000-0000-0000-00000000aab3"; @@ -248,10 +248,10 @@ public abstract class AbstractSecurityTest extends AbstractInitializedModelInteg protected static final File ROLE_MANAGER_FULL_CONTROL_FILE = new File(TEST_DIR, "role-manager-full-control.xml"); protected static final String ROLE_MANAGER_FULL_CONTROL_OID = "e2c88fea-db21-11e5-80ba-d7b2f1155264"; - + protected static final File ROLE_MANAGER_USER_ADMIN_FILE = new File(TEST_DIR, "role-manager-user-admin.xml"); protected static final String ROLE_MANAGER_USER_ADMIN_OID = "c545323c-5d68-11e7-acba-2b32ef514121"; - + protected static final File ROLE_ROLE_OWNER_FULL_CONTROL_FILE = new File(TEST_DIR, "role-role-owner-full-control.xml"); protected static final String ROLE_ROLE_OWNER_FULL_CONTROL_OID = "9c6e597e-dbd7-11e5-a538-97834c1cd5ba"; @@ -260,13 +260,13 @@ public abstract class AbstractSecurityTest extends AbstractInitializedModelInteg protected static final File ROLE_META_NONSENSE_FILE = new File(TEST_DIR, "role-meta-nonsense.xml"); protected static final String ROLE_META_NONSENSE_OID = "602f72b8-2a11-11e5-8dd9-001e8c717e5b"; - + protected static final File ROLE_BASIC_FILE = new File(TEST_DIR, "role-basic.xml"); protected static final String ROLE_BASIC_OID = "00000000-0000-0000-0000-00000000aad1"; protected static final File ROLE_AUDITOR_FILE = new File(TEST_DIR, "role-auditor.xml"); protected static final String ROLE_AUDITOR_OID = "475e37e8-b178-11e6-8339-83e2fa7b9828"; - + protected static final File ROLE_LIMITED_USER_ADMIN_FILE = new File(TEST_DIR, "role-limited-user-admin.xml"); protected static final String ROLE_LIMITED_USER_ADMIN_OID = "66ee3a78-1b8a-11e7-aac6-5f43a0a86116"; @@ -275,67 +275,67 @@ public abstract class AbstractSecurityTest extends AbstractInitializedModelInteg protected static final File ROLE_SELF_TASK_OWNER_FILE = new File(TEST_DIR, "role-self-task-owner.xml"); protected static final String ROLE_SELF_TASK_OWNER_OID = "455edc40-30c6-11e7-937f-df84f38dd402"; - + protected static final File ROLE_PERSONA_MANAGEMENT_FILE = new File(TEST_DIR, "role-persona-management.xml"); protected static final String ROLE_PERSONA_MANAGEMENT_OID = "2f0246f8-30df-11e7-b35b-bbb92a001091"; - + protected static final File ROLE_APPROVER_UNASSIGN_ROLES_FILE = new File(TEST_DIR, "role-approver-unassign-roles.xml"); protected static final String ROLE_APPROVER_UNASSIGN_ROLES_OID = "5d9cead8-3a2e-11e7-8609-f762a755b58e"; - + protected static final File ROLE_ORDINARY_FILE = new File(TEST_DIR, "role-ordinary.xml"); protected static final String ROLE_ORDINARY_OID = "7a7ad698-3a37-11e7-9af7-6fd138dd9572"; - + protected static final File ROLE_UNINTERESTING_FILE = new File(TEST_DIR, "role-uninteresting.xml"); protected static final String ROLE_UNINTERESTING_OID = "2264afee-3ae4-11e7-a63c-8b53efadd642"; - + protected static final File ROLE_READ_ROLE_MEMBERS_FILE = new File(TEST_DIR, "role-read-role-members.xml"); protected static final String ROLE_READ_ROLE_MEMBERS_OID = "40df00e8-3efc-11e7-8d18-7b955ccb96a1"; - + protected static final File ROLE_READ_ROLE_MEMBERS_WRONG_FILE = new File(TEST_DIR, "role-read-role-members-wrong.xml"); protected static final String ROLE_READ_ROLE_MEMBERS_WRONG_OID = "8418e248-3efc-11e7-a546-931a90cb8ee3"; - + protected static final File ROLE_READ_ROLE_MEMBERS_NONE_FILE = new File(TEST_DIR, "role-read-role-members-none.xml"); protected static final String ROLE_READ_ROLE_MEMBERS_NONE_OID = "9e93dfb2-3eff-11e7-b56b-1b0e35f837fc"; - + protected static final File ROLE_READ_SELF_MODIFY_ORGUNIT_FILE = new File(TEST_DIR, "role-read-self-modify-orgunit.xml"); protected static final String ROLE_READ_SELF_MODIFY_ORGUNIT_OID = "97cc13ac-5660-11e7-8687-d76f3a88c78d"; - + protected static final File ROLE_INDIRECT_PIRATE_FILE = new File(TEST_DIR, "role-indirect-pirate.xml"); protected static final String ROLE_INDIRECT_PIRATE_OID = "67680a40-582c-11e7-b5b1-abcfbb047b34"; - + protected static final File ORG_REQUESTABLE_FILE = new File(TEST_DIR,"org-requestable.xml"); protected static final String ORG_REQUESTABLE_OID = "8f2bd344-a46c-4c0b-aa34-db08b7d7f7f2"; - + protected static final File ORG_INDIRECT_PIRATE_FILE = new File(TEST_DIR,"org-indirect-pirate.xml"); protected static final String ORG_INDIRECT_PIRATE_OID = "59024142-5830-11e7-80e6-ffbee06efb45"; - + protected static final File ORG_CHEATERS_FILE = new File(TEST_DIR, "org-cheaters.xml"); protected static final String ORG_CHEATERS_OID = "944cef84-6570-11e7-8262-079921253d05"; - + protected static final File TASK_USELESS_ADMINISTRATOR_FILE = new File(TEST_DIR,"task-useless-administrator.xml"); protected static final String TASK_USELESS_ADMINISTRATOR_OID = "daa36dba-30c7-11e7-bd7d-6311953a3ecd"; - + protected static final File TASK_USELESS_JACK_FILE = new File(TEST_DIR,"task-useless-jack.xml"); protected static final String TASK_USELESS_JACK_OID = "642d8174-30c8-11e7-b338-c3cf3a6c548a"; protected static final String TASK_USELESS_HANDLER_URI = "http://midpoint.evolveum.com/xml/ns/public/model/synchronization/task/useless/handler-3"; protected static final File USER_TEMPLATE_SECURITY_FILE = new File(TEST_DIR,"user-template-security.xml"); protected static final String USER_TEMPLATE_SECURITY_OID = "b3a8f244-565a-11e7-8802-7b2586c1ce99"; - + protected static final String TASK_T1_OID = "a46459b8-30e4-11e7-bd37-7bba86e91983"; protected static final String TASK_T2_OID = "a4ab296a-30e4-11e7-a3fd-7f34286d17fa"; protected static final String TASK_T3_OID = "a4cfec28-30e4-11e7-946f-07f8d55b4498"; protected static final String TASK_T4_OID = "a4ed0312-30e4-11e7-aaff-c3f6264d4bd1"; protected static final String TASK_T5_OID = "a507e1c8-30e4-11e7-a739-538d921aa79e"; protected static final String TASK_T6_OID = "a522b610-30e4-11e7-ab1c-6f834b9ae963"; - + protected static final String LOG_PREFIX_FAIL = "SSSSS=X "; protected static final String LOG_PREFIX_ATTEMPT = "SSSSS=> "; protected static final String LOG_PREFIX_DENY = "SSSSS=- "; protected static final String LOG_PREFIX_ALLOW = "SSSSS=+ "; protected static final File CAMPAIGNS_FILE = new File(TEST_DIR, "campaigns.xml"); - + protected static final ItemPath PASSWORD_PATH = new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE); protected static final XMLGregorianCalendar JACK_VALID_FROM_LONG_AGO = XmlTypeConverter.createXMLGregorianCalendar(10000L); @@ -343,7 +343,7 @@ public abstract class AbstractSecurityTest extends AbstractInitializedModelInteg protected static final int NUMBER_OF_ALL_USERS = 11; protected static final int NUMBER_OF_IMPORTED_ROLES = 61; protected static final int NUMBER_OF_ALL_ORGS = 11; - + protected String userRumRogersOid; protected String userCobbOid; @@ -352,7 +352,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti super.initSystem(initTask, initResult); repoAddObjectsFromFile(CAMPAIGNS_FILE, initResult); - + repoAddObjectFromFile(ROLE_READONLY_FILE, initResult); repoAddObjectFromFile(ROLE_READONLY_REQ_FILE, initResult); repoAddObjectFromFile(ROLE_READONLY_EXEC_FILE, initResult); @@ -386,19 +386,19 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti repoAddObjectFromFile(ROLE_ORG_READ_ORGS_MINISTRY_OF_RUM_FILE, initResult); repoAddObjectFromFile(ROLE_FILTER_OBJECT_USER_LOCATION_SHADOWS_FILE, initResult); repoAddObjectFromFile(ROLE_FILTER_OBJECT_USER_TYPE_SHADOWS_FILE, initResult); - + repoAddObjectFromFile(ROLE_APPLICATION_1_FILE, initResult); repoAddObjectFromFile(ROLE_APPLICATION_2_FILE, initResult); repoAddObjectFromFile(ROLE_BUSINESS_1_FILE, initResult); repoAddObjectFromFile(ROLE_BUSINESS_2_FILE, initResult); repoAddObjectFromFile(ROLE_BUSINESS_3_FILE, initResult); - + repoAddObjectFromFile(ROLE_CONDITIONAL_FILE, RoleType.class, initResult); repoAddObjectFromFile(ROLE_META_NONSENSE_FILE, RoleType.class, initResult); repoAddObjectFromFile(ROLE_BASIC_FILE, RoleType.class, initResult); repoAddObjectFromFile(ROLE_AUDITOR_FILE, RoleType.class, initResult); repoAddObjectFromFile(ROLE_LIMITED_USER_ADMIN_FILE, RoleType.class, initResult); - + repoAddObjectFromFile(ROLE_END_USER_FILE, initResult); repoAddObjectFromFile(ROLE_MODIFY_USER_FILE, initResult); repoAddObjectFromFile(ROLE_MANAGER_FULL_CONTROL_FILE, initResult); @@ -417,28 +417,28 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti repoAddObjectFromFile(ROLE_READ_ROLE_MEMBERS_NONE_FILE, initResult); repoAddObjectFromFile(ROLE_READ_SELF_MODIFY_ORGUNIT_FILE, initResult); repoAddObjectFromFile(ROLE_INDIRECT_PIRATE_FILE, initResult); - + repoAddObjectFromFile(ORG_REQUESTABLE_FILE, initResult); repoAddObjectFromFile(ORG_INDIRECT_PIRATE_FILE, initResult); - + repoAddObjectFromFile(TASK_USELESS_ADMINISTRATOR_FILE, initResult); repoAddObjectFromFile(TASK_USELESS_JACK_FILE, initResult); repoAddObjectFromFile(OBJECT_TEMPLATE_PERSONA_ADMIN_FILE, initResult); repoAddObjectFromFile(USER_TEMPLATE_SECURITY_FILE, initResult); - + assignOrg(USER_GUYBRUSH_OID, ORG_SWASHBUCKLER_SECTION_OID, initTask, initResult); assignOrg(RoleType.class, ROLE_BUSINESS_3_OID, ORG_MINISTRY_OF_RUM_OID, initTask, initResult); - + repoAddObjectFromFile(USER_CHARLES_FILE, initResult); - + PrismObject userRum = createUser(USER_RUM_ROGERS_NAME, "Rum Rogers"); addObject(userRum, initTask, initResult); userRumRogersOid = userRum.getOid(); assignOrg(userRumRogersOid, ORG_MINISTRY_OF_RUM_OID, initTask, initResult); assignRole(userRumRogersOid, ROLE_ORDINARY_OID, initTask, initResult); assignRole(userRumRogersOid, ROLE_UNINTERESTING_OID, initTask, initResult); - + PrismObject userCobb = createUser(USER_COBB_NAME, "Cobb"); addObject(userCobb, initTask, initResult); userCobbOid = userCobb.getOid(); @@ -446,7 +446,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti assignRole(userCobbOid, ROLE_ORDINARY_OID, initTask, initResult); assignRole(userCobbOid, ROLE_UNINTERESTING_OID, initTask, initResult); } - + protected int getNumberOfRoles() { return super.getNumberOfRoles() + NUMBER_OF_IMPORTED_ROLES; } @@ -459,7 +459,7 @@ public void test000Sanity() throws Exception { // WHEN PrismObject roleSelf = getRole(ROLE_SELF_OID); - + // THEN display("Role self", roleSelf); List authorizations = roleSelf.asObjectable().getAuthorization(); @@ -474,7 +474,7 @@ public void test000Sanity() throws Exception { SpecialObjectSpecificationType special = specials.get(0); assertEquals("Wrong special in object specs in authorization", SpecialObjectSpecificationType.SELF, special); } - + protected AuthorizationType findAutz(List authorizations, String actionUrl) { for (AuthorizationType authorization: authorizations) { if (authorization.getAction().contains(actionUrl)) { @@ -494,7 +494,7 @@ protected void assertSuperuserAccess(int readUserNum) throws Exception { assertSearch(AccessCertificationCampaignType.class, null, 2); // 2 campaigns there assertReadCertCasesAllow(); assertSearch(TaskType.class, null, 2); - + RoleSelectionSpecification roleSpec = getAssignableRoleSpecification(getUser(USER_JACK_OID)); assertNotNull("Null role spec "+roleSpec, roleSpec); assertNull("Non-null role types in spec "+roleSpec, roleSpec.getRoleTypes()); @@ -510,7 +510,7 @@ protected void assertNoAccess(PrismObject userJack) throws Exception { assertDeleteDeny(); assertReadCertCasesDeny(); - + RoleSelectionSpecification roleSpec = getAssignableRoleSpecification(userJack); assertNotNull("Null role spec "+roleSpec, roleSpec); assertRoleTypes(roleSpec); @@ -518,11 +518,11 @@ protected void assertNoAccess(PrismObject userJack) throws Exception { assertAuditReadDeny(); } - + protected void assertItemFlags(PrismObjectDefinition editSchema, QName itemName, boolean expectedRead, boolean expectedAdd, boolean expectedModify) { assertItemFlags(editSchema, new ItemPath(itemName), expectedRead, expectedAdd, expectedModify); } - + protected void assertItemFlags(PrismObjectDefinition editSchema, ItemPath itemPath, boolean expectedRead, boolean expectedAdd, boolean expectedModify) { ItemDefinition itemDefinition = editSchema.findItemDefinition(itemPath); assertEquals("Wrong readability flag for "+itemPath, expectedRead, itemDefinition.canRead()); @@ -537,7 +537,7 @@ protected void assertAssignmentsWithTargets(PrismObject user, int expe assertNotNull("No targetRef in assignment in "+user, cval.asContainerable().getTargetRef()); } } - + protected void assertAttributeFlags(RefinedObjectClassDefinition rOcDef, QName attrName, boolean expectedRead, boolean expectedAdd, boolean expectedModify) { RefinedAttributeDefinition rAttrDef = rOcDef.findAttributeDefinition(attrName); assertEquals("Wrong readability flag for "+attrName, expectedRead, rAttrDef.canRead()); @@ -545,16 +545,16 @@ protected void assertAttributeFlags(RefinedObjectClassDefinition rOcDef, QName a assertEquals("Wrong modification flag for "+attrName, expectedModify, rAttrDef.canModify()); } - + protected void cleanupAutzTest(String userOid) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException, IOException { login(userAdministrator); if (userOid != null) { unassignAllRoles(userOid); } - + Task task = taskManager.createTaskInstance(AbstractSecurityTest.class.getName() + ".cleanupAutzTest"); OperationResult result = task.getResult(); - + cleanupDelete(UserType.class, USER_HERMAN_OID, task, result); cleanupDelete(UserType.class, USER_DRAKE_OID, task, result); cleanupDelete(UserType.class, USER_RAPP_OID, task, result); @@ -562,19 +562,19 @@ protected void cleanupAutzTest(String userOid) throws ObjectNotFoundException, S cleanupAdd(USER_LARGO_FILE, task, result); cleanupAdd(USER_LECHUCK_FILE, task, result); cleanupAdd(USER_ESTEVAN_FILE, task, result); - + modifyUserReplace(USER_JACK_OID, UserType.F_HONORIFIC_PREFIX, task, result); modifyUserReplace(USER_JACK_OID, UserType.F_FULL_NAME, task, result, PrismTestUtil.createPolyString(USER_JACK_FULL_NAME)); modifyUserReplace(userRumRogersOid, UserType.F_TITLE, task, result); modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_HONORIFIC_PREFIX, task, result, PrismTestUtil.createPolyString("Wannabe")); modifyUserReplace(USER_JACK_OID, SchemaConstants.PATH_ACTIVATION_VALID_FROM, task, result); modifyUserReplace(USER_JACK_OID, UserType.F_GIVEN_NAME, task, result, createPolyString(USER_JACK_GIVEN_NAME)); - + unassignOrg(USER_JACK_OID, ORG_MINISTRY_OF_RUM_OID, SchemaConstants.ORG_MANAGER, task, result); unassignOrg(USER_JACK_OID, ORG_MINISTRY_OF_RUM_OID, null, task, result); unassignOrg(USER_JACK_OID, ORG_MINISTRY_OF_DEFENSE_OID, SchemaConstants.ORG_MANAGER, task, result); unassignOrg(USER_JACK_OID, ORG_MINISTRY_OF_DEFENSE_OID, null, task, result); - + cleanupDelete(TaskType.class, TASK_T1_OID, task, result); cleanupDelete(TaskType.class, TASK_T2_OID, task, result); cleanupDelete(TaskType.class, TASK_T3_OID, task, result); @@ -582,7 +582,7 @@ protected void cleanupAutzTest(String userOid) throws ObjectNotFoundException, S cleanupDelete(TaskType.class, TASK_T5_OID, task, result); cleanupDelete(TaskType.class, TASK_T6_OID, task, result); } - + protected void cleanupAdd(File userLargoFile, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException, IOException { try { addObject(userLargoFile, task, result); @@ -600,12 +600,12 @@ protected void cleanupDelete(Class type, String oid, T result.getLastSubresult().setStatus(OperationResultStatus.HANDLED_ERROR); } } - + protected void assertVisibleUsers(int expectedNumAllUsers) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { assertSearch(UserType.class, null, expectedNumAllUsers); } - + protected void assertReadDeny() throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { assertReadDeny(0); } @@ -627,7 +627,7 @@ protected void assertReadDeny(int expectedNumAllUsers) throws ObjectNotFoundExce assertGetDeny(UserType.class, USER_JACK_OID, SelectorOptions.createCollection(GetOperationOptions.createRaw())); assertGetDeny(UserType.class, USER_GUYBRUSH_OID); assertGetDeny(UserType.class, USER_GUYBRUSH_OID, SelectorOptions.createCollection(GetOperationOptions.createRaw())); - + assertSearch(UserType.class, null, expectedNumAllUsers); assertSearch(UserType.class, createNameQuery(USER_JACK_USERNAME), 0); assertSearch(UserType.class, createNameQuery(USER_JACK_USERNAME), SelectorOptions.createCollection(GetOperationOptions.createRaw()), 0); @@ -638,20 +638,20 @@ protected void assertReadDeny(int expectedNumAllUsers) throws ObjectNotFoundExce protected void assertReadAllow() throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { assertReadAllow(NUMBER_OF_ALL_USERS); } - + protected void assertReadAllow(int expectedNumAllUsers) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { assertGetAllow(UserType.class, USER_JACK_OID); assertGetAllow(UserType.class, USER_JACK_OID, SelectorOptions.createCollection(GetOperationOptions.createRaw())); assertGetAllow(UserType.class, USER_GUYBRUSH_OID); assertGetAllow(UserType.class, USER_GUYBRUSH_OID, SelectorOptions.createCollection(GetOperationOptions.createRaw())); - + assertSearch(UserType.class, null, expectedNumAllUsers); assertSearch(UserType.class, createNameQuery(USER_JACK_USERNAME), 1); assertSearch(UserType.class, createNameQuery(USER_JACK_USERNAME), SelectorOptions.createCollection(GetOperationOptions.createRaw()), 1); assertSearch(UserType.class, createNameQuery(USER_GUYBRUSH_USERNAME), 1); assertSearch(UserType.class, createNameQuery(USER_GUYBRUSH_USERNAME), SelectorOptions.createCollection(GetOperationOptions.createRaw()), 1); } - + protected void assertAddDeny() throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, IOException { assertAddDeny(USER_HERMAN_FILE); assertAddDeny(USER_DRAKE_FILE, ModelExecuteOptions.createRaw()); @@ -691,11 +691,11 @@ protected void assertDeleteAllow() throws ObjectAlreadyExistsException, ObjectNo assertDeleteAllow(UserType.class, USER_LARGO_OID); assertDeleteAllow(UserType.class, USER_LECHUCK_OID, ModelExecuteOptions.createRaw()); } - + protected void assertGetDeny(Class type, String oid) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException { assertGetDeny(type, oid, null); } - + protected void assertGetDeny(Class type, String oid, Collection> options) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException { Task task = taskManager.createTaskInstance(AbstractSecurityTest.class.getName() + ".assertGetDeny"); OperationResult result = task.getResult(); @@ -710,11 +710,11 @@ protected void assertGetDeny(Class type, String oid, C TestUtil.assertFailure(result); } } - + protected PrismObject assertGetAllow(Class type, String oid) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { return assertGetAllow(type, oid, null); } - + protected PrismObject assertGetAllow(Class type, String oid, Collection> options) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { Task task = taskManager.createTaskInstance(AbstractSecurityTest.class.getName() + ".assertGetAllow"); OperationResult result = task.getResult(); @@ -725,7 +725,7 @@ protected PrismObject assertGetAllow(Class type, St logAllow("get", type, oid, null); return object; } - + protected void assertSearch(Class type, ObjectQuery query, int expectedResults) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { assertSearch(type, query, null, expectedResults); } @@ -733,8 +733,8 @@ protected void assertSearch(Class type, ObjectQuery qu protected void assertContainerSearch(Class type, ObjectQuery query, int expectedResults) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException { assertContainerSearch(type, query, null, expectedResults); } - - protected void assertSearch(Class type, ObjectQuery query, + + protected void assertSearch(Class type, ObjectQuery query, Collection> options, int expectedResults) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { Task task = taskManager.createTaskInstance(AbstractSecurityTest.class.getName() + ".assertSearchObjects"); OperationResult result = task.getResult(); @@ -783,7 +783,7 @@ public boolean handle(PrismObject object, OperationResult parentResult) { TestUtil.assertFailure(result); failAllow("searchIterative", type, query, e); } - + task = taskManager.createTaskInstance(AbstractSecurityTest.class.getName() + ".assertSearchObjects.count"); result = task.getResult(); try { @@ -828,11 +828,11 @@ void assertContainerSearch(Class type, ObjectQuery query, failAllow("search", type, query, e); } } - + protected void assertAddDeny(File file) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, IOException { assertAddDeny(file, null); } - + protected void assertAddDeny(File file, ModelExecuteOptions options) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, IOException { Task task = taskManager.createTaskInstance(AbstractSecurityTest.class.getName() + ".assertAddDeny"); OperationResult result = task.getResult(); @@ -853,7 +853,7 @@ protected void assertAddDeny(File file, ModelExecuteOptio protected void assertAddAllow(File file) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException, IOException { assertAddAllow(file, null); } - + protected void assertAddAllow(File file, ModelExecuteOptions options) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException, IOException { Task task = taskManager.createTaskInstance(AbstractSecurityTest.class.getName() + ".assertAddAllow"); OperationResult result = task.getResult(); @@ -869,19 +869,19 @@ protected void assertAddAllow(File file, ModelExecuteOpti TestUtil.assertSuccess(result); logAllow("add", object.getCompileTimeClass(), object.getOid(), null); } - + protected void assertModifyDeny(Class type, String oid, QName propertyName, Object... newRealValue) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { assertModifyDenyOptions(type, oid, propertyName, null, newRealValue); } - + protected void assertModifyDeny(Class type, String oid, ItemPath itemPath, Object... newRealValue) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { assertModifyDenyOptions(type, oid, itemPath, null, newRealValue); } - + protected void assertModifyDenyOptions(Class type, String oid, QName propertyName, ModelExecuteOptions options, Object... newRealValue) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { assertModifyDenyOptions(type, oid, new ItemPath(propertyName), options, newRealValue); } - + protected void assertModifyDenyOptions(Class type, String oid, ItemPath itemPath, ModelExecuteOptions options, Object... newRealValue) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { Task task = taskManager.createTaskInstance(AbstractSecurityTest.class.getName() + ".assertModifyDeny"); OperationResult result = task.getResult(); @@ -898,19 +898,19 @@ protected void assertModifyDenyOptions(Class type, Str TestUtil.assertFailure(result); } } - + protected void assertModifyAllow(Class type, String oid, ItemPath itemPath, Object... newRealValue) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { assertModifyAllowOptions(type, oid, itemPath, null, newRealValue); } - + protected void assertModifyAllow(Class type, String oid, QName propertyName, Object... newRealValue) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { assertModifyAllowOptions(type, oid, propertyName, null, newRealValue); } - + protected void assertModifyAllowOptions(Class type, String oid, QName propertyName, ModelExecuteOptions options, Object... newRealValue) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { assertModifyAllowOptions(type, oid, new ItemPath(propertyName), options, newRealValue); } - + protected void assertModifyAllowOptions(Class type, String oid, ItemPath itemPath, ModelExecuteOptions options, Object... newRealValue) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { Task task = taskManager.createTaskInstance(AbstractSecurityTest.class.getName() + ".assertModifyAllow"); OperationResult result = task.getResult(); @@ -930,7 +930,7 @@ protected void assertModifyAllowOptions(Class type, St protected void assertDeleteDeny(Class type, String oid) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { assertDeleteDeny(type, oid, null); } - + protected void assertDeleteDeny(Class type, String oid, ModelExecuteOptions options) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { Task task = taskManager.createTaskInstance(AbstractSecurityTest.class.getName() + ".assertDeleteDeny"); OperationResult result = task.getResult(); @@ -952,11 +952,11 @@ protected void assertDeleteDeny(Class type, String oid TestUtil.assertFailure(result); } } - + protected void assertDeleteAllow(Class type, String oid) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { assertDeleteAllow(type, oid, null); } - + protected void assertDeleteAllow(Class type, String oid, ModelExecuteOptions options) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { Task task = taskManager.createTaskInstance(AbstractSecurityTest.class.getName() + ".assertDeleteAllow"); OperationResult result = task.getResult(); @@ -971,7 +971,7 @@ protected void assertDeleteAllow(Class type, String oi TestUtil.assertSuccess(result); logAllow("delete", type, oid, null); } - + protected void assertImportDeny(File file) throws FileNotFoundException { Task task = taskManager.createTaskInstance(AbstractSecurityTest.class.getName() + ".assertImportDeny"); OperationResult result = task.getResult(); @@ -988,7 +988,7 @@ protected void assertImportAllow(File file) throws FileNotFoundException { result.computeStatus(); TestUtil.assertSuccess(result); } - + protected void assertImportStreamDeny(File file) throws FileNotFoundException { Task task = taskManager.createTaskInstance(AbstractSecurityTest.class.getName() + ".assertImportStreamDeny"); OperationResult result = task.getResult(); @@ -996,7 +996,7 @@ protected void assertImportStreamDeny(File file) throws FileNotFoundException { // This does not throw exception, failure is indicated in the result modelService.importObjectsFromStream(stream, null, task, result); result.computeStatus(); - TestUtil.assertFailure(result); + TestUtil.assertFailure(result); } protected void assertImportStreamAllow(File file) throws FileNotFoundException { @@ -1007,35 +1007,35 @@ protected void assertImportStreamAllow(File file) throws FileNotFoundException { result.computeStatus(); TestUtil.assertSuccess(result); } - + protected void assertJack(MidPointPrincipal principal) { display("Principal jack", principal); assertEquals("wrong username", USER_JACK_USERNAME, principal.getUsername()); assertEquals("wrong oid", USER_JACK_OID, principal.getOid()); - assertJack(principal.getUser()); + assertJack(principal.getUser()); } - + protected void assertJack(UserType userType) { display("User in principal jack", userType.asPrismObject()); assertUserJack(userType.asPrismObject()); - - userType.asPrismObject().checkConsistence(true, true); + + userType.asPrismObject().checkConsistence(true, true); } - + protected void assertHasAuthotizationAllow(Authorization authorization, String... action) { assertNotNull("Null authorization", authorization); assertEquals("Wrong decision in "+authorization, AuthorizationDecisionType.ALLOW, authorization.getDecision()); TestUtil.assertSetEquals("Wrong action in "+authorization, authorization.getAction(), action); } - + protected void failDeny(String action, Class type, ObjectQuery query, int expected, int actual) { failDeny(action, type, (query==null?"null":query.toString())+", expected "+expected+", actual "+actual); } - + protected void failDeny(String action, Class type, String oid, ItemPath itemPath) { failDeny(action, type, oid+" prop "+itemPath); } - + protected void failDeny(String action, Class type, String desc) { String msg = "Failed to deny "+action+" of "+type.getSimpleName()+":"+desc; System.out.println(LOG_PREFIX_FAIL+msg); @@ -1061,7 +1061,7 @@ protected void failAllow(String action, Class type, ObjectQuery query, int ex protected void failAllow(String action, Class type, String oid, ItemPath itemPath, SecurityViolationException e) throws SecurityViolationException { failAllow(action, type, oid+" prop "+itemPath, e); } - + protected void failAllow(String action, Class type, String desc, SecurityViolationException e) throws SecurityViolationException { String msg = "Failed to allow "+action+" of "+type.getSimpleName()+":"+desc; System.out.println(LOG_PREFIX_FAIL+msg); @@ -1087,73 +1087,73 @@ protected void failAllow(String action, SecurityViolation protected void logAttempt(String action, Class type, ObjectQuery query) { logAttempt(action, type, query==null?"null":query.toString()); } - + protected void logAttempt(String action, Class type, String oid, ItemPath itemPath) { logAttempt(action, type, oid+" prop "+itemPath); } - + protected void logAttempt(String action, Class type, String desc) { String msg = LOG_PREFIX_ATTEMPT+"Trying "+action+" of "+type.getSimpleName()+":"+desc; System.out.println(msg); LOGGER.info(msg); } - + protected void logAttempt(String action) { String msg = LOG_PREFIX_ATTEMPT+"Trying "+action; System.out.println(msg); LOGGER.info(msg); } - + protected void logDeny(String action, Class type, ObjectQuery query) { logDeny(action, type, query==null?"null":query.toString()); } - + protected void logDeny(String action, Class type, String oid, ItemPath itemPath) { logDeny(action, type, oid+" prop "+itemPath); } - + protected void logDeny(String action, Class type, String desc) { String msg = LOG_PREFIX_DENY+"Denied "+action+" of "+type.getSimpleName()+":"+desc; System.out.println(msg); LOGGER.info(msg); } - + protected void logDeny(String action) { String msg = LOG_PREFIX_DENY+"Denied "+action; System.out.println(msg); LOGGER.info(msg); } - + protected void logAllow(String action, Class type, ObjectQuery query) { logAllow(action, type, query==null?"null":query.toString()); } - + protected void logAllow(String action, Class type, String oid, ItemPath itemPath) { logAllow(action, type, oid+" prop "+itemPath); } - + protected void logAllow(String action, Class type, String desc) { String msg = LOG_PREFIX_ALLOW+"Allowed "+action+" of "+type.getSimpleName()+":"+desc; System.out.println(msg); LOGGER.info(msg); } - + protected void logAllow(String action) { String msg = LOG_PREFIX_ALLOW+"Allowed "+action; System.out.println(msg); LOGGER.info(msg); } - + protected void logError(String action, Class type, String oid, ItemPath itemPath, Throwable e) { logError(action, type, oid+" prop "+itemPath, e); } - + protected void logError(String action, Class type, String desc, Throwable e) { String msg = LOG_PREFIX_DENY+"Error "+action+" of "+type.getSimpleName()+":"+desc + "("+e+")"; System.out.println(msg); LOGGER.info(msg); } - + protected void assertDeny(String opname, Attempt attempt) throws Exception { Task task = taskManager.createTaskInstance(AbstractSecurityTest.class.getName() + ".assertDeny."+opname); OperationResult result = task.getResult(); @@ -1168,7 +1168,7 @@ protected void assertDeny(String opname, Attempt attempt) TestUtil.assertFailure(result); } } - + protected void assertAllow(String opname, Attempt attempt) throws Exception { Task task = taskManager.createTaskInstance(AbstractSecurityTest.class.getName() + ".assertAllow."+opname); OperationResult result = task.getResult(); @@ -1182,12 +1182,12 @@ protected void assertAllow(String opname, Attempt attempt TestUtil.assertSuccess(result); logAllow(opname); } - + @FunctionalInterface interface Attempt { void run(Task task, OperationResult result) throws Exception; } - + protected void assertGlobalStateUntouched() throws SchemaException { RefinedResourceSchema refinedSchema = RefinedResourceSchema.getRefinedSchema(getDummyResourceObject()); RefinedObjectClassDefinition rOcDef = refinedSchema.getDefaultRefinedDefinition(ShadowKindType.ACCOUNT); @@ -1196,7 +1196,7 @@ protected void assertGlobalStateUntouched() throws SchemaException { assertAttributeFlags(rOcDef, new QName("location"), true, true, true); assertAttributeFlags(rOcDef, new QName("weapon"), true, true, true); } - + protected void assertAuditReadDeny() throws Exception { assertDeny("auditHistory", (task,result) -> getAllAuditRecords(result)); @@ -1208,14 +1208,14 @@ protected void assertAuditReadAllow() throws Exception { assertTrue("No audit records", auditRecords != null && !auditRecords.isEmpty()); }); } - + protected void assertCanSearchRoleMemberUsers(String roleOid, boolean expectedResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { - assertCanSearch("Search user members of role "+roleOid, UserType.class, + assertCanSearch("Search user members of role "+roleOid, UserType.class, null, null, false, createMembersQuery(UserType.class, roleOid), expectedResult); } - + protected void assertCanSearchRoleMembers(String roleOid, boolean expectedResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { - assertCanSearch("Search all members of role "+roleOid, FocusType.class, + assertCanSearch("Search all members of role "+roleOid, FocusType.class, null, null, false, createMembersQuery(FocusType.class, roleOid), expectedResult); } @@ -1224,9 +1224,9 @@ protected void assertCanSearch(Stri OperationResult result = task.getResult(); String opName = "canSearch("+message+")"; logAttempt(opName); - + boolean decision = modelInteractionService.canSearch(resultType, objectType, objectOid, includeSpecial, query, task, result); - + assertSuccess(result); if (expectedResult) { if (decision) { 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 86e6be30851..37f22a2ba8e 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 @@ -60,11 +60,11 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestSecurityAdvanced extends AbstractSecurityTest { - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + setDefaultObjectTemplate(UserType.COMPLEX_TYPE, USER_TEMPLATE_SECURITY_OID, initResult); } @@ -77,15 +77,15 @@ public void test100AutzJackPersonaManagement() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PERSONA_MANAGEMENT_OID); login(USER_JACK_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + assertGetAllow(UserType.class, USER_JACK_OID); assertGetDeny(UserType.class, USER_GUYBRUSH_OID); assertGetDeny(UserType.class, USER_LECHUCK_OID); assertGetDeny(UserType.class, USER_CHARLES_OID); - + assertSearch(UserType.class, null, 1); assertSearch(ObjectType.class, null, 1); assertSearch(OrgType.class, null, 0); @@ -104,10 +104,10 @@ public void test102AutzLechuckPersonaManagement() throws Exception { cleanupAutzTest(USER_LECHUCK_OID); assignRole(USER_LECHUCK_OID, ROLE_PERSONA_MANAGEMENT_OID); login(USER_LECHUCK_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + assertGetDeny(UserType.class, USER_JACK_OID); assertGetDeny(UserType.class, USER_GUYBRUSH_OID); assertGetAllow(UserType.class, USER_LECHUCK_OID); @@ -123,7 +123,7 @@ public void test102AutzLechuckPersonaManagement() throws Exception { assertDeleteDeny(); assertGlobalStateUntouched(); } - + @Test public void test110AutzJackPersonaAdmin() throws Exception { final String TEST_NAME = "test110AutzJackAddPersonaAdmin"; @@ -132,65 +132,65 @@ public void test110AutzJackPersonaAdmin() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PERSONA_MANAGEMENT_OID); login(USER_JACK_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); - assertAllow("assign application role 1 to jack", + assertAllow("assign application role 1 to jack", (task,result) -> assignRole(USER_JACK_OID, ROLE_PERSONA_ADMIN_OID, task, result)); - + PrismObject userJack = assertGetAllow(UserType.class, USER_JACK_OID); assertGetDeny(UserType.class, USER_GUYBRUSH_OID); assertGetDeny(UserType.class, USER_LECHUCK_OID); assertGetDeny(UserType.class, USER_CHARLES_OID); - + assertPersonaLinks(userJack, 1); String personaJackOid = userJack.asObjectable().getPersonaRef().get(0).getOid(); - + PrismObject personaJack = assertGetAllow(UserType.class, personaJackOid); assertEquals("Wrong jack persona givenName before change", USER_JACK_GIVEN_NAME, personaJack.asObjectable().getGivenName().getOrig()); - + // TODO: MID-3899 // assertSearch(UserType.class, null, 2); // assertSearch(ObjectType.class, null, 2); assertSearch(OrgType.class, null, 0); - - assertAllow("modify jack givenName", - (task,result) -> modifyUserReplace(USER_JACK_OID, UserType.F_GIVEN_NAME, task, result, + + assertAllow("modify jack givenName", + (task,result) -> modifyUserReplace(USER_JACK_OID, UserType.F_GIVEN_NAME, task, result, createPolyString(USER_JACK_GIVEN_NAME_NEW))); - + userJack = assertGetAllow(UserType.class, USER_JACK_OID); assertEquals("Wrong jack givenName after change", USER_JACK_GIVEN_NAME_NEW, userJack.asObjectable().getGivenName().getOrig()); personaJack = assertGetAllow(UserType.class, personaJackOid); assertEquals("Wrong jack persona givenName after change", USER_JACK_GIVEN_NAME_NEW, personaJack.asObjectable().getGivenName().getOrig()); - assertAllow("unassign application role 1 to jack", + assertAllow("unassign application role 1 to jack", (task,result) -> unassignRole(USER_JACK_OID, ROLE_PERSONA_ADMIN_OID, task, result)); - + userJack = assertGetAllow(UserType.class, USER_JACK_OID); assertPersonaLinks(userJack, 0); - + assertNoObject(UserType.class, personaJackOid); - + assertAddDeny(); assertModifyDeny(); assertDeleteDeny(); assertGlobalStateUntouched(); } - + @Test public void test120AutzJackDelagator() throws Exception { final String TEST_NAME = "test120AutzJackDelagator"; TestUtil.displayTestTitle(this, TEST_NAME); // GIVEN - cleanupAutzTest(USER_JACK_OID); + cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_DELEGATOR_OID); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + login(USER_JACK_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); @@ -202,95 +202,95 @@ public void test120AutzJackDelagator() throws Exception { PrismObject userJack = getUser(USER_JACK_OID); assertAssignments(userJack, 1); assertAssignedRole(userJack, ROLE_DELEGATOR_OID); - + PrismObject userBarbossa = getUser(USER_BARBOSSA_OID); assertNoAssignments(userBarbossa); - + assertDeny("assign business role to jack", (task, result) -> { assignRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, task, result); }); - + userJack = getUser(USER_JACK_OID); assertAssignments(userJack, 1); - + // Wrong direction. It should NOT work. - assertDeny("delegate from Barbossa to Jack", + assertDeny("delegate from Barbossa to Jack", (task, result) -> { assignDeputy(USER_JACK_OID, USER_BARBOSSA_OID, task, result); }); // Good direction - assertAllow("delegate to Barbossa", + assertAllow("delegate to Barbossa", (task, result) -> { assignDeputy(USER_BARBOSSA_OID, USER_JACK_OID, task, result); }); - + userJack = getUser(USER_JACK_OID); display("Jack delegator", userJack); assertAssignments(userJack, 1); - + userBarbossa = getUser(USER_BARBOSSA_OID); display("Barbossa delegate", userBarbossa); assertAssignments(userBarbossa, 1); assertAssignedDeputy(userBarbossa, USER_JACK_OID); - + // Non-delegate. We should be able to read just the name. Not the assignments. PrismObject userRum = getUser(userRumRogersOid); display("User Rum Rogers", userRum); assertNoAssignments(userRum); - + login(USER_BARBOSSA_USERNAME); // WHEN TestUtil.displayWhen(TEST_NAME); display("Logged in as Barbossa"); - + assertReadAllow(NUMBER_OF_ALL_USERS); assertAddDeny(); assertModifyDeny(); assertDeleteDeny(); - + login(USER_JACK_USERNAME); // WHEN TestUtil.displayWhen(TEST_NAME); display("Logged in as Jack"); - assertAllow("undelegate from Barbossa", + assertAllow("undelegate from Barbossa", (task, result) -> { unassignDeputy(USER_BARBOSSA_OID, USER_JACK_OID, task, result); }); userJack = getUser(USER_JACK_OID); assertAssignments(userJack, 1); - + userBarbossa = getUser(USER_BARBOSSA_OID); assertNoAssignments(userBarbossa); - + assertGlobalStateUntouched(); - + login(USER_BARBOSSA_USERNAME); // WHEN TestUtil.displayWhen(TEST_NAME); display("Logged in as Barbossa"); - + assertReadDeny(); assertAddDeny(); assertModifyDeny(); assertDeleteDeny(); - assertDeny("delegate to Jack", + assertDeny("delegate to Jack", (task, result) -> { assignDeputy(USER_JACK_OID, USER_BARBOSSA_OID, task, result); }); - - assertDeny("delegate from Jack to Barbossa", + + assertDeny("delegate from Jack to Barbossa", (task, result) -> { assignDeputy(USER_BARBOSSA_OID, USER_JACK_OID, task, result); }); - + assertGlobalStateUntouched(); } - + @Test public void test150AutzJackApproverUnassignRoles() throws Exception { final String TEST_NAME = "test150AutzJackApproverUnassignRoles"; @@ -299,20 +299,20 @@ public void test150AutzJackApproverUnassignRoles() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_APPROVER_UNASSIGN_ROLES_OID); assignRole(USER_JACK_OID, ROLE_ORDINARY_OID, SchemaConstants.ORG_APPROVER); - + PrismObject userCobbBefore = getUser(userCobbOid); IntegrationTestTools.display("User cobb before", userCobbBefore); assertRoleMembershipRef(userCobbBefore, ROLE_ORDINARY_OID, ROLE_UNINTERESTING_OID, ORG_SCUMM_BAR_OID); - + login(USER_JACK_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); assertGetAllow(RoleType.class, ROLE_ORDINARY_OID); assertGetDeny(RoleType.class, ROLE_PERSONA_ADMIN_OID); // no assignment assertGetDeny(RoleType.class, ROLE_APPROVER_UNASSIGN_ROLES_OID); // assignment exists, but wrong relation - + PrismObject userRum = assertGetAllow(UserType.class, userRumRogersOid); // member of ROLE_ORDINARY_OID display("User Rum Rogers", userRumRogersOid); assertRoleMembershipRef(userRum, ROLE_ORDINARY_OID, ROLE_UNINTERESTING_OID, ORG_MINISTRY_OF_RUM_OID); @@ -320,9 +320,9 @@ public void test150AutzJackApproverUnassignRoles() throws Exception { assertGetDeny(UserType.class, USER_JACK_OID); // assignment exists, but wrong relation assertGetDeny(UserType.class, USER_GUYBRUSH_OID); // no assignment to ROLE_ORDINARY_OID assertGetDeny(UserType.class, USER_LECHUCK_OID); // no assignment to ROLE_ORDINARY_OID - + assertSearch(OrgType.class, null, 0); - + // The appr-read-roles authorization is maySkipOnSearch and there is no other authorization that would // allow read, so no role are returned assertSearch(RoleType.class, null, 0); @@ -330,12 +330,12 @@ public void test150AutzJackApproverUnassignRoles() throws Exception { // The appr-read-users authorization is maySkipOnSearch and there is no other authorization that would // allow read, so no users are returned assertSearch(UserType.class, null, 0); - + assertSearch(UserType.class, createMembersQuery(UserType.class, ROLE_APPROVER_UNASSIGN_ROLES_OID), 0); - + assert15xCommon(); } - + @Test public void test151AutzJackApproverUnassignRolesAndRead() throws Exception { final String TEST_NAME = "test151AutzJackApproverUnassignRolesAndRead"; @@ -345,16 +345,16 @@ public void test151AutzJackApproverUnassignRolesAndRead() throws Exception { assignRole(USER_JACK_OID, ROLE_APPROVER_UNASSIGN_ROLES_OID); assignRole(USER_JACK_OID, ROLE_READ_BASIC_ITEMS_OID); assignRole(USER_JACK_OID, ROLE_ORDINARY_OID, SchemaConstants.ORG_APPROVER); - + login(USER_JACK_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); assertGetAllow(RoleType.class, ROLE_ORDINARY_OID); assertGetAllow(RoleType.class, ROLE_PERSONA_ADMIN_OID); // no assignment assertGetAllow(RoleType.class, ROLE_APPROVER_UNASSIGN_ROLES_OID); // assignment exists, but wrong relation - + PrismObject userRum = assertGetAllow(UserType.class, userRumRogersOid); // member of ROLE_ORDINARY_OID display("User Rum Rogers", userRumRogersOid); assertRoleMembershipRef(userRum, ROLE_ORDINARY_OID, ROLE_UNINTERESTING_OID, ORG_MINISTRY_OF_RUM_OID); @@ -363,19 +363,19 @@ public void test151AutzJackApproverUnassignRolesAndRead() throws Exception { assertNoRoleMembershipRef(userJack); assertGetAllow(UserType.class, USER_GUYBRUSH_OID); // no assignment to ROLE_ORDINARY_OID assertGetAllow(UserType.class, USER_LECHUCK_OID); // no assignment to ROLE_ORDINARY_OID - + assertSearch(OrgType.class, null, NUMBER_OF_ALL_ORGS); - + // The appr-read-roles authorization is maySkipOnSearch and the readonly role allows read. assertSearch(RoleType.class, null, getNumberOfRoles()); // The appr-read-users authorization is maySkipOnSearch and the readonly role allows read. assertSearch(UserType.class, null, NUMBER_OF_ALL_USERS); - + assert15xCommon(); } - + /** * Jack is an approver of a role, but he does not have any authorization * except very basic object read. @@ -388,9 +388,9 @@ public void test154AutzJackApproverRead() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READ_BASIC_ITEMS_OID); assignRole(USER_JACK_OID, ROLE_ORDINARY_OID, SchemaConstants.ORG_APPROVER); - + login(USER_JACK_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); @@ -399,48 +399,48 @@ public void test154AutzJackApproverRead() throws Exception { assertGetAllow(RoleType.class, ROLE_PERSONA_ADMIN_OID); PrismObject roleAppr = assertGetAllow(RoleType.class, ROLE_APPROVER_UNASSIGN_ROLES_OID); assertNoRoleMembershipRef(roleAppr); - + PrismObject userRum = assertGetAllow(UserType.class, userRumRogersOid); assertNoRoleMembershipRef(userRum); assertGetAllow(UserType.class, userCobbOid); assertGetAllow(UserType.class, USER_JACK_OID); assertGetAllow(UserType.class, USER_GUYBRUSH_OID); assertGetAllow(UserType.class, USER_LECHUCK_OID); - - assertSearch(OrgType.class, null, NUMBER_OF_ALL_ORGS); + + assertSearch(OrgType.class, null, NUMBER_OF_ALL_ORGS); assertSearch(RoleType.class, null, getNumberOfRoles()); assertSearch(UserType.class, null, NUMBER_OF_ALL_USERS); - + assertSearch(UserType.class, createMembersQuery(UserType.class, ROLE_ORDINARY_OID), 0); assertSearch(UserType.class, createMembersQuery(UserType.class, ROLE_APPROVER_UNASSIGN_ROLES_OID), 0); - + assertCanSearchRoleMemberUsers(ROLE_ORDINARY_OID, false); assertCanSearchRoleMembers(ROLE_ORDINARY_OID, false); assertCanSearchRoleMemberUsers(ROLE_UNINTERESTING_OID, false); assertCanSearchRoleMembers(ROLE_UNINTERESTING_OID, false); assertCanSearchRoleMemberUsers(ROLE_APPROVER_UNASSIGN_ROLES_OID, false); assertCanSearchRoleMembers(ROLE_UNINTERESTING_OID, false); - - assertDeny("unassign ordinary role from cobb", + + assertDeny("unassign ordinary role from cobb", (task,result) -> unassignRole(userCobbOid, ROLE_ORDINARY_OID, task, result)); - + assertSearch(UserType.class, createMembersQuery(UserType.class, ROLE_ORDINARY_OID), 0); - - assertDeny("unassign uninteresting role from cobb", + + assertDeny("unassign uninteresting role from cobb", (task,result) -> unassignRole(userCobbOid, ROLE_UNINTERESTING_OID, task, result)); - assertDeny("unassign uninteresting role from rum", - (task,result) -> unassignRole(userRumRogersOid, ROLE_UNINTERESTING_OID, task, result)); - assertDeny("unassign approver role from jack", + assertDeny("unassign uninteresting role from rum", + (task,result) -> unassignRole(userRumRogersOid, ROLE_UNINTERESTING_OID, task, result)); + assertDeny("unassign approver role from jack", (task,result) -> unassignRole(USER_JACK_OID, ROLE_APPROVER_UNASSIGN_ROLES_OID, task, result)); - assertDeny("unassign ordinary role from lechuck", + assertDeny("unassign ordinary role from lechuck", (task,result) -> unassignRole(USER_LECHUCK_OID, ROLE_ORDINARY_OID, task, result)); - + assertAddDeny(); assertModifyDeny(); assertDeleteDeny(); assertGlobalStateUntouched(); } - + /** * Jack is an approver of a role, but he does not have any authorization * except reading self. @@ -454,56 +454,56 @@ public void test155AutzJackApproverSelf() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_SELF_OID); assignRole(USER_JACK_OID, ROLE_ORDINARY_OID, SchemaConstants.ORG_APPROVER); - + login(USER_JACK_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); assertGetDeny(RoleType.class, ROLE_ORDINARY_OID); assertGetDeny(RoleType.class, ROLE_PERSONA_ADMIN_OID); assertGetDeny(RoleType.class, ROLE_APPROVER_UNASSIGN_ROLES_OID); - + assertGetAllow(UserType.class, USER_JACK_OID); - + assertGetDeny(UserType.class, userRumRogersOid); assertGetDeny(UserType.class, userCobbOid); assertGetDeny(UserType.class, USER_GUYBRUSH_OID); assertGetDeny(UserType.class, USER_LECHUCK_OID); - + assertSearch(OrgType.class, null, 0); assertSearch(RoleType.class, null, 0); assertSearch(UserType.class, null, 1); - + assertSearch(UserType.class, createMembersQuery(UserType.class, ROLE_ORDINARY_OID), 0); assertSearch(UserType.class, createMembersQuery(UserType.class, ROLE_APPROVER_UNASSIGN_ROLES_OID), 0); - + assertCanSearchRoleMemberUsers(ROLE_ORDINARY_OID, false); assertCanSearchRoleMembers(ROLE_ORDINARY_OID, false); assertCanSearchRoleMemberUsers(ROLE_UNINTERESTING_OID, false); assertCanSearchRoleMembers(ROLE_UNINTERESTING_OID, false); assertCanSearchRoleMemberUsers(ROLE_APPROVER_UNASSIGN_ROLES_OID, false); assertCanSearchRoleMembers(ROLE_UNINTERESTING_OID, false); - - assertDeny("unassign ordinary role from cobb", + + assertDeny("unassign ordinary role from cobb", (task,result) -> unassignRole(userCobbOid, ROLE_ORDINARY_OID, task, result)); - + assertSearch(UserType.class, createMembersQuery(UserType.class, ROLE_ORDINARY_OID), 0); - - assertDeny("unassign uninteresting role from cobb", + + assertDeny("unassign uninteresting role from cobb", (task,result) -> unassignRole(userCobbOid, ROLE_UNINTERESTING_OID, task, result)); - assertDeny("unassign uninteresting role from rum", - (task,result) -> unassignRole(userRumRogersOid, ROLE_UNINTERESTING_OID, task, result)); - assertDeny("unassign ordinary role from lechuck", + assertDeny("unassign uninteresting role from rum", + (task,result) -> unassignRole(userRumRogersOid, ROLE_UNINTERESTING_OID, task, result)); + assertDeny("unassign ordinary role from lechuck", (task,result) -> unassignRole(USER_LECHUCK_OID, ROLE_ORDINARY_OID, task, result)); - + assertAddDeny(); assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Captain")); assertModifyDeny(UserType.class, USER_GUYBRUSH_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Pirate")); assertDeleteDeny(); assertGlobalStateUntouched(); } - + @Test public void test157AutzJackReadRoleMembers() throws Exception { final String TEST_NAME = "test157AutzJackReadRoleMembers"; @@ -511,9 +511,9 @@ public void test157AutzJackReadRoleMembers() throws Exception { // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READ_ROLE_MEMBERS_OID); - + login(USER_JACK_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); @@ -522,41 +522,41 @@ public void test157AutzJackReadRoleMembers() throws Exception { PrismObject roleAppr = assertGetAllow(RoleType.class, ROLE_APPROVER_UNASSIGN_ROLES_OID); assertNoRoleMembershipRef(roleAppr); assertGetAllow(RoleType.class, ROLE_PERSONA_ADMIN_OID); - + PrismObject userRum = assertGetAllow(UserType.class, userRumRogersOid); assertRoleMembershipRef(userRum, ROLE_ORDINARY_OID, ROLE_UNINTERESTING_OID, ORG_MINISTRY_OF_RUM_OID); - assertGetAllow(UserType.class, userCobbOid); + assertGetAllow(UserType.class, userCobbOid); assertGetAllow(UserType.class, USER_JACK_OID); assertGetAllow(UserType.class, USER_GUYBRUSH_OID); assertGetAllow(UserType.class, USER_LECHUCK_OID); - + assertSearch(RoleType.class, null, getNumberOfRoles()); assertSearch(UserType.class, null, NUMBER_OF_ALL_USERS); assertSearch(OrgType.class, null, 0); - + assertSearch(UserType.class, createMembersQuery(UserType.class, ROLE_ORDINARY_OID), 2); assertSearch(UserType.class, createMembersQuery(UserType.class, ROLE_APPROVER_UNASSIGN_ROLES_OID), 0); - + assertCanSearchRoleMemberUsers(ROLE_ORDINARY_OID, true); assertCanSearchRoleMembers(ROLE_ORDINARY_OID, true); assertCanSearchRoleMemberUsers(ROLE_UNINTERESTING_OID, true); assertCanSearchRoleMembers(ROLE_UNINTERESTING_OID, true); assertCanSearchRoleMemberUsers(ROLE_APPROVER_UNASSIGN_ROLES_OID, true); assertCanSearchRoleMembers(ROLE_UNINTERESTING_OID, true); - - assertDeny("unassign ordinary role from cobb", - (task,result) -> unassignRole(userCobbOid, ROLE_ORDINARY_OID, task, result)); - assertDeny("unassign uninteresting role from rum", + + assertDeny("unassign ordinary role from cobb", + (task,result) -> unassignRole(userCobbOid, ROLE_ORDINARY_OID, task, result)); + assertDeny("unassign uninteresting role from rum", (task,result) -> unassignRole(userRumRogersOid, ROLE_UNINTERESTING_OID, task, result)); - assertDeny("unassign approver role from jack", + assertDeny("unassign approver role from jack", (task,result) -> unassignRole(USER_JACK_OID, ROLE_APPROVER_UNASSIGN_ROLES_OID, task, result)); - + assertAddDeny(); assertModifyDeny(); assertDeleteDeny(); assertGlobalStateUntouched(); } - + @Test public void test158AutzJackReadRoleMembersWrong() throws Exception { final String TEST_NAME = "test158AutzJackReadRoleMembersWrong"; @@ -564,9 +564,9 @@ public void test158AutzJackReadRoleMembersWrong() throws Exception { // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READ_ROLE_MEMBERS_WRONG_OID); - + login(USER_JACK_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); @@ -575,41 +575,41 @@ public void test158AutzJackReadRoleMembersWrong() throws Exception { PrismObject roleAppr = assertGetAllow(RoleType.class, ROLE_APPROVER_UNASSIGN_ROLES_OID); assertNoRoleMembershipRef(roleAppr); assertGetAllow(RoleType.class, ROLE_PERSONA_ADMIN_OID); - + PrismObject userRum = assertGetAllow(UserType.class, userRumRogersOid); // member of ROLE_ORDINARY_OID assertNoRoleMembershipRef(userRum); - assertGetAllow(UserType.class, userCobbOid); + assertGetAllow(UserType.class, userCobbOid); assertGetAllow(UserType.class, USER_JACK_OID); assertGetAllow(UserType.class, USER_GUYBRUSH_OID); assertGetAllow(UserType.class, USER_LECHUCK_OID); - + assertSearch(RoleType.class, null, getNumberOfRoles()); assertSearch(UserType.class, null, NUMBER_OF_ALL_USERS); assertSearch(OrgType.class, null, 0); - + assertSearch(UserType.class, createMembersQuery(UserType.class, ROLE_ORDINARY_OID), 0); assertSearch(UserType.class, createMembersQuery(UserType.class, ROLE_APPROVER_UNASSIGN_ROLES_OID), 0); - + assertCanSearchRoleMemberUsers(ROLE_ORDINARY_OID, false); assertCanSearchRoleMembers(ROLE_ORDINARY_OID, true); // We can read roleMembershipRef from roles that are members of those roles assertCanSearchRoleMemberUsers(ROLE_UNINTERESTING_OID, false); assertCanSearchRoleMembers(ROLE_UNINTERESTING_OID, true); assertCanSearchRoleMemberUsers(ROLE_APPROVER_UNASSIGN_ROLES_OID, false); assertCanSearchRoleMembers(ROLE_UNINTERESTING_OID, true); - - assertDeny("unassign ordinary role from cobb", - (task,result) -> unassignRole(userCobbOid, ROLE_ORDINARY_OID, task, result)); - assertDeny("unassign uninteresting role from rum", + + assertDeny("unassign ordinary role from cobb", + (task,result) -> unassignRole(userCobbOid, ROLE_ORDINARY_OID, task, result)); + assertDeny("unassign uninteresting role from rum", (task,result) -> unassignRole(userRumRogersOid, ROLE_UNINTERESTING_OID, task, result)); - assertDeny("unassign approver role from jack", + assertDeny("unassign approver role from jack", (task,result) -> unassignRole(USER_JACK_OID, ROLE_APPROVER_UNASSIGN_ROLES_OID, task, result)); - + assertAddDeny(); assertModifyDeny(); assertDeleteDeny(); assertGlobalStateUntouched(); } - + @Test public void test159AutzJackReadRoleMembersNone() throws Exception { final String TEST_NAME = "test159AutzJackReadRoleMembersNone"; @@ -617,9 +617,9 @@ public void test159AutzJackReadRoleMembersNone() throws Exception { // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READ_ROLE_MEMBERS_NONE_OID); - + login(USER_JACK_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); @@ -628,35 +628,35 @@ public void test159AutzJackReadRoleMembersNone() throws Exception { PrismObject roleAppr = assertGetAllow(RoleType.class, ROLE_APPROVER_UNASSIGN_ROLES_OID); assertNoRoleMembershipRef(roleAppr); assertGetAllow(RoleType.class, ROLE_PERSONA_ADMIN_OID); - + PrismObject userRum = assertGetAllow(UserType.class, userRumRogersOid); // member of ROLE_ORDINARY_OID assertNoRoleMembershipRef(userRum); - assertGetAllow(UserType.class, userCobbOid); + assertGetAllow(UserType.class, userCobbOid); assertGetAllow(UserType.class, USER_JACK_OID); assertGetAllow(UserType.class, USER_GUYBRUSH_OID); assertGetAllow(UserType.class, USER_LECHUCK_OID); - + assertSearch(RoleType.class, null, getNumberOfRoles()); assertSearch(UserType.class, null, NUMBER_OF_ALL_USERS); assertSearch(OrgType.class, null, 0); - + assertSearch(UserType.class, createMembersQuery(UserType.class, ROLE_ORDINARY_OID), 0); assertSearch(UserType.class, createMembersQuery(UserType.class, ROLE_APPROVER_UNASSIGN_ROLES_OID), 0); - + assertCanSearchRoleMemberUsers(ROLE_ORDINARY_OID, false); assertCanSearchRoleMembers(ROLE_ORDINARY_OID, false); assertCanSearchRoleMemberUsers(ROLE_UNINTERESTING_OID, false); assertCanSearchRoleMembers(ROLE_UNINTERESTING_OID, false); assertCanSearchRoleMemberUsers(ROLE_APPROVER_UNASSIGN_ROLES_OID, false); assertCanSearchRoleMembers(ROLE_UNINTERESTING_OID, false); - - assertDeny("unassign ordinary role from cobb", - (task,result) -> unassignRole(userCobbOid, ROLE_ORDINARY_OID, task, result)); - assertDeny("unassign uninteresting role from rum", + + assertDeny("unassign ordinary role from cobb", + (task,result) -> unassignRole(userCobbOid, ROLE_ORDINARY_OID, task, result)); + assertDeny("unassign uninteresting role from rum", (task,result) -> unassignRole(userRumRogersOid, ROLE_UNINTERESTING_OID, task, result)); - assertDeny("unassign approver role from jack", + assertDeny("unassign approver role from jack", (task,result) -> unassignRole(USER_JACK_OID, ROLE_APPROVER_UNASSIGN_ROLES_OID, task, result)); - + assertAddDeny(); assertModifyDeny(); assertDeleteDeny(); @@ -664,7 +664,7 @@ public void test159AutzJackReadRoleMembersNone() throws Exception { } private void assert15xCommon() throws Exception { - + // list ordinary role members, this is allowed assertSearch(UserType.class, createMembersQuery(UserType.class, ROLE_ORDINARY_OID), 2); assertSearch(FocusType.class, createMembersQuery(FocusType.class, ROLE_ORDINARY_OID), 2); @@ -672,7 +672,7 @@ private void assert15xCommon() throws Exception { // list approver role members, this is not allowed assertSearch(UserType.class, createMembersQuery(UserType.class, ROLE_APPROVER_UNASSIGN_ROLES_OID), 0); assertSearch(FocusType.class, createMembersQuery(FocusType.class, ROLE_APPROVER_UNASSIGN_ROLES_OID), 0); - + assertCanSearchRoleMemberUsers(ROLE_ORDINARY_OID, true); assertCanSearchRoleMembers(ROLE_ORDINARY_OID, true); assertCanSearchRoleMemberUsers(ROLE_UNINTERESTING_OID, false); @@ -680,33 +680,33 @@ private void assert15xCommon() throws Exception { assertCanSearchRoleMemberUsers(ROLE_APPROVER_UNASSIGN_ROLES_OID, false); assertCanSearchRoleMembers(ROLE_APPROVER_UNASSIGN_ROLES_OID, false); - assertAllow("unassign ordinary role from cobb", + assertAllow("unassign ordinary role from cobb", (task,result) -> unassignRole(userCobbOid, ROLE_ORDINARY_OID, task, result)); - + assertSearch(UserType.class, createMembersQuery(UserType.class, ROLE_ORDINARY_OID), 1); - + // Jack is not approver of uninteresting role, so this should be denied - assertDeny("unassign uninteresting role from cobb", + assertDeny("unassign uninteresting role from cobb", (task,result) -> unassignRole(userCobbOid, ROLE_UNINTERESTING_OID, task, result)); - - // Jack is not approver of uninteresting role, so this should be denied + + // Jack is not approver of uninteresting role, so this should be denied // - even though Rum Rogers is a member of a role that jack is an approver of - assertDeny("unassign uninteresting role from rum", + assertDeny("unassign uninteresting role from rum", (task,result) -> unassignRole(userRumRogersOid, ROLE_UNINTERESTING_OID, task, result)); - - assertDeny("unassign approver role from jack", + + assertDeny("unassign approver role from jack", (task,result) -> unassignRole(USER_JACK_OID, ROLE_APPROVER_UNASSIGN_ROLES_OID, task, result)); - - // Lechuck is not a member of ordinary role - assertDeny("unassign ordinary role from lechuck", + + // Lechuck is not a member of ordinary role + assertDeny("unassign ordinary role from lechuck", (task,result) -> unassignRole(USER_LECHUCK_OID, ROLE_ORDINARY_OID, task, result)); - + assertAddDeny(); assertModifyDeny(); assertDeleteDeny(); assertGlobalStateUntouched(); } - + /** * User template will assign organizations to this user. However, the user * does not have request authorization for organizations. Check that this @@ -718,13 +718,13 @@ public void test200AutzJackModifyOrgunit() throws Exception { final String TEST_NAME = "test200AutzJackModifyOrgunit"; TestUtil.displayTestTitle(this, TEST_NAME); // GIVEN - cleanupAutzTest(USER_JACK_OID); + cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READ_SELF_MODIFY_ORGUNIT_OID); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + login(USER_JACK_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); @@ -732,40 +732,40 @@ public void test200AutzJackModifyOrgunit() throws Exception { assertAddDeny(); assertModifyDeny(); assertDeleteDeny(); - + // This is supposed to fail. Jack does not have authorization for org assignment - assertDeny("assign org to jack", + assertDeny("assign org to jack", (task, result) -> assignOrg(USER_JACK_OID, ORG_SCUMM_BAR_OID, task, result)); - + PrismObject user = getUser(USER_JACK_OID); assertAssignments(user, 1); - + // ... but this should work. Indirect assignment in object template is OK. - assertModifyAllow(UserType.class, USER_JACK_OID, + assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, createPolyString(ORG_SCUMM_BAR_NAME)); user = getUser(USER_JACK_OID); display("Jack in medias res", user); assertAssignments(user, 2); assertAssignedOrg(user, ORG_SCUMM_BAR_OID); - - assertModifyAllow(UserType.class, USER_JACK_OID, + + assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, createPolyString(ORG_MINISTRY_OF_RUM_NAME)); user = getUser(USER_JACK_OID); display("Jack in medias res", user); assertAssignments(user, 2); assertAssignedOrg(user, ORG_MINISTRY_OF_RUM_OID); - - assertModifyAllow(UserType.class, USER_JACK_OID, + + assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT); - + user = getUser(USER_JACK_OID); assertAssignments(user, 1); - + assertGlobalStateUntouched(); } - + /** * User template will assign organizations to this user. However, the user * does not have request authorization for organizations. Check that this @@ -779,14 +779,14 @@ public void test202AutzJackModifyOrgunitAndAssignRole() throws Exception { final String TEST_NAME = "test202AutzJackModifyOrgunitAndAssignRole"; TestUtil.displayTestTitle(this, TEST_NAME); // GIVEN - cleanupAutzTest(USER_JACK_OID); + cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READ_SELF_MODIFY_ORGUNIT_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_REQUESTABLE_ROLES_OID); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + login(USER_JACK_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); @@ -794,15 +794,15 @@ public void test202AutzJackModifyOrgunitAndAssignRole() throws Exception { assertAddDeny(); assertModifyDeny(); assertDeleteDeny(); - + // This is supposed to fail. Jack does not have authorization for org assignment - assertDeny("assign org to jack", + assertDeny("assign org to jack", (task, result) -> assignOrg(USER_JACK_OID, ORG_SCUMM_BAR_OID, task, result)); - + PrismObject user = getUser(USER_JACK_OID); assertAssignments(user, 2); - - assertAllow("doing the thing", + + assertAllow("doing the thing", (task, result) -> { ObjectDelta focusDelta = createAssignmentFocusDelta(UserType.class, USER_JACK_OID, ROLE_BUSINESS_1_OID, RoleType.COMPLEX_TYPE, null, null, true); @@ -810,14 +810,14 @@ public void test202AutzJackModifyOrgunitAndAssignRole() throws Exception { Collection> deltas = MiscSchemaUtil.createCollection(focusDelta); modelService.executeChanges(deltas, null, task, result); }); - + user = getUser(USER_JACK_OID); display("Jack in medias res", user); assertAssignments(user, 4); assertAssignedOrg(user, ORG_SCUMM_BAR_OID); assertAssignedRole(user, ROLE_BUSINESS_1_OID); - - assertModifyAllow(UserType.class, USER_JACK_OID, + + assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT, createPolyString(ORG_MINISTRY_OF_RUM_NAME)); user = getUser(USER_JACK_OID); @@ -825,36 +825,36 @@ public void test202AutzJackModifyOrgunitAndAssignRole() throws Exception { assertAssignments(user, 4); assertAssignedOrg(user, ORG_MINISTRY_OF_RUM_OID); assertAssignedRole(user, ROLE_BUSINESS_1_OID); - - assertModifyAllow(UserType.class, USER_JACK_OID, + + assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_ORGANIZATIONAL_UNIT); - + user = getUser(USER_JACK_OID); assertAssignments(user, 3); assertAssignedRole(user, ROLE_BUSINESS_1_OID); assertNotAssignedOrg(user, ORG_MINISTRY_OF_RUM_OID); - - assertAllow("unassign role from jack", + + assertAllow("unassign role from jack", (task, result) -> unassignRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, task, result)); - + user = getUser(USER_JACK_OID); assertAssignments(user, 2); assertNotAssignedRole(user, ROLE_BUSINESS_1_OID); - + assertGlobalStateUntouched(); } - + @Override protected void cleanupAutzTest(String userOid) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException, IOException { super.cleanupAutzTest(userOid); - + Task task = taskManager.createTaskInstance(TestSecurityAdvanced.class.getName() + ".cleanupAutzTest"); OperationResult result = task.getResult(); - + assignRole(userRumRogersOid, ROLE_ORDINARY_OID, task, result); assignRole(userRumRogersOid, ROLE_UNINTERESTING_OID, task, result); assignRole(userCobbOid, ROLE_ORDINARY_OID, task, result); assignRole(userCobbOid, ROLE_UNINTERESTING_OID, task, result); - + } } 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 a69ebe39f0d..8339d5f14a6 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 @@ -98,7 +98,7 @@ public class TestSecurityBasic extends AbstractSecurityTest { public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); } - + @Test public void test200AutzJackNoRole() throws Exception { final String TEST_NAME = "test200AutzJackNoRole"; @@ -107,13 +107,13 @@ public void test200AutzJackNoRole() throws Exception { cleanupAutzTest(USER_JACK_OID); PrismObject userJack = getUser(USER_JACK_OID); login(USER_JACK_USERNAME); - + // WHEN assertNoAccess(userJack); - + assertGlobalStateUntouched(); } - + @Test public void test201AutzJackSuperuserRole() throws Exception { final String TEST_NAME = "test201AutzJackSuperuserRole"; @@ -122,13 +122,13 @@ public void test201AutzJackSuperuserRole() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_SUPERUSER_OID); login(USER_JACK_USERNAME); - + // WHEN assertSuperuserAccess(NUMBER_OF_ALL_USERS); - + assertGlobalStateUntouched(); } - + @Test public void test202AutzJackReadonlyRole() throws Exception { @@ -138,7 +138,7 @@ public void test202AutzJackReadonlyRole() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READONLY_OID); login(USER_JACK_USERNAME); - + // WHEN assertReadAllow(); assertAddDeny(); @@ -146,7 +146,7 @@ public void test202AutzJackReadonlyRole() throws Exception { assertDeleteDeny(); assertReadCertCasesAllow(); - + assertGlobalStateUntouched(); assertAuditReadDeny(); @@ -163,18 +163,18 @@ public void test202rAutzJackReadonlyReqRole() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READONLY_REQ_OID); login(USER_JACK_USERNAME); - + // WHEN assertReadDeny(); assertAddDeny(); assertModifyDeny(); assertDeleteDeny(); - + assertGlobalStateUntouched(); assertAuditReadDeny(); } - + /** * Authorized only for execution but not request. Everything should be denied. */ @@ -186,18 +186,18 @@ public void test202eAutzJackReadonlyExecRole() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READONLY_EXEC_OID); login(USER_JACK_USERNAME); - + // WHEN assertReadDeny(); assertAddDeny(); assertModifyDeny(); assertDeleteDeny(); - + assertGlobalStateUntouched(); assertAuditReadDeny(); } - + @Test public void test202reAutzJackReadonlyReqExecRole() throws Exception { final String TEST_NAME = "test202reAutzJackReadonlyReqExecRole"; @@ -206,13 +206,13 @@ public void test202reAutzJackReadonlyReqExecRole() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READONLY_OID); login(USER_JACK_USERNAME); - + // WHEN assertReadAllow(); assertAddDeny(); assertModifyDeny(); assertDeleteDeny(); - + assertGlobalStateUntouched(); assertAuditReadDeny(); @@ -226,18 +226,18 @@ public void test203AutzJackReadonlyDeepRole() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READONLY_DEEP_OID); login(USER_JACK_USERNAME); - + // WHEN assertReadAllow(); assertAddDeny(); assertModifyDeny(); assertDeleteDeny(); - + assertGlobalStateUntouched(); assertAuditReadDeny(); } - + @Test public void test203eAutzJackReadonlyDeepExecRole() throws Exception { final String TEST_NAME = "test203eAutzJackReadonlyDeepExecRole"; @@ -246,16 +246,16 @@ public void test203eAutzJackReadonlyDeepExecRole() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READONLY_DEEP_OID); login(USER_JACK_USERNAME); - + // WHEN assertReadAllow(); assertAddDeny(); assertModifyDeny(); assertDeleteDeny(); - + assertGlobalStateUntouched(); } - + @Test public void test204AutzJackSelfRole() throws Exception { final String TEST_NAME = "test204AutzJackSelfRole"; @@ -265,41 +265,41 @@ public void test204AutzJackSelfRole() throws Exception { assignRole(USER_JACK_OID, ROLE_SELF_OID); assignRole(USER_JACK_OID, ROLE_READ_JACKS_CAMPAIGNS_OID); // we cannot specify "own campaigns" yet login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertGetAllow(UserType.class, USER_JACK_OID); assertGetDeny(UserType.class, USER_GUYBRUSH_OID); - + assertVisibleUsers(1); assertSearch(OrgType.class, null, 0); assertSearch(RoleType.class, null, 0); // The search with ObjectClass is important. It is a very different case // than searching just for UserType assertSearch(ObjectType.class, null, 2); // user + campaign - + assertGetDeny(RoleType.class, ROLE_ORDINARY_OID); assertGetDeny(RoleType.class, ROLE_PERSONA_ADMIN_OID); - + assertSearch(UserType.class, createMembersQuery(UserType.class, ROLE_ORDINARY_OID), 0); assertSearch(UserType.class, createMembersQuery(UserType.class, ROLE_APPROVER_UNASSIGN_ROLES_OID), 0); - + assertCanSearchRoleMemberUsers(ROLE_ORDINARY_OID, false); assertCanSearchRoleMembers(ROLE_ORDINARY_OID, false); assertCanSearchRoleMemberUsers(ROLE_UNINTERESTING_OID, false); assertCanSearchRoleMembers(ROLE_UNINTERESTING_OID, false); assertAddDeny(); - + assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Captain")); assertModifyDeny(UserType.class, USER_GUYBRUSH_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Pirate")); - + assertDeleteDeny(); assertDeleteDeny(UserType.class, USER_JACK_OID); assertReadCertCases(2); - + assertGlobalStateUntouched(); } @@ -311,23 +311,23 @@ public void test205AutzJackObjectFilterModifyCaribbeanfRole() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_OBJECT_FILTER_MODIFY_CARIBBEAN_OID); login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertReadAllow(); assertAddDeny(); - + assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Captain")); assertModifyDeny(UserType.class, USER_GUYBRUSH_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Pirate")); assertModifyAllow(UserType.class, USER_BARBOSSA_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Mutinier")); - + assertDeleteDeny(); - + assertGlobalStateUntouched(); } - + @Test public void test207AutzJackObjectFilterCaribbeanRole() throws Exception { final String TEST_NAME = "test207AutzJackObjectFilterCaribbeanfRole"; @@ -336,15 +336,15 @@ public void test207AutzJackObjectFilterCaribbeanRole() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_OBJECT_FILTER_CARIBBEAN_OID); login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertGetAllow(UserType.class, USER_JACK_OID); assertGetAllow(UserType.class, USER_JACK_OID, SelectorOptions.createCollection(GetOperationOptions.createRaw())); assertGetDeny(UserType.class, USER_GUYBRUSH_OID); assertGetDeny(UserType.class, USER_GUYBRUSH_OID, SelectorOptions.createCollection(GetOperationOptions.createRaw())); - + assertSearch(UserType.class, null, 2); assertSearch(ObjectType.class, null, 2); assertSearch(UserType.class, createNameQuery(USER_JACK_USERNAME), 1); @@ -355,16 +355,16 @@ public void test207AutzJackObjectFilterCaribbeanRole() throws Exception { assertSearch(ObjectType.class, createNameQuery(USER_GUYBRUSH_USERNAME), 0); assertAddDeny(); - + assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Captain")); assertModifyDeny(UserType.class, USER_GUYBRUSH_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Pirate")); assertModifyAllow(UserType.class, USER_BARBOSSA_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Mutinier")); - + assertDeleteDeny(); - + assertGlobalStateUntouched(); } - + /** * MID-3647 */ @@ -376,34 +376,34 @@ public void test208AutzJackReadSomeRoles() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READ_SOME_ROLES_OID); login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertReadDeny(); assertAddDeny(); assertModifyDeny(); assertDeleteDeny(); - + assertSearch(UserType.class, null, 0); assertSearch(RoleType.class, null, 5); - + assertGetDeny(UserType.class, USER_JACK_OID); assertGetDeny(UserType.class, USER_GUYBRUSH_OID); - + assertGetDeny(RoleType.class, ROLE_SUPERUSER_OID); assertGetDeny(RoleType.class, ROLE_SELF_OID); assertGetDeny(RoleType.class, ROLE_ASSIGN_APPLICATION_ROLES_OID); - + assertGetAllow(RoleType.class, ROLE_APPLICATION_1_OID); assertGetAllow(RoleType.class, ROLE_APPLICATION_2_OID); assertGetAllow(RoleType.class, ROLE_BUSINESS_1_OID); assertGetAllow(RoleType.class, ROLE_BUSINESS_2_OID); assertGetAllow(RoleType.class, ROLE_BUSINESS_3_OID); - + assertGlobalStateUntouched(); } - + /** * MID-3126 */ @@ -415,30 +415,30 @@ public void test210AutzJackPropReadAllModifySome() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_READ_ALL_MODIFY_SOME_OID); login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertReadAllow(); assertAddDeny(); - + assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Captain Jack Sparrow")); assertModifyAllow(UserType.class, USER_GUYBRUSH_OID, UserType.F_DESCRIPTION, "Pirate wannabe"); - + assertModifyDeny(UserType.class, USER_JACK_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Captain")); assertModifyDeny(UserType.class, USER_GUYBRUSH_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Pirate")); assertModifyDeny(UserType.class, USER_BARBOSSA_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Mutinier")); - + assertDeleteDeny(); - + PrismObject userJack = getUser(USER_JACK_OID); display("Jack", userJack); assertJackEditSchemaReadAllModifySome(userJack); - + assertGlobalStateUntouched(); } - + /** * MID-3126 */ @@ -450,15 +450,15 @@ public void test211AutzJackPropReadAllModifySomeUser() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_READ_ALL_MODIFY_SOME_USER_OID); login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertGetAllow(UserType.class, USER_JACK_OID); assertGetAllow(UserType.class, USER_JACK_OID, SelectorOptions.createCollection(GetOperationOptions.createRaw())); assertGetDeny(UserType.class, USER_GUYBRUSH_OID); assertGetDeny(UserType.class, USER_GUYBRUSH_OID, SelectorOptions.createCollection(GetOperationOptions.createRaw())); - + assertSearch(UserType.class, null, 1); assertSearch(UserType.class, createNameQuery(USER_JACK_USERNAME), 1); assertSearch(UserType.class, createNameQuery(USER_JACK_USERNAME), SelectorOptions.createCollection(GetOperationOptions.createRaw()), 1); @@ -466,23 +466,23 @@ public void test211AutzJackPropReadAllModifySomeUser() throws Exception { assertSearch(UserType.class, createNameQuery(USER_GUYBRUSH_USERNAME), SelectorOptions.createCollection(GetOperationOptions.createRaw()), 0); assertAddDeny(); - + assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Captain Jack Sparrow")); assertModifyDeny(UserType.class, USER_GUYBRUSH_OID, UserType.F_DESCRIPTION, "Pirate wannabe"); - + assertModifyDeny(UserType.class, USER_JACK_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Captain")); assertModifyDeny(UserType.class, USER_GUYBRUSH_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Pirate")); assertModifyDeny(UserType.class, USER_BARBOSSA_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Mutinier")); - + assertDeleteDeny(); - + PrismObject userJack = getUser(USER_JACK_OID); display("Jack", userJack); assertJackEditSchemaReadAllModifySome(userJack); - + assertGlobalStateUntouched(); } - + private void assertJackEditSchemaReadAllModifySome(PrismObject userJack) throws SchemaException, ConfigurationException, ObjectNotFoundException { PrismObjectDefinition userJackEditSchema = getEditObjectDefinition(userJack); display("Jack's edit schema", userJackEditSchema); @@ -500,7 +500,7 @@ private void assertJackEditSchemaReadAllModifySome(PrismObject userJac assertItemFlags(userJackEditSchema, new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), true, false, false); assertItemFlags(userJackEditSchema, new ItemPath(UserType.F_ACTIVATION, ActivationType.F_EFFECTIVE_STATUS), true, false, false); } - + @Test public void test215AutzJackPropReadSomeModifySome() throws Exception { final String TEST_NAME = "test215AutzJackPropReadSomeModifySome"; @@ -512,7 +512,7 @@ public void test215reAutzJackPropReadSomeModifySomeReqExec() throws Exception { final String TEST_NAME = "test215reAutzJackPropReadSomeModifySomeReqExec"; testAutzJackPropReadSomeModifySome(TEST_NAME, ROLE_PROP_READ_SOME_MODIFY_SOME_REQ_EXEC_OID); } - + /** * MID-3126 */ @@ -524,40 +524,40 @@ public void test216AutzJackPropReadSomeModifySomeUser() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_READ_SOME_MODIFY_SOME_USER_OID); login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + PrismObject userJack = getUser(USER_JACK_OID); display("Jack", userJack); assertUserJackReadSomeModifySome(userJack); assertJackEditSchemaReadSomeModifySome(userJack); - + PrismObject userGuybrush = findUserByUsername(USER_GUYBRUSH_USERNAME); display("Guybrush", userGuybrush); assertNull("Unexpected Guybrush", userGuybrush); - + assertAddDeny(); - + assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_FULL_NAME, createPolyString("Captain Jack Sparrow")); - assertModifyAllow(UserType.class, USER_JACK_OID, SchemaConstants.PATH_ACTIVATION_VALID_FROM, + assertModifyAllow(UserType.class, USER_JACK_OID, SchemaConstants.PATH_ACTIVATION_VALID_FROM, JACK_VALID_FROM_LONG_AGO); assertModifyDeny(UserType.class, USER_GUYBRUSH_OID, UserType.F_DESCRIPTION, "Pirate wannabe"); - + assertModifyDeny(UserType.class, USER_JACK_OID, UserType.F_HONORIFIC_PREFIX, createPolyString("Captain")); assertModifyDeny(UserType.class, USER_GUYBRUSH_OID, UserType.F_HONORIFIC_PREFIX, createPolyString("Pirate")); assertModifyDeny(UserType.class, USER_BARBOSSA_OID, UserType.F_HONORIFIC_PREFIX, createPolyString("Mutinier")); - + assertModifyDeny(UserType.class, USER_JACK_OID, UserType.F_COST_CENTER, "V3RYC0STLY"); assertModifyDeny(UserType.class, USER_JACK_OID, UserType.F_ORGANIZATION, createPolyString("Brethren of the Coast")); - + assertDeleteDeny(); - + assertGlobalStateUntouched(); } - + private void assertUserJackReadSomeModifySome(PrismObject userJack) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException { - + PrismAsserts.assertPropertyValue(userJack, UserType.F_NAME, PrismTestUtil.createPolyString(USER_JACK_USERNAME)); PrismAsserts.assertPropertyValue(userJack, UserType.F_FULL_NAME, PrismTestUtil.createPolyString(USER_JACK_FULL_NAME)); PrismAsserts.assertPropertyValue(userJack, new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), @@ -569,7 +569,7 @@ private void assertUserJackReadSomeModifySome(PrismObject userJack) th PrismAsserts.assertNoItem(userJack, new ItemPath(UserType.F_ACTIVATION, ActivationType.F_EFFECTIVE_STATUS)); assertAssignmentsWithTargets(userJack, 1); } - + private void assertJackEditSchemaReadSomeModifySome(PrismObject userJack) throws SchemaException, ConfigurationException, ObjectNotFoundException { PrismObjectDefinition userJackEditSchema = getEditObjectDefinition(userJack); display("Jack's edit schema", userJackEditSchema); @@ -595,19 +595,19 @@ public void testAutzJackPropReadSomeModifySome(final String TEST_NAME, String ro cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, roleOid); login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertReadAllow(); - + assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_ADDITIONAL_NAME, PrismTestUtil.createPolyString("Captain")); - + PrismObject userJack = getUser(USER_JACK_OID); display("Jack", userJack); assertUserJackReadSomeModifySome(userJack); assertJackEditSchemaReadSomeModifySome(userJack); - + PrismObject userGuybrush = findUserByUsername(USER_GUYBRUSH_USERNAME); display("Guybrush", userGuybrush); PrismAsserts.assertPropertyValue(userGuybrush, UserType.F_NAME, PrismTestUtil.createPolyString(USER_GUYBRUSH_USERNAME)); @@ -622,25 +622,25 @@ public void testAutzJackPropReadSomeModifySome(final String TEST_NAME, String ro assertAssignmentsWithTargets(userGuybrush, 1); assertAddDeny(); - + assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_FULL_NAME, createPolyString("Captain Jack Sparrow")); - assertModifyAllow(UserType.class, USER_JACK_OID, SchemaConstants.PATH_ACTIVATION_VALID_FROM, + assertModifyAllow(UserType.class, USER_JACK_OID, SchemaConstants.PATH_ACTIVATION_VALID_FROM, JACK_VALID_FROM_LONG_AGO); assertModifyAllow(UserType.class, USER_GUYBRUSH_OID, UserType.F_DESCRIPTION, "Pirate wannabe"); - + assertModifyDeny(UserType.class, USER_JACK_OID, UserType.F_HONORIFIC_PREFIX, createPolyString("Captain")); assertModifyDeny(UserType.class, USER_GUYBRUSH_OID, UserType.F_HONORIFIC_PREFIX, createPolyString("Pirate")); assertModifyDeny(UserType.class, USER_BARBOSSA_OID, UserType.F_HONORIFIC_PREFIX, createPolyString("Mutinier")); - + assertModifyDeny(UserType.class, USER_JACK_OID, UserType.F_COST_CENTER, "V3RYC0STLY"); assertModifyDeny(UserType.class, USER_JACK_OID, UserType.F_ORGANIZATION, createPolyString("Brethren of the Coast")); - + assertDeleteDeny(); - + assertGlobalStateUntouched(); } - + @Test public void test218AutzJackPropReadSomeModifySomeExecAll() throws Exception { final String TEST_NAME = "test218AutzJackPropReadSomeModifySomeExecAll"; @@ -649,14 +649,14 @@ public void test218AutzJackPropReadSomeModifySomeExecAll() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_READ_SOME_MODIFY_SOME_EXEC_ALL_OID); login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertReadAllow(); - + assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_ADDITIONAL_NAME, PrismTestUtil.createPolyString("Captain")); - + PrismObject userJack = getUser(USER_JACK_OID); display("Jack", userJack); PrismAsserts.assertPropertyValue(userJack, UserType.F_NAME, PrismTestUtil.createPolyString(USER_JACK_USERNAME)); @@ -669,7 +669,7 @@ public void test218AutzJackPropReadSomeModifySomeExecAll() throws Exception { PrismAsserts.assertNoItem(userJack, UserType.F_DESCRIPTION); PrismAsserts.assertNoItem(userJack, new ItemPath(UserType.F_ACTIVATION, ActivationType.F_EFFECTIVE_STATUS)); assertAssignmentsWithTargets(userJack, 1); - + PrismObjectDefinition userJackEditSchema = getEditObjectDefinition(userJack); display("Jack's edit schema", userJackEditSchema); assertItemFlags(userJackEditSchema, UserType.F_NAME, true, false, false); @@ -685,7 +685,7 @@ public void test218AutzJackPropReadSomeModifySomeExecAll() throws Exception { assertItemFlags(userJackEditSchema, new ItemPath(UserType.F_ASSIGNMENT, UserType.F_METADATA, MetadataType.F_CREATE_TIMESTAMP), true, false, false); assertItemFlags(userJackEditSchema, new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), true, false, false); assertItemFlags(userJackEditSchema, new ItemPath(UserType.F_ACTIVATION, ActivationType.F_EFFECTIVE_STATUS), false, false, false); - + PrismObject userGuybrush = findUserByUsername(USER_GUYBRUSH_USERNAME); display("Guybrush", userGuybrush); PrismAsserts.assertPropertyValue(userGuybrush, UserType.F_NAME, PrismTestUtil.createPolyString(USER_GUYBRUSH_USERNAME)); @@ -700,19 +700,19 @@ public void test218AutzJackPropReadSomeModifySomeExecAll() throws Exception { assertAssignmentsWithTargets(userGuybrush, 1); assertAddDeny(); - + assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Captain Jack Sparrow")); assertModifyAllow(UserType.class, USER_GUYBRUSH_OID, UserType.F_DESCRIPTION, "Pirate wannabe"); assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_COST_CENTER, "V3RYC0STLY"); - + assertModifyDeny(UserType.class, USER_JACK_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Captain")); assertModifyDeny(UserType.class, USER_GUYBRUSH_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Pirate")); assertModifyDeny(UserType.class, USER_BARBOSSA_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Mutinier")); - + assertModifyDeny(UserType.class, USER_JACK_OID, UserType.F_ORGANIZATION, PrismTestUtil.createPolyString("Brethren of the Coast")); - + assertDeleteDeny(); - + assertGlobalStateUntouched(); } @@ -724,15 +724,15 @@ public void test220AutzJackPropDenyModifySome() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_DENY_MODIFY_SOME_OID); login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertReadAllow(); - + PrismObject userJack = getUser(USER_JACK_OID); display("Jack", userJack); - + PrismAsserts.assertPropertyValue(userJack, UserType.F_NAME, PrismTestUtil.createPolyString(USER_JACK_USERNAME)); PrismAsserts.assertPropertyValue(userJack, UserType.F_FULL_NAME, PrismTestUtil.createPolyString(USER_JACK_FULL_NAME)); PrismAsserts.assertPropertyValue(userJack, UserType.F_GIVEN_NAME, PrismTestUtil.createPolyString(USER_JACK_GIVEN_NAME)); @@ -742,7 +742,7 @@ public void test220AutzJackPropDenyModifySome() throws Exception { PrismAsserts.assertNoItem(userJack, UserType.F_ADDITIONAL_NAME); PrismAsserts.assertNoItem(userJack, UserType.F_DESCRIPTION); assertAssignmentsWithTargets(userJack, 1); - + PrismObjectDefinition userJackEditSchema = getEditObjectDefinition(userJack); display("Jack's edit schema", userJackEditSchema); assertItemFlags(userJackEditSchema, UserType.F_NAME, true, true, true); @@ -751,7 +751,7 @@ public void test220AutzJackPropDenyModifySome() throws Exception { assertItemFlags(userJackEditSchema, UserType.F_GIVEN_NAME, true, true, false); assertItemFlags(userJackEditSchema, UserType.F_FAMILY_NAME, true, true, true); assertItemFlags(userJackEditSchema, UserType.F_ADDITIONAL_NAME, false, true, true); - + PrismObject userGuybrush = findUserByUsername(USER_GUYBRUSH_USERNAME); display("Guybrush", userGuybrush); PrismAsserts.assertPropertyValue(userGuybrush, UserType.F_NAME, PrismTestUtil.createPolyString(USER_GUYBRUSH_USERNAME)); @@ -763,24 +763,24 @@ public void test220AutzJackPropDenyModifySome() throws Exception { PrismAsserts.assertNoItem(userGuybrush, UserType.F_ADDITIONAL_NAME); PrismAsserts.assertNoItem(userGuybrush, UserType.F_DESCRIPTION); assertAssignmentsWithTargets(userGuybrush, 1); - + assertAddAllow(); - + assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Captain Jack Sparrow")); assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_ADDITIONAL_NAME, PrismTestUtil.createPolyString("Captain")); assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_COST_CENTER, "V3RYC0STLY"); assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_ORGANIZATION, PrismTestUtil.createPolyString("Brethren of the Coast")); assertModifyDeny(UserType.class, USER_JACK_OID, UserType.F_GIVEN_NAME, PrismTestUtil.createPolyString("Jackie")); - + assertModifyDeny(UserType.class, USER_GUYBRUSH_OID, UserType.F_DESCRIPTION, "Pirate wannabe"); assertModifyDeny(UserType.class, USER_GUYBRUSH_OID, UserType.F_GIVEN_NAME, PrismTestUtil.createPolyString("Brushie")); assertModifyDeny(UserType.class, USER_BARBOSSA_OID, UserType.F_GIVEN_NAME, PrismTestUtil.createPolyString("Hectie")); - + assertDeleteAllow(); - + assertGlobalStateUntouched(); } - + @Test public void test230AutzJackMasterMinistryOfRum() throws Exception { final String TEST_NAME = "test230AutzJackMasterMinistryOfRum"; @@ -789,26 +789,26 @@ public void test230AutzJackMasterMinistryOfRum() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_MASTER_MINISTRY_OF_RUM_OID); login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertReadDeny(3); assertAddDeny(); assertModifyDeny(); assertDeleteDeny(); - + assertGetAllow(UserType.class, userRumRogersOid); assertModifyAllow(UserType.class, userRumRogersOid, UserType.F_TITLE, PrismTestUtil.createPolyString("drunk")); assertGetAllow(UserType.class, userCobbOid); assertAddAllow(USER_MANCOMB_FILE); - + assertVisibleUsers(4); - + assertDeleteAllow(UserType.class, USER_ESTEVAN_OID); - + assertVisibleUsers(3); - + assertGlobalStateUntouched(); } @@ -820,10 +820,10 @@ public void test232AutzJackReadOrgMinistryOfRum() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ORG_READ_ORGS_MINISTRY_OF_RUM_OID); login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertReadDeny(0); assertAddDeny(); assertModifyDeny(); @@ -833,14 +833,14 @@ public void test232AutzJackReadOrgMinistryOfRum() throws Exception { // The search wit ObjectClass is important. It is a very different case // than searching just for UserType or OrgType assertSearch(ObjectType.class, null, 1); - + assertGetDeny(UserType.class, userRumRogersOid); assertModifyDeny(UserType.class, userRumRogersOid, UserType.F_TITLE, PrismTestUtil.createPolyString("drunk")); assertAddDeny(USER_MANCOMB_FILE); - + assertGlobalStateUntouched(); } - + /** * MID-3874 */ @@ -850,48 +850,48 @@ public void test240AutzJackManagerFullControlNoOrg() throws Exception { displayTestTitle(TEST_NAME); // GIVEN cleanupAutzTest(USER_JACK_OID); - + assignRole(USER_JACK_OID, ROLE_MANAGER_FULL_CONTROL_OID); assignAccount(USER_JACK_OID, RESOURCE_DUMMY_OID, null); - + PrismObject user = getUser(USER_JACK_OID); String accountOid = getSingleLinkOid(user); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertReadDeny(0); assertAddDeny(); assertModifyDeny(); assertDeleteDeny(); - + assertGetDeny(UserType.class, userRumRogersOid); assertModifyDeny(UserType.class, userRumRogersOid, UserType.F_TITLE, PrismTestUtil.createPolyString("drunk")); assertGetDeny(UserType.class, userCobbOid); assertAddDeny(USER_MANCOMB_FILE); // MID-3874 - + assertVisibleUsers(0); - + assertGetDeny(OrgType.class, ORG_MINISTRY_OF_RUM_OID); assertSearch(OrgType.class, null, 0); - + assertModifyDeny(OrgType.class, ORG_MINISTRY_OF_RUM_OID, OrgType.F_DESCRIPTION, "blababla"); assertModifyDeny(OrgType.class, ORG_SCUMM_BAR_OID, OrgType.F_DESCRIPTION, "Hosting the worst scumm of the World."); - + assertDeleteDeny(UserType.class, USER_ESTEVAN_OID); - + assertGetDeny(ShadowType.class, accountOid); assertGetDeny(ShadowType.class, ACCOUNT_SHADOW_ELAINE_DUMMY_OID); - + assertSearch(ShadowType.class, ObjectQuery.createObjectQuery( - ObjectQueryUtil.createResourceAndObjectClassFilter(RESOURCE_DUMMY_OID, + ObjectQueryUtil.createResourceAndObjectClassFilter(RESOURCE_DUMMY_OID, new QName(RESOURCE_DUMMY_NAMESPACE, "AccountObjectClass"), prismContext)), 0); - + assertGlobalStateUntouched(); } - + /** * MID-3874 */ @@ -901,21 +901,21 @@ public void test241AutzJackManagerFullControlMemberMinistryOfRum() throws Except displayTestTitle(TEST_NAME); // GIVEN cleanupAutzTest(USER_JACK_OID); - + assignRole(USER_JACK_OID, ROLE_MANAGER_FULL_CONTROL_OID); assignOrg(USER_JACK_OID, ORG_MINISTRY_OF_RUM_OID, null); assignAccount(USER_JACK_OID, RESOURCE_DUMMY_OID, null); - + PrismObject user = getUser(USER_JACK_OID); String accountOid = getSingleLinkOid(user); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertJack24xMember(accountOid, true); - + assertGlobalStateUntouched(); } @@ -928,23 +928,23 @@ public void test242AutzJackManagerFullControlManagerMinistryOfRum() throws Excep displayTestTitle(TEST_NAME); // GIVEN cleanupAutzTest(USER_JACK_OID); - + assignRole(USER_JACK_OID, ROLE_MANAGER_FULL_CONTROL_OID); assignOrg(USER_JACK_OID, ORG_MINISTRY_OF_RUM_OID, SchemaConstants.ORG_MANAGER); assignAccount(USER_JACK_OID, RESOURCE_DUMMY_OID, null); - + // precondition PrismObject elaineShadow = getObject(ShadowType.class, ACCOUNT_SHADOW_ELAINE_DUMMY_OID); assertNotNull(elaineShadow); display("Elaine's shadow", elaineShadow); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertJack24xManager(TEST_NAME, true); - + assertGlobalStateUntouched(); } @@ -957,27 +957,27 @@ public void test243AutzJackManagerFullControlManagerMinistryOfRumAndDefense() th displayTestTitle(TEST_NAME); // GIVEN cleanupAutzTest(USER_JACK_OID); - + assignRole(USER_JACK_OID, ROLE_MANAGER_FULL_CONTROL_OID); assignOrg(USER_JACK_OID, ORG_MINISTRY_OF_RUM_OID, SchemaConstants.ORG_MANAGER); assignOrg(USER_JACK_OID, ORG_MINISTRY_OF_DEFENSE_OID, SchemaConstants.ORG_MANAGER); assignAccount(USER_JACK_OID, RESOURCE_DUMMY_OID, null); - + // precondition PrismObject elaineShadow = getObject(ShadowType.class, ACCOUNT_SHADOW_ELAINE_DUMMY_OID); assertNotNull(elaineShadow); display("Elaine's shadow", elaineShadow); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertJack24xManagerDefense(TEST_NAME, true); - + assertGlobalStateUntouched(); } - + /** * MID-3874 */ @@ -987,24 +987,24 @@ public void test245AutzJackManagerUserAdminMemberMinistryOfRum() throws Exceptio displayTestTitle(TEST_NAME); // GIVEN cleanupAutzTest(USER_JACK_OID); - + assignRole(USER_JACK_OID, ROLE_MANAGER_USER_ADMIN_OID); assignOrg(USER_JACK_OID, ORG_MINISTRY_OF_RUM_OID, null); assignAccount(USER_JACK_OID, RESOURCE_DUMMY_OID, null); - + PrismObject user = getUser(USER_JACK_OID); String accountOid = getSingleLinkOid(user); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertJack24xMember(accountOid, false); - + assertGlobalStateUntouched(); } - + /** * MID-3874 */ @@ -1014,26 +1014,26 @@ public void test246AutzJackManagerUserAdminManagerMinistryOfRum() throws Excepti displayTestTitle(TEST_NAME); // GIVEN cleanupAutzTest(USER_JACK_OID); - + assignRole(USER_JACK_OID, ROLE_MANAGER_USER_ADMIN_OID); assignOrg(USER_JACK_OID, ORG_MINISTRY_OF_RUM_OID, SchemaConstants.ORG_MANAGER); assignAccount(USER_JACK_OID, RESOURCE_DUMMY_OID, null); - + // precondition PrismObject elaineShadow = getObject(ShadowType.class, ACCOUNT_SHADOW_ELAINE_DUMMY_OID); assertNotNull(elaineShadow); display("Elaine's shadow", elaineShadow); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertJack24xManager(TEST_NAME, false); - + assertGlobalStateUntouched(); } - + /** * MID-3874 */ @@ -1043,81 +1043,81 @@ public void test247AutzJackManagerUserAdminManagerMinistryOfRumAndDefense() thro displayTestTitle(TEST_NAME); // GIVEN cleanupAutzTest(USER_JACK_OID); - + assignRole(USER_JACK_OID, ROLE_MANAGER_USER_ADMIN_OID); assignOrg(USER_JACK_OID, ORG_MINISTRY_OF_RUM_OID, SchemaConstants.ORG_MANAGER); assignOrg(USER_JACK_OID, ORG_MINISTRY_OF_DEFENSE_OID, SchemaConstants.ORG_MANAGER); assignAccount(USER_JACK_OID, RESOURCE_DUMMY_OID, null); - + // precondition PrismObject elaineShadow = getObject(ShadowType.class, ACCOUNT_SHADOW_ELAINE_DUMMY_OID); assertNotNull(elaineShadow); display("Elaine's shadow", elaineShadow); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertJack24xManagerDefense(TEST_NAME, false); - + assertGlobalStateUntouched(); } - + private void assertJack24xMember(String accountOid, boolean fullControl) throws Exception { assertReadDeny(0); assertAddDeny(); assertModifyDeny(); assertDeleteDeny(); - + assertGetDeny(UserType.class, userRumRogersOid); assertModifyDeny(UserType.class, userRumRogersOid, UserType.F_TITLE, PrismTestUtil.createPolyString("drunk")); assertGetDeny(UserType.class, userCobbOid); assertAddDeny(USER_MANCOMB_FILE); // MID-3874 - + assertVisibleUsers(0); - + assertGetDeny(OrgType.class, ORG_MINISTRY_OF_RUM_OID); assertSearch(OrgType.class, null, 0); - + assertModifyDeny(OrgType.class, ORG_MINISTRY_OF_RUM_OID, OrgType.F_DESCRIPTION, "blababla"); assertModifyDeny(OrgType.class, ORG_SCUMM_BAR_OID, OrgType.F_DESCRIPTION, "Hosting the worst scumm of the World."); - + assertDeleteDeny(UserType.class, USER_ESTEVAN_OID); - + assertGetDeny(ShadowType.class, accountOid); assertGetDeny(ShadowType.class, ACCOUNT_SHADOW_ELAINE_DUMMY_OID); - + assertSearch(ShadowType.class, ObjectQuery.createObjectQuery( - ObjectQueryUtil.createResourceAndObjectClassFilter(RESOURCE_DUMMY_OID, + ObjectQueryUtil.createResourceAndObjectClassFilter(RESOURCE_DUMMY_OID, new QName(RESOURCE_DUMMY_NAMESPACE, "AccountObjectClass"), prismContext)), 0); } - + private void assertJack24xManager(final String TEST_NAME, boolean fullControl) throws Exception { assertGetAllow(UserType.class, USER_JACK_OID); assertGetAllow(UserType.class, USER_JACK_OID, SelectorOptions.createCollection(GetOperationOptions.createRaw())); assertGetDeny(UserType.class, USER_GUYBRUSH_OID); assertGetDeny(UserType.class, USER_GUYBRUSH_OID, SelectorOptions.createCollection(GetOperationOptions.createRaw())); - + assertSearch(UserType.class, null, 4); assertSearch(UserType.class, createNameQuery(USER_JACK_USERNAME), 1); assertSearch(UserType.class, createNameQuery(USER_JACK_USERNAME), SelectorOptions.createCollection(GetOperationOptions.createRaw()), 1); assertSearch(UserType.class, createNameQuery(USER_GUYBRUSH_USERNAME), 0); assertSearch(UserType.class, createNameQuery(USER_GUYBRUSH_USERNAME), SelectorOptions.createCollection(GetOperationOptions.createRaw()), 0); - + assertAddDeny(); - + assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Captain")); assertModifyAllowOptions(UserType.class, USER_JACK_OID, UserType.F_HONORIFIC_SUFFIX, ModelExecuteOptions.createRaw(), PrismTestUtil.createPolyString("CSc")); assertModifyDeny(UserType.class, USER_GUYBRUSH_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Pirate")); - + assertDeleteDeny(); - + assertGetAllow(UserType.class, userRumRogersOid); assertModifyAllow(UserType.class, userRumRogersOid, UserType.F_TITLE, PrismTestUtil.createPolyString("drunk")); assertGetAllow(UserType.class, userCobbOid); // Cobb is in Scumm Bar, transitive descendant of Ministry of Rum assertAddAllow(USER_MANCOMB_FILE); // MID-3874 - + Task task = taskManager.createTaskInstance(TestSecurityBasic.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); try { @@ -1126,30 +1126,30 @@ private void assertJack24xManager(final String TEST_NAME, boolean fullControl) t } catch (PolicyViolationException e) { display("Expected exception", e); assertFailure(result); - } - + } + PrismObject user = getUser(USER_JACK_OID); String accountOid = getSingleLinkOid(user); assertGetAllow(ShadowType.class, accountOid); PrismObject shadow = getObject(ShadowType.class, accountOid); display("Jack's shadow", shadow); - + assertGetDeny(ShadowType.class, ACCOUNT_SHADOW_ELAINE_DUMMY_OID); - + assertVisibleUsers(5); - + assertGetAllow(OrgType.class, ORG_MINISTRY_OF_RUM_OID); assertSearch(OrgType.class, null, 2); - + assertModifyDeny(OrgType.class, ORG_MINISTRY_OF_RUM_OID, OrgType.F_DESCRIPTION, "blababla"); if (fullControl) { assertModifyAllow(OrgType.class, ORG_SCUMM_BAR_OID, OrgType.F_DESCRIPTION, "Hosting the worst scumm of the World."); } else { assertModifyDeny(OrgType.class, ORG_SCUMM_BAR_OID, OrgType.F_DESCRIPTION, "Hosting the worst scumm of the World."); } - + assignAccount(USER_ESTEVAN_OID, RESOURCE_DUMMY_OID, null); - + PrismObject userEstevan = getUser(USER_ESTEVAN_OID); String accountEstevanOid = getSingleLinkOid(userEstevan); assertGetAllow(ShadowType.class, accountEstevanOid); @@ -1157,83 +1157,83 @@ private void assertJack24xManager(final String TEST_NAME, boolean fullControl) t display("Estevan shadow", shadowEstevan); // MID-2822 - + task = taskManager.createTaskInstance(TestSecurityBasic.class.getName() + "." + TEST_NAME); result = task.getResult(); ObjectQuery query = ObjectQuery.createObjectQuery( - ObjectQueryUtil.createResourceAndObjectClassFilter(RESOURCE_DUMMY_OID, + ObjectQueryUtil.createResourceAndObjectClassFilter(RESOURCE_DUMMY_OID, new QName(RESOURCE_DUMMY_NAMESPACE, "AccountObjectClass"), prismContext)); // When finally fixed is should be like this: // assertSearch(ShadowType.class, query, 2); - + try { - + modelService.searchObjects(ShadowType.class, query, null, task, result); - + AssertJUnit.fail("unexpected success"); - + } catch (SchemaException e) { // This is expected. The authorizations will mix on-resource and off-resource search. display("Expected exception", e); } result.computeStatus(); TestUtil.assertFailure(result); - - + + assertDeleteAllow(UserType.class, USER_ESTEVAN_OID); - + assertVisibleUsers(4); } - + private void assertJack24xManagerDefense(String TEST_NAME, boolean fullControl) throws Exception { assertGetAllow(UserType.class, USER_JACK_OID); assertGetAllow(UserType.class, USER_JACK_OID, SelectorOptions.createCollection(GetOperationOptions.createRaw())); assertGetDeny(UserType.class, USER_GUYBRUSH_OID); assertGetDeny(UserType.class, USER_GUYBRUSH_OID, SelectorOptions.createCollection(GetOperationOptions.createRaw())); - + assertSearch(UserType.class, null, 4); assertSearch(UserType.class, createNameQuery(USER_JACK_USERNAME), 1); assertSearch(UserType.class, createNameQuery(USER_JACK_USERNAME), SelectorOptions.createCollection(GetOperationOptions.createRaw()), 1); assertSearch(UserType.class, createNameQuery(USER_GUYBRUSH_USERNAME), 0); assertSearch(UserType.class, createNameQuery(USER_GUYBRUSH_USERNAME), SelectorOptions.createCollection(GetOperationOptions.createRaw()), 0); - + assertAddDeny(); - + assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Captain")); assertModifyAllowOptions(UserType.class, USER_JACK_OID, UserType.F_HONORIFIC_SUFFIX, ModelExecuteOptions.createRaw(), PrismTestUtil.createPolyString("CSc")); assertModifyDeny(UserType.class, USER_GUYBRUSH_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Pirate")); - + assertDeleteDeny(); - + assertGetAllow(UserType.class, userRumRogersOid); assertModifyAllow(UserType.class, userRumRogersOid, UserType.F_TITLE, PrismTestUtil.createPolyString("drunk")); assertGetAllow(UserType.class, userCobbOid); // Cobb is in Scumm Bar, transitive descendant of Ministry of Rum assertAddAllow(USER_MANCOMB_FILE); // MID-3874 - + PrismObject user = getUser(USER_JACK_OID); String accountOid = getSingleLinkOid(user); assertGetAllow(ShadowType.class, accountOid); PrismObject shadow = getObject(ShadowType.class, accountOid); display("Jack's shadow", shadow); - + assertGetDeny(ShadowType.class, ACCOUNT_SHADOW_ELAINE_DUMMY_OID); - + assertVisibleUsers(5); - + assertGetAllow(OrgType.class, ORG_MINISTRY_OF_RUM_OID); assertSearch(OrgType.class, null, 3); - + assertModifyDeny(OrgType.class, ORG_MINISTRY_OF_RUM_OID, OrgType.F_DESCRIPTION, "blababla"); if (fullControl) { assertModifyAllow(OrgType.class, ORG_SCUMM_BAR_OID, OrgType.F_DESCRIPTION, "Hosting the worst scumm of the World."); } else { assertModifyDeny(OrgType.class, ORG_SCUMM_BAR_OID, OrgType.F_DESCRIPTION, "Hosting the worst scumm of the World."); } - + assignAccount(USER_ESTEVAN_OID, RESOURCE_DUMMY_OID, null); - + PrismObject userEstevan = getUser(USER_ESTEVAN_OID); String accountEstevanOid = getSingleLinkOid(userEstevan); assertGetAllow(ShadowType.class, accountEstevanOid); @@ -1241,77 +1241,77 @@ private void assertJack24xManagerDefense(String TEST_NAME, boolean fullControl) display("Estevan shadow", shadowEstevan); // MID-2822 - + Task task = taskManager.createTaskInstance(TestSecurityBasic.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); ObjectQuery query = ObjectQuery.createObjectQuery( - ObjectQueryUtil.createResourceAndObjectClassFilter(RESOURCE_DUMMY_OID, + ObjectQueryUtil.createResourceAndObjectClassFilter(RESOURCE_DUMMY_OID, new QName(RESOURCE_DUMMY_NAMESPACE, "AccountObjectClass"), prismContext)); // When finally fixed is should be like this: // assertSearch(ShadowType.class, query, 2); - + try { - + modelService.searchObjects(ShadowType.class, query, null, task, result); - + AssertJUnit.fail("unexpected success"); - + } catch (SchemaException e) { // This is expected. The authorizations will mix on-resource and off-resource search. display("Expected exception", e); } result.computeStatus(); TestUtil.assertFailure(result); - - + + assertDeleteAllow(UserType.class, USER_ESTEVAN_OID); - + assertVisibleUsers(4); } - + @Test public void test250AutzJackSelfAccountsRead() throws Exception { final String TEST_NAME = "test250AutzJackSelfAccountsRead"; displayTestTitle(TEST_NAME); // GIVEN cleanupAutzTest(USER_JACK_OID); - + // precondition PrismObject elaineShadow = getObject(ShadowType.class, ACCOUNT_SHADOW_ELAINE_DUMMY_OID); assertNotNull(elaineShadow); display("Elaine's shadow", elaineShadow); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + assignRole(USER_JACK_OID, ROLE_SELF_ACCOUNTS_READ_OID); assignAccount(USER_JACK_OID, RESOURCE_DUMMY_OID, null); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertGetAllow(UserType.class, USER_JACK_OID); assertGetDeny(UserType.class, USER_GUYBRUSH_OID); assertAddDeny(); - + assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Captain")); assertModifyDeny(UserType.class, USER_GUYBRUSH_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Pirate")); - + assertDeleteDeny(); assertDeleteDeny(UserType.class, USER_JACK_OID); - + PrismObject user = getUser(USER_JACK_OID); String accountOid = getSingleLinkOid(user); assertGetAllow(ShadowType.class, accountOid); PrismObject shadow = getObject(ShadowType.class, accountOid); display("Jack's shadow", shadow); - + // Not linked to jack assertGetDeny(ShadowType.class, ACCOUNT_SHADOW_ELAINE_DUMMY_OID); @@ -1322,29 +1322,29 @@ public void test250AutzJackSelfAccountsRead() throws Exception { // .build(); // assertSearch(ShadowType.class, query, null, 1); // assertSearch(ShadowType.class, query, SelectorOptions.createCollection(GetOperationOptions.createRaw()), 1); - + // Not linked to jack assertAddDeny(ACCOUNT_JACK_DUMMY_RED_FILE); // Not even jack's account assertAddDeny(ACCOUNT_GUYBRUSH_DUMMY_FILE); - + // Linked to jack - assertDeny("add jack's account to jack", + assertDeny("add jack's account to jack", (task, result) -> modifyUserAddAccount(USER_JACK_OID, ACCOUNT_JACK_DUMMY_RED_FILE, task, result)); - + // Linked to other user - assertDeny("add jack's account to gyubrush", + assertDeny("add jack's account to gyubrush", (task, result) -> modifyUserAddAccount(USER_GUYBRUSH_OID, ACCOUNT_JACK_DUMMY_RED_FILE, task, result)); - + assertDeleteDeny(ShadowType.class, accountOid); assertDeleteDeny(ShadowType.class, ACCOUNT_SHADOW_ELAINE_DUMMY_OID); - + PrismObjectDefinition userEditSchema = getEditObjectDefinition(user); // TODO: assert items - + PrismObjectDefinition shadowEditSchema = getEditObjectDefinition(shadow); // TODO: assert items - + assertGlobalStateUntouched(); } @@ -1353,27 +1353,27 @@ public void test255AutzJackSelfAccountsReadWrite() throws Exception { final String TEST_NAME = "test255AutzJackSelfAccountsReadWrite"; displayTestTitle(TEST_NAME); // GIVEN - cleanupAutzTest(USER_JACK_OID); + cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_SELF_ACCOUNTS_READ_WRITE_OID); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertGetAllow(UserType.class, USER_JACK_OID); assertGetDeny(UserType.class, USER_GUYBRUSH_OID); assertAddDeny(); - + assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Captain")); assertModifyDeny(UserType.class, USER_GUYBRUSH_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Pirate")); - + assertDeleteDeny(); assertDeleteDeny(UserType.class, USER_JACK_OID); - + PrismObject user = getUser(USER_JACK_OID); String accountOid = getSingleLinkOid(user); assertGetAllow(ShadowType.class, accountOid); @@ -1383,31 +1383,31 @@ public void test255AutzJackSelfAccountsReadWrite() throws Exception { display("Refined objectclass def", rOcDef); assertAttributeFlags(rOcDef, SchemaConstants.ICFS_UID, true, false, false); assertAttributeFlags(rOcDef, SchemaConstants.ICFS_NAME, true, true, true); - + // Not linked to jack assertGetDeny(ShadowType.class, ACCOUNT_SHADOW_ELAINE_DUMMY_OID); - + // Not linked to jack assertAddDeny(ACCOUNT_JACK_DUMMY_RED_FILE); // Not even jack's account assertAddDeny(ACCOUNT_GUYBRUSH_DUMMY_FILE); - + // Linked to jack - assertAllow("add jack's account to jack", + assertAllow("add jack's account to jack", (task, result) -> modifyUserAddAccount(USER_JACK_OID, ACCOUNT_JACK_DUMMY_RED_FILE, task, result)); user = getUser(USER_JACK_OID); display("Jack after red account link", user); String accountRedOid = getLinkRefOid(user, RESOURCE_DUMMY_RED_OID); assertNotNull("Strange, red account not linked to jack", accountRedOid); - + // Linked to other user - assertDeny("add gyubrush's account", + assertDeny("add gyubrush's account", (task, result) -> modifyUserAddAccount(USER_LARGO_OID, ACCOUNT_HERMAN_DUMMY_FILE, task, result)); - + assertDeleteAllow(ShadowType.class, accountRedOid); assertDeleteDeny(ShadowType.class, ACCOUNT_SHADOW_ELAINE_DUMMY_OID); - + assertGlobalStateUntouched(); } @@ -1457,7 +1457,7 @@ public void test256AutzJackSelfAccountsPartialControl() throws Exception { assertAddDeny(ACCOUNT_JACK_DUMMY_RED_FILE); // Not even jack's account assertAddDeny(ACCOUNT_GUYBRUSH_DUMMY_FILE); - + ProtectedStringType passwordPs = new ProtectedStringType(); passwordPs.setClearValue("nbusr123"); assertModifyDeny(UserType.class, USER_JACK_OID, PASSWORD_PATH, passwordPs); @@ -1467,7 +1467,7 @@ public void test256AutzJackSelfAccountsPartialControl() throws Exception { OperationResult result = task.getResult(); PrismObjectDefinition rDef = modelInteractionService.getEditObjectDefinition(user, AuthorizationPhaseType.REQUEST, task, result); assertItemFlags(rDef, PASSWORD_PATH, true, false, false); - + // // Linked to jack // assertAllow("add jack's account to jack", new Attempt() { // @Override @@ -1490,10 +1490,10 @@ public void test256AutzJackSelfAccountsPartialControl() throws Exception { // // assertDeleteAllow(ShadowType.class, accountRedOid); // assertDeleteDeny(ShadowType.class, ACCOUNT_SHADOW_ELAINE_DUMMY_OID); - + assertGlobalStateUntouched(); } - + @Test public void test258AutzJackSelfAccountsPartialControlPassword() throws Exception { final String TEST_NAME = "test258AutzJackSelfAccountsPartialControlPassword"; @@ -1540,7 +1540,7 @@ public void test258AutzJackSelfAccountsPartialControlPassword() throws Exception assertAddDeny(ACCOUNT_JACK_DUMMY_RED_FILE); // Not even jack's account assertAddDeny(ACCOUNT_GUYBRUSH_DUMMY_FILE); - + ProtectedStringType passwordPs = new ProtectedStringType(); passwordPs.setClearValue("nbusr123"); assertModifyAllow(UserType.class, USER_JACK_OID, PASSWORD_PATH, passwordPs); @@ -1550,7 +1550,7 @@ public void test258AutzJackSelfAccountsPartialControlPassword() throws Exception OperationResult result = task.getResult(); PrismObjectDefinition rDef = modelInteractionService.getEditObjectDefinition(user, AuthorizationPhaseType.REQUEST, task, result); assertItemFlags(rDef, PASSWORD_PATH, true, false, false); - + assertGlobalStateUntouched(); } @@ -1562,15 +1562,15 @@ public void test260AutzJackObjectFilterLocationShadowRole() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_FILTER_OBJECT_USER_LOCATION_SHADOWS_OID); login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertGetAllow(UserType.class, USER_JACK_OID); assertGetAllow(UserType.class, USER_JACK_OID, SelectorOptions.createCollection(GetOperationOptions.createRaw())); assertGetDeny(UserType.class, USER_GUYBRUSH_OID); assertGetDeny(UserType.class, USER_GUYBRUSH_OID, SelectorOptions.createCollection(GetOperationOptions.createRaw())); - + assertSearch(UserType.class, null, 2); assertSearch(ObjectType.class, null, 8); assertSearch(OrgType.class, null, 6); @@ -1582,15 +1582,15 @@ public void test260AutzJackObjectFilterLocationShadowRole() throws Exception { assertSearch(ObjectType.class, createNameQuery(USER_GUYBRUSH_USERNAME), 0); assertAddDeny(); - + assertModifyAllow(UserType.class, USER_JACK_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Captain")); assertModifyDeny(UserType.class, USER_GUYBRUSH_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Pirate")); assertModifyAllow(UserType.class, USER_BARBOSSA_OID, UserType.F_HONORIFIC_PREFIX, PrismTestUtil.createPolyString("Mutinier")); - + assertDeleteDeny(); - + // Linked to jack - assertAllow("add jack's account to jack", + assertAllow("add jack's account to jack", (task, result) -> { modifyUserAddAccount(USER_JACK_OID, ACCOUNT_JACK_DUMMY_RED_FILE, task, result); }); @@ -1599,7 +1599,7 @@ public void test260AutzJackObjectFilterLocationShadowRole() throws Exception { String accountRedOid = getLinkRefOid(user, RESOURCE_DUMMY_RED_OID); assertNotNull("Strange, red account not linked to jack", accountRedOid); assertGetAllow(ShadowType.class, accountRedOid); - + assertGlobalStateUntouched(); } @@ -1613,17 +1613,17 @@ public void test261AutzAngelicaObjectFilterLocationCreateUserShadowRole() throws final String TEST_NAME = "test261AutzJackObjectFilterLocationCreateUserShadowRole"; displayTestTitle(TEST_NAME); // GIVEN - + cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_FILTER_OBJECT_USER_TYPE_SHADOWS_OID); login(USER_JACK_USERNAME); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); // WHEN displayWhen(TEST_NAME); - assertAllow("add user angelica", + assertAllow("add user angelica", (task, result) -> addObject(USER_ANGELICA_FILE, task, result)); // THEN @@ -1636,22 +1636,22 @@ public void test261AutzAngelicaObjectFilterLocationCreateUserShadowRole() throws assertUser(angelica, null, USER_ANGELICA_NAME, "angelika", "angelika", "angelika"); assertAssignedRole(angelica, ROLE_BASIC_OID); assertAccount(angelica, RESOURCE_DUMMY_OID); - + assertGlobalStateUntouched(); } - + @Test public void test270AutzJackAssignApplicationRoles() throws Exception { final String TEST_NAME = "test270AutzJackAssignApplicationRoles"; displayTestTitle(TEST_NAME); // GIVEN - cleanupAutzTest(USER_JACK_OID); + cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_APPLICATION_ROLES_OID); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); @@ -1663,32 +1663,32 @@ public void test270AutzJackAssignApplicationRoles() throws Exception { PrismObject user = getUser(USER_JACK_OID); assertAssignments(user, 2); assertAssignedRole(user, ROLE_ASSIGN_APPLICATION_ROLES_OID); - - assertAllow("assign application role to jack", + + assertAllow("assign application role to jack", (task, result) -> assignRole(USER_JACK_OID, ROLE_APPLICATION_1_OID, task, result) ); - + user = getUser(USER_JACK_OID); assertAssignments(user, 3); assertAssignedRole(user, ROLE_APPLICATION_1_OID); - assertDeny("assign business role to jack", + assertDeny("assign business role to jack", (task, result) -> assignRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, task, result)); - assertAllow("unassign application role from jack", + assertAllow("unassign application role from jack", (task, result) -> unassignRole(USER_JACK_OID, ROLE_APPLICATION_1_OID, task, result) ); user = getUser(USER_JACK_OID); assertAssignments(user, 2); - + RoleSelectionSpecification spec = getAssignableRoleSpecification(getUser(USER_JACK_OID)); assertRoleTypes(spec, "application", "nonexistent"); assertFilter(spec.getFilter(), TypeFilter.class); - - assertAllowRequestItems(USER_JACK_OID, ROLE_APPLICATION_1_OID, null, + + assertAllowRequestItems(USER_JACK_OID, ROLE_APPLICATION_1_OID, null, AssignmentType.F_TARGET_REF, ActivationType.F_VALID_FROM, ActivationType.F_VALID_TO); - + assertGlobalStateUntouched(); } @@ -1697,13 +1697,13 @@ public void test272AutzJackAssignAnyRoles() throws Exception { final String TEST_NAME = "test272AutzJackAssignAnyRoles"; displayTestTitle(TEST_NAME); // GIVEN - cleanupAutzTest(USER_JACK_OID); + cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_ANY_ROLES_OID); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); @@ -1715,16 +1715,16 @@ public void test272AutzJackAssignAnyRoles() throws Exception { PrismObject user = getUser(USER_JACK_OID); assertAssignments(user, 2); assertAssignedRole(user, ROLE_ASSIGN_ANY_ROLES_OID); - - assertAllow("assign application role to jack", + + assertAllow("assign application role to jack", (task, result) -> assignRole(USER_JACK_OID, ROLE_APPLICATION_1_OID, task, result) ); - + user = getUser(USER_JACK_OID); assertAssignments(user, 3); assertAssignedRole(user, ROLE_APPLICATION_1_OID); - assertAllow("assign business role to jack", + assertAllow("assign business role to jack", (task, result) -> assignRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, task, result)); assertAllow("unassign application role from jack", @@ -1733,16 +1733,16 @@ public void test272AutzJackAssignAnyRoles() throws Exception { user = getUser(USER_JACK_OID); assertAssignments(user, 3); - + RoleSelectionSpecification spec = getAssignableRoleSpecification(getUser(USER_JACK_OID)); assertRoleTypes(spec); assertFilter(spec.getFilter(), TypeFilter.class); - + assertAllowRequestItems(USER_JACK_OID, ROLE_APPLICATION_1_OID, AuthorizationDecisionType.ALLOW); - + assertGlobalStateUntouched(); } - + /** * Check that the #assign authorization does not allow assignment that contains * policyException or policyRule. @@ -1752,13 +1752,13 @@ public void test273AutzJackRedyAssignmentExceptionRules() throws Exception { final String TEST_NAME = "test273AutzJackRedyAssignmentExceptionRules"; displayTestTitle(TEST_NAME); // GIVEN - cleanupAutzTest(USER_JACK_OID); + cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_ANY_ROLES_OID); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); @@ -1770,8 +1770,8 @@ public void test273AutzJackRedyAssignmentExceptionRules() throws Exception { PrismObject user = getUser(USER_JACK_OID); assertAssignments(user, 2); assertAssignedRole(user, ROLE_ASSIGN_ANY_ROLES_OID); - - assertDeny("assign application role to jack", + + assertDeny("assign application role to jack", (task, result) -> assignRole(USER_JACK_OID, ROLE_APPLICATION_1_OID, null, assignment -> { PolicyExceptionType policyException = new PolicyExceptionType(); @@ -1780,11 +1780,11 @@ public void test273AutzJackRedyAssignmentExceptionRules() throws Exception { }, task, result) ); - + user = getUser(USER_JACK_OID); assertAssignments(user, 2); - assertDeny("assign application role to jack", + assertDeny("assign application role to jack", (task, result) -> assignRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, null, assignment -> { PolicyRuleType policyRule = new PolicyRuleType(); @@ -1797,7 +1797,7 @@ public void test273AutzJackRedyAssignmentExceptionRules() throws Exception { user = getUser(USER_JACK_OID); assertAssignments(user, 2); - + assertGlobalStateUntouched(); } @@ -1806,13 +1806,13 @@ public void test274AutzJackAssignNonApplicationRoles() throws Exception { final String TEST_NAME = "test274AutzJackAssignNonApplicationRoles"; displayTestTitle(TEST_NAME); // GIVEN - cleanupAutzTest(USER_JACK_OID); + cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_NON_APPLICATION_ROLES_OID); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); @@ -1824,27 +1824,27 @@ public void test274AutzJackAssignNonApplicationRoles() throws Exception { PrismObject user = getUser(USER_JACK_OID); assertAssignments(user, 2); assertAssignedRole(user, ROLE_ASSIGN_NON_APPLICATION_ROLES_OID); - - assertAllow("assign business role to jack", + + assertAllow("assign business role to jack", (task, result) -> assignRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, task, result)); - + user = getUser(USER_JACK_OID); assertAssignments(user, 3); assertAssignedRole(user, ROLE_BUSINESS_1_OID); - assertDeny("assign application role to jack", + assertDeny("assign application role to jack", (task, result) -> assignRole(USER_JACK_OID, ROLE_APPLICATION_1_OID, task, result)); - assertAllow("unassign business role from jack", + assertAllow("unassign business role from jack", (task, result) -> unassignRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, task, result)); user = getUser(USER_JACK_OID); assertAssignments(user, 2); - + RoleSelectionSpecification spec = getAssignableRoleSpecification(getUser(USER_JACK_OID)); assertRoleTypes(spec); assertFilter(spec.getFilter(), TypeFilter.class); - + assertGlobalStateUntouched(); } @@ -1853,13 +1853,13 @@ public void test275aAutzJackAssignRequestableRoles() throws Exception { final String TEST_NAME = "test275aAutzJackAssignRequestableRoles"; displayTestTitle(TEST_NAME); // GIVEN - cleanupAutzTest(USER_JACK_OID); + cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_REQUESTABLE_ROLES_OID); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); @@ -1871,27 +1871,27 @@ public void test275aAutzJackAssignRequestableRoles() throws Exception { PrismObject user = getUser(USER_JACK_OID); assertAssignments(user, 2); assertAssignedRole(user, ROLE_ASSIGN_REQUESTABLE_ROLES_OID); - - assertAllow("assign business role to jack", + + assertAllow("assign business role to jack", (task, result) -> assignRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, task, result)); - + user = getUser(USER_JACK_OID); assertAssignments(user, 3); assertAssignedRole(user, ROLE_BUSINESS_1_OID); - assertDeny("assign application role to jack", + assertDeny("assign application role to jack", (task, result) -> assignRole(USER_JACK_OID, ROLE_BUSINESS_2_OID, task, result)); - assertAllow("unassign business role from jack", + assertAllow("unassign business role from jack", (task, result) -> unassignRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, task, result)); user = getUser(USER_JACK_OID); assertAssignments(user, 2); - + RoleSelectionSpecification spec = getAssignableRoleSpecification(getUser(USER_JACK_OID)); assertRoleTypes(spec); assertFilter(spec.getFilter(), TypeFilter.class); - + assertGlobalStateUntouched(); } @@ -1916,7 +1916,7 @@ public void test275bAutzJackAssignRequestableOrgs() throws Exception { assertAssignments(user, 2); assertAssignedRole(user, ROLE_END_USER_REQUESTABLE_ABSTACTROLES_OID); - assertAllow("assign requestable org to jack", + assertAllow("assign requestable org to jack", (task, result) -> assignOrg(USER_JACK_OID, ORG_REQUESTABLE_OID, task, result)); user = getUser(USER_JACK_OID); @@ -1930,7 +1930,7 @@ public void test275bAutzJackAssignRequestableOrgs() throws Exception { query.addFilter(spec.getFilter()); assertSearch(AbstractRoleType.class, query, 6); // set to 6 with requestable org - assertAllow("unassign business role from jack", + assertAllow("unassign business role from jack", (task, result) -> unassignOrg(USER_JACK_OID, ORG_REQUESTABLE_OID, task, result)); user = getUser(USER_JACK_OID); @@ -1947,13 +1947,13 @@ public void test276AutzJackAssignRequestableRolesWithOrgRef() throws Exception { final String TEST_NAME = "test276AutzJackAssignRequestableRolesWithOrgRef"; displayTestTitle(TEST_NAME); // GIVEN - cleanupAutzTest(USER_JACK_OID); + cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_REQUESTABLE_ROLES_OID); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); @@ -1965,31 +1965,31 @@ public void test276AutzJackAssignRequestableRolesWithOrgRef() throws Exception { PrismObject user = getUser(USER_JACK_OID); assertAssignments(user, 2); assertAssignedRole(user, ROLE_ASSIGN_REQUESTABLE_ROLES_OID); - - assertAllow("assign business role to jack", + + assertAllow("assign business role to jack", (task, result) -> assignParametricRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, ORG_MINISTRY_OF_RUM_OID, null, task, result)); - + user = getUser(USER_JACK_OID); assertAssignments(user, 3); assertAssignedRole(user, ROLE_BUSINESS_1_OID); - assertDeny("assign application role to jack", + assertDeny("assign application role to jack", (task, result) -> assignRole(USER_JACK_OID, ROLE_BUSINESS_2_OID, task, result)); - assertAllow("unassign business role from jack", + assertAllow("unassign business role from jack", (task, result) -> unassignParametricRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, ORG_MINISTRY_OF_RUM_OID, null, task, result)); user = getUser(USER_JACK_OID); display("user after (expected 2 assignments)", user); assertAssignments(user, 2); - + RoleSelectionSpecification spec = getAssignableRoleSpecification(getUser(USER_JACK_OID)); assertRoleTypes(spec); assertFilter(spec.getFilter(), TypeFilter.class); - + assertGlobalStateUntouched(); } - + /** * Assign a role with parameter while the user already has the same role without a parameter. * It seems that in this case the deltas are processed in a slightly different way. @@ -2000,13 +2000,13 @@ public void test277AutzJackAssignRequestableRolesWithOrgRefSecondTime() throws E final String TEST_NAME = "test277AutzJackAssignRequestableRolesWithOrgRefSecondTime"; displayTestTitle(TEST_NAME); // GIVEN - cleanupAutzTest(USER_JACK_OID); + cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_REQUESTABLE_ROLES_OID); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); @@ -2018,62 +2018,62 @@ public void test277AutzJackAssignRequestableRolesWithOrgRefSecondTime() throws E PrismObject user = getUser(USER_JACK_OID); assertAssignments(user, 2); assertAssignedRole(user, ROLE_ASSIGN_REQUESTABLE_ROLES_OID); - - assertAllow("assign business role to jack (no param)", + + assertAllow("assign business role to jack (no param)", (task, result) -> assignParametricRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, null, null, task, result)); - + user = getUser(USER_JACK_OID); assertAssignments(user, 3); assertAssignedRole(user, ROLE_BUSINESS_1_OID); - - assertAllow("assign business role to jack (org MoR)", + + assertAllow("assign business role to jack (org MoR)", (task, result) -> assignParametricRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, ORG_MINISTRY_OF_RUM_OID, null, task, result)); - + user = getUser(USER_JACK_OID); assertAssignments(user, 4); display("user after (expected 4 assignments)", user); assertAssignedRole(user, ROLE_BUSINESS_1_OID); - assertAllow("assign business role to jack (org Scumm)", + assertAllow("assign business role to jack (org Scumm)", (task, result) -> assignParametricRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, ORG_SCUMM_BAR_OID, null, task, result)); - + user = getUser(USER_JACK_OID); assertAssignments(user, 5); display("user after (expected 5 assignments)", user); assertAssignedRole(user, ROLE_BUSINESS_1_OID); - assertAllow("unassign business role from jack (org Scumm)", + assertAllow("unassign business role from jack (org Scumm)", (task, result) -> unassignParametricRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, ORG_SCUMM_BAR_OID, null, task, result)); - + user = getUser(USER_JACK_OID); assertAssignments(user, 4); display("user after (expected 4 assignments)", user); assertAssignedRole(user, ROLE_BUSINESS_1_OID); - - assertDeny("assign application role to jack", + + assertDeny("assign application role to jack", (task, result) -> assignRole(USER_JACK_OID, ROLE_BUSINESS_2_OID, task, result)); - assertAllow("unassign business role from jack (no param)", + assertAllow("unassign business role from jack (no param)", (task, result) -> unassignParametricRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, null, null, task, result)); - + user = getUser(USER_JACK_OID); display("user after (expected 3 assignments)", user); assertAssignments(user, 3); - - assertAllow("unassign business role from jack (org MoR)", + + assertAllow("unassign business role from jack (org MoR)", (task, result) -> unassignParametricRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, ORG_MINISTRY_OF_RUM_OID, null, task, result)); user = getUser(USER_JACK_OID); display("user after (expected 2 assignments)", user); assertAssignments(user, 2); - + RoleSelectionSpecification spec = getAssignableRoleSpecification(getUser(USER_JACK_OID)); assertRoleTypes(spec); assertFilter(spec.getFilter(), TypeFilter.class); - + assertGlobalStateUntouched(); } - + /** * MID-3136 */ @@ -2082,13 +2082,13 @@ public void test278AutzJackAssignRequestableRolesWithOrgRefTweakedDelta() throws final String TEST_NAME = "test278AutzJackAssignRequestableRolesWithOrgRefTweakedDelta"; displayTestTitle(TEST_NAME); // GIVEN - cleanupAutzTest(USER_JACK_OID); + cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_REQUESTABLE_ROLES_OID); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); @@ -2100,15 +2100,15 @@ public void test278AutzJackAssignRequestableRolesWithOrgRefTweakedDelta() throws PrismObject user = getUser(USER_JACK_OID); assertAssignments(user, 2); assertAssignedRole(user, ROLE_ASSIGN_REQUESTABLE_ROLES_OID); - - assertAllow("assign business role to jack", + + assertAllow("assign business role to jack", (task, result) -> assignParametricRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, ORG_MINISTRY_OF_RUM_OID, null, task, result)); - + user = getUser(USER_JACK_OID); assertAssignments(user, 3); assertAssignedRole(user, ROLE_BUSINESS_1_OID); - assertDeny("assign application role to jack", + assertDeny("assign application role to jack", (task, result) -> { Collection> modifications = new ArrayList<>(); ContainerDelta assignmentDelta1 = ContainerDelta.createDelta(UserType.F_ASSIGNMENT, getUserDefinition()); @@ -2127,20 +2127,20 @@ public void test278AutzJackAssignRequestableRolesWithOrgRefTweakedDelta() throws modelService.executeChanges(deltas, null, task, result); }); - assertAllow("unassign business role from jack", + assertAllow("unassign business role from jack", (task, result) -> unassignParametricRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, ORG_MINISTRY_OF_RUM_OID, null, task, result)); user = getUser(USER_JACK_OID); display("user after (expected 2 assignments)", user); assertAssignments(user, 2); - + RoleSelectionSpecification spec = getAssignableRoleSpecification(getUser(USER_JACK_OID)); assertRoleTypes(spec); assertFilter(spec.getFilter(), TypeFilter.class); - + assertGlobalStateUntouched(); } - + /** * MID-3136 */ @@ -2149,13 +2149,13 @@ public void test279AutzJackAssignRequestableRolesWithTenantRef() throws Exceptio final String TEST_NAME = "test279AutzJackAssignRequestableRolesWithTenantRef"; displayTestTitle(TEST_NAME); // GIVEN - cleanupAutzTest(USER_JACK_OID); + cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_REQUESTABLE_ROLES_OID); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); @@ -2167,11 +2167,11 @@ public void test279AutzJackAssignRequestableRolesWithTenantRef() throws Exceptio PrismObject user = getUser(USER_JACK_OID); assertAssignments(user, 2); assertAssignedRole(user, ROLE_ASSIGN_REQUESTABLE_ROLES_OID); - - assertAllow("assign business role to jack", + + assertAllow("assign business role to jack", (task, result) -> assignParametricRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, null, ORG_GOVERNOR_OFFICE_OID, task, result)); - + user = getUser(USER_JACK_OID); assertAssignments(user, 3); assertAssignedRole(user, ROLE_BUSINESS_1_OID); @@ -2190,28 +2190,28 @@ public void run(Task task, OperationResult result) throws Exception { user = getUser(USER_JACK_OID); display("user after (expected 2 assignments)", user); assertAssignments(user, 2); - + RoleSelectionSpecification spec = getAssignableRoleSpecification(getUser(USER_JACK_OID)); assertRoleTypes(spec); assertFilter(spec.getFilter(), TypeFilter.class); - + assertGlobalStateUntouched(); } - + @Test public void test280AutzJackEndUser() throws Exception { final String TEST_NAME = "test280AutzJackEndUser"; displayTestTitle(TEST_NAME); // GIVEN - cleanupAutzTest(USER_JACK_OID); - + cleanupAutzTest(USER_JACK_OID); + assignRole(USER_JACK_OID, ROLE_END_USER_OID); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); @@ -2219,83 +2219,83 @@ public void test280AutzJackEndUser() throws Exception { assertGetAllow(UserType.class, USER_JACK_OID, SelectorOptions.createCollection(GetOperationOptions.createRaw())); assertGetDeny(UserType.class, USER_GUYBRUSH_OID); assertGetDeny(UserType.class, USER_GUYBRUSH_OID, SelectorOptions.createCollection(GetOperationOptions.createRaw())); - + assertSearch(UserType.class, null, 1); assertSearch(UserType.class, createNameQuery(USER_JACK_USERNAME), 1); assertSearch(UserType.class, createNameQuery(USER_JACK_USERNAME), SelectorOptions.createCollection(GetOperationOptions.createRaw()), 1); assertSearch(UserType.class, createNameQuery(USER_GUYBRUSH_USERNAME), 0); assertSearch(UserType.class, createNameQuery(USER_GUYBRUSH_USERNAME), SelectorOptions.createCollection(GetOperationOptions.createRaw()), 0); - + assertAddDeny(); assertModifyDeny(); assertDeleteDeny(); PrismObject user = getUser(USER_JACK_OID); assertAssignments(user, 2); - + user = getUser(USER_JACK_OID); - + // MID-3136 - assertAllow("assign business role to jack", + assertAllow("assign business role to jack", (task, result) -> assignParametricRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, null, ORG_GOVERNOR_OFFICE_OID, task, result)); - + user = getUser(USER_JACK_OID); assertAssignments(user, 3); assertAssignedRole(user, ROLE_BUSINESS_1_OID); - - assertDeny("assign application role to jack", + + assertDeny("assign application role to jack", (task, result) -> assignRole(USER_JACK_OID, ROLE_BUSINESS_2_OID, task, result)); // End-user role has authorization to assign, but not to unassign - assertDeny("unassign business role from jack", + assertDeny("unassign business role from jack", (task, result) -> unassignParametricRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, null, ORG_GOVERNOR_OFFICE_OID, task, result)); user = getUser(USER_JACK_OID); display("user after (expected 3 assignments)", user); assertAssignments(user, 3); - + assertGlobalStateUntouched(); - + assertCredentialsPolicy(user); } - + @Test public void test281AutzJackEndUserSecondTime() throws Exception { final String TEST_NAME = "test281AutzJackEndUserSecondTime"; displayTestTitle(TEST_NAME); // GIVEN - cleanupAutzTest(USER_JACK_OID); - + cleanupAutzTest(USER_JACK_OID); + assignRole(USER_JACK_OID, ROLE_END_USER_OID); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); PrismObject user = getUser(USER_JACK_OID); assertAssignments(user, 2); - + user = getUser(USER_JACK_OID); - + // MID-3136 - assertAllow("assign business role to jack (no param)", + assertAllow("assign business role to jack (no param)", (task, result) -> assignParametricRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, null, null, task, result)); - + user = getUser(USER_JACK_OID); assertAssignments(user, 3); assertAssignedRole(user, ROLE_BUSINESS_1_OID); - + // MID-3136 - assertAllow("assign business role to jack (org governor)", + assertAllow("assign business role to jack (org governor)", (task, result) -> assignParametricRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, null, ORG_GOVERNOR_OFFICE_OID, task, result)); - + user = getUser(USER_JACK_OID); assertAssignments(user, 4); assertAssignedRole(user, ROLE_BUSINESS_1_OID); - + assertDeny("assign application role to jack", new Attempt() { @Override public void run(Task task, OperationResult result) throws Exception { @@ -2304,18 +2304,18 @@ public void run(Task task, OperationResult result) throws Exception { }); // End-user role has authorization to assign, but not to unassign - assertDeny("unassign business role from jack", + assertDeny("unassign business role from jack", (task, result) -> unassignParametricRole(USER_JACK_OID, ROLE_BUSINESS_1_OID, null, ORG_GOVERNOR_OFFICE_OID, task, result)); user = getUser(USER_JACK_OID); display("user after (expected 4 assignments)", user); assertAssignments(user, 4); - + assertGlobalStateUntouched(); - + assertCredentialsPolicy(user); } - + private void assertCredentialsPolicy(PrismObject user) throws ObjectNotFoundException, SchemaException { OperationResult result = new OperationResult("assertCredentialsPolicy"); CredentialsPolicyType credentialsPolicy = modelInteractionService.getCredentialsPolicy(user, null, result); @@ -2331,15 +2331,15 @@ public void test282AutzJackEndUserAndModify() throws Exception { final String TEST_NAME = "test282AutzJackEndUserAndModify"; displayTestTitle(TEST_NAME); // GIVEN - cleanupAutzTest(USER_JACK_OID); - + cleanupAutzTest(USER_JACK_OID); + assignRole(USER_JACK_OID, ROLE_END_USER_OID); assignRole(USER_JACK_OID, ROLE_MODIFY_USER_OID); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); @@ -2350,13 +2350,13 @@ public void test282AutzJackEndUserAndModify() throws Exception { PrismObject user = getUser(USER_JACK_OID); assertAssignments(user, 3); - - assertAllow("modify jack's familyName", + + assertAllow("modify jack's familyName", (task, result) -> modifyObjectReplaceProperty(UserType.class, USER_JACK_OID, new ItemPath(UserType.F_FAMILY_NAME), task, result, PrismTestUtil.createPolyString("changed"))); - + user = getUser(USER_JACK_OID); assertUser(user, USER_JACK_OID, USER_JACK_USERNAME, USER_JACK_FULL_NAME, "Jack", "changed"); - + assertGlobalStateUntouched(); } @@ -2366,16 +2366,16 @@ public void test283AutzJackModifyAndEndUser() throws Exception { final String TEST_NAME = "test283AutzJackModifyAndEndUser"; displayTestTitle(TEST_NAME); // GIVEN - cleanupAutzTest(USER_JACK_OID); - + cleanupAutzTest(USER_JACK_OID); + assignRole(USER_JACK_OID, ROLE_MODIFY_USER_OID); assignRole(USER_JACK_OID, ROLE_END_USER_OID); - - + + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); @@ -2386,28 +2386,28 @@ public void test283AutzJackModifyAndEndUser() throws Exception { PrismObject user = getUser(USER_JACK_OID); assertAssignments(user, 3); - + assertAllow("modify jack's familyName", (task, result) -> modifyObjectReplaceProperty(UserType.class, USER_JACK_OID, new ItemPath(UserType.F_FAMILY_NAME), task, result, PrismTestUtil.createPolyString("changed"))); - + user = getUser(USER_JACK_OID); assertUser(user, USER_JACK_OID, USER_JACK_USERNAME, USER_JACK_FULL_NAME, "Jack", "changed"); assertGlobalStateUntouched(); } - + @Test public void test290AutzJackRoleOwnerAssign() throws Exception { final String TEST_NAME = "test290AutzJackRoleOwnerAssign"; displayTestTitle(TEST_NAME); // GIVEN - cleanupAutzTest(USER_JACK_OID); + cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ROLE_OWNER_ASSIGN_OID); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); @@ -2419,10 +2419,10 @@ public void test290AutzJackRoleOwnerAssign() throws Exception { PrismObject user = getUser(USER_JACK_OID); assertAssignments(user, 2); assertAssignedRole(user, ROLE_ROLE_OWNER_ASSIGN_OID); - - assertAllow("assign application role 1 to jack", + + assertAllow("assign application role 1 to jack", (task,result) -> assignRole(USER_JACK_OID, ROLE_APPLICATION_1_OID, task, result)); - + user = getUser(USER_JACK_OID); assertAssignments(user, 3); assertAssignedRole(user, ROLE_APPLICATION_1_OID); @@ -2434,12 +2434,12 @@ public void run(Task task, OperationResult result) throws Exception { } }); - assertAllow("unassign application role 1 from jack", + assertAllow("unassign application role 1 from jack", (task,result) -> unassignRole(USER_JACK_OID, ROLE_APPLICATION_1_OID, task, result)); user = getUser(USER_JACK_OID); assertAssignments(user, 2); - + RoleSelectionSpecification spec = getAssignableRoleSpecification(getUser(USER_JACK_OID)); assertRoleTypes(spec); assertFilter(spec.getFilter(), TypeFilter.class); @@ -2448,32 +2448,32 @@ public void run(Task task, OperationResult result) throws Exception { assertFilter(subfilter, RefFilter.class); assertEquals(1, ((RefFilter)subfilter).getValues().size()); assertEquals("Wrong OID in ref filter", USER_JACK_OID, ((RefFilter)subfilter).getValues().get(0).getOid()); - + assertGlobalStateUntouched(); } - + @Test public void test292AutzJackRoleOwnerFullControl() throws Exception { final String TEST_NAME = "test292AutzJackRoleOwnerFullControl"; displayTestTitle(TEST_NAME); // GIVEN - cleanupAutzTest(USER_JACK_OID); + cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ROLE_OWNER_FULL_CONTROL_OID); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); assertGetAllow(UserType.class, USER_JACK_OID); assertGetDeny(UserType.class, USER_GUYBRUSH_OID); - + assertSearch(UserType.class, null, 1); assertSearch(UserType.class, createNameQuery(USER_JACK_USERNAME), 1); assertSearch(UserType.class, createNameQuery(USER_GUYBRUSH_USERNAME), 0); - + assertAddDeny(); assertModifyDeny(); assertDeleteDeny(); @@ -2481,18 +2481,18 @@ public void test292AutzJackRoleOwnerFullControl() throws Exception { assertSearch(RoleType.class, null, 2); // TODO - + // PrismObject user = getUser(USER_JACK_OID); // assertAssignments(user, 2); // assertAssignedRole(user, ROLE_ROLE_OWNER_FULL_CONTROL_OID); -// +// // assertAllow("assign application role 1 to jack", new Attempt() { // @Override // public void run(Task task, OperationResult result) throws Exception { // assignRole(USER_JACK_OID, ROLE_APPLICATION_1_OID, task, result); // } // }); -// +// // user = getUser(USER_JACK_OID); // assertAssignments(user, 3); // assertAssignedRole(user, ROLE_APPLICATION_1_OID); @@ -2513,7 +2513,7 @@ public void test292AutzJackRoleOwnerFullControl() throws Exception { // // user = getUser(USER_JACK_OID); // assertAssignments(user, 2); -// +// // RoleSelectionSpecification spec = getAssignableRoleSpecification(getUser(USER_JACK_OID)); // assertRoleTypes(spec); // assertFilter(spec.getFilter(), TypeFilter.class); @@ -2522,47 +2522,47 @@ public void test292AutzJackRoleOwnerFullControl() throws Exception { // assertFilter(subfilter, RefFilter.class); // assertEquals(1, ((RefFilter)subfilter).getValues().size()); // assertEquals("Wrong OID in ref filter", USER_JACK_OID, ((RefFilter)subfilter).getValues().get(0).getOid()); - + assertGlobalStateUntouched(); } - + @Test public void test295AutzJackAssignOrgRelation() throws Exception { final String TEST_NAME = "test295AutzJackAssignOrgRelation"; displayTestTitle(TEST_NAME); // GIVEN cleanupAutzTest(USER_JACK_OID); - + assignRole(USER_JACK_OID, ROLE_ASSIGN_ORGRELATION_OID); assignOrg(USER_JACK_OID, ORG_MINISTRY_OF_RUM_OID, null); - + login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + RoleSelectionSpecification specJack = getAssignableRoleSpecification(getUser(USER_JACK_OID)); display("Spec (jack)", specJack); assertRoleTypes(specJack); - + Task task = taskManager.createTaskInstance(); - SearchResultList> assignableRolesJack = + SearchResultList> assignableRolesJack = modelService.searchObjects(AbstractRoleType.class, ObjectQuery.createObjectQuery(specJack.getFilter()), null, task, task.getResult()); display("Assignable roles", assignableRolesJack); assertObjectOids("Wrong assignable roles (jack)", assignableRolesJack, ROLE_BUSINESS_3_OID); - + RoleSelectionSpecification specRum = getAssignableRoleSpecification(getUser(userRumRogersOid)); display("Spec (rum)", specRum); assertRoleTypes(specRum); - - SearchResultList> assignableRolesRum = + + SearchResultList> assignableRolesRum = modelService.searchObjects(AbstractRoleType.class, ObjectQuery.createObjectQuery(specRum.getFilter()), null, task, task.getResult()); display("Assignable roles", assignableRolesRum); assertObjectOids("Wrong assignable roles (rum)", assignableRolesRum, ROLE_BUSINESS_3_OID); - + assertGlobalStateUntouched(); } - + @Test public void test300AutzAnonymous() throws Exception { final String TEST_NAME = "test300AutzAnonymous"; @@ -2571,13 +2571,13 @@ public void test300AutzAnonymous() throws Exception { cleanupAutzTest(USER_JACK_OID); PrismObject userJack = getUser(USER_JACK_OID); loginAnonymous(); - - // WHEN + + // WHEN assertNoAccess(userJack); - + assertGlobalStateUntouched(); } - + @Test public void test310AutzJackNoRolePrivileged() throws Exception { final String TEST_NAME = "test310AutzJackNoRolePrivileged"; @@ -2586,29 +2586,29 @@ public void test310AutzJackNoRolePrivileged() throws Exception { cleanupAutzTest(USER_JACK_OID); PrismObject userJack = getUser(USER_JACK_OID); login(USER_JACK_USERNAME); - + // precondition assertNoAccess(userJack); - + // WHEN (security context elevated) securityEnforcer.runPrivileged(() -> { try { - + assertSuperuserAccess(NUMBER_OF_ALL_USERS + 1); - + } catch (Exception e) { new RuntimeException(e.getMessage(), e); } - + return null; }); - + // WHEN (security context back to normal) assertNoAccess(userJack); - + assertGlobalStateUntouched(); } - + @Test public void test312AutzAnonymousPrivileged() throws Exception { final String TEST_NAME = "test312AutzAnonymousPrivileged"; @@ -2617,29 +2617,29 @@ public void test312AutzAnonymousPrivileged() throws Exception { cleanupAutzTest(USER_JACK_OID); PrismObject userJack = getUser(USER_JACK_OID); loginAnonymous(); - + // precondition assertNoAccess(userJack); - + // WHEN (security context elevated) securityEnforcer.runPrivileged(() -> { try { - + assertSuperuserAccess(NUMBER_OF_ALL_USERS + 1); - + } catch (Exception e) { new RuntimeException(e.getMessage(), e); } - + return null; }); - + // WHEN (security context back to normal) assertNoAccess(userJack); - + assertGlobalStateUntouched(); } - + @Test public void test313AutzAnonymousPrivilegedRestore() throws Exception { final String TEST_NAME = "test313AutzAnonymousPrivilegedRestore"; @@ -2648,18 +2648,18 @@ public void test313AutzAnonymousPrivilegedRestore() throws Exception { cleanupAutzTest(USER_JACK_OID); PrismObject userJack = getUser(USER_JACK_OID); loginAnonymous(); - + // WHEN (security context elevated) securityEnforcer.runPrivileged(() -> { - + // do nothing. - + return null; }); - + // WHEN (security context back to normal) assertNoAccess(userJack); - + assertGlobalStateUntouched(); } @@ -2684,7 +2684,7 @@ public void test360AutzJackAuditorRole() throws Exception { assertAuditReadAllow(); } - + /** * MID-3826 */ @@ -2696,26 +2696,26 @@ public void test370AutzJackLimitedUserAdmin() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_LIMITED_USER_ADMIN_OID); login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertGetAllow(UserType.class, USER_JACK_OID); assertGetAllow(UserType.class, USER_GUYBRUSH_OID); - + assertSearch(UserType.class, null, NUMBER_OF_ALL_USERS + 1); assertSearch(ObjectType.class, null, NUMBER_OF_ALL_USERS + 1); assertSearch(OrgType.class, null, 0); assertAddAllow(USER_HERMAN_FILE); - + assertModifyDeny(); - + assertDeleteDeny(); - + assertGlobalStateUntouched(); } - + @Test public void test380AutzJackSelfTaskOwner() throws Exception { final String TEST_NAME = "test380AutzJackSelfTaskOwner"; @@ -2724,21 +2724,21 @@ public void test380AutzJackSelfTaskOwner() throws Exception { cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_SELF_TASK_OWNER_OID); login(USER_JACK_USERNAME); - + // WHEN displayWhen(TEST_NAME); - + assertGetDeny(UserType.class, USER_JACK_OID); assertGetDeny(UserType.class, USER_GUYBRUSH_OID); - + assertGetDeny(TaskType.class, TASK_USELESS_ADMINISTRATOR_OID); assertGetAllow(TaskType.class, TASK_USELESS_JACK_OID); - + assertSearch(UserType.class, null, 0); assertSearch(ObjectType.class, null, 0); assertSearch(OrgType.class, null, 0); assertSearch(TaskType.class, null, 1); - + assertTaskAddAllow(TASK_T1_OID, "t1", USER_JACK_OID, TASK_USELESS_HANDLER_URI); assertTaskAddDeny(TASK_T2_OID, "t2", USER_JACK_OID, "nonsense"); assertTaskAddDeny(TASK_T3_OID, "t3", USER_ADMINISTRATOR_OID, TASK_USELESS_HANDLER_URI); @@ -2746,28 +2746,28 @@ public void test380AutzJackSelfTaskOwner() throws Exception { assertTaskAddDeny(TASK_T5_OID, "t5", null, TASK_USELESS_HANDLER_URI); assertAddDeny(); - + assertModifyDeny(); - + assertDeleteDeny(); - + assertGlobalStateUntouched(); } private void assertTaskAddAllow(String oid, String name, String ownerOid, String handlerUri) throws Exception { - assertAllow("add task "+name, + assertAllow("add task "+name, (task, result) -> { addTask(oid, name, ownerOid, handlerUri, task, result); }); } - + private void assertTaskAddDeny(String oid, String name, String ownerOid, String handlerUri) throws Exception { - assertDeny("add task "+name, + assertDeny("add task "+name, (task, result) -> { addTask(oid, name, ownerOid, handlerUri, task, result); }); } - + private void addTask(String oid, String name, String ownerOid, String handlerUri, Task execTask, OperationResult result) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { PrismObject task = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(TaskType.class).instantiate(); task.setOid(oid); 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 8b7b2cfe150..1e507a150eb 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 @@ -42,7 +42,7 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestSecurityPrincipal extends AbstractSecurityTest { - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -56,7 +56,7 @@ public void test010GetUserAdministrator() throws Exception { // WHEN MidPointPrincipal principal = userProfileService.getPrincipal(USER_ADMINISTRATOR_USERNAME); - + // THEN display("Administrator principal", principal); assertEquals("Wrong number of authorizations", 1, principal.getAuthorities().size()); @@ -65,7 +65,7 @@ public void test010GetUserAdministrator() throws Exception { assertAuthorized(principal, AUTZ_LOOT_URL); assertAuthorized(principal, AUTZ_COMMAND_URL); } - + @Test public void test050GetUserJack() throws Exception { final String TEST_NAME = "test050GetUserJack"; @@ -74,7 +74,7 @@ public void test050GetUserJack() throws Exception { // WHEN MidPointPrincipal principal = userProfileService.getPrincipal(USER_JACK_USERNAME); - + // THEN assertNoAuthentication(); assertJack(principal); @@ -85,7 +85,7 @@ public void test050GetUserJack() throws Exception { assertNotAuthorized(principal, AUTZ_COMMAND_URL); assertNoAuthentication(); } - + @Test public void test051GetUserBarbossa() throws Exception { final String TEST_NAME = "test051GetUserBarbossa"; @@ -94,7 +94,7 @@ public void test051GetUserBarbossa() throws Exception { // WHEN MidPointPrincipal principal = userProfileService.getPrincipal(USER_BARBOSSA_USERNAME); - + // THEN display("Principal barbossa", principal); assertNotNull("No principal for username "+USER_BARBOSSA_USERNAME, principal); @@ -102,121 +102,121 @@ public void test051GetUserBarbossa() throws Exception { assertEquals("wrong oid", USER_BARBOSSA_OID, principal.getOid()); assertTrue("Unexpected authorizations", principal.getAuthorities().isEmpty()); display("User in principal barbossa", principal.getUser().asPrismObject()); - + principal.getUser().asPrismObject().checkConsistence(true, true); - + assertNotAuthorized(principal, AUTZ_LOOT_URL); assertNotAuthorized(principal, AUTZ_COMMAND_URL); } - + @Test public void test052GetUserGuybrush() throws Exception { final String TEST_NAME = "test052GetUserGuybrush"; - displayTestTitle(TEST_NAME); + displayTestTitle(TEST_NAME); resetAuthentication(); // WHEN MidPointPrincipal principal = userProfileService.getPrincipal(USER_GUYBRUSH_USERNAME); - + // THEN display("Principal guybrush", principal); assertEquals("wrong username", USER_GUYBRUSH_USERNAME, principal.getUsername()); assertEquals("wrong oid", USER_GUYBRUSH_OID, principal.getOid()); assertTrue("Unexpected authorizations", principal.getAuthorities().isEmpty()); display("User in principal guybrush", principal.getUser().asPrismObject()); - + principal.getUser().asPrismObject().checkConsistence(true, true); - + assertNotAuthorized(principal, AUTZ_LOOT_URL); assertNotAuthorized(principal, AUTZ_COMMAND_URL); } - + @Test public void test060GuybrushConditionalRoleFalse() throws Exception { final String TEST_NAME = "test060GuybrushConditionalRoleFalse"; displayTestTitle(TEST_NAME); login(USER_ADMINISTRATOR_USERNAME); - + assignRole(USER_GUYBRUSH_OID, ROLE_CONDITIONAL_OID); - + resetAuthentication(); // WHEN MidPointPrincipal principal = userProfileService.getPrincipal(USER_GUYBRUSH_USERNAME); - + // THEN display("Principal guybrush", principal); assertEquals("wrong username", USER_GUYBRUSH_USERNAME, principal.getUsername()); assertEquals("wrong oid", USER_GUYBRUSH_OID, principal.getOid()); assertTrue("Unexpected authorizations", principal.getAuthorities().isEmpty()); display("User in principal guybrush", principal.getUser().asPrismObject()); - + principal.getUser().asPrismObject().checkConsistence(true, true); - + assertNotAuthorized(principal, AUTZ_LOOT_URL); assertNotAuthorized(principal, AUTZ_COMMAND_URL); assertNotAuthorized(principal, AUTZ_SUPERSPECIAL_URL); assertNotAuthorized(principal, AUTZ_NONSENSE_URL); } - + @Test public void test061GuybrushConditionalRoleTrue() throws Exception { final String TEST_NAME = "test061GuybrushConditionalRoleTrue"; displayTestTitle(TEST_NAME); login(USER_ADMINISTRATOR_USERNAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_EMPLOYEE_TYPE, task, result, "special"); - + resetAuthentication(); // WHEN TestUtil.displayWhen(TEST_NAME); MidPointPrincipal principal = userProfileService.getPrincipal(USER_GUYBRUSH_USERNAME); - + // THEN TestUtil.displayThen(TEST_NAME); display("Principal guybrush", principal); assertEquals("wrong username", USER_GUYBRUSH_USERNAME, principal.getUsername()); assertEquals("wrong oid", USER_GUYBRUSH_OID, principal.getOid()); display("User in principal guybrush", principal.getUser().asPrismObject()); - + principal.getUser().asPrismObject().checkConsistence(true, true); - + assertAuthorized(principal, AUTZ_SUPERSPECIAL_URL); assertNotAuthorized(principal, AUTZ_LOOT_URL); assertNotAuthorized(principal, AUTZ_COMMAND_URL); assertNotAuthorized(principal, AUTZ_CAPSIZE_URL); assertNotAuthorized(principal, AUTZ_NONSENSE_URL); } - + @Test public void test062GuybrushConditionalRoleUnassign() throws Exception { final String TEST_NAME = "test062GuybrushConditionalRoleUnassign"; displayTestTitle(TEST_NAME); login(USER_ADMINISTRATOR_USERNAME); - + unassignRole(USER_GUYBRUSH_OID, ROLE_CONDITIONAL_OID); - + resetAuthentication(); // WHEN MidPointPrincipal principal = userProfileService.getPrincipal(USER_GUYBRUSH_USERNAME); - + // THEN display("Principal guybrush", principal); assertEquals("wrong username", USER_GUYBRUSH_USERNAME, principal.getUsername()); assertEquals("wrong oid", USER_GUYBRUSH_OID, principal.getOid()); assertTrue("Unexpected authorizations", principal.getAuthorities().isEmpty()); display("User in principal guybrush", principal.getUser().asPrismObject()); - + principal.getUser().asPrismObject().checkConsistence(true, true); - + assertNotAuthorized(principal, AUTZ_LOOT_URL); assertNotAuthorized(principal, AUTZ_COMMAND_URL); } - + @Test public void test100JackRolePirate() throws Exception { final String TEST_NAME = "test100JackRolePirate"; @@ -226,26 +226,26 @@ public void test100JackRolePirate() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); - + resetAuthentication(); - + // WHEN MidPointPrincipal principal = userProfileService.getPrincipal(USER_JACK_USERNAME); - + // THEN assertJack(principal); - + assertEquals("Wrong number of authorizations", 1, principal.getAuthorities().size()); assertHasAuthotizationAllow(principal.getAuthorities().iterator().next(), AUTZ_LOOT_URL); - + assertAuthorized(principal, AUTZ_LOOT_URL, AuthorizationPhaseType.EXECUTION); assertNotAuthorized(principal, AUTZ_LOOT_URL, AuthorizationPhaseType.REQUEST); assertNotAuthorized(principal, AUTZ_LOOT_URL, null); assertNotAuthorized(principal, AUTZ_COMMAND_URL); - + assertAdminGuiConfigurations(principal, 1, 2, 3, 2, 2); } - + @Test public void test109JackUnassignRolePirate() throws Exception { final String TEST_NAME = "test109JackUnassignRolePirate"; @@ -255,23 +255,23 @@ public void test109JackUnassignRolePirate() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); - + resetAuthentication(); - + // WHEN MidPointPrincipal principal = userProfileService.getPrincipal(USER_JACK_USERNAME); - + // THEN assertJack(principal); - + assertEquals("Wrong number of authorizations", 0, principal.getAuthorities().size()); - + assertNotAuthorized(principal, AUTZ_LOOT_URL); assertNotAuthorized(principal, AUTZ_COMMAND_URL); - + assertAdminGuiConfigurations(principal, 0, 1, 3, 1, 0); } - + @Test public void test110GuybrushRoleNicePirate() throws Exception { final String TEST_NAME = "test110GuybrushRoleNicePirate"; @@ -281,22 +281,22 @@ public void test110GuybrushRoleNicePirate() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assignRole(USER_GUYBRUSH_OID, ROLE_NICE_PIRATE_OID, task, result); - + resetAuthentication(); - + // WHEN displayWhen(TEST_NAME); MidPointPrincipal principal = userProfileService.getPrincipal(USER_GUYBRUSH_USERNAME); - + // THEN displayThen(TEST_NAME); display("Principal guybrush", principal); assertEquals("Wrong number of authorizations", 2, principal.getAuthorities().size()); - + assertNotAuthorized(principal, AUTZ_LOOT_URL); assertNotAuthorized(principal, AUTZ_COMMAND_URL); } - + @Test public void test111GuybrushRoleCaptain() throws Exception { final String TEST_NAME = "test111GuybrushRoleCaptain"; @@ -306,22 +306,22 @@ public void test111GuybrushRoleCaptain() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assignRole(USER_GUYBRUSH_OID, ROLE_CAPTAIN_OID, task, result); - + resetAuthentication(); - + // WHEN displayWhen(TEST_NAME); MidPointPrincipal principal = userProfileService.getPrincipal(USER_GUYBRUSH_USERNAME); - + // THEN displayThen(TEST_NAME); display("Principal guybrush", principal); assertEquals("Wrong number of authorizations", 3, principal.getAuthorities().size()); - + assertNotAuthorized(principal, AUTZ_LOOT_URL); assertAuthorized(principal, AUTZ_COMMAND_URL); } - + @Test public void test119GuybrushUnassignRoles() throws Exception { final String TEST_NAME = "test119GuybrushUnassignRoles"; @@ -332,21 +332,21 @@ public void test119GuybrushUnassignRoles() throws Exception { OperationResult result = task.getResult(); unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); unassignRole(USER_JACK_OID, ROLE_CAPTAIN_OID, task, result); - + resetAuthentication(); - + // WHEN displayWhen(TEST_NAME); MidPointPrincipal principal = userProfileService.getPrincipal(USER_JACK_USERNAME); - + // THEN displayThen(TEST_NAME); assertEquals("Wrong number of authorizations", 0, principal.getAuthorities().size()); - + assertNotAuthorized(principal, AUTZ_LOOT_URL); assertNotAuthorized(principal, AUTZ_COMMAND_URL); } - + /** * MID-3650 */ @@ -356,30 +356,30 @@ public void test120JackRoleIndirectPirate() throws Exception { displayTestTitle(TEST_NAME); // GIVEN login(USER_ADMINISTRATOR_USERNAME); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User before", userBefore); assertAssignments(userBefore, 0); - + assignRole(USER_JACK_OID, ROLE_INDIRECT_PIRATE_OID); - + resetAuthentication(); - + // WHEN displayWhen(TEST_NAME); MidPointPrincipal principal = userProfileService.getPrincipal(USER_JACK_USERNAME); - + // THEN displayThen(TEST_NAME); display("Principal guybrush", principal); assertEquals("Wrong number of authorizations", 1, principal.getAuthorities().size()); - + assertAuthorized(principal, AUTZ_LOOT_URL, AuthorizationPhaseType.EXECUTION); - + login(USER_ADMINISTRATOR_USERNAME); unassignRole(USER_JACK_OID, ROLE_INDIRECT_PIRATE_OID); } - + /** * MID-3650 */ @@ -389,26 +389,26 @@ public void test122JackOrgIndirectPirate() throws Exception { displayTestTitle(TEST_NAME); // GIVEN login(USER_ADMINISTRATOR_USERNAME); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User before", userBefore); assertAssignments(userBefore, 0); - + assignOrg(USER_JACK_OID, ORG_INDIRECT_PIRATE_OID); - + resetAuthentication(); - + // WHEN displayWhen(TEST_NAME); MidPointPrincipal principal = userProfileService.getPrincipal(USER_JACK_USERNAME); - + // THEN displayThen(TEST_NAME); display("Principal guybrush", principal); assertEquals("Wrong number of authorizations", 1, principal.getAuthorities().size()); - + assertAuthorized(principal, AUTZ_LOOT_URL, AuthorizationPhaseType.EXECUTION); - + login(USER_ADMINISTRATOR_USERNAME); unassignOrg(USER_JACK_OID, ORG_INDIRECT_PIRATE_OID); } 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 1e687445b1f..5b0b7a5efd5 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 @@ -55,15 +55,15 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public abstract class AbstractInboundSyncTest extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/sync"); - + protected static final File TASK_LIVE_SYNC_DUMMY_EMERALD_FILE = new File(TEST_DIR, "task-dummy-emerald-livesync.xml"); protected static final String TASK_LIVE_SYNC_DUMMY_EMERALD_OID = "10000000-0000-0000-5555-55550000e404"; - + 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); @@ -72,18 +72,18 @@ public abstract class AbstractInboundSyncTest extends AbstractInitializedModelIn protected static final String ACCOUNT_POSIXUSER_DUMMY_USERNAME = "posixuser"; protected static String userWallyOid; - + protected boolean allwaysCheckTimestamp = false; protected long timeBeforeSync; @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + } - + protected File getResourceDummyEmeraldFile() { return RESOURCE_DUMMY_EMERALD_FILE; } @@ -91,11 +91,11 @@ protected File getResourceDummyEmeraldFile() { protected abstract void importSyncTask(PrismObject resource) throws FileNotFoundException; protected abstract String getSyncTaskOid(PrismObject resource); - + protected int getWaitTimeout() { return DEFAULT_TASK_WAIT_TIMEOUT; } - + protected int getNumberOfExtraDummyUsers() { return 0; } @@ -109,17 +109,17 @@ public void test100ImportLiveSyncTaskDummyEmerald() throws Exception { // GIVEN Task task = createTask(AbstractInboundSyncTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + /// WHEN TestUtil.displayWhen(TEST_NAME); importSyncTask(resourceDummyEmerald); - + // THEN TestUtil.displayThen(TEST_NAME); - + waitForSyncTaskStart(resourceDummyEmerald); } - + @Test public void test110AddDummyEmeraldAccountMancomb() throws Exception { final String TEST_NAME = "test110AddDummyEmeraldAccountMancomb"; @@ -130,7 +130,7 @@ public void test110AddDummyEmeraldAccountMancomb() throws Exception { OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); - + // Preconditions assertUsers(5); @@ -142,26 +142,26 @@ public void test110AddDummyEmeraldAccountMancomb() throws Exception { account.addAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOOT_NAME, loot); String gossip = XmlTypeConverter.createXMLGregorianCalendar(ACCOUNT_MANCOMB_VALID_TO_DATE).toXMLFormat(); account.addAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, gossip); - + /// WHEN TestUtil.displayWhen(TEST_NAME); - + display("Adding dummy account", account.debugDump()); - + dummyResourceEmerald.addAccount(account); - + waitForSyncTaskNextRun(resourceDummyEmerald); - + // THEN TestUtil.displayThen(TEST_NAME); - + PrismObject accountMancomb = findAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME, resourceDummyEmerald); display("Account mancomb", accountMancomb); assertNotNull("No mancomb account shadow", accountMancomb); - assertEquals("Wrong resourceRef in mancomb account", RESOURCE_DUMMY_EMERALD_OID, + assertEquals("Wrong resourceRef in mancomb account", RESOURCE_DUMMY_EMERALD_OID, accountMancomb.asObjectable().getResourceRef().getOid()); assertShadowOperationalData(accountMancomb, SynchronizationSituationType.LINKED); - + PrismObject userMancomb = findUserByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); display("User mancomb", userMancomb); assertNotNull("User mancomb was not created", userMancomb); @@ -169,15 +169,15 @@ public void test110AddDummyEmeraldAccountMancomb() throws Exception { assertAdministrativeStatusEnabled(userMancomb); assertValidFrom(userMancomb, ACCOUNT_MANCOMB_VALID_FROM_DATE); assertValidTo(userMancomb, ACCOUNT_MANCOMB_VALID_TO_DATE); - + assertLinked(userMancomb, accountMancomb); - + assertUsers(6); // notifications notificationManager.setDisabled(true); } - + @Test public void test120ModifyDummyEmeraldAccountMancombSeepbad() throws Exception { final String TEST_NAME = "test120ModifyDummyEmeraldAccountMancombSeepbad"; @@ -188,33 +188,33 @@ public void test120ModifyDummyEmeraldAccountMancombSeepbad() throws Exception { OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); - + // Preconditions assertUsers(6); DummyAccount account = dummyResourceEmerald.getAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); - + /// WHEN TestUtil.displayWhen(TEST_NAME); - + account.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Mancomb Seepbad"); display("Modified dummy account", account.debugDump()); waitForSyncTaskNextRun(resourceDummyEmerald); - + // THEN TestUtil.displayThen(TEST_NAME); - + PrismObject accountAfter = findAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME, resourceDummyEmerald); display("Account mancomb", accountAfter); assertNotNull("No mancomb account shadow", accountAfter); - assertEquals("Wrong resourceRef in mancomb account", RESOURCE_DUMMY_EMERALD_OID, + assertEquals("Wrong resourceRef in mancomb account", RESOURCE_DUMMY_EMERALD_OID, accountAfter.asObjectable().getResourceRef().getOid()); assertShadowOperationalData(accountAfter, SynchronizationSituationType.LINKED); - assertDummyAccountAttribute(RESOURCE_DUMMY_EMERALD_NAME, ACCOUNT_MANCOMB_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_EMERALD_NAME, ACCOUNT_MANCOMB_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Mancomb Seepbad"); - + PrismObject userAfter = findUserByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); display("User mancomb", userAfter); assertNotNull("User mancomb was not created", userAfter); @@ -222,17 +222,17 @@ public void test120ModifyDummyEmeraldAccountMancombSeepbad() throws Exception { assertAdministrativeStatusEnabled(userAfter); assertValidFrom(userAfter, ACCOUNT_MANCOMB_VALID_FROM_DATE); assertValidTo(userAfter, ACCOUNT_MANCOMB_VALID_TO_DATE); - + assertLinked(userAfter, accountAfter); - + PrismAsserts.assertPropertyValue(userAfter, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Mancomb Seepbad")); - + assertUsers(6); // notifications notificationManager.setDisabled(true); } - + @Test public void test122ModifyDummyEmeraldAccountMancombSeepNULL() throws Exception { final String TEST_NAME = "test122ModifyDummyEmeraldAccountMancombSeepNULL"; @@ -243,33 +243,33 @@ public void test122ModifyDummyEmeraldAccountMancombSeepNULL() throws Exception { OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); - + // Preconditions assertUsers(6); DummyAccount account = dummyResourceEmerald.getAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); - + /// WHEN TestUtil.displayWhen(TEST_NAME); - + account.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Mancomb SeepNULL"); display("Modified dummy account", account.debugDump()); waitForSyncTaskNextRun(resourceDummyEmerald); - + // THEN TestUtil.displayThen(TEST_NAME); - + PrismObject accountAfter = findAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME, resourceDummyEmerald); display("Account mancomb", accountAfter); assertNotNull("No mancomb account shadow", accountAfter); - assertEquals("Wrong resourceRef in mancomb account", RESOURCE_DUMMY_EMERALD_OID, + assertEquals("Wrong resourceRef in mancomb account", RESOURCE_DUMMY_EMERALD_OID, accountAfter.asObjectable().getResourceRef().getOid()); assertShadowOperationalData(accountAfter, SynchronizationSituationType.LINKED); - assertDummyAccountAttribute(RESOURCE_DUMMY_EMERALD_NAME, ACCOUNT_MANCOMB_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_EMERALD_NAME, ACCOUNT_MANCOMB_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Mancomb SeepNULL"); - + PrismObject userAfter = findUserByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); display("User mancomb", userAfter); assertNotNull("User mancomb was not created", userAfter); @@ -277,11 +277,11 @@ public void test122ModifyDummyEmeraldAccountMancombSeepNULL() throws Exception { assertAdministrativeStatusEnabled(userAfter); assertValidFrom(userAfter, ACCOUNT_MANCOMB_VALID_FROM_DATE); assertValidTo(userAfter, ACCOUNT_MANCOMB_VALID_TO_DATE); - + assertLinked(userAfter, accountAfter); - + PrismAsserts.assertNoItem(userAfter, UserType.F_FULL_NAME); - + assertUsers(6); // notifications @@ -298,33 +298,33 @@ public void test124ModifyDummyEmeraldAccountMancombSeepevil() throws Exception { OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); - + // Preconditions assertUsers(6); DummyAccount account = dummyResourceEmerald.getAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); - + /// WHEN TestUtil.displayWhen(TEST_NAME); - + account.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Mancomb Seepevil"); display("Modified dummy account", account.debugDump()); waitForSyncTaskNextRun(resourceDummyEmerald); - + // THEN TestUtil.displayThen(TEST_NAME); - + PrismObject accountAfter = findAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME, resourceDummyEmerald); display("Account mancomb", accountAfter); assertNotNull("No mancomb account shadow", accountAfter); - assertEquals("Wrong resourceRef in mancomb account", RESOURCE_DUMMY_EMERALD_OID, + assertEquals("Wrong resourceRef in mancomb account", RESOURCE_DUMMY_EMERALD_OID, accountAfter.asObjectable().getResourceRef().getOid()); assertShadowOperationalData(accountAfter, SynchronizationSituationType.LINKED); - assertDummyAccountAttribute(RESOURCE_DUMMY_EMERALD_NAME, ACCOUNT_MANCOMB_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_EMERALD_NAME, ACCOUNT_MANCOMB_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Mancomb Seepevil"); - + PrismObject userAfter = findUserByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); display("User mancomb", userAfter); assertNotNull("User mancomb was not created", userAfter); @@ -332,17 +332,17 @@ public void test124ModifyDummyEmeraldAccountMancombSeepevil() throws Exception { assertAdministrativeStatusEnabled(userAfter); assertValidFrom(userAfter, ACCOUNT_MANCOMB_VALID_FROM_DATE); assertValidTo(userAfter, ACCOUNT_MANCOMB_VALID_TO_DATE); - + assertLinked(userAfter, accountAfter); - + PrismAsserts.assertPropertyValue(userAfter, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Mancomb Seepevil")); - + assertUsers(6); // notifications notificationManager.setDisabled(true); } - + @Test public void test126ModifyDummyEmeraldAccountMancombTitlePirate() throws Exception { final String TEST_NAME = "test126ModifyDummyEmeraldAccountMancombTitlePirate"; @@ -353,33 +353,33 @@ public void test126ModifyDummyEmeraldAccountMancombTitlePirate() throws Exceptio OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); - + // Preconditions assertUsers(6); DummyAccount account = dummyResourceEmerald.getAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); - + /// WHEN TestUtil.displayWhen(TEST_NAME); - + account.replaceAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Pirate"); display("Modified dummy account", account.debugDump()); waitForSyncTaskNextRun(resourceDummyEmerald); - + // THEN TestUtil.displayThen(TEST_NAME); - + PrismObject accountAfter = findAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME, resourceDummyEmerald); display("Account mancomb", accountAfter); assertNotNull("No mancomb account shadow", accountAfter); - assertEquals("Wrong resourceRef in mancomb account", RESOURCE_DUMMY_EMERALD_OID, + assertEquals("Wrong resourceRef in mancomb account", RESOURCE_DUMMY_EMERALD_OID, accountAfter.asObjectable().getResourceRef().getOid()); assertShadowOperationalData(accountAfter, SynchronizationSituationType.LINKED); - assertDummyAccountAttribute(RESOURCE_DUMMY_EMERALD_NAME, ACCOUNT_MANCOMB_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_EMERALD_NAME, ACCOUNT_MANCOMB_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Pirate"); - + PrismObject userAfter = findUserByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); display("User mancomb", userAfter); assertNotNull("User mancomb was not created", userAfter); @@ -387,12 +387,12 @@ public void test126ModifyDummyEmeraldAccountMancombTitlePirate() throws Exceptio assertAdministrativeStatusEnabled(userAfter); assertValidFrom(userAfter, ACCOUNT_MANCOMB_VALID_FROM_DATE); assertValidTo(userAfter, ACCOUNT_MANCOMB_VALID_TO_DATE); - + assertLinked(userAfter, accountAfter); - + PrismAsserts.assertPropertyValue(userAfter, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Mancomb Seepevil")); PrismAsserts.assertPropertyValue(userAfter, UserType.F_TITLE, PrismTestUtil.createPolyString("Pirate")); - + assertUsers(6); // notifications @@ -409,33 +409,33 @@ public void test127ModifyDummyEmeraldAccountMancombTitlePirateNull() throws Exce OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); - + // Preconditions assertUsers(6); DummyAccount account = dummyResourceEmerald.getAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); - + /// WHEN TestUtil.displayWhen(TEST_NAME); - + account.replaceAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME); display("Modified dummy account", account.debugDump()); waitForSyncTaskNextRun(resourceDummyEmerald); - + // THEN TestUtil.displayThen(TEST_NAME); - + PrismObject accountAfter = findAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME, resourceDummyEmerald); display("Account mancomb", accountAfter); assertNotNull("No mancomb account shadow", accountAfter); - assertEquals("Wrong resourceRef in mancomb account", RESOURCE_DUMMY_EMERALD_OID, + assertEquals("Wrong resourceRef in mancomb account", RESOURCE_DUMMY_EMERALD_OID, accountAfter.asObjectable().getResourceRef().getOid()); assertShadowOperationalData(accountAfter, SynchronizationSituationType.LINKED); - assertDummyAccountAttribute(RESOURCE_DUMMY_EMERALD_NAME, ACCOUNT_MANCOMB_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_EMERALD_NAME, ACCOUNT_MANCOMB_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME); - + PrismObject userAfter = findUserByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); display("User mancomb", userAfter); assertNotNull("User mancomb was not created", userAfter); @@ -443,12 +443,12 @@ public void test127ModifyDummyEmeraldAccountMancombTitlePirateNull() throws Exce assertAdministrativeStatusEnabled(userAfter); assertValidFrom(userAfter, ACCOUNT_MANCOMB_VALID_FROM_DATE); assertValidTo(userAfter, ACCOUNT_MANCOMB_VALID_TO_DATE); - + assertLinked(userAfter, accountAfter); - + PrismAsserts.assertPropertyValue(userAfter, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Mancomb Seepevil")); PrismAsserts.assertNoItem(userAfter, UserType.F_TITLE); - + assertUsers(6); // notifications @@ -465,33 +465,33 @@ public void test129ModifyDummyEmeraldAccountMancombSeepgood() throws Exception { OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); - + // Preconditions assertUsers(6); DummyAccount account = dummyResourceEmerald.getAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); - + /// WHEN TestUtil.displayWhen(TEST_NAME); - + account.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Mancomb Seepgood"); display("Modified dummy account", account.debugDump()); waitForSyncTaskNextRun(resourceDummyEmerald); - + // THEN TestUtil.displayThen(TEST_NAME); - + PrismObject accountAfter = findAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME, resourceDummyEmerald); display("Account mancomb", accountAfter); assertNotNull("No mancomb account shadow", accountAfter); - assertEquals("Wrong resourceRef in mancomb account", RESOURCE_DUMMY_EMERALD_OID, + assertEquals("Wrong resourceRef in mancomb account", RESOURCE_DUMMY_EMERALD_OID, accountAfter.asObjectable().getResourceRef().getOid()); assertShadowOperationalData(accountAfter, SynchronizationSituationType.LINKED); - assertDummyAccountAttribute(RESOURCE_DUMMY_EMERALD_NAME, ACCOUNT_MANCOMB_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_EMERALD_NAME, ACCOUNT_MANCOMB_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Mancomb Seepgood"); - + PrismObject userAfter = findUserByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); display("User mancomb", userAfter); assertNotNull("User mancomb was not created", userAfter); @@ -499,11 +499,11 @@ public void test129ModifyDummyEmeraldAccountMancombSeepgood() throws Exception { assertAdministrativeStatusEnabled(userAfter); assertValidFrom(userAfter, ACCOUNT_MANCOMB_VALID_FROM_DATE); assertValidTo(userAfter, ACCOUNT_MANCOMB_VALID_TO_DATE); - + assertLinked(userAfter, accountAfter); - + PrismAsserts.assertPropertyValue(userAfter, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Mancomb Seepgood")); - + assertUsers(6); // notifications @@ -572,7 +572,7 @@ public void test300AddDummyEmeraldAccountPosixUser() throws Exception { // notifications notificationManager.setDisabled(true); - + // TODO create and test inbounds for uid and gid numbers; also other attributes // (Actually I'm not sure it will work, as even now the auxiliary object class is // removed right during the livesync. This has to be solved somehow...) @@ -633,12 +633,12 @@ public void test310ModifyDummyEmeraldAccountPosixUserUidNumber() throws Exceptio protected void waitForSyncTaskStart(PrismObject resource) throws Exception { waitForTaskStart(getSyncTaskOid(resource), false, getWaitTimeout()); } - + protected void waitForSyncTaskNextRun(PrismObject resource) throws Exception { waitForTaskNextRunAssertSuccess(getSyncTaskOid(resource), false, getWaitTimeout()); } - - + + protected void rememberTimeBeforeSync() { timeBeforeSync = System.currentTimeMillis(); } 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 7c69510233d..304c541c6ef 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 @@ -51,28 +51,28 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public abstract class AbstractObjTemplateSyncTest extends AbstractInitializedModelIntegrationTest { - + public static final File TEST_DIR = new File("src/test/resources/sync"); - + protected static final File RESOURCE_DUMMY_BYZANTINE_FILE = new File(TEST_DIR, "resource-dummy-byzantine.xml"); protected static final String RESOURCE_DUMMY_BYZANTINE_OID = "10000000-0000-0000-0000-00000000f904"; protected static final String RESOURCE_DUMMY_BYZANTINE_NAME = "byzantine"; 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; protected PrismObject resourceDummyByzantine; - + protected static final String ACCOUNT_MANCOMB_DUMMY_USERNAME = "mancomb"; private static final Date ACCOUNT_MANCOMB_VALID_FROM_DATE = MiscUtil.asDate(2011, 2, 3, 4, 5, 6); private static final Date ACCOUNT_MANCOMB_VALID_TO_DATE = MiscUtil.asDate(2066, 5, 4, 3, 2, 1); - + protected long timeBeforeSync; public static final File SYSTEM_CONFIGURATION_FILE = new File(TEST_DIR, "system-configuration-byzantine.xml"); @@ -95,7 +95,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti repoAddObjectFromFile(USER_TEMPLATE_FILE, initResult); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + dummyResourceCtlByzantine = DummyResourceContoller.create(RESOURCE_DUMMY_BYZANTINE_NAME, resourceDummyByzantine); dummyResourceCtlByzantine.extendSchemaPirate(); dummyResourceByzantine = dummyResourceCtlByzantine.getDummyResource(); @@ -103,7 +103,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti resourceDummyByzantineType = resourceDummyByzantine.asObjectable(); dummyResourceCtlByzantine.setResource(resourceDummyByzantine); } - + protected File getResourceDummyByzantineFile() { return RESOURCE_DUMMY_BYZANTINE_FILE; } @@ -111,11 +111,11 @@ protected File getResourceDummyByzantineFile() { protected abstract void importSyncTask(PrismObject resource) throws FileNotFoundException; protected abstract String getSyncTaskOid(PrismObject resource); - + protected int getWaitTimeout() { return DEFAULT_TASK_WAIT_TIMEOUT; } - + @Test public void test100ImportLiveSyncTaskDummyByzantine() throws Exception { final String TEST_NAME = "test100ImportLiveSyncTaskDummyByzantine"; @@ -124,14 +124,14 @@ public void test100ImportLiveSyncTaskDummyByzantine() throws Exception { // GIVEN Task task = createTask(AbstractObjTemplateSyncTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + /// WHEN TestUtil.displayWhen(TEST_NAME); importSyncTask(resourceDummyByzantine); - + // THEN TestUtil.displayThen(TEST_NAME); - + waitForSyncTaskStart(resourceDummyByzantine); } @@ -146,7 +146,7 @@ public void test110AddDummyByzantineAccountMancomb() throws Exception { OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); - + // Preconditions assertUsers(5); @@ -158,26 +158,26 @@ public void test110AddDummyByzantineAccountMancomb() throws Exception { account.addAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOOT_NAME, loot); String gossip = XmlTypeConverter.createXMLGregorianCalendar(ACCOUNT_MANCOMB_VALID_TO_DATE).toXMLFormat(); account.addAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, gossip); - + /// WHEN TestUtil.displayWhen(TEST_NAME); - + display("Adding dummy account", account.debugDump()); - + dummyResourceByzantine.addAccount(account); - + waitForSyncTaskNextRun(resourceDummyByzantine); - + // THEN TestUtil.displayThen(TEST_NAME); - + PrismObject accountMancomb = findAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME, resourceDummyByzantine); display("Account mancomb", accountMancomb); assertNotNull("No mancomb account shadow", accountMancomb); assertEquals("Wrong resourceRef in mancomb account", RESOURCE_DUMMY_BYZANTINE_OID, accountMancomb.asObjectable().getResourceRef().getOid()); assertShadowOperationalData(accountMancomb, SynchronizationSituationType.LINKED); - + PrismObject userMancomb = findUserByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); display("User mancomb", userMancomb); assertNotNull("User mancomb was not created", userMancomb); @@ -189,7 +189,7 @@ public void test110AddDummyByzantineAccountMancomb() throws Exception { assertEquals("Wrong e-mail address for mancomb", "mancomb.Mr@test.com", userMancomb.asObjectable().getEmailAddress()); assertAssignedOrg(userMancomb, ORG_F0001_OID); assertHasOrg(userMancomb, ORG_F0001_OID); - + assertUsers(6); // notifications @@ -200,7 +200,7 @@ public void test110AddDummyByzantineAccountMancomb() throws Exception { protected void waitForSyncTaskStart(PrismObject resource) throws Exception { waitForTaskStart(getSyncTaskOid(resource), false, getWaitTimeout()); } - + protected void waitForSyncTaskNextRun(PrismObject resource) throws Exception { waitForTaskNextRunAssertSuccess(getSyncTaskOid(resource), false, getWaitTimeout()); } 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 33c375b5f8d..c603c0fd8df 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 @@ -72,21 +72,21 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public abstract class AbstractSynchronizationStoryTest extends AbstractInitializedModelIntegrationTest { - + protected static final String ACCOUNT_WALLY_DUMMY_USERNAME = "wally"; protected static final String ACCOUNT_MANCOMB_DUMMY_USERNAME = "mancomb"; private static final Date ACCOUNT_MANCOMB_VALID_FROM_DATE = MiscUtil.asDate(2011, 2, 3, 4, 5, 6); private static final Date ACCOUNT_MANCOMB_VALID_TO_DATE = MiscUtil.asDate(2066, 5, 4, 3, 2, 1); - + protected static String userWallyOid; - + protected boolean allwaysCheckTimestamp = false; protected long timeBeforeSync; @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); // DebugUtil.setDetailedDebugDump(true); } @@ -99,15 +99,15 @@ protected ConflictResolutionActionType getDefaultConflictResolutionAction() { protected abstract void importSyncTask(PrismObject resource) throws FileNotFoundException; protected abstract String getSyncTaskOid(PrismObject resource); - + protected int getWaitTimeout() { return DEFAULT_TASK_WAIT_TIMEOUT; } - + protected int getNumberOfExtraDummyUsers() { return 0; } - + protected boolean isReconciliation() { return false; } @@ -121,17 +121,17 @@ public void test100ImportLiveSyncTaskDummyGreen() throws Exception { // GIVEN Task task = createTask(AbstractSynchronizationStoryTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + /// WHEN TestUtil.displayWhen(TEST_NAME); importSyncTask(resourceDummyGreen); - + // THEN TestUtil.displayThen(TEST_NAME); - + waitForSyncTaskStart(resourceDummyGreen); } - + @Test public void test110AddDummyGreenAccountMancomb() throws Exception { final String TEST_NAME = "test110AddDummyGreenAccountMancomb"; @@ -142,7 +142,7 @@ public void test110AddDummyGreenAccountMancomb() throws Exception { OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); - + // Preconditions assertUsers(5); @@ -152,26 +152,26 @@ public void test110AddDummyGreenAccountMancomb() throws Exception { account.setValidTo(ACCOUNT_MANCOMB_VALID_TO_DATE); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Mancomb Seepgood"); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Melee Island"); - + /// WHEN TestUtil.displayWhen(TEST_NAME); - + dummyResourceGreen.addAccount(account); - + waitForSyncTaskNextRunAssertSuccess(resourceDummyGreen); - + // THEN TestUtil.displayThen(TEST_NAME); - + PrismObject accountMancomb = findAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME, resourceDummyGreen); display("Account mancomb", accountMancomb); assertNotNull("No mancomb account shadow", accountMancomb); - assertEquals("Wrong resourceRef in mancomb account", RESOURCE_DUMMY_GREEN_OID, + assertEquals("Wrong resourceRef in mancomb account", RESOURCE_DUMMY_GREEN_OID, accountMancomb.asObjectable().getResourceRef().getOid()); assertShadowOperationalData(accountMancomb, SynchronizationSituationType.LINKED); assertValidFrom(accountMancomb, ACCOUNT_MANCOMB_VALID_FROM_DATE); assertValidTo(accountMancomb, ACCOUNT_MANCOMB_VALID_TO_DATE); - + PrismObject userMancomb = findUserByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); display("User mancomb", userMancomb); assertNotNull("User mancomb was not created", userMancomb); @@ -179,9 +179,9 @@ public void test110AddDummyGreenAccountMancomb() throws Exception { assertAdministrativeStatusEnabled(userMancomb); assertValidFrom(userMancomb, ACCOUNT_MANCOMB_VALID_FROM_DATE); assertValidTo(userMancomb, ACCOUNT_MANCOMB_VALID_TO_DATE); - + assertLinked(userMancomb, accountMancomb); - + assertUsers(6); // notifications @@ -203,14 +203,14 @@ public void test200ImportLiveSyncTaskDummyBlue() throws Exception { // GIVEN Task task = createTask(AbstractSynchronizationStoryTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + /// WHEN TestUtil.displayWhen(TEST_NAME); importSyncTask(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME)); - + // THEN TestUtil.displayThen(TEST_NAME); - + waitForSyncTaskStart(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME)); } @@ -281,7 +281,7 @@ public void test220AddDummyBlueAccountWally() throws Exception { /// WHEN TestUtil.displayWhen(TEST_NAME); getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).addAccount(ACCOUNT_WALLY_DUMMY_USERNAME, "Wally Feed", "Scabb Island"); - + // Wait for sync task to pick up the change // However, blue is not authoritative regarding creating new users, so wally will not be created at this time waitForSyncTaskNextRunAssertSuccess(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME)); @@ -297,7 +297,7 @@ public void test220AddDummyBlueAccountWally() throws Exception { PrismObject accountWallyGreen = checkWallyAccount(resourceDummyGreen, dummyResourceGreen, "green", "Wally Feed"); assertShadowOperationalData(accountWallyGreen, SynchronizationSituationType.LINKED); - PrismObject accountWallyBlue = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), + PrismObject accountWallyBlue = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), getDummyResource(RESOURCE_DUMMY_BLUE_NAME), "blue", "Wally Feed"); assertShadowOperationalData(accountWallyBlue, SynchronizationSituationType.LINKED); @@ -323,7 +323,7 @@ public void test220AddDummyBlueAccountWally() throws Exception { // checkDummyTransportMessages("simpleUserNotifier-ADD", 1); } - + /** * Add mancomb also to the blue dummy resource. This account should be linked to the existing user. * Similar to the previous test but blue resource has a slightly different correlation expression. @@ -342,23 +342,23 @@ public void test315AddDummyBlueAccountMancomb() throws Exception { /// WHEN TestUtil.displayWhen(TEST_NAME); getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).addAccount(ACCOUNT_MANCOMB_DUMMY_USERNAME, "Mancomb Seepgood", "Melee Island"); - + // Wait for sync task to pick up the change waitForSyncTaskNextRunAssertSuccess(getDummyResourceObject(RESOURCE_DUMMY_BLUE_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 waitForSyncTaskNextRunAssertSuccess(resourceDummyGreen); waitForSyncTaskNextRunAssertSuccess(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME)); - + // THEN TestUtil.displayThen(TEST_NAME); // The ckecks are simplified here because the developer has a lazy mood :-) assertDummyAccount(RESOURCE_DUMMY_BLUE_NAME, ACCOUNT_MANCOMB_DUMMY_USERNAME, "Mancomb Seepgood", true); assertDummyAccount(RESOURCE_DUMMY_GREEN_NAME, ACCOUNT_MANCOMB_DUMMY_USERNAME, "Mancomb Seepgood", true); - + PrismObject userMancomb = findUserByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); display("User mancomb", userMancomb); assertNotNull("User mancomb disappeared", userMancomb); @@ -380,7 +380,7 @@ public void test315AddDummyBlueAccountMancomb() throws Exception { // checkDummyTransportMessages("simpleUserNotifier-ADD", 0); } - + /** * Import sync task for default dummy resource as well. This does not do much as we will no be manipulating * the default dummy account directly. Just make sure that it does not do anything bad. @@ -393,22 +393,22 @@ public void test350ImportLiveSyncTaskDummyDefault() throws Exception { // GIVEN Task task = createTask(AbstractSynchronizationStoryTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + /// WHEN TestUtil.displayWhen(TEST_NAME); importSyncTask(getDummyResourceObject()); - + // THEN TestUtil.displayThen(TEST_NAME); - + waitForSyncTaskStart(getDummyResourceObject()); - + // Dummy resource has some extra users that may be created in recon, so let's give it a chance to do it now waitForSyncTaskNextRunAssertSuccess(getDummyResourceObject()); - + assertUsers(7 + getNumberOfExtraDummyUsers()); } - + /** * Import sync task for default dummy resource as well. This does not do much as we will no be manipulating * the default dummy account directly. Just make sure that it does not do anything bad. @@ -422,35 +422,35 @@ public void test360ModifyUserAddDummyDefaultAccount() throws Exception { Task task = createTask(AbstractSynchronizationStoryTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); rememberTimeBeforeSync(); - + PrismObject userWally = findUserByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); assertEquals("OID of user wally have changed", userWallyOid, userWally.getOid()); - + ObjectDelta userDelta = createModifyUserAddAccount(userWally.getOid(), getDummyResourceObject()); Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); - + /// WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); - + // Make sure we have steady state waitForSyncTaskNextRunAssertSuccess(getDummyResourceObject()); waitForSyncTaskNextRunAssertSuccess(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME)); waitForSyncTaskNextRunAssertSuccess(resourceDummyGreen); - + PrismObject accountWallyDefault = checkWallyAccount(getDummyResourceObject(), getDummyResource(), "default", "Wally Feed"); assertShadowOperationalData(accountWallyDefault, SynchronizationSituationType.LINKED); - PrismObject accountWallyBlue = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), + PrismObject accountWallyBlue = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), getDummyResource(RESOURCE_DUMMY_BLUE_NAME), "blue", "Wally Feed"); if (allwaysCheckTimestamp) assertShadowOperationalData(accountWallyBlue, SynchronizationSituationType.LINKED); - PrismObject accountWallyGreen = checkWallyAccount(resourceDummyGreen, dummyResourceGreen, + PrismObject accountWallyGreen = checkWallyAccount(resourceDummyGreen, dummyResourceGreen, "green", "Wally Feed"); if (allwaysCheckTimestamp) assertShadowOperationalData(accountWallyGreen, SynchronizationSituationType.LINKED); - + userWally = findUserByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); display("User wally", userWally); assertNotNull("User wally disappeared", userWally); @@ -460,10 +460,10 @@ public void test360ModifyUserAddDummyDefaultAccount() throws Exception { assertLinked(userWally, accountWallyDefault); assertLinked(userWally, accountWallyGreen); assertLinked(userWally, accountWallyBlue); - + assertUsers(7 + getNumberOfExtraDummyUsers()); } - + // @Test // public void test365ModifyDummyGreenAccountWallyUserTemplate() throws Exception { // final String TEST_NAME = "test390ModifyDummyGreenAccountWallyUserTemplate"; @@ -473,20 +473,20 @@ public void test360ModifyUserAddDummyDefaultAccount() throws Exception { // 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, resourceDummyGreen.asObjectable(), result); -// +// // DummyAccount wallyDummyAccount = dummyResourceGreen.getAccountByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); -// +// // /// WHEN // displayWhen(TEST_NAME); // 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(resourceDummyGreen); -// +// //// // 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 @@ -494,33 +494,33 @@ public void test360ModifyUserAddDummyDefaultAccount() throws Exception { // waitForSyncTaskNextRun(resourceDummyGreen); //// // Make sure we have steady state // waitForSyncTaskNextRun(resourceDummy); -// +// // // THEN // displayThen(TEST_NAME); -// +// // 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(resourceDummyGreen, dummyResourceGreen, "blue", "Wally Bloodnose"); // if (allwaysCheckTimestamp) assertShadowOperationalData(accountWallyGreen, SynchronizationSituationType.LINKED); -// +// //// PrismObject accountWallyGreen = checkWallyAccount(resourceDummyGreen, dummyResourceGreen, "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. @@ -533,22 +533,22 @@ public void test370ModifyDummyGreenAccountWally() throws Exception { // GIVEN Task task = createTask(AbstractSynchronizationStoryTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + repoAddObjectFromFile(USER_TEMPLATE_SYNC_FILENAME, result); assumeUserTemplate(USER_TEMPLATE_SYNC_OID, resourceDummyGreen.asObjectable(), "default account type", result); - + rememberTimeBeforeSync(); prepareNotifications(); - + DummyAccount wallyDummyAccount = dummyResourceGreen.getAccountByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); - + /// WHEN TestUtil.displayWhen(TEST_NAME); wallyDummyAccount.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Wally B. Feed"); - + // Wait for sync task to pick up the change waitForSyncTaskNextRunAssertSuccess(resourceDummyGreen); - + // 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 @@ -556,16 +556,16 @@ public void test370ModifyDummyGreenAccountWally() throws Exception { waitForSyncTaskNextRunAssertSuccess(resourceDummyGreen); // Make sure we have steady state waitForSyncTaskNextRunAssertSuccess(getDummyResourceObject()); - + // THEN TestUtil.displayThen(TEST_NAME); - + PrismObject userWally = findUserByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); display("User wally", userWally); assertNotNull("User wally disappeared", userWally); assertUser(userWally, userWallyOid, ACCOUNT_WALLY_DUMMY_USERNAME, "Wally B. Feed", null, "Wally B. Feed from Sync"); - - PrismObject accountWallyBlue = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), + + PrismObject accountWallyBlue = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), getDummyResource(RESOURCE_DUMMY_BLUE_NAME), "blue", "Wally Feed"); if (allwaysCheckTimestamp) assertShadowOperationalData(accountWallyBlue, SynchronizationSituationType.LINKED); PrismObject accountWallyGreen = checkWallyAccount(resourceDummyGreen, dummyResourceGreen, "green", "Wally B. Feed"); @@ -573,22 +573,22 @@ public void test370ModifyDummyGreenAccountWally() throws Exception { PrismObject accountWallyDefault; // See MID-2518 if (isReconciliation()) { - + // Can be iether "Wally Feed" or "Wally B. Feed". Both are correct. Depends on he order of recon // task execution. accountWallyDefault = checkWallyAccount(getDummyResourceObject(), getDummyResource(), "default", null); - + } else { accountWallyDefault = checkWallyAccount(getDummyResourceObject(), getDummyResource(), "default", "Wally B. Feed"); } assertShadowOperationalData(accountWallyDefault, SynchronizationSituationType.LINKED); - + assertLinks(userWally, 3); assertLinked(userWally, accountWallyGreen); assertLinked(userWally, accountWallyBlue); assertLinked(userWally, accountWallyDefault); - + assertUsers(7 + getNumberOfExtraDummyUsers()); // notifications @@ -604,7 +604,7 @@ public void test370ModifyDummyGreenAccountWally() throws Exception { } /** - * Change user fullname. Fullname has normal mapping on default dummy. + * Change user fullname. Fullname has normal mapping on default dummy. * See if the change propagates correctly. Also see that there are no side-effects. */ @Test @@ -617,13 +617,13 @@ public void test380ModifyUserWallyFullName() throws Exception { OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); - + DummyAccount wallyDummyAccount = dummyResourceGreen.getAccountByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); - + /// WHEN TestUtil.displayWhen(TEST_NAME); modifyUserReplace(userWallyOid, UserType.F_FULL_NAME, task, result, PrismTestUtil.createPolyString("Bloodnose")); - + // Wait for sync tasks to pick up the change and have some chance to screw things waitForSyncTaskNextRunAssertSuccess(getDummyResourceObject()); waitForSyncTaskNextRunAssertSuccess(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME)); @@ -635,42 +635,42 @@ public void test380ModifyUserWallyFullName() throws Exception { // and it will be propagated to other resources. The next recon run should fix it in the user. // But as the mapping to default dummy is normal, the recon will not fix it on the resource. waitForSyncTaskNextRunAssertSuccess(resourceDummyGreen); - + // THEN TestUtil.displayThen(TEST_NAME); - + PrismObject userWally = findUserByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); display("User wally", userWally); assertNotNull("User wally disappeared", userWally); assertUser(userWally, userWallyOid, ACCOUNT_WALLY_DUMMY_USERNAME, "Bloodnose", null, "Bloodnose from Sync"); - - PrismObject accountWallyBlue = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), + + PrismObject accountWallyBlue = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), getDummyResource(RESOURCE_DUMMY_BLUE_NAME), "blue", "Wally Feed"); if (allwaysCheckTimestamp) assertShadowOperationalData(accountWallyBlue, SynchronizationSituationType.LINKED); PrismObject accountWallyGreen = checkWallyAccount(resourceDummyGreen, dummyResourceGreen, "green", "Bloodnose"); assertShadowOperationalData(accountWallyGreen, SynchronizationSituationType.LINKED); - + PrismObject accountWallyDefault = findAccountByUsername(ACCOUNT_WALLY_DUMMY_USERNAME, getDummyResourceObject()); - String fullNameDummyAttribute = IntegrationTestTools.getAttributeValue(accountWallyDefault.asObjectable(), + 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); } assertShadowOperationalData(accountWallyDefault, SynchronizationSituationType.LINKED); - + assertLinks(userWally, 3); assertLinked(userWally, accountWallyGreen); assertLinked(userWally, accountWallyBlue); assertLinked(userWally, accountWallyDefault); - + assertUsers(7 + getNumberOfExtraDummyUsers()); notificationManager.setDisabled(true); } /** - * Change user locality. Locality has strong mapping on default dummy. + * Change user locality. Locality has strong mapping on default dummy. * See if the change propagates correctly. Also see that there are no side-effects. */ @Test @@ -683,13 +683,13 @@ public void test382ModifyUserWallyLocality() throws Exception { OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); - + DummyAccount wallyDummyAccount = dummyResourceGreen.getAccountByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); - + /// WHEN TestUtil.displayWhen(TEST_NAME); modifyUserReplace(userWallyOid, UserType.F_LOCALITY, task, result, PrismTestUtil.createPolyString("Plunder island")); - + // Wait for sync tasks to pick up the change and have some chance to screw things waitForSyncTaskNextRunAssertSuccess(getDummyResourceObject()); waitForSyncTaskNextRunAssertSuccess(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME)); @@ -701,50 +701,50 @@ public void test382ModifyUserWallyLocality() throws Exception { // and it will be propagated to other resources. The next recon run should fix it. // Both in user and on the resource. waitForSyncTaskNextRunAssertSuccess(resourceDummyGreen); - + // THEN TestUtil.displayThen(TEST_NAME); - + PrismObject userWally = findUserByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); display("User wally", userWally); assertNotNull("User wally disappeared", userWally); assertUser(userWally, userWallyOid, ACCOUNT_WALLY_DUMMY_USERNAME, "Bloodnose", null, "Bloodnose from Sync"); PrismAsserts.assertPropertyValue(userWally, UserType.F_LOCALITY, PrismTestUtil.createPolyString("Plunder island")); - - PrismObject accountWallyBlue = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), + + PrismObject accountWallyBlue = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), getDummyResource(RESOURCE_DUMMY_BLUE_NAME), "blue", "Wally Feed"); if (allwaysCheckTimestamp) assertShadowOperationalData(accountWallyBlue, SynchronizationSituationType.LINKED); PrismObject accountWallyGreen = checkWallyAccount(resourceDummyGreen, dummyResourceGreen, "green", "Bloodnose"); assertShadowOperationalData(accountWallyGreen, SynchronizationSituationType.LINKED); - + PrismObject accountWallyDefault = findAccountByUsername(ACCOUNT_WALLY_DUMMY_USERNAME, getDummyResourceObject()); - String fullNameDummyAttribute = IntegrationTestTools.getAttributeValue(accountWallyDefault.asObjectable(), + 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); } assertShadowOperationalData(accountWallyDefault, SynchronizationSituationType.LINKED); assertShadowOperationalData(accountWallyDefault, SynchronizationSituationType.LINKED); - - assertDummyAccountAttribute(RESOURCE_DUMMY_GREEN_NAME, ACCOUNT_WALLY_DUMMY_USERNAME, + + assertDummyAccountAttribute(RESOURCE_DUMMY_GREEN_NAME, ACCOUNT_WALLY_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Plunder island"); - assertDummyAccountAttribute(RESOURCE_DUMMY_BLUE_NAME, ACCOUNT_WALLY_DUMMY_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_BLUE_NAME, ACCOUNT_WALLY_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Scabb Island"); - assertDummyAccountAttribute(null, ACCOUNT_WALLY_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_WALLY_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Plunder island"); - + assertLinks(userWally, 3); assertLinked(userWally, accountWallyGreen); assertLinked(userWally, accountWallyBlue); assertLinked(userWally, accountWallyDefault); - + assertUsers(7 + getNumberOfExtraDummyUsers()); notificationManager.setDisabled(true); } - - + + /** * Delete default dummy account. * Dummy resource has unlinkAccount sync reaction for deleted situation. The account should be unlinked @@ -764,26 +764,26 @@ public void test400DeleteDummyDefaultAccount() throws Exception { /// WHEN TestUtil.displayWhen(TEST_NAME); getDummyResource().deleteAccountByName(ACCOUNT_WALLY_DUMMY_USERNAME); - + display("Dummy (default) resource", getDummyResource().debugDump()); - + // Make sure we have steady state waitForSyncTaskNextRunAssertSuccess(getDummyResourceObject()); waitForSyncTaskNextRunAssertSuccess(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME)); waitForSyncTaskNextRunAssertSuccess(resourceDummyGreen); - + // THEN TestUtil.displayThen(TEST_NAME); - + assertNoDummyAccount(ACCOUNT_WALLY_DUMMY_USERNAME); assertNoShadow(ACCOUNT_WALLY_DUMMY_USERNAME, getDummyResourceObject(), task, result); - - PrismObject accountWallyBlue = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), + + PrismObject accountWallyBlue = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), getDummyResource(RESOURCE_DUMMY_BLUE_NAME), "blue", "Wally Feed"); if (allwaysCheckTimestamp) assertShadowOperationalData(accountWallyBlue, SynchronizationSituationType.LINKED); PrismObject accountWallyGreen = checkWallyAccount(resourceDummyGreen, dummyResourceGreen, "green", "Bloodnose"); if (allwaysCheckTimestamp) assertShadowOperationalData(accountWallyGreen, SynchronizationSituationType.LINKED); - + PrismObject userWally = findUserByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); display("User wally", userWally); assertNotNull("User wally disappeared", userWally); @@ -792,7 +792,7 @@ public void test400DeleteDummyDefaultAccount() throws Exception { assertLinked(userWally, accountWallyGreen); assertLinked(userWally, accountWallyBlue); - + assertUsers(7 + getNumberOfExtraDummyUsers()); // notifications @@ -806,7 +806,7 @@ public void test400DeleteDummyDefaultAccount() throws Exception { // checkDummyTransportMessages("simpleUserNotifier-ADD", 0); } - + /** * Delete green dummy account. * Green dummy resource has deleteUser sync reaction for deleted situation. This should delete the user @@ -825,27 +825,27 @@ public void test410DeleteDummyGreenAccount() throws Exception { /// WHEN TestUtil.displayWhen(TEST_NAME); dummyResourceGreen.deleteAccountByName(ACCOUNT_WALLY_DUMMY_USERNAME); - + // Make sure we have steady state waitForSyncTaskNextRunAssertSuccess(getDummyResourceObject()); OperationResult takResultBlue = waitForSyncTaskNextRun(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME)); waitForSyncTaskNextRunAssertSuccess(resourceDummyGreen); - + // THEN TestUtil.displayThen(TEST_NAME); - + assertNoDummyAccount(ACCOUNT_WALLY_DUMMY_USERNAME); assertNoShadow(ACCOUNT_WALLY_DUMMY_USERNAME, getDummyResourceObject(), task, result); - + assertNoDummyAccount(RESOURCE_DUMMY_GREEN_NAME, ACCOUNT_WALLY_DUMMY_USERNAME); assertNoShadow(ACCOUNT_WALLY_DUMMY_USERNAME, resourceDummyGreen, task, result); - + PrismObject userWally = findUserByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); display("User wally", userWally); assertNull("User wally is not gone", userWally); - + assertNoDummyAccount(RESOURCE_DUMMY_BLUE_NAME, ACCOUNT_WALLY_DUMMY_USERNAME); - + // Interesting things can happen here. Like this: // // Recon blue: Search on resource, remeber results in connector, sending them one @@ -865,15 +865,15 @@ public void test410DeleteDummyGreenAccount() throws Exception { // // So, if that happens we will just wait for the next recon run and check that it // sorts it out. - + ObjectQuery wallyBlueAccountsQuery = createAccountShadowQuery(ACCOUNT_WALLY_DUMMY_USERNAME, getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME)); List> wallyBlueAccounts = repositoryService.searchObjects(ShadowType.class, wallyBlueAccountsQuery, null, result); if (!wallyBlueAccounts.isEmpty()) { waitForSyncTaskNextRun(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME)); } - + assertNoShadow(ACCOUNT_WALLY_DUMMY_USERNAME, getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), task, result); - + assertUsers(6 + getNumberOfExtraDummyUsers()); if (isReconciliation()) { @@ -886,7 +886,7 @@ public void test410DeleteDummyGreenAccount() throws Exception { } else { TestUtil.assertSuccess("Blue resource syncronization has failed", takResultBlue); } - + // notifications notificationManager.setDisabled(true); // checkDummyTransportMessages("accountPasswordNotifier", 0); @@ -898,32 +898,32 @@ public void test410DeleteDummyGreenAccount() throws Exception { // checkDummyTransportMessages("simpleUserNotifier-ADD", 0); } - + @Test public void test510AddDummyGreenAccountWallyUserTemplate() throws Exception { final String TEST_NAME = "test510AddDummyGreenAccountWallyUserTemplate"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = createTask(AbstractSynchronizationStoryTest.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); rememberTimeBeforeSync(); assumeUserTemplate(USER_TEMPLATE_SYNC_OID, resourceDummyGreen.asObjectable(), null, result); - + /// WHEN TestUtil.displayWhen(TEST_NAME); dummyResourceCtlGreen.addAccount(ACCOUNT_WALLY_DUMMY_USERNAME, "Wally Feed", "Scabb Island"); - + // Wait for sync task to pick up the change waitForSyncTaskNextRunAssertSuccess(resourceDummyGreen); - + // THEN TestUtil.displayThen(TEST_NAME); - + PrismObject accountWallyGreen = checkWallyAccount(resourceDummyGreen, dummyResourceGreen, "green", "Wally Feed"); assertShadowOperationalData(accountWallyGreen, SynchronizationSituationType.LINKED); - + PrismObject userWally = findUserByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); display("User wally", userWally); assertNotNull("User wally was not created", userWally); @@ -931,9 +931,9 @@ public void test510AddDummyGreenAccountWallyUserTemplate() throws Exception { assertUser(userWally, userWallyOid, ACCOUNT_WALLY_DUMMY_USERNAME, "Wally Feed", null, "Wally Feed from Sync"); assertLinks(userWally, 1); assertLinked(userWally, accountWallyGreen); - + assertUsers(7 + getNumberOfExtraDummyUsers()); - + // sync = ResourceTypeUtil.determineSynchronization(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME).asObjectable(), UserType.class); // if (sync != null){ // sync.setObjectTemplateRef(null); @@ -953,7 +953,7 @@ public void test600AddDummyGreenAccountCalypso() throws Exception { OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); - + // Preconditions assertUsers(7 + getNumberOfExtraDummyUsers()); @@ -961,31 +961,31 @@ public void test600AddDummyGreenAccountCalypso() throws Exception { account.setEnabled(true); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Calypso"); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "The Seven Seas"); - + /// WHEN TestUtil.displayWhen(TEST_NAME); - + dummyResourceGreen.addAccount(account); - + waitForSyncTaskNextRunAssertSuccess(resourceDummyGreen); - + // THEN TestUtil.displayThen(TEST_NAME); - + PrismObject accountShadow = findAccountByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME, resourceDummyGreen); display("Account calypso", accountShadow); assertNotNull("No calypso account shadow", accountShadow); - assertEquals("Wrong resourceRef in calypso account", RESOURCE_DUMMY_GREEN_OID, + assertEquals("Wrong resourceRef in calypso account", RESOURCE_DUMMY_GREEN_OID, accountShadow.asObjectable().getResourceRef().getOid()); assertTrue("Calypso shadow is NOT protected", accountShadow.asObjectable().isProtectedObject()); - + PrismObject userCalypso = findUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); display("User calypso", userCalypso); assertNull("User calypso was created, it should not", userCalypso); - + assertUsers(7 + getNumberOfExtraDummyUsers()); } - + /** * Accounts starting with X are admin accounts (intent "admin"). Check if synchronization gets this right. */ @@ -999,7 +999,7 @@ public void test700AddDummyGreenAccountXjojo() throws Exception { OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); - + // Preconditions assertUsers(7 + getNumberOfExtraDummyUsers()); @@ -1007,33 +1007,33 @@ public void test700AddDummyGreenAccountXjojo() throws Exception { account.setEnabled(true); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Jojo the Monkey"); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Scabb Island"); - + /// WHEN TestUtil.displayWhen(TEST_NAME); - + dummyResourceGreen.addAccount(account); - + waitForSyncTaskNextRunAssertSuccess(resourceDummyGreen); - + // THEN TestUtil.displayThen(TEST_NAME); - + PrismObject accountAfter = findAccountByUsername("Xjojo", resourceDummyGreen); display("Account after", accountAfter); assertNotNull("No account shadow", accountAfter); - assertEquals("Wrong resourceRef in account shadow", RESOURCE_DUMMY_GREEN_OID, + assertEquals("Wrong resourceRef in account shadow", RESOURCE_DUMMY_GREEN_OID, accountAfter.asObjectable().getResourceRef().getOid()); assertShadowOperationalData(accountAfter, SynchronizationSituationType.LINKED); assertShadowKindIntent(accountAfter, ShadowKindType.ACCOUNT, "admin"); - + PrismObject userAfter = findUserByUsername("jojo"); display("User after", userAfter); assertNotNull("User jojo was not created", userAfter); assertLinks(userAfter, 1); assertAdministrativeStatusEnabled(userAfter); - + assertLinked(userAfter, accountAfter); - + assertUsers(8 + getNumberOfExtraDummyUsers()); // notifications @@ -1046,14 +1046,14 @@ public void test700AddDummyGreenAccountXjojo() throws Exception { // checkDummyTransportMessages("simpleUserNotifier", 1); // checkDummyTransportMessages("simpleUserNotifier-ADD", 1); } - + private void assumeUserTemplate(String templateOid, ResourceType resource, String syncConfigName, OperationResult result) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { SynchronizationType resourceSync = resource.getSynchronization(); resourceSync.getObjectSynchronization().get(0).setObjectTemplateRef(ObjectTypeUtil.createObjectRef(templateOid, ObjectTypes.OBJECT_TEMPLATE)); - + Collection refDelta = PropertyDelta.createModificationReplacePropertyCollection(ResourceType.F_SYNCHRONIZATION, resource.asPrismObject().getDefinition(), resourceSync); repositoryService.modifyObject(ResourceType.class, resource.getOid(), refDelta, result); - + ResourceType res = repositoryService.getObject(ResourceType.class, resource.getOid(), null, result).asObjectable(); assertNotNull(res); assertNotNull("Synchronization is not specified", res.getSynchronization()); @@ -1061,13 +1061,13 @@ private void assumeUserTemplate(String templateOid, ResourceType resource, Strin assertNotNull("object sync type is not specified", ost); assertNotNull("user template not specified", ost.getObjectTemplateRef()); assertEquals("Wrong user template in resource", templateOid, ost.getObjectTemplateRef().getOid()); - - } - + + } + protected void waitForSyncTaskStart(PrismObject resource) throws Exception { waitForTaskStart(getSyncTaskOid(resource), false, getWaitTimeout()); } - + protected OperationResult waitForSyncTaskNextRunAssertSuccess(PrismObject resource) throws Exception { return waitForTaskNextRunAssertSuccess(getSyncTaskOid(resource), false, getWaitTimeout()); } @@ -1080,39 +1080,39 @@ private PrismObject checkWallyAccount(PrismObject reso String expectedFullName) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException, ExpressionEvaluationException { return checkWallyAccount(resource, dummy, resourceDesc, expectedFullName, null, null); } - + 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 { PrismObject accountShadowWally = findAccountByUsername(ACCOUNT_WALLY_DUMMY_USERNAME, resource); display("Account shadow wally ("+resourceDesc+")", accountShadowWally); - assertEquals("Wrong resourceRef in wally account ("+resourceDesc+")", resource.getOid(), + 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); } - + DummyAccount dummyAccount = dummy.getAccountByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); display("Account wally ("+resourceDesc+")", dummyAccount); assertNotNull("No dummy account ("+resourceDesc+")", dummyAccount); if (expectedFullName != null) { - assertEquals("Wrong dummy account fullname ("+resourceDesc+")", expectedFullName, + 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, + 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, + assertEquals("Wrong dummy account quote ("+resourceDesc+")", quote, dummyAccount.getAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME)); } - + return accountShadowWally; } - + protected void rememberTimeBeforeSync() { timeBeforeSync = System.currentTimeMillis(); } 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 b0993d0428b..c89e7c1f5c1 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 @@ -105,36 +105,36 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestImportRecon extends AbstractInitializedModelIntegrationTest { - + private static final File TEST_DIR = new File("src/test/resources/sync"); - + private static final String ACCOUNT_OTIS_NAME = "otis"; private static final String ACCOUNT_OTIS_FULLNAME = "Otis"; - + private static final File ACCOUNT_STAN_FILE = new File(TEST_DIR, "account-stan-dummy.xml"); private static final String ACCOUNT_STAN_OID = "22220000-2200-0000-0000-444400004455"; private static final String ACCOUNT_STAN_NAME = "stan"; private static final String ACCOUNT_STAN_FULLNAME = "Stan the Salesman"; - + private static final String ACCOUNT_RUM_NAME = "rum"; - + private static final String ACCOUNT_MURRAY_NAME = "murray"; - + private static final String ACCOUNT_CAPSIZE_NAME = "capsize"; private static final String ACCOUNT_CAPSIZE_FULLNAME = "Kata Capsize"; - + private static final String USER_AUGUSTUS_NAME = "augustus"; private static final File ACCOUNT_AUGUSTUS_FILE = new File(TEST_DIR, "account-augustus-dummy.xml"); private static final String ACCOUNT_AUGUSTUS_OID = "22220000-2200-0000-0000-444400004457"; private static final String ACCOUNT_AUGUSTUS_NAME = "augustus"; private static final String ACCOUNT_AUGUSTUS_FULLNAME = "Augustus DeWaat"; - + private static final File ACCOUNT_TAUGUSTUS_FILE = new File(TEST_DIR, "account-taugustus-dummy.xml"); private static final String ACCOUNT_TAUGUSTUS_OID = "22220000-2200-0000-0000-444400004456"; private static final String ACCOUNT_TAUGUSTUS_NAME = "Taugustus"; private static final String ACCOUNT_TAUGUSTUS_FULLNAME = "Augustus DeWaat"; - + private static final File ACCOUNT_KENNY_FILE = new File(TEST_DIR, "account-kenny-dummy.xml"); private static final String ACCOUNT_KENNY_OID = "22220000-2200-0000-0000-444400004461"; private static final String ACCOUNT_KENNY_NAME = "kenny"; @@ -145,7 +145,7 @@ public class TestImportRecon extends AbstractInitializedModelIntegrationTest { private static final String ACCOUNT_TPALIDO_OID = "22220000-2200-0000-0000-444400004462"; private static final String ACCOUNT_TPALIDO_NAME = "Tpalido"; private static final String ACCOUNT_TPALIDO_FULLNAME = "Palido Domingo"; - + private static final File ACCOUNT_LECHIMP_FILE = new File(TEST_DIR, "account-lechimp-dummy.xml"); private static final String ACCOUNT_LECHIMP_OID = "22220000-2200-0000-0000-444400004463"; private static final String ACCOUNT_LECHIMP_NAME = "lechimp"; @@ -155,32 +155,32 @@ public class TestImportRecon extends AbstractInitializedModelIntegrationTest { private static final String ACCOUNT_TLECHIMP_OID = "22220000-2200-0000-0000-444400004464"; private static final String ACCOUNT_TLECHIMP_NAME = "Tlechimp"; private static final String ACCOUNT_TLECHIMP_FULLNAME = "Captain LeChimp"; - + private static final File ACCOUNT_ANDRE_FILE = new File(TEST_DIR, "account-andre-dummy.xml"); private static final String ACCOUNT_ANDRE_OID = "22220000-2200-0000-0000-444400004465"; private static final String ACCOUNT_ANDRE_NAME = "andre"; private static final String ACCOUNT_ANDRE_FULLNAME = "King Andre"; - + private static final File ACCOUNT_TANDRE_FILE = new File(TEST_DIR, "account-tandre-dummy.xml"); private static final String ACCOUNT_TANDRE_OID = "22220000-2200-0000-0000-444400004466"; private static final String ACCOUNT_TANDRE_NAME = "Tandre"; private static final String ACCOUNT_TANDRE_FULLNAME = "King Andre"; - + private static final String USER_LAFOOT_NAME = "lafoot"; private static final File ACCOUNT_TLAFOOT_FILE = new File(TEST_DIR, "account-tlafoot-dummy.xml"); private static final String ACCOUNT_TLAFOOT_OID = "22220000-2200-0000-0000-444400004467"; private static final String ACCOUNT_TLAFOOT_NAME = "Tlafoot"; private static final String ACCOUNT_TLAFOOT_FULLNAME = "Effete LaFoot"; - + private static final File ACCOUNT_CRUFF_FILE = new File(TEST_DIR, "account-cruff-dummy.xml"); private static final String ACCOUNT_CRUFF_OID = "22220000-2200-0000-0000-444400004468"; private static final String ACCOUNT_CRUFF_NAME = "cruff"; private static final String ACCOUNT_CRUFF_FULLNAME = "Cruff"; - + private static final String ACCOUNT_HTM_NAME = "htm"; private static final String ACCOUNT_HTM_FULL_NAME = "Horatio Torquemada Marley"; - // AZURE resource. It disables unmatched accounts. + // AZURE resource. It disables unmatched accounts. // It also has several objectType definitions that are designed to confuse // the code that determines refined schema definitions protected static final File RESOURCE_DUMMY_AZURE_FILE = new File(TEST_DIR, "resource-dummy-azure.xml"); @@ -188,7 +188,7 @@ public class TestImportRecon extends AbstractInitializedModelIntegrationTest { protected static final String RESOURCE_DUMMY_AZURE_OID = "10000000-0000-0000-0000-00000000a204"; protected static final String RESOURCE_DUMMY_AZURE_NAME = "azure"; protected static final String RESOURCE_DUMMY_AZURE_NAMESPACE = MidPointConstants.NS_RI; - + // LIME dummy resource. This is a pure authoritative resource. It has only inbound mappings. protected static final File RESOURCE_DUMMY_LIME_FILE = new File(TEST_DIR, "resource-dummy-lime.xml"); protected static final File RESOURCE_DUMMY_LIME_DEPRECATED_FILE = new File(TEST_DIR, "resource-dummy-lime-deprecated.xml"); @@ -198,13 +198,13 @@ public class TestImportRecon extends AbstractInitializedModelIntegrationTest { protected static final File USER_TEMPLATE_LIME_FILE = new File(TEST_DIR, "user-template-lime.xml"); protected static final String USER_TEMPLACE_LIME_OID = "3cf43520-241d-11e6-afa5-a377b674950d"; - + private static final File ROLE_CORPSE_FILE = new File(TEST_DIR, "role-corpse.xml"); private static final String ROLE_CORPSE_OID = "1c64c778-e7ac-11e5-b91a-9f44177e2359"; - + protected static final File PASSWORD_POLICY_LOWER_CASE_ALPHA_AZURE_FILE = new File(TEST_DIR, "password-policy-azure.xml"); protected static final String PASSWORD_POLICY_LOWER_CASE_ALPHA_AZURE_OID = "81818181-76e0-59e2-8888-3d4f02d3fffd"; - + protected static final File TASK_RECONCILE_DUMMY_SINGLE_FILE = new File(TEST_DIR, "task-reconcile-dummy-single.xml"); protected static final String TASK_RECONCILE_DUMMY_SINGLE_OID = "10000000-0000-0000-5656-565600000004"; @@ -213,7 +213,7 @@ public class TestImportRecon extends AbstractInitializedModelIntegrationTest { protected static final File TASK_RECONCILE_DUMMY_LIME_FILE = new File(TEST_DIR, "task-reconcile-dummy-lime.xml"); protected static final String TASK_RECONCILE_DUMMY_LIME_OID = "10000000-0000-0000-5656-565600131204"; - + protected static final File TASK_DELETE_DUMMY_SHADOWS_FILE = new File(TEST_DIR, "task-delete-dummy-shadows.xml"); protected static final String TASK_DELETE_DUMMY_SHADOWS_OID = "abaab842-18be-11e5-9416-001e8c717e5b"; @@ -223,7 +223,7 @@ public class TestImportRecon extends AbstractInitializedModelIntegrationTest { private static final String GROUP_CORPSES_NAME = "corpses"; private static final String ACCOUNT_CAPSIZE_PASSWORD = "is0mud01d"; - + @Autowired(required = true) private ValuePolicyProcessor valuePolicyProcessor; @@ -231,7 +231,7 @@ public class TestImportRecon extends AbstractInitializedModelIntegrationTest { protected DummyResourceContoller dummyResourceCtlAzure; protected ResourceType resourceDummyAzureType; protected PrismObject resourceDummyAzure; - + protected DummyResource dummyResourceLime; protected DummyResourceContoller dummyResourceCtlLime; protected ResourceType resourceDummyLimeType; @@ -239,71 +239,71 @@ public class TestImportRecon extends AbstractInitializedModelIntegrationTest { @Autowired(required=true) private ReconciliationTaskHandler reconciliationTaskHandler; - + private DebugReconciliationTaskResultListener reconciliationTaskResultListener; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + reconciliationTaskResultListener = new DebugReconciliationTaskResultListener(); reconciliationTaskHandler.setReconciliationTaskResultListener(reconciliationTaskResultListener); - + dummyResourceCtlAzure = DummyResourceContoller.create(RESOURCE_DUMMY_AZURE_NAME, resourceDummyAzure); dummyResourceCtlAzure.extendSchemaPirate(); dummyResourceCtlAzure.addOrgTop(); dummyResourceAzure = dummyResourceCtlAzure.getDummyResource(); - resourceDummyAzure = importAndGetObjectFromFile(ResourceType.class, getDummyResourceAzureFile(), RESOURCE_DUMMY_AZURE_OID, initTask, initResult); + resourceDummyAzure = importAndGetObjectFromFile(ResourceType.class, getDummyResourceAzureFile(), RESOURCE_DUMMY_AZURE_OID, initTask, initResult); resourceDummyAzureType = resourceDummyAzure.asObjectable(); - dummyResourceCtlAzure.setResource(resourceDummyAzure); - + dummyResourceCtlAzure.setResource(resourceDummyAzure); + dummyResourceCtlLime = DummyResourceContoller.create(RESOURCE_DUMMY_LIME_NAME, resourceDummyLime); dummyResourceCtlLime.extendSchemaPirate(); dummyResourceLime = dummyResourceCtlLime.getDummyResource(); - resourceDummyLime = importAndGetObjectFromFile(ResourceType.class, getDummyResourceLimeFile(), RESOURCE_DUMMY_LIME_OID, initTask, initResult); + resourceDummyLime = importAndGetObjectFromFile(ResourceType.class, getDummyResourceLimeFile(), RESOURCE_DUMMY_LIME_OID, initTask, initResult); resourceDummyLimeType = resourceDummyLime.asObjectable(); dummyResourceCtlLime.setResource(resourceDummyLime); - + // 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"); - + dummyResourceCtlLime.addAccount(USER_RAPP_USERNAME, USER_RAPP_FULLNAME, "Scabb Island"); dummyResourceLime.getAccountByUsername(USER_RAPP_USERNAME) .replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "The Elaine"); dummyResourceCtlLime.addAccount(ACCOUNT_RUM_NAME, "Rum Rogers"); dummyResourceCtlLime.addAccount(ACCOUNT_MURRAY_NAME, "Murray"); - + // Groups dummyResourceCtlAzure.addGroup(GROUP_CORPSES_NAME); - + // Roles repoAddObjectFromFile(ROLE_CORPSE_FILE, initResult); - + // Password policy repoAddObjectFromFile(PASSWORD_POLICY_GLOBAL_FILE, initResult); repoAddObjectFromFile(PASSWORD_POLICY_LOWER_CASE_ALPHA_AZURE_FILE, initResult); - + applyPasswordPolicy(PASSWORD_POLICY_GLOBAL_OID, SECURITY_POLICY_OID, initTask, initResult); - + // Object templates repoAddObjectFromFile(USER_TEMPLATE_LIME_FILE, initResult); - + // And a user that will be correlated to that account repoAddObjectFromFile(USER_RAPP_FILE, initResult); - + PrismObject accountStan = PrismTestUtil.parseObject(ACCOUNT_STAN_FILE); provisioningService.addObject(accountStan, null, null, initTask, initResult); - + addObject(SHADOW_GROUP_DUMMY_TESTERS_FILE, initTask, initResult); - + InternalMonitor.reset(); InternalMonitor.setTrace(InternalOperationClasses.SHADOW_FETCH_OPERATIONS, true); - + // DebugUtil.setDetailedDebugDump(true); } - + protected File getDummyResourceLimeFile() { return RESOURCE_DUMMY_LIME_FILE; } @@ -311,26 +311,26 @@ protected File getDummyResourceLimeFile() { protected File getDummyResourceAzureFile() { return RESOURCE_DUMMY_AZURE_FILE; } - + @Test public void test001SanityAzure() throws Exception { final String TEST_NAME = "test001SanityAzure"; displayTestTitle(TEST_NAME); display("Dummy resource azure", dummyResourceAzure); - + // WHEN ResourceSchema resourceSchemaAzure = RefinedResourceSchemaImpl.getResourceSchema(resourceDummyAzureType, prismContext); - + display("Dummy azure resource schema", resourceSchemaAzure); - + // THEN dummyResourceCtlAzure.assertDummyResourceSchemaSanityExtended(resourceSchemaAzure); - + ObjectClassComplexTypeDefinition orgOcDef = resourceSchemaAzure.findObjectClassDefinition(dummyResourceCtlAzure.getOrgObjectClassQName()); assertNotNull("No org object class def in azure resource schema", orgOcDef); } - + @Test public void test002SanityAzureRefined() throws Exception { final String TEST_NAME = "test002SanityAzureRefined"; @@ -338,12 +338,12 @@ public void test002SanityAzureRefined() throws Exception { // WHEN RefinedResourceSchema refinedSchemaAzure = RefinedResourceSchemaImpl.getRefinedSchema(resourceDummyAzureType, prismContext); - + display("Dummy azure refined schema", refinedSchemaAzure); - + // THEN dummyResourceCtlAzure.assertRefinedSchemaSanity(refinedSchemaAzure); - + ObjectClassComplexTypeDefinition orgOcDef = refinedSchemaAzure.findObjectClassDefinition(dummyResourceCtlAzure.getOrgObjectClassQName()); assertNotNull("No org object class def in azure refined schema", orgOcDef); } @@ -357,37 +357,37 @@ public void test100ImportStanFromResourceDummy() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + // Preconditions assertUsers(6); dummyAuditService.clear(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN displayWhen(TEST_NAME); modelService.importFromResource(ACCOUNT_STAN_OID, task, result); - + // THEN displayThen(TEST_NAME); display(result); assertSuccess(result); - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); assertImportedUserByOid(USER_BARBOSSA_OID); assertImportedUserByOid(USER_GUYBRUSH_OID, RESOURCE_DUMMY_OID); PrismObject userStan = assertImportedUserByUsername(ACCOUNT_STAN_NAME, RESOURCE_DUMMY_OID); - + // These are protected accounts, they should not be imported assertNoImporterUserByUsername(ACCOUNT_DAVIEJONES_DUMMY_USERNAME); assertNoImporterUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); - + assertUsers(7); - + assertPasswordCompliesWithPolicy(userStan, PASSWORD_POLICY_GLOBAL_OID); // MID-4028 - + // Check audit assertImportAuditModifications(1); @@ -402,40 +402,40 @@ public void test150ImportFromResourceDummy() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + // Preconditions List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users before import", users); assertEquals("Unexpected number of users", 7, users.size()); - + PrismObject rapp = getUser(USER_RAPP_OID); assertNotNull("No rapp", rapp); // Rapp has dummy account but it is not linked assertLinks(rapp, 0); - + dummyAuditService.clear(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN displayWhen(TEST_NAME); modelService.importFromResource(RESOURCE_DUMMY_OID, new QName(RESOURCE_DUMMY_NAMESPACE, "AccountObjectClass"), task, result); - + // THEN displayThen(TEST_NAME); OperationResult subresult = result.getLastSubresult(); TestUtil.assertInProgress("importAccountsFromResource result", subresult); - + waitForTaskFinish(task, true, 40000); - + // THEN displayThen(TEST_NAME); TestUtil.assertSuccess(task.getResult()); - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 3); - + users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after import", users); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); assertImportedUserByOid(USER_BARBOSSA_OID); @@ -443,22 +443,22 @@ public void test150ImportFromResourceDummy() throws Exception { assertImportedUserByOid(USER_RAPP_OID, RESOURCE_DUMMY_OID); assertImportedUserByUsername(ACCOUNT_HERMAN_DUMMY_USERNAME, RESOURCE_DUMMY_OID); assertImportedUserByUsername(ACCOUNT_STAN_NAME, RESOURCE_DUMMY_OID); - + // These are protected accounts, they should not be imported assertNoImporterUserByUsername(ACCOUNT_DAVIEJONES_DUMMY_USERNAME); assertNoImporterUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); - + PrismObject userRappAfter = getUser(USER_RAPP_OID); display("User rapp after", userRappAfter); - PrismAsserts.assertPropertyValue(userRappAfter, UserType.F_ORGANIZATIONAL_UNIT, + PrismAsserts.assertPropertyValue(userRappAfter, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of The Elaine")); - + assertEquals("Unexpected number of users", 8, users.size()); - + // Check audit assertImportAuditModifications(4); } - + @Test public void test155ImportFromResourceDummyAgain() throws Exception { final String TEST_NAME = "test155ImportFromResourceDummyAgain"; @@ -470,27 +470,27 @@ public void test155ImportFromResourceDummyAgain() throws Exception { assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); dummyAuditService.clear(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN displayWhen(TEST_NAME); modelService.importFromResource(RESOURCE_DUMMY_OID, new QName(RESOURCE_DUMMY_NAMESPACE, "AccountObjectClass"), task, result); - + // THEN displayThen(TEST_NAME); OperationResult subresult = result.getLastSubresult(); TestUtil.assertInProgress("importAccountsFromResource result", subresult); - + waitForTaskFinish(task, true, 40000); - + // THEN displayThen(TEST_NAME); assertSuccess(task.getResult()); - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 3); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after import", users); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); assertImportedUserByOid(USER_BARBOSSA_OID); @@ -498,22 +498,22 @@ public void test155ImportFromResourceDummyAgain() throws Exception { assertImportedUserByOid(USER_RAPP_OID, RESOURCE_DUMMY_OID); assertImportedUserByUsername(ACCOUNT_HERMAN_DUMMY_USERNAME, RESOURCE_DUMMY_OID); assertImportedUserByUsername(ACCOUNT_STAN_NAME, RESOURCE_DUMMY_OID); - + // These are protected accounts, they should not be imported assertNoImporterUserByUsername(ACCOUNT_DAVIEJONES_DUMMY_USERNAME); assertNoImporterUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); - + PrismObject userRappAfter = getUser(USER_RAPP_OID); display("User rapp after", userRappAfter); - PrismAsserts.assertPropertyValue(userRappAfter, UserType.F_ORGANIZATIONAL_UNIT, + PrismAsserts.assertPropertyValue(userRappAfter, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of The Elaine")); - + assertEquals("Unexpected number of users", 8, users.size()); - + // Check audit assertImportAuditModifications(0); } - + @Test public void test160ImportFromResourceDummyLime() throws Exception { final String TEST_NAME = "test160ImportFromResourceDummyLime"; @@ -523,36 +523,36 @@ public void test160ImportFromResourceDummyLime() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + // Preconditions assertUsers(8); dummyAuditService.clear(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + display("Rapp lime account before", dummyResourceLime.getAccountByUsername(USER_RAPP_USERNAME)); - + PrismObject userRappBefore = getUser(USER_RAPP_OID); display("User rapp before", userRappBefore); - PrismAsserts.assertPropertyValue(userRappBefore, UserType.F_ORGANIZATIONAL_UNIT, + PrismAsserts.assertPropertyValue(userRappBefore, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of The Elaine")); - + // WHEN displayWhen(TEST_NAME); modelService.importFromResource(RESOURCE_DUMMY_LIME_OID, new QName(RESOURCE_DUMMY_LIME_NAMESPACE, "AccountObjectClass"), task, result); - + // THEN displayThen(TEST_NAME); OperationResult subresult = result.getLastSubresult(); TestUtil.assertInProgress("importAccountsFromResource result", subresult); - + waitForTaskFinish(task, true, 40000); - + // THEN displayThen(TEST_NAME); TestUtil.assertSuccess(task.getResult()); - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 2); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); assertImportedUserByOid(USER_BARBOSSA_OID); @@ -562,24 +562,24 @@ public void test160ImportFromResourceDummyLime() throws Exception { assertImportedUserByUsername(ACCOUNT_STAN_NAME, RESOURCE_DUMMY_OID); assertImportedUserByUsername(ACCOUNT_RUM_NAME, RESOURCE_DUMMY_LIME_OID); assertImportedUserByUsername(ACCOUNT_MURRAY_NAME, RESOURCE_DUMMY_LIME_OID); - + PrismObject userRappAfter = getUser(USER_RAPP_OID); display("User rapp after", userRappAfter); - PrismAsserts.assertPropertyValue(userRappAfter, UserType.F_ORGANIZATIONAL_UNIT, + PrismAsserts.assertPropertyValue(userRappAfter, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of The Elaine")); - + // These are protected accounts, they should not be imported assertNoImporterUserByUsername(ACCOUNT_DAVIEJONES_DUMMY_USERNAME); assertNoImporterUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); - + display("Rapp lime account after", dummyResourceLime.getAccountByUsername(USER_RAPP_USERNAME)); - + assertUsers(10); - + // Check audit assertImportAuditModifications(3); } - + /** * MID-2427 */ @@ -592,7 +592,7 @@ public void test162ImportFromResourceDummyLimeRappOrganizationScummBar() throws Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + DummyAccount accountRappLimeBefore = dummyResourceLime.getAccountByUsername(USER_RAPP_USERNAME); accountRappLimeBefore.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, ORG_SCUMM_BAR_NAME); @@ -602,7 +602,7 @@ public void test162ImportFromResourceDummyLimeRappOrganizationScummBar() throws PrismObject userRappBefore = getUser(USER_RAPP_OID); display("User rapp before", userRappBefore); - PrismAsserts.assertPropertyValue(userRappBefore, UserType.F_ORGANIZATIONAL_UNIT, + PrismAsserts.assertPropertyValue(userRappBefore, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of The Elaine")); assertNoAssignments(userRappBefore); @@ -613,20 +613,20 @@ public void test162ImportFromResourceDummyLimeRappOrganizationScummBar() throws // WHEN displayWhen(TEST_NAME); modelService.importFromResource(RESOURCE_DUMMY_LIME_OID, new QName(RESOURCE_DUMMY_LIME_NAMESPACE, "AccountObjectClass"), task, result); - + // THEN displayThen(TEST_NAME); OperationResult subresult = result.getLastSubresult(); TestUtil.assertInProgress("importAccountsFromResource result", subresult); - + waitForTaskFinish(task, true, 40000); - + // THEN displayThen(TEST_NAME); TestUtil.assertSuccess(task.getResult()); - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 2); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); assertImportedUserByOid(USER_BARBOSSA_OID); @@ -636,29 +636,29 @@ public void test162ImportFromResourceDummyLimeRappOrganizationScummBar() throws assertImportedUserByUsername(ACCOUNT_STAN_NAME, RESOURCE_DUMMY_OID); assertImportedUserByUsername(ACCOUNT_RUM_NAME, RESOURCE_DUMMY_LIME_OID); assertImportedUserByUsername(ACCOUNT_MURRAY_NAME, RESOURCE_DUMMY_LIME_OID); - + PrismObject userRappAfter = getUser(USER_RAPP_OID); display("User rapp after", userRappAfter); - PrismAsserts.assertPropertyValue(userRappAfter, UserType.F_ORGANIZATIONAL_UNIT, + PrismAsserts.assertPropertyValue(userRappAfter, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of The Elaine")); - PrismAsserts.assertPropertyValue(userRappAfter, UserType.F_ORGANIZATION, + PrismAsserts.assertPropertyValue(userRappAfter, UserType.F_ORGANIZATION, PrismTestUtil.createPolyString(ORG_SCUMM_BAR_NAME)); - + // These are protected accounts, they should not be imported assertNoImporterUserByUsername(ACCOUNT_DAVIEJONES_DUMMY_USERNAME); assertNoImporterUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); - + DummyAccount accountRappLimeAfter = dummyResourceLime.getAccountByUsername(USER_RAPP_USERNAME); display("Rapp lime account after", accountRappLimeAfter); assertAssignedOrg(userRappAfter, ORG_SCUMM_BAR_OID); assertAssignments(userRappAfter, 1); - + assertUsers(10); - + // Check audit assertImportAuditModifications(1); } - + /** * MID-2427 */ @@ -671,7 +671,7 @@ public void test164ImportFromResourceDummyLimeRappOrganizationNull() throws Exce Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + DummyAccount accountRappLimeBefore = dummyResourceLime.getAccountByUsername(USER_RAPP_USERNAME); accountRappLimeBefore.replaceAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME /* no value */); display("Rapp lime account before", accountRappLimeBefore); @@ -680,9 +680,9 @@ public void test164ImportFromResourceDummyLimeRappOrganizationNull() throws Exce PrismObject userRappBefore = getUser(USER_RAPP_OID); display("User rapp before", userRappBefore); - PrismAsserts.assertPropertyValue(userRappBefore, UserType.F_ORGANIZATIONAL_UNIT, + PrismAsserts.assertPropertyValue(userRappBefore, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of The Elaine")); - PrismAsserts.assertPropertyValue(userRappBefore, UserType.F_ORGANIZATION, + PrismAsserts.assertPropertyValue(userRappBefore, UserType.F_ORGANIZATION, PrismTestUtil.createPolyString(ORG_SCUMM_BAR_NAME)); assertAssignedOrg(userRappBefore, ORG_SCUMM_BAR_OID); assertAssignments(userRappBefore, 1); @@ -694,20 +694,20 @@ public void test164ImportFromResourceDummyLimeRappOrganizationNull() throws Exce // WHEN displayWhen(TEST_NAME); modelService.importFromResource(RESOURCE_DUMMY_LIME_OID, new QName(RESOURCE_DUMMY_LIME_NAMESPACE, "AccountObjectClass"), task, result); - + // THEN displayThen(TEST_NAME); OperationResult subresult = result.getLastSubresult(); TestUtil.assertInProgress("importAccountsFromResource result", subresult); - + waitForTaskFinish(task, true, 40000); - + // THEN displayThen(TEST_NAME); assertSuccess(task.getResult()); - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 2); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); assertImportedUserByOid(USER_BARBOSSA_OID); @@ -717,23 +717,23 @@ public void test164ImportFromResourceDummyLimeRappOrganizationNull() throws Exce assertImportedUserByUsername(ACCOUNT_STAN_NAME, RESOURCE_DUMMY_OID); assertImportedUserByUsername(ACCOUNT_RUM_NAME, RESOURCE_DUMMY_LIME_OID); assertImportedUserByUsername(ACCOUNT_MURRAY_NAME, RESOURCE_DUMMY_LIME_OID); - + PrismObject userRappAfter = getUser(USER_RAPP_OID); display("User rapp after", userRappAfter); - PrismAsserts.assertPropertyValue(userRappAfter, UserType.F_ORGANIZATIONAL_UNIT, + PrismAsserts.assertPropertyValue(userRappAfter, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of The Elaine")); PrismAsserts.assertNoItem(userRappAfter, UserType.F_ORGANIZATION); - + // These are protected accounts, they should not be imported assertNoImporterUserByUsername(ACCOUNT_DAVIEJONES_DUMMY_USERNAME); assertNoImporterUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); - + DummyAccount accountRappLimeAfter = dummyResourceLime.getAccountByUsername(USER_RAPP_USERNAME); display("Rapp lime account after", accountRappLimeAfter); assertNoAssignments(userRappAfter); - + assertUsers(10); - + // Check audit assertImportAuditModifications(1); } @@ -750,65 +750,65 @@ public void test200ReconcileDummy() throws Exception { // Lets do some local changes on dummy resource DummyAccount guybrushDummyAccount = getDummyResource().getAccountByUsername(ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - + // fullname has a normal outbound mapping, this change should NOT be corrected guybrushDummyAccount.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Dubrish Freepweed"); - + // location has strong outbound mapping, this change should be corrected guybrushDummyAccount.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "The Forbidded Dodecahedron"); - + // Weapon has a weak mapping, this change should be left as it is guybrushDummyAccount.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, "Feather duster"); - + // Drink is not tolerant. The extra values should be removed guybrushDummyAccount.addAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, "water"); // 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"); - + PrismObject userRappBefore = getUser(USER_RAPP_OID); display("User rapp before", userRappBefore); - PrismAsserts.assertPropertyValue(userRappBefore, UserType.F_ORGANIZATIONAL_UNIT, + PrismAsserts.assertPropertyValue(userRappBefore, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of The Elaine")); - + getDummyResource().purgeScriptHistory(); dummyAuditService.clear(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); reconciliationTaskResultListener.clear(); - + // WHEN displayWhen(TEST_NAME); importObjectFromFile(TASK_RECONCILE_DUMMY_SINGLE_FILE); - + // THEN displayThen(TEST_NAME); - + waitForTaskFinish(TASK_RECONCILE_DUMMY_OID, false); - + // THEN displayThen(TEST_NAME); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 4); - + reconciliationTaskResultListener.assertResult(RESOURCE_DUMMY_OID, 0, 7, 0, 0); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after import", users); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); assertImportedUserByOid(USER_BARBOSSA_OID); - + assertImportedUserByOid(USER_GUYBRUSH_OID, RESOURCE_DUMMY_OID); // Guybrushes fullname should NOT be corrected back to real fullname - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Dubrish Freepweed"); // Guybrushes location should be corrected back to real value - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Melee Island"); // Guybrushes weapon should be left untouched assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, @@ -817,15 +817,15 @@ public void test200ReconcileDummy() throws Exception { assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, "rum"); // Guybrushes quotes should be left untouched - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "Arr!", "I want to be a pirate!"); - + assertImportedUserByOid(USER_RAPP_OID, RESOURCE_DUMMY_OID, RESOURCE_DUMMY_LIME_OID); PrismObject userRappAfter = getUser(USER_RAPP_OID); display("User rapp after", userRappAfter); - PrismAsserts.assertPropertyValue(userRappAfter, UserType.F_ORGANIZATIONAL_UNIT, + PrismAsserts.assertPropertyValue(userRappAfter, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of The Elaine")); - + assertImportedUserByUsername(ACCOUNT_HERMAN_DUMMY_USERNAME, RESOURCE_DUMMY_OID); // These are protected accounts, they should not be imported @@ -834,13 +834,13 @@ public void test200ReconcileDummy() throws Exception { // Calypso is protected account. Reconciliation should not touch it assertDummyAccountAttribute(null, ACCOUNT_CALYPSO_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Calypso"); - + assertEquals("Unexpected number of users", 10, users.size()); - + display("Dummy resource", getDummyResource().debugDump()); - + display("Script history", getDummyResource().getScriptHistory()); - + ArrayList scripts = new ArrayList(); addReconScripts(scripts, ACCOUNT_HERMAN_DUMMY_USERNAME, "Herman Toothrot", false); addReconScripts(scripts, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood", true); @@ -848,9 +848,9 @@ public void test200ReconcileDummy() throws Exception { addReconScripts(scripts, USER_RAPP_USERNAME, USER_RAPP_FULLNAME, false); addReconScripts(scripts, ACCOUNT_STAN_NAME, ACCOUNT_STAN_FULLNAME, false); IntegrationTestTools.assertScripts(getDummyResource().getScriptHistory(), scripts.toArray(new ProvisioningScriptSpec[0])); - + assertReconAuditModifications(1, TASK_RECONCILE_DUMMY_OID); - + // Task result PrismObject reconTaskAfter = getTask(TASK_RECONCILE_DUMMY_OID); OperationResultType reconTaskResult = reconTaskAfter.asObjectable().getResult(); @@ -865,68 +865,68 @@ public void test210ReconcileDummyBroken() throws Exception { // GIVEN Task task = createTask(TEST_NAME); - OperationResult result = task.getResult(); + OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - // Lets do some local changes on dummy resource ... + // Lets do some local changes on dummy resource ... DummyAccount guybrushDummyAccount = getDummyResource().getAccountByUsername(ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - + // location has strong outbound mapping, this change should be corrected guybrushDummyAccount.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Phatt Island"); - + // BREAK it! getDummyResource().setBreakMode(BreakMode.NETWORK); getDummyResource().purgeScriptHistory(); dummyAuditService.clear(); reconciliationTaskResultListener.clear(); - + // WHEN displayWhen(TEST_NAME); restartTask(TASK_RECONCILE_DUMMY_OID); waitForTaskFinish(TASK_RECONCILE_DUMMY_OID, false, DEFAULT_TASK_WAIT_TIMEOUT, true); - + // THEN displayThen(TEST_NAME); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after reconciliation (broken resource)", users); - + // Total error in the recon process. No reasonable result here. // reconciliationTaskResultListener.assertResult(RESOURCE_DUMMY_OID, 0, 7, 1, 0); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); assertImportedUserByOid(USER_BARBOSSA_OID); - assertImportedUserByOid(USER_GUYBRUSH_OID, RESOURCE_DUMMY_OID); + assertImportedUserByOid(USER_GUYBRUSH_OID, RESOURCE_DUMMY_OID); assertImportedUserByOid(USER_RAPP_OID, RESOURCE_DUMMY_OID, RESOURCE_DUMMY_LIME_OID); assertImportedUserByUsername(ACCOUNT_HERMAN_DUMMY_USERNAME, RESOURCE_DUMMY_OID); assertNoImporterUserByUsername(ACCOUNT_DAVIEJONES_DUMMY_USERNAME); assertNoImporterUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); - + assertEquals("Unexpected number of users", 10, users.size()); - + display("Dummy resource", getDummyResource().debugDump()); - + display("Script history", getDummyResource().getScriptHistory()); - + // no scripts IntegrationTestTools.assertScripts(getDummyResource().getScriptHistory()); - + // Task result PrismObject reconTaskAfter = getTask(TASK_RECONCILE_DUMMY_OID); OperationResultType reconTaskResult = reconTaskAfter.asObjectable().getResult(); display("Recon task result", reconTaskResult); TestUtil.assertFailure(reconTaskResult); - + // Check audit display("Audit", dummyAuditService); - + dummyAuditService.assertRecords(2); dummyAuditService.assertExecutionOutcome(OperationResultStatus.FATAL_ERROR); dummyAuditService.assertExecutionMessage(); } - + /** * Simply re-run recon after the resource is fixed. This should correct the data. */ @@ -939,7 +939,7 @@ public void test219ReconcileDummyFixed() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + // Fix it! getDummyResource().setBreakMode(BreakMode.NONE); @@ -947,21 +947,21 @@ public void test219ReconcileDummyFixed() throws Exception { dummyAuditService.clear(); reconciliationTaskResultListener.clear(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN displayWhen(TEST_NAME); restartTask(TASK_RECONCILE_DUMMY_OID); waitForTaskFinish(TASK_RECONCILE_DUMMY_OID, false, DEFAULT_TASK_WAIT_TIMEOUT, true); - + // THEN displayThen(TEST_NAME); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 4); - + reconciliationTaskResultListener.assertResult(RESOURCE_DUMMY_OID, 0, 7, 0, 0); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after import", users); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); assertImportedUserByOid(USER_BARBOSSA_OID); @@ -976,20 +976,20 @@ public void test219ReconcileDummyFixed() throws Exception { "rum"); assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "Arr!", "I want to be a pirate!"); - + assertImportedUserByOid(USER_RAPP_OID, RESOURCE_DUMMY_OID, RESOURCE_DUMMY_LIME_OID); assertImportedUserByUsername(ACCOUNT_HERMAN_DUMMY_USERNAME, RESOURCE_DUMMY_OID); assertNoImporterUserByUsername(ACCOUNT_DAVIEJONES_DUMMY_USERNAME); assertNoImporterUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); - assertDummyAccountAttribute(null, ACCOUNT_CALYPSO_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, + assertDummyAccountAttribute(null, ACCOUNT_CALYPSO_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Calypso"); - + assertEquals("Unexpected number of users", 10, users.size()); - + display("Dummy resource", getDummyResource().debugDump()); - + display("Script history", getDummyResource().getScriptHistory()); - + ArrayList scripts = new ArrayList(); addReconScripts(scripts, ACCOUNT_HERMAN_DUMMY_USERNAME, "Herman Toothrot", false); addReconScripts(scripts, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood", true); @@ -997,16 +997,16 @@ public void test219ReconcileDummyFixed() throws Exception { addReconScripts(scripts, USER_RAPP_USERNAME, USER_RAPP_FULLNAME, false); addReconScripts(scripts, ACCOUNT_STAN_NAME, ACCOUNT_STAN_FULLNAME, false); IntegrationTestTools.assertScripts(getDummyResource().getScriptHistory(), scripts.toArray(new ProvisioningScriptSpec[0])); - + assertReconAuditModifications(1, TASK_RECONCILE_DUMMY_OID); - + // Task result PrismObject reconTaskAfter = getTask(TASK_RECONCILE_DUMMY_OID); OperationResultType reconTaskResult = reconTaskAfter.asObjectable().getResult(); display("Recon task result", reconTaskResult); TestUtil.assertSuccess(reconTaskResult); } - + /** * The resource itself works, just the guybrush account is broken. */ @@ -1017,15 +1017,15 @@ public void test220ReconcileDummyBrokenGuybrush() throws Exception { // GIVEN Task task = createTask(TEST_NAME); - OperationResult result = task.getResult(); + OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - // Lets do some local changes on dummy resource ... + // Lets do some local changes on dummy resource ... DummyAccount guybrushDummyAccount = getDummyResource().getAccountByUsername(ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - + // location has strong outbound mapping, this change should be corrected guybrushDummyAccount.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Forbidden Dodecahedron"); - + // BREAK it! getDummyResource().setBreakMode(BreakMode.NONE); guybrushDummyAccount.setModifyBreakMode(BreakMode.NETWORK); @@ -1033,33 +1033,33 @@ public void test220ReconcileDummyBrokenGuybrush() throws Exception { getDummyResource().purgeScriptHistory(); dummyAuditService.clear(); reconciliationTaskResultListener.clear(); - + // WHEN displayWhen(TEST_NAME); restartTask(TASK_RECONCILE_DUMMY_OID); waitForTaskFinish(TASK_RECONCILE_DUMMY_OID, false, DEFAULT_TASK_WAIT_TIMEOUT, true); - + // THEN displayThen(TEST_NAME); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after reconciliation (broken resource)", users); - + reconciliationTaskResultListener.assertResult(RESOURCE_DUMMY_OID, 0, 7, 1, 0); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); assertImportedUserByOid(USER_BARBOSSA_OID); - assertImportedUserByOid(USER_GUYBRUSH_OID, RESOURCE_DUMMY_OID); + assertImportedUserByOid(USER_GUYBRUSH_OID, RESOURCE_DUMMY_OID); assertImportedUserByOid(USER_RAPP_OID, RESOURCE_DUMMY_OID, RESOURCE_DUMMY_LIME_OID); assertImportedUserByUsername(ACCOUNT_HERMAN_DUMMY_USERNAME, RESOURCE_DUMMY_OID); assertNoImporterUserByUsername(ACCOUNT_DAVIEJONES_DUMMY_USERNAME); assertNoImporterUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); - + assertEquals("Unexpected number of users", 10, users.size()); - + display("Dummy resource", getDummyResource().debugDump()); - + display("Script history", getDummyResource().getScriptHistory()); ArrayList scripts = new ArrayList(); addReconScripts(scripts, ACCOUNT_HERMAN_DUMMY_USERNAME, "Herman Toothrot", false); @@ -1069,14 +1069,14 @@ public void test220ReconcileDummyBrokenGuybrush() throws Exception { addReconScripts(scripts, USER_RAPP_USERNAME, USER_RAPP_FULLNAME, false); addReconScripts(scripts, ACCOUNT_STAN_NAME, ACCOUNT_STAN_FULLNAME, false); IntegrationTestTools.assertScripts(getDummyResource().getScriptHistory(), scripts.toArray(new ProvisioningScriptSpec[0])); - + // Task result PrismObject reconTaskAfter = getTask(TASK_RECONCILE_DUMMY_OID); OperationResultType reconTaskResult = reconTaskAfter.asObjectable().getResult(); display("Recon task result", reconTaskResult); TestUtil.assertStatus(reconTaskResult, OperationResultStatusType.PARTIAL_ERROR); assertTrue("Errors not mentioned in the task message", reconTaskResult.getMessage().contains("got 1 error")); - + // Check audit display("Audit", dummyAuditService); assertReconAuditModifications(1, TASK_RECONCILE_DUMMY_OID); @@ -1094,7 +1094,7 @@ public void test229ReconcileDummyFixed() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + // Fix it! getDummyResource().setBreakMode(BreakMode.NONE); getDummyResource().getAccountByUsername(ACCOUNT_GUYBRUSH_DUMMY_USERNAME).setModifyBreakMode(BreakMode.NONE); @@ -1103,54 +1103,54 @@ public void test229ReconcileDummyFixed() throws Exception { dummyAuditService.clear(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); reconciliationTaskResultListener.clear(); - + // WHEN displayWhen(TEST_NAME); restartTask(TASK_RECONCILE_DUMMY_OID); waitForTaskFinish(TASK_RECONCILE_DUMMY_OID, false, DEFAULT_TASK_WAIT_TIMEOUT, true); - + // THEN displayThen(TEST_NAME); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 4); - + reconciliationTaskResultListener.assertResult(RESOURCE_DUMMY_OID, 0, 7, 0, 0); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after import", users); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); assertImportedUserByOid(USER_BARBOSSA_OID); assertImportedUserByOid(USER_GUYBRUSH_OID, RESOURCE_DUMMY_OID); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Dubrish Freepweed"); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Melee Island"); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, "Feather duster"); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, "rum"); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "Arr!", "I want to be a pirate!"); - + assertImportedUserByOid(USER_RAPP_OID, RESOURCE_DUMMY_OID, RESOURCE_DUMMY_LIME_OID); PrismObject userRappAfter = getUser(USER_RAPP_OID); display("User rapp after", userRappAfter); - PrismAsserts.assertPropertyValue(userRappAfter, UserType.F_ORGANIZATIONAL_UNIT, + PrismAsserts.assertPropertyValue(userRappAfter, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of The Elaine")); - + assertImportedUserByUsername(ACCOUNT_HERMAN_DUMMY_USERNAME, RESOURCE_DUMMY_OID); assertNoImporterUserByUsername(ACCOUNT_DAVIEJONES_DUMMY_USERNAME); assertNoImporterUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); assertDummyAccountAttribute(null, ACCOUNT_CALYPSO_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Calypso"); - + assertEquals("Unexpected number of users", 10, users.size()); - + display("Dummy resource", getDummyResource().debugDump()); - + display("Script history", getDummyResource().getScriptHistory()); - + ArrayList scripts = new ArrayList(); addReconScripts(scripts, ACCOUNT_HERMAN_DUMMY_USERNAME, "Herman Toothrot", false); addReconScripts(scripts, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood", true); @@ -1158,9 +1158,9 @@ public void test229ReconcileDummyFixed() throws Exception { addReconScripts(scripts, USER_RAPP_USERNAME, USER_RAPP_FULLNAME, false); addReconScripts(scripts, ACCOUNT_STAN_NAME, ACCOUNT_STAN_FULLNAME, false); IntegrationTestTools.assertScripts(getDummyResource().getScriptHistory(), scripts.toArray(new ProvisioningScriptSpec[0])); - + assertReconAuditModifications(1, TASK_RECONCILE_DUMMY_OID); - + // Task result PrismObject reconTaskAfter = getTask(TASK_RECONCILE_DUMMY_OID); OperationResultType reconTaskResult = reconTaskAfter.asObjectable().getResult(); @@ -1180,67 +1180,67 @@ public void test230ReconcileDummyRename() throws Exception { getDummyResource().setBreakMode(BreakMode.NONE); getDummyResource().getAccountByUsername(ACCOUNT_GUYBRUSH_DUMMY_USERNAME).setModifyBreakMode(BreakMode.NONE); - + PrismObject userHerman = findUserByUsername(ACCOUNT_HERMAN_DUMMY_USERNAME); String hermanShadowOid = getSingleLinkOid(userHerman); - + assertShadows(14); getDummyResource().renameAccount(ACCOUNT_HERMAN_DUMMY_USERNAME, ACCOUNT_HERMAN_DUMMY_USERNAME, ACCOUNT_HTM_NAME); DummyAccount dummyAccountHtm = getDummyAccount(null, ACCOUNT_HTM_NAME); dummyAccountHtm.replaceAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, ACCOUNT_HTM_FULL_NAME); - + getDummyResource().purgeScriptHistory(); dummyAuditService.clear(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); reconciliationTaskResultListener.clear(); - + // WHEN displayWhen(TEST_NAME); restartTask(TASK_RECONCILE_DUMMY_OID); waitForTaskFinish(TASK_RECONCILE_DUMMY_OID, false, DEFAULT_TASK_WAIT_TIMEOUT, true); - + // THEN displayThen(TEST_NAME); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 4); - + reconciliationTaskResultListener.assertResult(RESOURCE_DUMMY_OID, 0, 7, 0, 1); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after import", users); - + assertImportedUserByUsername(ACCOUNT_HTM_NAME, RESOURCE_DUMMY_OID); assertImportedUserByUsername(ACCOUNT_HERMAN_DUMMY_USERNAME); // not deleted. reaction=unlink - + assertNoObject(ShadowType.class, hermanShadowOid, task, result); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); assertImportedUserByOid(USER_BARBOSSA_OID); assertImportedUserByOid(USER_GUYBRUSH_OID, RESOURCE_DUMMY_OID); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Dubrish Freepweed"); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME, "Melee Island"); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, "Feather duster"); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, "rum"); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "Arr!", "I want to be a pirate!"); - + assertImportedUserByOid(USER_RAPP_OID, RESOURCE_DUMMY_OID, RESOURCE_DUMMY_LIME_OID); assertNoImporterUserByUsername(ACCOUNT_DAVIEJONES_DUMMY_USERNAME); assertNoImporterUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); - assertDummyAccountAttribute(null, ACCOUNT_CALYPSO_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, + assertDummyAccountAttribute(null, ACCOUNT_CALYPSO_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Calypso"); - + assertEquals("Unexpected number of users", 11, users.size()); - + display("Dummy resource", getDummyResource().debugDump()); - + display("Script history", getDummyResource().getScriptHistory()); - + ArrayList scripts = new ArrayList(); addReconScripts(scripts, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood", false); addReconScripts(scripts, ACCOUNT_ELAINE_DUMMY_USERNAME, "Elaine Marley", false); @@ -1248,11 +1248,11 @@ public void test230ReconcileDummyRename() throws Exception { addReconScripts(scripts, ACCOUNT_STAN_NAME, ACCOUNT_STAN_FULLNAME, false); addReconScripts(scripts, ACCOUNT_HTM_NAME, ACCOUNT_HTM_FULL_NAME, true); IntegrationTestTools.assertScripts(getDummyResource().getScriptHistory(), scripts.toArray(new ProvisioningScriptSpec[0])); - + assertReconAuditModifications(2, TASK_RECONCILE_DUMMY_OID); // the second modification is unlink - + assertShadows(14); - + // Task result PrismObject reconTaskAfter = getTask(TASK_RECONCILE_DUMMY_OID); OperationResultType reconTaskResult = reconTaskAfter.asObjectable().getResult(); @@ -1263,14 +1263,14 @@ public void test230ReconcileDummyRename() throws Exception { private void addReconScripts(Collection scripts, String username, String fullName, boolean modified) { addReconScripts(scripts, username, fullName, modified, true); } - - private void addReconScripts(Collection scripts, String username, String fullName, + + private void addReconScripts(Collection scripts, String username, String fullName, boolean modified, boolean afterRecon) { // before recon ProvisioningScriptSpec script = new ProvisioningScriptSpec("The vorpal blade went snicker-snack!"); script.addArgSingle("who", username); scripts.add(script); - + if (modified) { script = new ProvisioningScriptSpec("Beware the Jabberwock, my son!"); script.addArgSingle("howMuch", null); @@ -1279,7 +1279,7 @@ private void addReconScripts(Collection scripts, String script.addArgSingle("whatchacallit", fullName); scripts.add(script); } - + if (afterRecon) { // after recon script = new ProvisioningScriptSpec("He left it dead, and with its head"); @@ -1287,7 +1287,7 @@ private void addReconScripts(Collection scripts, String scripts.add(script); } } - + /** * Create illegal (non-correlable) account. See that it is disabled. */ @@ -1302,60 +1302,60 @@ public void test300ReconcileDummyAzureAddAccountOtis() throws Exception { assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); getDummyResource().setBreakMode(BreakMode.NONE); dummyResourceAzure.setBreakMode(BreakMode.NONE); - + // Create some illegal account dummyResourceCtlAzure.addAccount(ACCOUNT_OTIS_NAME, ACCOUNT_OTIS_FULLNAME); display("Otis account before", dummyResourceAzure.getAccountByUsername(ACCOUNT_OTIS_NAME)); - + dummyResourceAzure.purgeScriptHistory(); dummyAuditService.clear(); reconciliationTaskResultListener.clear(); - + // WHEN displayWhen(TEST_NAME); importObjectFromFile(TASK_RECONCILE_DUMMY_AZURE_FILE); - + // THEN displayThen(TEST_NAME); - + waitForTaskFinish(TASK_RECONCILE_DUMMY_AZURE_OID, false); - + displayThen(TEST_NAME); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after reconcile", users); - + reconciliationTaskResultListener.assertResult(RESOURCE_DUMMY_AZURE_OID, 0, 1, 0, 0); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); - assertImportedUserByOid(USER_BARBOSSA_OID); + assertImportedUserByOid(USER_BARBOSSA_OID); assertImportedUserByOid(USER_RAPP_OID, RESOURCE_DUMMY_OID, RESOURCE_DUMMY_LIME_OID); assertImportedUserByUsername(ACCOUNT_HERMAN_DUMMY_USERNAME); assertImportedUserByUsername(ACCOUNT_HTM_NAME, RESOURCE_DUMMY_OID); - + // Otis assertNoImporterUserByUsername(ACCOUNT_OTIS_NAME); display("Otis account after", dummyResourceAzure.getAccountByUsername(ACCOUNT_OTIS_NAME)); assertDummyAccount(RESOURCE_DUMMY_AZURE_NAME, ACCOUNT_OTIS_NAME, ACCOUNT_OTIS_FULLNAME, false); - + // These are protected accounts, they should not be imported assertNoImporterUserByUsername(ACCOUNT_DAVIEJONES_DUMMY_USERNAME); assertNoImporterUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); // Calypso is protected account. Reconciliation should not touch it - assertDummyAccountAttribute(null, ACCOUNT_CALYPSO_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, + assertDummyAccountAttribute(null, ACCOUNT_CALYPSO_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Calypso"); - - - assertEquals("Unexpected number of users", 11, users.size()); - + + + assertEquals("Unexpected number of users", 11, users.size()); + display("Dummy resource (azure)", dummyResourceAzure.debugDump()); - + assertReconAuditModifications(1, TASK_RECONCILE_DUMMY_AZURE_OID); - + assertShadows(16); } - + @Test public void test310ReconcileDummyAzureAgain() throws Exception { final String TEST_NAME = "test310ReconcileDummyAzureAgain"; @@ -1367,62 +1367,62 @@ public void test310ReconcileDummyAzureAgain() throws Exception { assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); getDummyResource().setBreakMode(BreakMode.NONE); dummyResourceAzure.setBreakMode(BreakMode.NONE); - + PrismObject reconTask = getTask(TASK_RECONCILE_DUMMY_AZURE_OID); display("Recon task", reconTask); - + dummyResourceAzure.purgeScriptHistory(); dummyAuditService.clear(); reconciliationTaskResultListener.clear(); - + // WHEN displayWhen(TEST_NAME); restartTask(TASK_RECONCILE_DUMMY_AZURE_OID); - + // THEN displayThen(TEST_NAME); - + waitForTaskFinish(TASK_RECONCILE_DUMMY_AZURE_OID, false); - + displayThen(TEST_NAME); reconciliationTaskResultListener.assertResult(RESOURCE_DUMMY_AZURE_OID, 0, 1, 0, 0); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after reconcile", users); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); - assertImportedUserByOid(USER_BARBOSSA_OID); + assertImportedUserByOid(USER_BARBOSSA_OID); assertImportedUserByOid(USER_RAPP_OID, RESOURCE_DUMMY_OID, RESOURCE_DUMMY_LIME_OID); 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); - + PrismObject userRappAfter = getUser(USER_RAPP_OID); display("User rapp after", userRappAfter); - PrismAsserts.assertPropertyValue(userRappAfter, UserType.F_ORGANIZATIONAL_UNIT, + PrismAsserts.assertPropertyValue(userRappAfter, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of The Elaine")); - + // These are protected accounts, they should not be imported assertNoImporterUserByUsername(ACCOUNT_DAVIEJONES_DUMMY_USERNAME); assertNoImporterUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); // Calypso is protected account. Reconciliation should not touch it assertDummyAccountAttribute(null, ACCOUNT_CALYPSO_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Calypso"); - + assertEquals("Unexpected number of users", 11, users.size()); - + display("Dummy resource (azure)", dummyResourceAzure.debugDump()); - + assertReconAuditModifications(0, TASK_RECONCILE_DUMMY_AZURE_OID); - + assertShadows(16); } - + @Test public void test320ReconcileDummyAzureDeleteOtis() throws Exception { final String TEST_NAME = "test320ReconcileDummyAzureDeleteOtis"; @@ -1434,58 +1434,58 @@ public void test320ReconcileDummyAzureDeleteOtis() throws Exception { assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); getDummyResource().setBreakMode(BreakMode.NONE); dummyResourceAzure.setBreakMode(BreakMode.NONE); - + assertShadows(16); - + PrismObject otisShadow = findShadowByName(ShadowKindType.ACCOUNT, SchemaConstants.INTENT_DEFAULT, ACCOUNT_OTIS_NAME, resourceDummyAzure, result); - + dummyResourceAzure.deleteAccountByName(ACCOUNT_OTIS_NAME); - + dummyResourceAzure.purgeScriptHistory(); dummyAuditService.clear(); reconciliationTaskResultListener.clear(); - + // WHEN displayWhen(TEST_NAME); restartTask(TASK_RECONCILE_DUMMY_AZURE_OID); - + // THEN displayThen(TEST_NAME); - + waitForTaskFinish(TASK_RECONCILE_DUMMY_AZURE_OID, false); - + displayThen(TEST_NAME); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after reconcile", users); - + reconciliationTaskResultListener.assertResult(RESOURCE_DUMMY_AZURE_OID, 0, 0, 0, 1); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); - assertImportedUserByOid(USER_BARBOSSA_OID); + assertImportedUserByOid(USER_BARBOSSA_OID); assertImportedUserByOid(USER_RAPP_OID, RESOURCE_DUMMY_OID, RESOURCE_DUMMY_LIME_OID); assertImportedUserByUsername(ACCOUNT_HERMAN_DUMMY_USERNAME); assertImportedUserByUsername(ACCOUNT_HTM_NAME, RESOURCE_DUMMY_OID); - + // Otis assertNoImporterUserByUsername(ACCOUNT_OTIS_NAME); assertNoDummyAccount(RESOURCE_DUMMY_AZURE_NAME, ACCOUNT_OTIS_NAME); - + // These are protected accounts, they should not be imported assertNoImporterUserByUsername(ACCOUNT_DAVIEJONES_DUMMY_USERNAME); assertNoImporterUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); // Calypso is protected account. Reconciliation should not touch it - assertDummyAccountAttribute(null, ACCOUNT_CALYPSO_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, + assertDummyAccountAttribute(null, ACCOUNT_CALYPSO_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Calypso"); - + assertNoObject(ShadowType.class, otisShadow.getOid(), task, result); assertShadows(15); - + assertEquals("Unexpected number of users", 11, users.size()); - + display("Dummy resource (azure)", dummyResourceAzure.debugDump()); - + assertReconAuditModifications(0, TASK_RECONCILE_DUMMY_AZURE_OID); } @@ -1504,86 +1504,86 @@ public void test330ReconcileDummyAzureAddAccountRapp() throws Exception { assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); getDummyResource().setBreakMode(BreakMode.NONE); dummyResourceAzure.setBreakMode(BreakMode.NONE); - + dummyResourceCtlAzure.addAccount(USER_RAPP_USERNAME, USER_RAPP_FULLNAME); display("Rapp azure account before", dummyResourceAzure.getAccountByUsername(USER_RAPP_USERNAME)); - + PrismObject userRappBefore = getUser(USER_RAPP_OID); display("User rapp before", userRappBefore); - PrismAsserts.assertPropertyValue(userRappBefore, UserType.F_ORGANIZATIONAL_UNIT, + PrismAsserts.assertPropertyValue(userRappBefore, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of The Elaine")); - + dummyResourceAzure.purgeScriptHistory(); dummyAuditService.clear(); reconciliationTaskResultListener.clear(); - + // WHEN displayWhen(TEST_NAME); restartTask(TASK_RECONCILE_DUMMY_AZURE_OID); - + // THEN displayThen(TEST_NAME); - + waitForTaskFinish(TASK_RECONCILE_DUMMY_AZURE_OID, false); - + displayThen(TEST_NAME); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after reconcile", users); - + reconciliationTaskResultListener.assertResult(RESOURCE_DUMMY_AZURE_OID, 0, 1, 0, 0); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); - assertImportedUserByOid(USER_BARBOSSA_OID); + assertImportedUserByOid(USER_BARBOSSA_OID); assertImportedUserByUsername(ACCOUNT_HERMAN_DUMMY_USERNAME); assertImportedUserByUsername(ACCOUNT_HTM_NAME, RESOURCE_DUMMY_OID); - + // Rapp display("Rapp azure account after", dummyResourceAzure.getAccountByUsername(USER_RAPP_USERNAME)); assertImportedUserByOid(USER_RAPP_OID, RESOURCE_DUMMY_OID, RESOURCE_DUMMY_LIME_OID, RESOURCE_DUMMY_AZURE_OID); assertDummyAccount(RESOURCE_DUMMY_AZURE_NAME, USER_RAPP_USERNAME, USER_RAPP_FULLNAME, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_AZURE_NAME, USER_RAPP_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_AZURE_NAME, USER_RAPP_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "The crew of The Elaine"); - + //Checking password policy PrismObject userRapp = findUserByUsername(USER_RAPP_USERNAME); assertNotNull("No user Rapp", userRapp); UserType userTypeRapp = userRapp.asObjectable(); - + assertNotNull("User Rapp has no credentials", userTypeRapp.getCredentials()); PasswordType password = userTypeRapp.getCredentials().getPassword(); assertNotNull("User Rapp has no password", password); - + ProtectedStringType passwordType = password.getValue(); - + String stringPassword = null; if (passwordType.getClearValue() == null) { stringPassword = protector.decryptString(passwordType); } - + assertNotNull("No clear text password", stringPassword); - + PrismObject passwordPolicy = getObjectViaRepo(ValuePolicyType.class, PASSWORD_POLICY_LOWER_CASE_ALPHA_AZURE_OID); - + boolean isPasswordValid = valuePolicyProcessor.validateValue(stringPassword, passwordPolicy.asObjectable(), userRapp, TEST_NAME, task, result); - assertTrue("Password doesn't satisfy password policy, generated password: " + stringPassword, isPasswordValid); - + assertTrue("Password doesn't satisfy password policy, generated password: " + stringPassword, isPasswordValid); + // These are protected accounts, they should not be imported assertNoImporterUserByUsername(ACCOUNT_DAVIEJONES_DUMMY_USERNAME); assertNoImporterUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); // Calypso is protected account. Reconciliation should not touch it - assertDummyAccountAttribute(null, ACCOUNT_CALYPSO_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, + assertDummyAccountAttribute(null, ACCOUNT_CALYPSO_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Calypso"); - + assertEquals("Unexpected number of users", 11, users.size()); - + display("Dummy resource (azure)", dummyResourceAzure.debugDump()); - + assertReconAuditModifications(1, TASK_RECONCILE_DUMMY_AZURE_OID); } - + /** * Make a repository modification of the user Rapp. Run recon. See that the * account is modified. @@ -1599,74 +1599,74 @@ public void test332ModifyUserRappAndReconcileDummyAzure() throws Exception { assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); getDummyResource().setBreakMode(BreakMode.NONE); dummyResourceAzure.setBreakMode(BreakMode.NONE); - + display("Rapp azure account before", dummyResourceAzure.getAccountByUsername(USER_RAPP_USERNAME)); - assertDummyAccountAttribute(RESOURCE_DUMMY_AZURE_NAME, USER_RAPP_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_AZURE_NAME, USER_RAPP_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "The crew of The Elaine"); - + PrismObject userRappBefore = getUser(USER_RAPP_OID); display("User rapp before", userRappBefore); - PrismAsserts.assertPropertyValue(userRappBefore, UserType.F_ORGANIZATIONAL_UNIT, + PrismAsserts.assertPropertyValue(userRappBefore, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of The Elaine")); - ObjectDelta userRappDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_RAPP_OID, + ObjectDelta userRappDelta = ObjectDelta.createModificationReplaceProperty(UserType.class, USER_RAPP_OID, UserType.F_ORGANIZATIONAL_UNIT, prismContext, PrismTestUtil.createPolyString("The six feet under crew")); repositoryService.modifyObject(UserType.class, USER_RAPP_OID, userRappDelta.getModifications(), result); - + userRappBefore = getUser(USER_RAPP_OID); display("User rapp before (modified)", userRappBefore); - PrismAsserts.assertPropertyValue(userRappBefore, UserType.F_ORGANIZATIONAL_UNIT, + PrismAsserts.assertPropertyValue(userRappBefore, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The six feet under crew")); - + dummyResourceAzure.purgeScriptHistory(); dummyAuditService.clear(); reconciliationTaskResultListener.clear(); - + // WHEN displayWhen(TEST_NAME); restartTask(TASK_RECONCILE_DUMMY_AZURE_OID); - + // THEN displayThen(TEST_NAME); - + waitForTaskFinish(TASK_RECONCILE_DUMMY_AZURE_OID, false); - + displayThen(TEST_NAME); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after reconcile", users); - + reconciliationTaskResultListener.assertResult(RESOURCE_DUMMY_AZURE_OID, 0, 1, 0, 0); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); - assertImportedUserByOid(USER_BARBOSSA_OID); + assertImportedUserByOid(USER_BARBOSSA_OID); assertImportedUserByUsername(ACCOUNT_HERMAN_DUMMY_USERNAME); assertImportedUserByUsername(ACCOUNT_HTM_NAME, RESOURCE_DUMMY_OID); - + // Rapp display("Rapp azure account after", dummyResourceAzure.getAccountByUsername(USER_RAPP_USERNAME)); assertImportedUserByOid(USER_RAPP_OID, RESOURCE_DUMMY_OID, RESOURCE_DUMMY_LIME_OID, RESOURCE_DUMMY_AZURE_OID); assertDummyAccount(RESOURCE_DUMMY_AZURE_NAME, USER_RAPP_USERNAME, USER_RAPP_FULLNAME, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_AZURE_NAME, USER_RAPP_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_AZURE_NAME, USER_RAPP_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "The six feet under crew"); - + // These are protected accounts, they should not be imported assertNoImporterUserByUsername(ACCOUNT_DAVIEJONES_DUMMY_USERNAME); assertNoImporterUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); // Calypso is protected account. Reconciliation should not touch it - assertDummyAccountAttribute(null, ACCOUNT_CALYPSO_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, + assertDummyAccountAttribute(null, ACCOUNT_CALYPSO_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Calypso"); - + assertEquals("Unexpected number of users", 11, users.size()); - + display("Dummy resource (azure)", dummyResourceAzure.debugDump()); - + assertReconAuditModifications(2, TASK_RECONCILE_DUMMY_AZURE_OID); } - + /** - * Make a repository modification of the user Rapp: assign role corpse. + * Make a repository modification of the user Rapp: assign role corpse. * Run recon. See that the account is modified (added to group). * There is associationTargetSearch expression in the role. Make sure that the * search is done properly (has baseContext). @@ -1682,64 +1682,64 @@ public void test334AssignRoleCorpseToRappAndReconcileDummyAzure() throws Excepti assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); getDummyResource().setBreakMode(BreakMode.NONE); dummyResourceAzure.setBreakMode(BreakMode.NONE); - + display("Rapp azure account before", dummyResourceAzure.getAccountByUsername(USER_RAPP_USERNAME)); assertNoDummyGroupMember(RESOURCE_DUMMY_AZURE_NAME, GROUP_CORPSES_NAME, USER_RAPP_USERNAME); - - ObjectDelta userRappDelta = createAssignmentUserDelta(USER_RAPP_OID, ROLE_CORPSE_OID, + + ObjectDelta userRappDelta = createAssignmentUserDelta(USER_RAPP_OID, ROLE_CORPSE_OID, RoleType.COMPLEX_TYPE, null, null, true); repositoryService.modifyObject(UserType.class, USER_RAPP_OID, userRappDelta.getModifications(), result); - + PrismObject userRappBefore = getUser(USER_RAPP_OID); display("User rapp before (modified)", userRappBefore); - + dummyResourceAzure.purgeScriptHistory(); dummyAuditService.clear(); reconciliationTaskResultListener.clear(); - + // WHEN displayWhen(TEST_NAME); restartTask(TASK_RECONCILE_DUMMY_AZURE_OID); - + // THEN displayThen(TEST_NAME); - + waitForTaskFinish(TASK_RECONCILE_DUMMY_AZURE_OID, false); - + displayThen(TEST_NAME); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after reconcile", users); - + reconciliationTaskResultListener.assertResult(RESOURCE_DUMMY_AZURE_OID, 0, 1, 0, 0); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); - assertImportedUserByOid(USER_BARBOSSA_OID); + assertImportedUserByOid(USER_BARBOSSA_OID); assertImportedUserByUsername(ACCOUNT_HERMAN_DUMMY_USERNAME); assertImportedUserByUsername(ACCOUNT_HTM_NAME, RESOURCE_DUMMY_OID); - + // Rapp display("Rapp azure account after", dummyResourceAzure.getAccountByUsername(USER_RAPP_USERNAME)); assertImportedUserByOid(USER_RAPP_OID, RESOURCE_DUMMY_OID, RESOURCE_DUMMY_LIME_OID, RESOURCE_DUMMY_AZURE_OID); assertDummyAccount(RESOURCE_DUMMY_AZURE_NAME, USER_RAPP_USERNAME, USER_RAPP_FULLNAME, true); assertDummyGroupMember(RESOURCE_DUMMY_AZURE_NAME, GROUP_CORPSES_NAME, USER_RAPP_USERNAME); - + // These are protected accounts, they should not be imported assertNoImporterUserByUsername(ACCOUNT_DAVIEJONES_DUMMY_USERNAME); assertNoImporterUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); // Calypso is protected account. Reconciliation should not touch it - assertDummyAccountAttribute(null, ACCOUNT_CALYPSO_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, + assertDummyAccountAttribute(null, ACCOUNT_CALYPSO_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Calypso"); - + assertEquals("Unexpected number of users", 11, users.size()); - + display("Dummy resource (azure)", dummyResourceAzure.debugDump()); - + assertReconAuditModifications(1, TASK_RECONCILE_DUMMY_AZURE_OID); } - - + + @Test public void test339ReconcileDummyAzureDeleteRapp() throws Exception { final String TEST_NAME = "test339ReconcileDummyAzureDeleteRapp"; @@ -1751,70 +1751,70 @@ public void test339ReconcileDummyAzureDeleteRapp() throws Exception { assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); getDummyResource().setBreakMode(BreakMode.NONE); dummyResourceAzure.setBreakMode(BreakMode.NONE); - + assertShadows(17); - + // Remove the assignment. It may do bad things later. - ObjectDelta userRappDelta = createAssignmentUserDelta(USER_RAPP_OID, ROLE_CORPSE_OID, + ObjectDelta userRappDelta = createAssignmentUserDelta(USER_RAPP_OID, ROLE_CORPSE_OID, RoleType.COMPLEX_TYPE, null, null, false); repositoryService.modifyObject(UserType.class, USER_RAPP_OID, userRappDelta.getModifications(), result); - - PrismObject rappShadow = findShadowByName(ShadowKindType.ACCOUNT, + + PrismObject rappShadow = findShadowByName(ShadowKindType.ACCOUNT, SchemaConstants.INTENT_DEFAULT, USER_RAPP_USERNAME, resourceDummyAzure, result); - + dummyResourceAzure.deleteAccountByName(USER_RAPP_USERNAME); - + dummyResourceAzure.purgeScriptHistory(); dummyAuditService.clear(); reconciliationTaskResultListener.clear(); - + // WHEN displayWhen(TEST_NAME); restartTask(TASK_RECONCILE_DUMMY_AZURE_OID); - + // THEN displayThen(TEST_NAME); - + waitForTaskFinish(TASK_RECONCILE_DUMMY_AZURE_OID, false); - + displayThen(TEST_NAME); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after reconcile", users); - + reconciliationTaskResultListener.assertResult(RESOURCE_DUMMY_AZURE_OID, 0, 0, 0, 1); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); - assertImportedUserByOid(USER_BARBOSSA_OID); + assertImportedUserByOid(USER_BARBOSSA_OID); assertImportedUserByOid(USER_RAPP_OID, RESOURCE_DUMMY_OID, RESOURCE_DUMMY_LIME_OID); assertImportedUserByUsername(ACCOUNT_HERMAN_DUMMY_USERNAME); assertImportedUserByUsername(ACCOUNT_HTM_NAME, RESOURCE_DUMMY_OID); - + // Rapp assertNoImporterUserByUsername(ACCOUNT_OTIS_NAME); assertNoDummyAccount(RESOURCE_DUMMY_AZURE_NAME, USER_RAPP_USERNAME); - + assertNoDummyAccount(RESOURCE_DUMMY_AZURE_NAME, ACCOUNT_OTIS_NAME); // These are protected accounts, they should not be imported assertNoImporterUserByUsername(ACCOUNT_DAVIEJONES_DUMMY_USERNAME); assertNoImporterUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); // Calypso is protected account. Reconciliation should not touch it - assertDummyAccountAttribute(null, ACCOUNT_CALYPSO_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, + assertDummyAccountAttribute(null, ACCOUNT_CALYPSO_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Calypso"); - + assertNoObject(ShadowType.class, rappShadow.getOid(), task, result); assertShadows(16); - + assertEquals("Unexpected number of users", 11, users.size()); - + display("Dummy resource (azure)", dummyResourceAzure.debugDump()); - + // deleting linkRef assertReconAuditModifications(1, TASK_RECONCILE_DUMMY_AZURE_OID); } - + @Test public void test400ReconcileDummyLimeAddAccount() throws Exception { final String TEST_NAME = "test400ReconcileDummyLimeAddAccount"; @@ -1824,51 +1824,51 @@ public void test400ReconcileDummyLimeAddAccount() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + // Create some illegal account DummyAccount accountKate = dummyResourceCtlLime.addAccount(ACCOUNT_CAPSIZE_NAME, ACCOUNT_CAPSIZE_FULLNAME); accountKate.setPassword(ACCOUNT_CAPSIZE_PASSWORD); - + dummyResourceLime.purgeScriptHistory(); dummyAuditService.clear(); reconciliationTaskResultListener.clear(); - + // WHEN displayWhen(TEST_NAME); importObjectFromFile(TASK_RECONCILE_DUMMY_LIME_FILE); - + // THEN displayThen(TEST_NAME); - + waitForTaskFinish(TASK_RECONCILE_DUMMY_LIME_OID, false); - + displayThen(TEST_NAME); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after reconcile", users); - + reconciliationTaskResultListener.assertResult(RESOURCE_DUMMY_LIME_OID, 0, 4, 0, 0); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); - assertImportedUserByOid(USER_BARBOSSA_OID); + assertImportedUserByOid(USER_BARBOSSA_OID); assertImportedUserByOid(USER_RAPP_OID, RESOURCE_DUMMY_OID, RESOURCE_DUMMY_LIME_OID); assertImportedUserByUsername(ACCOUNT_HERMAN_DUMMY_USERNAME); assertImportedUserByUsername(ACCOUNT_HTM_NAME, RESOURCE_DUMMY_OID); - + // Kate Capsize: user should be created assertImportedUserByUsername(ACCOUNT_CAPSIZE_NAME, RESOURCE_DUMMY_LIME_OID); PrismObject userAfter = findUserByUsername(ACCOUNT_CAPSIZE_NAME); assertPassword(userAfter, ACCOUNT_CAPSIZE_PASSWORD); - + assertEquals("Unexpected number of users", 12, users.size()); - + display("Dummy resource (lime)", dummyResourceLime.debugDump()); - + // Audit record structure is somehow complex here. // assertReconAuditModifications(4, TASK_RECONCILE_DUMMY_LIME_OID); } - + @Test public void test401ReconcileDummyLimeKateOnlyEmpty() throws Exception { final String TEST_NAME = "test401ReconcileDummyLimeKateOnlyEmpty"; @@ -1878,31 +1878,31 @@ public void test401ReconcileDummyLimeKateOnlyEmpty() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + DummyAccount accountKate = dummyResourceLime.getAccountByUsername(ACCOUNT_CAPSIZE_NAME); accountKate.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, ""); - + PrismObject userBefore = findUserByUsername(ACCOUNT_CAPSIZE_NAME); PrismAsserts.assertNoItem(userBefore, UserType.F_COST_CENTER); - + dummyResourceLime.purgeScriptHistory(); dummyAuditService.clear(); reconciliationTaskResultListener.clear(); - + // WHEN displayWhen(TEST_NAME); reconcileUser(userBefore.getOid(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = findUserByUsername(ACCOUNT_CAPSIZE_NAME); display("User after reconcile", userAfter); - + PrismAsserts.assertPropertyValue(userAfter, UserType.F_COST_CENTER, ""); - + display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -1912,13 +1912,13 @@ public void test401ReconcileDummyLimeKateOnlyEmpty() throws Exception { PrismAsserts.assertModifications(dummyAuditService.getExecutionDelta(0).getObjectDelta(), 4); dummyAuditService.assertTarget(userBefore.getOid()); dummyAuditService.assertExecutionSuccess(); - + assertUsers(12); - - display("Dummy resource (lime)", dummyResourceLime.debugDump()); + + display("Dummy resource (lime)", dummyResourceLime.debugDump()); } - - + + @Test public void test402ReconcileDummyLimeKateOnlyGrog() throws Exception { final String TEST_NAME = "test402ReconcileDummyLimeKateOnlyGrog"; @@ -1928,30 +1928,30 @@ public void test402ReconcileDummyLimeKateOnlyGrog() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + DummyAccount accountKate = dummyResourceLime.getAccountByUsername(ACCOUNT_CAPSIZE_NAME); accountKate.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, "grog"); - + PrismObject userBefore = findUserByUsername(ACCOUNT_CAPSIZE_NAME); - + dummyResourceLime.purgeScriptHistory(); dummyAuditService.clear(); reconciliationTaskResultListener.clear(); - + // WHEN displayWhen(TEST_NAME); reconcileUser(userBefore.getOid(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = findUserByUsername(ACCOUNT_CAPSIZE_NAME); display("User after reconcile", userAfter); - + PrismAsserts.assertPropertyValue(userAfter, UserType.F_COST_CENTER, "grog"); - + display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -1961,12 +1961,12 @@ public void test402ReconcileDummyLimeKateOnlyGrog() throws Exception { PrismAsserts.assertModifications(dummyAuditService.getExecutionDelta(0).getObjectDelta(), 4); dummyAuditService.assertTarget(userBefore.getOid()); dummyAuditService.assertExecutionSuccess(); - + assertUsers(12); - - display("Dummy resource (lime)", dummyResourceLime.debugDump()); + + display("Dummy resource (lime)", dummyResourceLime.debugDump()); } - + @Test public void test403ReconcileDummyLimeKateOnlyNoValue() throws Exception { final String TEST_NAME = "test403ReconcileDummyLimeKateOnlyNoValue"; @@ -1976,31 +1976,31 @@ public void test403ReconcileDummyLimeKateOnlyNoValue() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + DummyAccount accountKate = dummyResourceLime.getAccountByUsername(ACCOUNT_CAPSIZE_NAME); accountKate.replaceAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME); - display("Dummy resource (lime)", dummyResourceLime.debugDump()); - + display("Dummy resource (lime)", dummyResourceLime.debugDump()); + PrismObject userBefore = findUserByUsername(ACCOUNT_CAPSIZE_NAME); - + dummyResourceLime.purgeScriptHistory(); dummyAuditService.clear(); reconciliationTaskResultListener.clear(); - + // WHEN displayWhen(TEST_NAME); reconcileUser(userBefore.getOid(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = findUserByUsername(ACCOUNT_CAPSIZE_NAME); display("User after reconcile", userAfter); - + PrismAsserts.assertNoItem(userAfter, UserType.F_COST_CENTER); - + display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -2010,10 +2010,10 @@ public void test403ReconcileDummyLimeKateOnlyNoValue() throws Exception { PrismAsserts.assertModifications(dummyAuditService.getExecutionDelta(0).getObjectDelta(), 4); dummyAuditService.assertTarget(userBefore.getOid()); dummyAuditService.assertExecutionSuccess(); - + assertUsers(12); } - + @Test public void test404ReconcileDummyLimeKateOnlyRum() throws Exception { final String TEST_NAME = "test404ReconcileDummyLimeKateOnlyRum"; @@ -2023,30 +2023,30 @@ public void test404ReconcileDummyLimeKateOnlyRum() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + DummyAccount accountKate = dummyResourceLime.getAccountByUsername(ACCOUNT_CAPSIZE_NAME); accountKate.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, "rum"); - + PrismObject userBefore = findUserByUsername(ACCOUNT_CAPSIZE_NAME); - + dummyResourceLime.purgeScriptHistory(); dummyAuditService.clear(); reconciliationTaskResultListener.clear(); - + // WHEN displayWhen(TEST_NAME); reconcileUser(userBefore.getOid(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = findUserByUsername(ACCOUNT_CAPSIZE_NAME); display("User after reconcile", userAfter); - + PrismAsserts.assertPropertyValue(userAfter, UserType.F_COST_CENTER, "rum"); - + display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -2056,12 +2056,12 @@ public void test404ReconcileDummyLimeKateOnlyRum() throws Exception { PrismAsserts.assertModifications(dummyAuditService.getExecutionDelta(0).getObjectDelta(), 4); dummyAuditService.assertTarget(userBefore.getOid()); dummyAuditService.assertExecutionSuccess(); - + assertUsers(12); - - display("Dummy resource (lime)", dummyResourceLime.debugDump()); + + display("Dummy resource (lime)", dummyResourceLime.debugDump()); } - + @Test public void test405ReconcileDummyLimeKateOnlyEmpty() throws Exception { final String TEST_NAME = "test405ReconcileDummyLimeKateOnlyEmpty"; @@ -2071,30 +2071,30 @@ public void test405ReconcileDummyLimeKateOnlyEmpty() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + DummyAccount accountKate = dummyResourceLime.getAccountByUsername(ACCOUNT_CAPSIZE_NAME); accountKate.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, ""); - + PrismObject userBefore = findUserByUsername(ACCOUNT_CAPSIZE_NAME); - + dummyResourceLime.purgeScriptHistory(); dummyAuditService.clear(); reconciliationTaskResultListener.clear(); - + // WHEN displayWhen(TEST_NAME); reconcileUser(userBefore.getOid(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = findUserByUsername(ACCOUNT_CAPSIZE_NAME); display("User after reconcile", userAfter); - + PrismAsserts.assertPropertyValue(userAfter, UserType.F_COST_CENTER, ""); - + display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -2104,12 +2104,12 @@ public void test405ReconcileDummyLimeKateOnlyEmpty() throws Exception { PrismAsserts.assertModifications(dummyAuditService.getExecutionDelta(0).getObjectDelta(), 4); dummyAuditService.assertTarget(userBefore.getOid()); dummyAuditService.assertExecutionSuccess(); - + assertUsers(12); - - display("Dummy resource (lime)", dummyResourceLime.debugDump()); + + display("Dummy resource (lime)", dummyResourceLime.debugDump()); } - + @Test public void test406ReconcileDummyLimeKateOnlyEmptyAgain() throws Exception { final String TEST_NAME = "test406ReconcileDummyLimeKateOnlyEmptyAgain"; @@ -2119,27 +2119,27 @@ public void test406ReconcileDummyLimeKateOnlyEmptyAgain() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + PrismObject userBefore = findUserByUsername(ACCOUNT_CAPSIZE_NAME); - + dummyResourceLime.purgeScriptHistory(); dummyAuditService.clear(); reconciliationTaskResultListener.clear(); - + // WHEN displayWhen(TEST_NAME); reconcileUser(userBefore.getOid(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = findUserByUsername(ACCOUNT_CAPSIZE_NAME); display("User after reconcile", userAfter); - + PrismAsserts.assertPropertyValue(userAfter, UserType.F_COST_CENTER, ""); - + display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -2147,12 +2147,12 @@ public void test406ReconcileDummyLimeKateOnlyEmptyAgain() throws Exception { dummyAuditService.assertExecutionDeltas(0); dummyAuditService.assertTarget(userBefore.getOid()); dummyAuditService.assertExecutionSuccess(); - + assertUsers(12); - - display("Dummy resource (lime)", dummyResourceLime.debugDump()); + + display("Dummy resource (lime)", dummyResourceLime.debugDump()); } - + @Test public void test410ReconcileDummyLimeKatePassword() throws Exception { final String TEST_NAME = "test410ReconcileDummyLimeKatePassword"; @@ -2162,30 +2162,30 @@ public void test410ReconcileDummyLimeKatePassword() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + DummyAccount accountKate = dummyResourceLime.getAccountByUsername(ACCOUNT_CAPSIZE_NAME); accountKate.setPassword("d0d3c4h3dr0n"); - + PrismObject userBefore = findUserByUsername(ACCOUNT_CAPSIZE_NAME); - + dummyResourceLime.purgeScriptHistory(); dummyAuditService.clear(); reconciliationTaskResultListener.clear(); - + // WHEN displayWhen(TEST_NAME); reconcileUser(userBefore.getOid(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = findUserByUsername(ACCOUNT_CAPSIZE_NAME); display("User after reconcile", userAfter); - + assertPassword(userAfter, "d0d3c4h3dr0n"); - + display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -2195,12 +2195,12 @@ public void test410ReconcileDummyLimeKatePassword() throws Exception { PrismAsserts.assertModifications(dummyAuditService.getExecutionDelta(0).getObjectDelta(), 7); dummyAuditService.assertTarget(userBefore.getOid()); dummyAuditService.assertExecutionSuccess(); - + assertUsers(12); - - display("Dummy resource (lime)", dummyResourceLime.debugDump()); + + display("Dummy resource (lime)", dummyResourceLime.debugDump()); } - + @Test public void test420ReconcileDummyLimeDeleteLinkedAccount() throws Exception { final String TEST_NAME = "test420ReconcileDummyLimeDeleteLinkedAccount"; @@ -2210,48 +2210,48 @@ public void test420ReconcileDummyLimeDeleteLinkedAccount() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + // Create some illegal account dummyResourceLime.deleteAccountByName(ACCOUNT_CAPSIZE_NAME); - + dummyResourceLime.purgeScriptHistory(); dummyAuditService.clear(); reconciliationTaskResultListener.clear(); - + // WHEN displayWhen(TEST_NAME); restartTask(TASK_RECONCILE_DUMMY_LIME_OID); - + // THEN displayThen(TEST_NAME); - + waitForTaskFinish(TASK_RECONCILE_DUMMY_LIME_OID, false); - + displayThen(TEST_NAME); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after reconcile", users); - + reconciliationTaskResultListener.assertResult(RESOURCE_DUMMY_LIME_OID, 0, 3, 0, 1); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); - assertImportedUserByOid(USER_BARBOSSA_OID); + assertImportedUserByOid(USER_BARBOSSA_OID); assertImportedUserByOid(USER_RAPP_OID, RESOURCE_DUMMY_OID, RESOURCE_DUMMY_LIME_OID); assertImportedUserByUsername(ACCOUNT_HERMAN_DUMMY_USERNAME); assertImportedUserByUsername(ACCOUNT_HTM_NAME, RESOURCE_DUMMY_OID); - + // Kate Capsize: user should be gone assertNoImporterUserByUsername(ACCOUNT_CAPSIZE_NAME); - + assertEquals("Unexpected number of users", 11, users.size()); - + display("Dummy resource (lime)", dummyResourceLime.debugDump()); - + // Audit record structure is somehow complex here. // assertReconAuditModifications(4, TASK_RECONCILE_DUMMY_LIME_OID); } - + /** * Imports a testing account (Taugustus) */ @@ -2264,57 +2264,57 @@ public void test500ImportTAugustusFromResourceDummy() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + PrismObject accountTaugustus = PrismTestUtil.parseObject(ACCOUNT_TAUGUSTUS_FILE); provisioningService.addObject(accountTaugustus, null, null, task, result); - + // Preconditions assertUsers(11); dummyAuditService.clear(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN displayWhen(TEST_NAME); modelService.importFromResource(ACCOUNT_TAUGUSTUS_OID, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); display(result); TestUtil.assertSuccess(result); - + // First fetch: import handler reading the account // Second fetch: fetchback to correctly process inbound (import changes the account). // assertShadowFetchOperationCountIncrement(2); - + // WHY??? assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); assertImportedUserByOid(USER_BARBOSSA_OID); assertImportedUserByOid(USER_GUYBRUSH_OID, RESOURCE_DUMMY_OID); assertImportedUserByUsername(ACCOUNT_STAN_NAME, RESOURCE_DUMMY_OID); PrismObject userAugustusAfter = assertImportedUserByUsername(USER_AUGUSTUS_NAME, RESOURCE_DUMMY_OID); - + // These are protected accounts, they should not be imported assertNoImporterUserByUsername(ACCOUNT_DAVIEJONES_DUMMY_USERNAME); assertNoImporterUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); - + assertUsers(12); - + assertShadowKindIntent(ACCOUNT_TAUGUSTUS_OID, ShadowKindType.ACCOUNT, INTENT_TEST); - + display("User augustus after", userAugustusAfter); assertLinks(userAugustusAfter, 1); - PrismAsserts.assertPropertyValue(userAugustusAfter, UserType.F_ORGANIZATIONAL_UNIT, + PrismAsserts.assertPropertyValue(userAugustusAfter, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of Titanicum Augusticum")); - + // Check audit assertImportAuditModifications(1); } - + /** * Imports a default account (augustus), it should be linked */ @@ -2327,61 +2327,61 @@ public void test502ImportAugustusFromResourceDummy() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + PrismObject userAugustusBefore = findUserByUsername(USER_AUGUSTUS_NAME); display("User augustus before", userAugustusBefore); - + PrismObject account = PrismTestUtil.parseObject(ACCOUNT_AUGUSTUS_FILE); provisioningService.addObject(account, null, null, task, result); display("Account augustus before", account); - + // Preconditions assertUsers(12); dummyAuditService.clear(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN displayWhen(TEST_NAME); modelService.importFromResource(ACCOUNT_AUGUSTUS_OID, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); display(result); TestUtil.assertSuccess(result); - + // First fetch: import handler reading the account // Second fetch: fetchback to correctly process inbound (import changes the account). // assertShadowFetchOperationCountIncrement(2); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); assertImportedUserByOid(USER_BARBOSSA_OID); assertImportedUserByOid(USER_GUYBRUSH_OID, RESOURCE_DUMMY_OID); assertImportedUserByUsername(ACCOUNT_STAN_NAME, RESOURCE_DUMMY_OID); PrismObject userAugustusAfter = assertImportedUserByUsername(USER_AUGUSTUS_NAME, RESOURCE_DUMMY_OID, RESOURCE_DUMMY_OID); - + // These are protected accounts, they should not be imported assertNoImporterUserByUsername(ACCOUNT_DAVIEJONES_DUMMY_USERNAME); assertNoImporterUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); - + assertUsers(12); - + assertShadowKindIntent(ACCOUNT_AUGUSTUS_OID, ShadowKindType.ACCOUNT, SchemaConstants.INTENT_DEFAULT); assertShadowKindIntent(ACCOUNT_TAUGUSTUS_OID, ShadowKindType.ACCOUNT, INTENT_TEST); - + display("User augustus after", userAugustusAfter); assertLinks(userAugustusAfter, 2); // Gives wrong results now. See MID-2532 -// PrismAsserts.assertPropertyValue(userAugustusAfter, UserType.F_ORGANIZATIONAL_UNIT, +// PrismAsserts.assertPropertyValue(userAugustusAfter, UserType.F_ORGANIZATIONAL_UNIT, // PrismTestUtil.createPolyString("The crew of Titanicum Augusticum"), // PrismTestUtil.createPolyString("The crew of Boatum Mailum")); - + // Check audit assertImportAuditModifications(1); } - + /** * This should import all the intents in the object class */ @@ -2394,10 +2394,10 @@ public void test510ImportFromResourceDummy() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + PrismObject account = PrismTestUtil.parseObject(ACCOUNT_KENNY_FILE); provisioningService.addObject(account, null, null, task, result); - + account = PrismTestUtil.parseObject(ACCOUNT_TPALIDO_FILE); provisioningService.addObject(account, null, null, task, result); @@ -2406,7 +2406,7 @@ public void test510ImportFromResourceDummy() throws Exception { account = PrismTestUtil.parseObject(ACCOUNT_TLECHIMP_FILE); provisioningService.addObject(account, null, null, task, result); - + account = PrismTestUtil.parseObject(ACCOUNT_ANDRE_FILE); provisioningService.addObject(account, null, null, task, result); @@ -2418,37 +2418,37 @@ public void test510ImportFromResourceDummy() throws Exception { account = PrismTestUtil.parseObject(ACCOUNT_CRUFF_FILE); provisioningService.addObject(account, null, null, task, result); - + // Preconditions assertUsers(12); dummyAuditService.clear(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN displayWhen(TEST_NAME); modelService.importFromResource(RESOURCE_DUMMY_OID, new QName(RESOURCE_DUMMY_NAMESPACE, "AccountObjectClass"), task, result); - + // THEN displayThen(TEST_NAME); OperationResult subresult = result.getLastSubresult(); TestUtil.assertInProgress("importAccountsFromResource result", subresult); - + waitForTaskFinish(task, true, 40000); - + // THEN displayThen(TEST_NAME); TestUtil.assertSuccess(task.getResult()); - + // First fetch: search in import handler // 6 fetches: fetchback to correctly process inbound (import changes the account). // The accounts are modified during import as there are also outbound mappings in // ther dummy resource. As the import is in fact just a recon the "fetchbacks" happens. // One is because of counting resource objects before importing them. // assertShadowFetchOperationCountIncrement(8); - + // WHY???? // assertShadowFetchOperationCountIncrement(4); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); assertImportedUserByOid(USER_BARBOSSA_OID); @@ -2464,17 +2464,17 @@ public void test510ImportFromResourceDummy() throws Exception { assertImportedUserByUsername(ACCOUNT_CRUFF_NAME, RESOURCE_DUMMY_OID); assertImportedUserByUsername(USER_LAFOOT_NAME, RESOURCE_DUMMY_OID); assertImportedUserByUsername(ACCOUNT_ANDRE_NAME, RESOURCE_DUMMY_OID, RESOURCE_DUMMY_OID); - + // These are protected accounts, they should not be imported assertNoImporterUserByUsername(ACCOUNT_DAVIEJONES_DUMMY_USERNAME); assertNoImporterUserByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); - + assertUsers(18); - + assertShadowKindIntent(ACCOUNT_AUGUSTUS_OID, ShadowKindType.ACCOUNT, SchemaConstants.INTENT_DEFAULT); assertShadowKindIntent(ACCOUNT_TAUGUSTUS_OID, ShadowKindType.ACCOUNT, INTENT_TEST); } - + @Test public void test600SearchAllDummyAccounts() throws Exception { final String TEST_NAME = "test600SearchAllDummyAccounts"; @@ -2483,24 +2483,24 @@ public void test600SearchAllDummyAccounts() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, new QName(RESOURCE_DUMMY_NAMESPACE, "AccountObjectClass"), prismContext); - + // WHEN displayWhen(TEST_NAME); SearchResultList> objects = modelService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + display("Found", objects); - + assertEquals("Wrong number of objects found", 17, objects.size()); } - + @Test public void test610SearchDummyAccountsNameSubstring() throws Exception { final String TEST_NAME = "test610SearchDummyAccountsNameSubstring"; @@ -2520,17 +2520,17 @@ public void test610SearchDummyAccountsNameSubstring() throws Exception { // WHEN displayWhen(TEST_NAME); SearchResultList> objects = modelService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + display("Found", objects); - + assertEquals("Wrong number of objects found", 6, objects.size()); } - + @Test public void test900DeleteDummyShadows() throws Exception { final String TEST_NAME = "test900DeleteDummyShadows"; @@ -2539,25 +2539,25 @@ public void test900DeleteDummyShadows() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // Preconditions assertUsers(18); dummyAuditService.clear(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN displayWhen(TEST_NAME); importObjectFromFile(TASK_DELETE_DUMMY_SHADOWS_FILE); - + // THEN displayThen(TEST_NAME); - + waitForTaskFinish(TASK_DELETE_DUMMY_SHADOWS_OID, true, 20000); - + // THEN displayThen(TEST_NAME); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + PrismObject deleteTask = getTask(TASK_DELETE_DUMMY_SHADOWS_OID); OperationResultType deleteTaskResultType = deleteTask.asObjectable().getResult(); display("Final delete task result", deleteTaskResultType); @@ -2570,13 +2570,13 @@ public void test900DeleteDummyShadows() throws Exception { TestUtil.assertSuccess(opExecResult); assertEquals("Wrong exec operation count", 17, opExecResult.getCount()); assertTrue("Too many subresults: "+deleteTaskResult.getSubresults().size(), deleteTaskResult.getSubresults().size() < 10); - + assertUsers(18); - + assertDummyAccountShadows(0, true, task, result); - assertDummyAccountShadows(17, false, task, result); + assertDummyAccountShadows(17, false, task, result); } - + @Test public void test910DeleteDummyAccounts() throws Exception { final String TEST_NAME = "test910DeleteDummyAccounts"; @@ -2585,25 +2585,25 @@ public void test910DeleteDummyAccounts() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // Preconditions assertUsers(18); dummyAuditService.clear(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN displayWhen(TEST_NAME); importObjectFromFile(TASK_DELETE_DUMMY_ACCOUNTS_FILE); - + // THEN displayThen(TEST_NAME); - + waitForTaskFinish(TASK_DELETE_DUMMY_ACCOUNTS_OID, true, 20000); - + // THEN displayThen(TEST_NAME); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 2); - + PrismObject deleteTask = getTask(TASK_DELETE_DUMMY_ACCOUNTS_OID); OperationResultType deleteTaskResultType = deleteTask.asObjectable().getResult(); display("Final delete task result", deleteTaskResultType); @@ -2616,17 +2616,17 @@ public void test910DeleteDummyAccounts() throws Exception { TestUtil.assertSuccess(opExecResult); assertEquals("Wrong exec operation count", 15, opExecResult.getCount()); assertTrue("Too many subresults: "+deleteTaskResult.getSubresults().size(), deleteTaskResult.getSubresults().size() < 10); - + assertUsers(18); - + assertDummyAccountShadows(2, true, task, result); // two protected accounts - assertDummyAccountShadows(2, false, task, result); + assertDummyAccountShadows(2, false, task, result); } - + private void assertDummyAccountShadows(int expected, boolean raw, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, new QName(RESOURCE_DUMMY_NAMESPACE, "AccountObjectClass"), prismContext); - + final MutableInt count = new MutableInt(0); ResultHandler handler = (shadow, parentResult) -> { count.increment(); @@ -2643,9 +2643,9 @@ private void assertDummyAccountShadows(int expected, boolean raw, Task task, Ope private void assertImportAuditModifications(int expectedModifications) { display("Audit", dummyAuditService); - + List auditRecords = dummyAuditService.getRecords(); - + int i=0; int modifications = 0; for (; i < (auditRecords.size() - 1); i+=2) { @@ -2653,16 +2653,16 @@ private void assertImportAuditModifications(int expectedModifications) { 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()); - + 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); @@ -2681,7 +2681,7 @@ private void assertImportAuditModifications(int expectedModifications) { private void assertReconAuditModifications(int expectedModifications, String taskOid) { // Check audit display("Audit", dummyAuditService); - + List auditRecords = dummyAuditService.getRecords(); Iterator iterator = auditRecords.iterator(); @@ -2718,7 +2718,7 @@ private void assertReconAuditModifications(int expectedModifications, String tas // end of audit records; break; } - + if (record.getEventStage() == AuditEventStage.REQUEST) { record = auditRecords.get(i); i++; @@ -2726,7 +2726,7 @@ record = auditRecords.get(i); assertNotNull("No execution audit record (" + i + ")", record); assertEquals("Got this instead of execution audit record (" + i + "): " + record, AuditEventStage.EXECUTION, record.getEventStage()); - + assertTrue("Empty deltas in execution audit record " + record, record.getDeltas() != null && !record.getDeltas().isEmpty()); modifications++; } @@ -2749,14 +2749,14 @@ private void assertImportedUserByOid(String userOid, String... resourceOids) thr 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); assertImportedUser(user, resourceOids); return user; } - + private void assertImportedUser(PrismObject user, String... resourceOids) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { assertLinks(user, resourceOids.length); for (String resourceOid: resourceOids) { diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestImportReconDeprecated.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestImportReconDeprecated.java index d1a0590b949..c43f9a065a0 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestImportReconDeprecated.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestImportReconDeprecated.java @@ -78,5 +78,5 @@ public void test900DeleteDummyShadows() throws Exception { public void test910DeleteDummyAccounts() throws Exception { // Not relevant for deprecated syntax } - + } 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 89962626b8a..5eedb3f193a 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 @@ -41,14 +41,14 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestInboundLiveSyncTask extends AbstractInboundSyncTest { - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - - dummyResourceEmerald.setSyncStyle(DummySyncStyle.SMART); + + dummyResourceEmerald.setSyncStyle(DummySyncStyle.SMART); } - + @Override protected void importSyncTask(PrismObject resource) throws FileNotFoundException { if (resource == resourceDummyEmerald) { @@ -66,7 +66,7 @@ protected String getSyncTaskOid(PrismObject resource) { throw new IllegalArgumentException("Unknown resource "+resource); } } - + @Override public void test199DeleteDummyEmeraldAccountMancomb() throws Exception { final String TEST_NAME = "test199DeleteDummyEmeraldAccountMancomb"; @@ -77,24 +77,24 @@ public void test199DeleteDummyEmeraldAccountMancomb() throws Exception { OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); - + // Preconditions assertUsers(6); /// WHEN TestUtil.displayWhen(TEST_NAME); - + dummyResourceEmerald.deleteAccountByName(ACCOUNT_MANCOMB_DUMMY_USERNAME); - + waitForSyncTaskNextRun(resourceDummyEmerald); - + // THEN TestUtil.displayThen(TEST_NAME); - + PrismObject accountMancomb = findAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME, resourceDummyEmerald); display("Account mancomb", accountMancomb); assertNull("Account shadow mancomb not gone", accountMancomb); - + PrismObject userMancomb = findUserByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); display("User mancomb", userMancomb); assertNotNull("User mancomb is gone", userMancomb); @@ -105,9 +105,9 @@ public void test199DeleteDummyEmeraldAccountMancomb() throws Exception { // assertNull("Unexpected valid to in user", userMancomb.asObjectable().getActivation().getValidTo()); assertValidFrom(userMancomb, ACCOUNT_MANCOMB_VALID_FROM_DATE); assertValidTo(userMancomb, ACCOUNT_MANCOMB_VALID_TO_DATE); - + assertNoDummyAccount(ACCOUNT_MANCOMB_DUMMY_USERNAME); - + assertUsers(6); // notifications diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestInboundLiveSyncTaskDeprecated.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestInboundLiveSyncTaskDeprecated.java index 649d9deaf94..fb368e175c4 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestInboundLiveSyncTaskDeprecated.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestInboundLiveSyncTaskDeprecated.java @@ -38,5 +38,5 @@ protected File getResourceDummyFile() { protected File getResourceDummyEmeraldFile() { return RESOURCE_DUMMY_EMERALD_DEPRECATED_FILE; } - + } 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 9cd23a51918..95fcbb791e7 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 @@ -43,17 +43,17 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestInboundReconTask extends AbstractInboundSyncTest { - + private static final Date ACCOUNT_MANCOMB_VALID_FROM_DATE = MiscUtil.asDate(2011, 2, 3, 4, 5, 6); private static final Date ACCOUNT_MANCOMB_VALID_TO_DATE = MiscUtil.asDate(2066, 5, 4, 3, 2, 1); - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - - dummyResourceEmerald.setSyncStyle(DummySyncStyle.DUMB); + + dummyResourceEmerald.setSyncStyle(DummySyncStyle.DUMB); } - + @Override protected void importSyncTask(PrismObject resource) throws FileNotFoundException { if (resource == resourceDummyEmerald) { @@ -125,24 +125,24 @@ public void test199DeleteDummyEmeraldAccountMancomb() throws Exception { OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); - + // Preconditions assertUsers(6); /// WHEN TestUtil.displayWhen(TEST_NAME); - + dummyResourceEmerald.deleteAccountByName(ACCOUNT_MANCOMB_DUMMY_USERNAME); - + waitForSyncTaskNextRun(resourceDummyEmerald); - + // THEN TestUtil.displayThen(TEST_NAME); - + PrismObject accountMancomb = findAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME, resourceDummyEmerald); display("Account mancomb", accountMancomb); assertNull("Account shadow mancomb not gone", accountMancomb); - + PrismObject userMancomb = findUserByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); display("User mancomb", userMancomb); assertNotNull("User mancomb is gone", userMancomb); @@ -153,9 +153,9 @@ public void test199DeleteDummyEmeraldAccountMancomb() throws Exception { // assertNull("Unexpected valid to in user", userMancomb.asObjectable().getActivation().getValidTo()); assertValidFrom(userMancomb, ACCOUNT_MANCOMB_VALID_FROM_DATE); assertValidTo(userMancomb, ACCOUNT_MANCOMB_VALID_TO_DATE); - + assertNoDummyAccount(ACCOUNT_MANCOMB_DUMMY_USERNAME); - + assertUsers(6); // notifications diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestInboundReconTaskDeprecated.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestInboundReconTaskDeprecated.java index 5467e49afb9..40af3360d60 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestInboundReconTaskDeprecated.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestInboundReconTaskDeprecated.java @@ -38,7 +38,7 @@ protected File getResourceDummyFile() { protected File getResourceDummyEmeraldFile() { return RESOURCE_DUMMY_EMERALD_DEPRECATED_FILE; } - + @Override protected File getResourceDummyBlueFile() { return RESOURCE_DUMMY_BLUE_DEPRECATED_FILE; 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 70e81608be2..d889bf9f428 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 @@ -34,17 +34,17 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestLiveSyncTask extends AbstractSynchronizationStoryTest { - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + dummyResourceGreen.setSyncStyle(DummySyncStyle.SMART); getDummyResource().setSyncStyle(DummySyncStyle.DUMB); getDummyResource(RESOURCE_DUMMY_BLUE_NAME).setSyncStyle(DummySyncStyle.SMART); - + } - + @Override protected void importSyncTask(PrismObject resource) throws FileNotFoundException { if (resource == resourceDummyGreen) { diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestLiveSyncTaskDeprecated.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestLiveSyncTaskDeprecated.java index 3ec1908e1bd..ec4baff7422 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestLiveSyncTaskDeprecated.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestLiveSyncTaskDeprecated.java @@ -33,7 +33,7 @@ public class TestLiveSyncTaskDeprecated extends TestLiveSyncTask { protected File getResourceDummyFile() { return RESOURCE_DUMMY_DEPRECATED_FILE; } - + @Override protected File getResourceDummyGreenFile() { return RESOURCE_DUMMY_GREEN_DEPRECATED_FILE; diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestObjTemplateLiveSyncTask.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestObjTemplateLiveSyncTask.java index e1801a3cd49..648fb6e476f 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestObjTemplateLiveSyncTask.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestObjTemplateLiveSyncTask.java @@ -34,14 +34,14 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestObjTemplateLiveSyncTask extends AbstractObjTemplateSyncTest { - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + dummyResourceByzantine.setSyncStyle(DummySyncStyle.SMART); } - + @Override protected void importSyncTask(PrismObject resource) throws FileNotFoundException { if (resource == resourceDummyByzantine) { diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestRecomputeTask.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestRecomputeTask.java index c4d6592aee5..11262f6c1ff 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestRecomputeTask.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestRecomputeTask.java @@ -74,18 +74,18 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestRecomputeTask extends AbstractInitializedModelIntegrationTest { - + private static final File TEST_DIR = new File("src/test/resources/sync"); - + private static final File TASK_USER_RECOMPUTE_FILE = new File(TEST_DIR, "task-user-recompute.xml"); private static final String TASK_USER_RECOMPUTE_OID = "91919191-76e0-59e2-86d6-3d4f02d3aaaa"; - + private static final File TASK_USER_RECOMPUTE_LIGHT_FILE = new File(TEST_DIR, "task-user-recompute-light.xml"); private static final String TASK_USER_RECOMPUTE_LIGHT_OID = "b7b6af78-fffe-11e6-ac04-2fdd62641ce2"; - + private static final File TASK_USER_RECOMPUTE_CAPTAIN_FILE = new File(TEST_DIR, "task-user-recompute-captain.xml"); private static final String TASK_USER_RECOMPUTE_CAPTAIN_OID = "91919191-76e0-59e2-86d6-3d4f02d3aaac"; - + private static final File TASK_USER_RECOMPUTE_HERMAN_BY_EXPRESSION_FILE = new File(TEST_DIR, "task-user-recompute-herman-by-expression.xml"); private static final String TASK_USER_RECOMPUTE_HERMAN_BY_EXPRESSION_OID = "91919191-76e0-59e2-86d6-3d4f02d3aadd"; @@ -104,30 +104,30 @@ public void test100RecomputeAll() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // Preconditions assertUsers(5); assertNoDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); assertNoDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME); - + // Do some ordinary operations - + assignRole(USER_GUYBRUSH_OID, ROLE_PIRATE_OID, task, result); assignRole(USER_JACK_OID, ROLE_JUDGE_OID, task, result); addObject(USER_HERMAN_FILE); assignRole(USER_HERMAN_OID, ROLE_JUDGE_OID, task, result); - + result.computeStatus(); TestUtil.assertSuccess(result); - + // Now do something evil - + // change definition of role "pirate". midPoint will not recompute automatically // the recompute task should do it - + // One simple change modifyRoleAddConstruction(ROLE_JUDGE_OID, 1111L, RESOURCE_DUMMY_RED_OID); - + // More complicated change PrismObject rolePirate = modelService.getObject(RoleType.class, ROLE_PIRATE_OID, null, task, result); ItemPath attrItemPath = new ItemPath( @@ -153,8 +153,8 @@ public void test100RecomputeAll() throws Exception { JAXBElement daggerExpressionEvalJaxbElement = new JAXBElement(SchemaConstants.C_VALUE, Object.class, daggerValueEvaluator); newAttrPVal.getValue().getOutbound().getExpression().getExpressionEvaluator().add(daggerExpressionEvalJaxbElement); newAttrPVal.getValue().getOutbound().setStrength(MappingStrengthType.STRONG); - - ObjectDelta rolePirateDelta = ObjectDelta.createModificationDeleteProperty(RoleType.class, ROLE_PIRATE_OID, + + ObjectDelta rolePirateDelta = ObjectDelta.createModificationDeleteProperty(RoleType.class, ROLE_PIRATE_OID, attrItemPath, prismContext, oldAttrPVal.getValue()); IntegrationTestTools.displayJaxb("AAAAAAAAAAA", newAttrPVal.getValue(), ConstructionType.F_ATTRIBUTE); display("BBBBBB", newAttrPVal.getValue().toString()); @@ -162,58 +162,58 @@ public void test100RecomputeAll() throws Exception { display("Role pirate delta", rolePirateDelta); modelService.executeChanges(MiscSchemaUtil.createCollection(rolePirateDelta), null, task, result); - + displayRoles(task, result); - + assertDummyAccount(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood", true); assertNoDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - + PrismObject userJack = getUser(USER_JACK_OID); display("User jack (before)", userJack); - + assertDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); assertNoDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME); - + result.computeStatus(); TestUtil.assertSuccess(result); - + // WHEN TestUtil.displayWhen(TEST_NAME); addTask(TASK_USER_RECOMPUTE_FILE); - + dummyAuditService.clear(); - + waitForTaskStart(TASK_USER_RECOMPUTE_OID, false); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + waitForTaskFinish(TASK_USER_RECOMPUTE_OID, true, 40000); - + // THEN TestUtil.displayThen(TEST_NAME); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after recompute", users); - + assertDummyAccount(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood", true); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, "cutlass", "dagger"); assertNoDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - + userJack = getUser(USER_JACK_OID); display("User jack (after)", userJack); - + assertNoDummyAccount(null, ACCOUNT_JACK_DUMMY_USERNAME); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); assertUsers(6); - + // Check audit display("Audit", dummyAuditService); - + List auditRecords = dummyAuditService.getRecords(); - + int i=0; int modifications = 0; for (; i < (auditRecords.size() - 1); i+=2) { @@ -225,10 +225,10 @@ public void test100RecomputeAll() throws Exception { 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()); modifications++; - + // check next records while (i < (auditRecords.size() - 2)) { AuditEventRecord nextRecord = auditRecords.get(i+2); @@ -242,10 +242,10 @@ public void test100RecomputeAll() throws Exception { } assertEquals("Unexpected number of audit modifications", 6, modifications); - + deleteObject(TaskType.class, TASK_USER_RECOMPUTE_OID, task, result); } - + private void displayRoles(Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject rolePirate = modelService.getObject(RoleType.class, ROLE_PIRATE_OID, null, task, result); display("Role pirate after modify", rolePirate); @@ -264,52 +264,52 @@ public void test110RecomputeSome() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // Preconditions assertUsers(6); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_HERMAN_USERNAME, "Herman Toothrot", true); - + result.computeStatus(); TestUtil.assertSuccess(result); - + // Now do something evil, remove "red" construction from judge role modifyRoleDeleteInducement(ROLE_JUDGE_OID, 1111L, false, null, null); - + displayRoles(task, result); - + // WHEN TestUtil.displayWhen(TEST_NAME); addTask(TASK_USER_RECOMPUTE_CAPTAIN_FILE); - + dummyAuditService.clear(); - + waitForTaskStart(TASK_USER_RECOMPUTE_CAPTAIN_OID, false); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + waitForTaskFinish(TASK_USER_RECOMPUTE_CAPTAIN_OID, true, 40000); - + // THEN TestUtil.displayThen(TEST_NAME); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after recompute", users); - + assertDummyAccount(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood", true); - assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, + assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, "cutlass", "dagger"); assertNoDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); - + // Red resource does not delete accounts on deprovision, it disables them assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", false); - + // Only captains are recomputed. Therefore herman stays unrecomputed assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_HERMAN_USERNAME, "Herman Toothrot", true); - + assertUsers(6); - + } /** @@ -369,7 +369,7 @@ public void test120RecomputeByExpression() throws Exception { assertUsers(6); } - + /** * Light recompute. Very efficient, no resource operations, just fix the focus. * MID-3384 @@ -390,7 +390,7 @@ public void test130RecomputeLight() throws Exception { display("User jack before", usetJackBefore); assertAssignedRole(usetJackBefore, ROLE_JUDGE_OID); assertRoleMembershipRef(usetJackBefore, ROLE_JUDGE_OID); - + assignOrg(USER_GUYBRUSH_OID, ORG_MINISTRY_OF_OFFENSE_OID, null); PrismObject usetGuybrushBefore = getUser(USER_GUYBRUSH_OID); display("User guybrush before", usetGuybrushBefore); @@ -398,10 +398,10 @@ public void test130RecomputeLight() throws Exception { assertRoleMembershipRef(usetGuybrushBefore, ROLE_PIRATE_OID, ORG_MINISTRY_OF_OFFENSE_OID); assertAssignedOrgs(usetGuybrushBefore, ORG_MINISTRY_OF_OFFENSE_OID); assertHasOrgs(usetGuybrushBefore, ORG_MINISTRY_OF_OFFENSE_OID); - + clearUserOrgAndRoleRefs(USER_JACK_OID); clearUserOrgAndRoleRefs(USER_GUYBRUSH_OID); - + rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); @@ -420,13 +420,13 @@ public void test130RecomputeLight() throws Exception { // THEN TestUtil.displayThen(TEST_NAME); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after recompute", users); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 0); - + assertDummyAccount(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood", true); assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, "cutlass", "dagger"); @@ -446,14 +446,14 @@ public void test130RecomputeLight() throws Exception { display("User jack after", usetJackAfter); assertAssignedRole(usetJackAfter, ROLE_JUDGE_OID); assertRoleMembershipRef(usetJackAfter, ROLE_JUDGE_OID); - + PrismObject usetGuybrushAfter = getUser(USER_GUYBRUSH_OID); display("User guybrush after", usetGuybrushAfter); assertAssignedRole(usetGuybrushAfter, ROLE_PIRATE_OID); assertRoleMembershipRef(usetGuybrushAfter, ROLE_PIRATE_OID, ORG_MINISTRY_OF_OFFENSE_OID); assertAssignedOrgs(usetGuybrushAfter, ORG_MINISTRY_OF_OFFENSE_OID); assertHasOrgs(usetGuybrushAfter, ORG_MINISTRY_OF_OFFENSE_OID); - + assertUsers(6); } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestReconTask.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestReconTask.java index e41b3e72a2d..4b1e8a292a2 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestReconTask.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestReconTask.java @@ -34,7 +34,7 @@ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestReconTask extends AbstractSynchronizationStoryTest { - + @Override protected boolean isReconciliation() { return true; @@ -43,16 +43,16 @@ protected boolean isReconciliation() { @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + // This should be the default but let's make sure ... dummyResourceGreen.setSyncStyle(DummySyncStyle.NONE); getDummyResource().setSyncStyle(DummySyncStyle.NONE); getDummyResource(RESOURCE_DUMMY_BLUE_NAME).setSyncStyle(DummySyncStyle.NONE); - + allwaysCheckTimestamp = true; - + } - + @Override protected void importSyncTask(PrismObject resource) throws FileNotFoundException { if (resource == resourceDummyGreen) { @@ -78,7 +78,7 @@ protected String getSyncTaskOid(PrismObject resource) { throw new IllegalArgumentException("Unknown resource "+resource); } } - + protected int getWaitTimeout() { return 70000; } @@ -87,7 +87,7 @@ protected int getWaitTimeout() { protected int getNumberOfExtraDummyUsers() { return 1; } - - + + } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestReconTaskDeprecated.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestReconTaskDeprecated.java index 1300ed5561e..79f31fa2de7 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestReconTaskDeprecated.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestReconTaskDeprecated.java @@ -43,7 +43,7 @@ protected File getResourceDummyBlueFile() { protected File getResourceDummyGreenFile() { return RESOURCE_DUMMY_GREEN_DEPRECATED_FILE; } - + @Override public void test700AddDummyGreenAccountXjojo() throws Exception { // Skip this test. It does not make sense in deprecated syntax 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 e5363a93c2a..852096de12b 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 @@ -71,59 +71,59 @@ @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestUuid extends AbstractInitializedModelIntegrationTest { - + private static final File TEST_DIR = new File("src/test/resources/sync"); 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"; - + private static final String USER_AUGUSTUS_NAME = "augustus"; - + private static final String ACCOUNT_AUGUSTUS_NAME = "augustus"; private static final String ACCOUNT_AUGUSTUS_FULLNAME = "Augustus DeWaat"; - + 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; protected PrismObject resourceDummyUuid; - + private String augustusShadowOid; - + @Autowired(required=true) private ReconciliationTaskHandler reconciliationTaskHandler; - + private DebugReconciliationTaskResultListener reconciliationTaskResultListener; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + reconciliationTaskResultListener = new DebugReconciliationTaskResultListener(); reconciliationTaskHandler.setReconciliationTaskResultListener(reconciliationTaskResultListener); - + dummyResourceCtlUuid = DummyResourceContoller.create(RESOURCE_DUMMY_UUID_NAME, resourceDummyUuid); dummyResourceCtlUuid.extendSchemaPirate(); dummyResourceUuid = dummyResourceCtlUuid.getDummyResource(); - resourceDummyUuid = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_UUID_FILE, RESOURCE_DUMMY_UUID_OID, initTask, initResult); + resourceDummyUuid = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_UUID_FILE, RESOURCE_DUMMY_UUID_OID, initTask, initResult); resourceDummyUuidType = resourceDummyUuid.asObjectable(); - dummyResourceCtlUuid.setResource(resourceDummyUuid); - + dummyResourceCtlUuid.setResource(resourceDummyUuid); + InternalMonitor.reset(); InternalMonitor.setTrace(InternalOperationClasses.SHADOW_FETCH_OPERATIONS, true); - + // DebugUtil.setDetailedDebugDump(true); } - + @Test public void test200ReconcileDummyUuid() throws Exception { @@ -136,38 +136,38 @@ public void test200ReconcileDummyUuid() throws Exception { assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); // TODO - + getDummyResource().purgeScriptHistory(); dummyAuditService.clear(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); reconciliationTaskResultListener.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); importObjectFromFile(TASK_RECONCILE_DUMMY_UUID_FILE); - + // THEN TestUtil.displayThen(TEST_NAME); - + waitForTaskFinish(TASK_RECONCILE_DUMMY_UUID_OID, false); - + // THEN - TestUtil.displayThen(TEST_NAME); + TestUtil.displayThen(TEST_NAME); reconciliationTaskResultListener.assertResult(RESOURCE_DUMMY_UUID_OID, 0, 0, 0, 0); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after import", users); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); assertImportedUserByOid(USER_BARBOSSA_OID); - + assertEquals("Unexpected number of users", 5, users.size()); - + display("Dummy resource", getDummyResource().debugDump()); - + assertReconAuditModifications(0, TASK_RECONCILE_DUMMY_UUID_OID); - + // Task result PrismObject reconTaskAfter = getTask(TASK_RECONCILE_DUMMY_UUID_OID); OperationResultType reconTaskResult = reconTaskAfter.asObjectable().getResult(); @@ -189,55 +189,55 @@ public void test210ReconcileDummyUuidAddAugustus() throws Exception { account.setEnabled(true); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, ACCOUNT_AUGUSTUS_FULLNAME); dummyResourceUuid.addAccount(account); - + getDummyResource().purgeScriptHistory(); dummyAuditService.clear(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); reconciliationTaskResultListener.clear(); - + Task taskBefore = taskManager.getTask(TASK_RECONCILE_DUMMY_UUID_OID, result); - + // WHEN TestUtil.displayWhen(TEST_NAME); restartTask(TASK_RECONCILE_DUMMY_UUID_OID); - + // THEN TestUtil.displayThen(TEST_NAME); - + waitForTaskNextRunAssertSuccess(taskBefore, true); - + // THEN - TestUtil.displayThen(TEST_NAME); + TestUtil.displayThen(TEST_NAME); reconciliationTaskResultListener.assertResult(RESOURCE_DUMMY_UUID_OID, 0, 1, 0, 0); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after import", users); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); assertImportedUserByOid(USER_BARBOSSA_OID); - + assertImportedUserByUsername(ACCOUNT_AUGUSTUS_NAME, RESOURCE_DUMMY_UUID_OID); - assertDummyAccountAttribute(RESOURCE_DUMMY_UUID_NAME, ACCOUNT_AUGUSTUS_NAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_UUID_NAME, ACCOUNT_AUGUSTUS_NAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, ACCOUNT_AUGUSTUS_FULLNAME); - + assertEquals("Unexpected number of users", 6, users.size()); - + display("Dummy resource", getDummyResource().debugDump()); - + assertReconAuditModifications(1, TASK_RECONCILE_DUMMY_UUID_OID); - + // Task result PrismObject reconTaskAfter = getTask(TASK_RECONCILE_DUMMY_UUID_OID); OperationResultType reconTaskResult = reconTaskAfter.asObjectable().getResult(); display("Recon task result", reconTaskResult); TestUtil.assertSuccess(reconTaskResult); - + PrismObject user = findUserByUsername(USER_AUGUSTUS_NAME); display("Augustus after recon", user); augustusShadowOid = getSingleLinkOid(user); PrismObject repoShadow = repositoryService.getObject(ShadowType.class, augustusShadowOid, null, result); - + } /** @@ -256,62 +256,62 @@ public void test220ReconcileDummyUuidDeleteAddAugustus() throws Exception { DummyAccount oldAccount = dummyResourceUuid.getAccountByUsername(ACCOUNT_AUGUSTUS_NAME); dummyResourceUuid.deleteAccountByName(ACCOUNT_AUGUSTUS_NAME); assertNoDummyAccount(ACCOUNT_AUGUSTUS_NAME, ACCOUNT_AUGUSTUS_NAME); - + DummyAccount account = new DummyAccount(ACCOUNT_AUGUSTUS_NAME); account.setEnabled(true); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, ACCOUNT_AUGUSTUS_FULLNAME); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, USER_AUGUSTUS_NAME); dummyResourceUuid.addAccount(account); account = dummyResourceUuid.getAccountByUsername(ACCOUNT_AUGUSTUS_NAME); - + assertFalse("Account IDs not changed", oldAccount.getId().equals(account.getId())); - + display("Old shadow OID", augustusShadowOid); display("Account ID "+ oldAccount.getId() + " -> " + account.getId()); - + Task taskBefore = taskManager.getTask(TASK_RECONCILE_DUMMY_UUID_OID, result); - + getDummyResource().purgeScriptHistory(); dummyAuditService.clear(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); reconciliationTaskResultListener.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); restartTask(TASK_RECONCILE_DUMMY_UUID_OID); - + // THEN TestUtil.displayThen(TEST_NAME); - + waitForTaskNextRunAssertSuccess(taskBefore, true); - + // THEN - TestUtil.displayThen(TEST_NAME); + TestUtil.displayThen(TEST_NAME); reconciliationTaskResultListener.assertResult(RESOURCE_DUMMY_UUID_OID, 0, 1, 0, 0); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after import", users); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); assertImportedUserByOid(USER_BARBOSSA_OID); - + assertImportedUserByUsername(ACCOUNT_AUGUSTUS_NAME, RESOURCE_DUMMY_UUID_OID); - assertDummyAccountAttribute(RESOURCE_DUMMY_UUID_NAME, ACCOUNT_AUGUSTUS_NAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_UUID_NAME, ACCOUNT_AUGUSTUS_NAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, ACCOUNT_AUGUSTUS_FULLNAME); - + assertEquals("Unexpected number of users", 6, users.size()); - + display("Dummy resource", getDummyResource().debugDump()); - + assertReconAuditModifications(1, TASK_RECONCILE_DUMMY_UUID_OID); - + // Task result PrismObject reconTaskAfter = getTask(TASK_RECONCILE_DUMMY_UUID_OID); OperationResultType reconTaskResult = reconTaskAfter.asObjectable().getResult(); display("Recon task result", reconTaskResult); TestUtil.assertSuccess(reconTaskResult); - + PrismObject user = findUserByUsername(USER_AUGUSTUS_NAME); display("Augustus after recon", user); String newAugustusShadowOid = getSingleLinkOid(user); @@ -319,7 +319,7 @@ public void test220ReconcileDummyUuidDeleteAddAugustus() throws Exception { assertFalse("Shadow OID is not changed", augustusShadowOid.equals(newAugustusShadowOid)); augustusShadowOid = newAugustusShadowOid; } - + /** * Augustus is deleted and Augustina re-added. They correlate to the same user. * New shadow needs to be created. @@ -337,62 +337,62 @@ public void test230ReconcileDummyUuidDeleteAugustusAddAugustina() throws Excepti DummyAccount oldAccount = dummyResourceUuid.getAccountByUsername(ACCOUNT_AUGUSTUS_NAME); dummyResourceUuid.deleteAccountByName(ACCOUNT_AUGUSTUS_NAME); assertNoDummyAccount(ACCOUNT_AUGUSTUS_NAME, ACCOUNT_AUGUSTUS_NAME); - + DummyAccount account = new DummyAccount(ACCOUNT_AUGUSTINA_NAME); account.setEnabled(true); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, ACCOUNT_AUGUSTINA_FULLNAME); account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, USER_AUGUSTUS_NAME); dummyResourceUuid.addAccount(account); account = dummyResourceUuid.getAccountByUsername(ACCOUNT_AUGUSTINA_NAME); - + assertFalse("Account IDs not changed", oldAccount.getId().equals(account.getId())); - + display("Old shadow OID", augustusShadowOid); display("Account ID "+ oldAccount.getId() + " -> " + account.getId()); - + Task taskBefore = taskManager.getTask(TASK_RECONCILE_DUMMY_UUID_OID, result); - + getDummyResource().purgeScriptHistory(); dummyAuditService.clear(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); reconciliationTaskResultListener.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); restartTask(TASK_RECONCILE_DUMMY_UUID_OID); - + // THEN TestUtil.displayThen(TEST_NAME); - + waitForTaskNextRunAssertSuccess(taskBefore, true); - + // THEN - TestUtil.displayThen(TEST_NAME); + TestUtil.displayThen(TEST_NAME); reconciliationTaskResultListener.assertResult(RESOURCE_DUMMY_UUID_OID, 0, 1, 0, 0); - + List> users = modelService.searchObjects(UserType.class, null, null, task, result); display("Users after import", users); - + assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); assertImportedUserByOid(USER_BARBOSSA_OID); - + assertImportedUserByUsername(USER_AUGUSTUS_NAME, RESOURCE_DUMMY_UUID_OID); - assertDummyAccountAttribute(RESOURCE_DUMMY_UUID_NAME, ACCOUNT_AUGUSTINA_NAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_UUID_NAME, ACCOUNT_AUGUSTINA_NAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, ACCOUNT_AUGUSTINA_FULLNAME); - + assertEquals("Unexpected number of users", 6, users.size()); - + display("Dummy resource", getDummyResource().debugDump()); - + assertReconAuditModifications(1, TASK_RECONCILE_DUMMY_UUID_OID); - + // Task result PrismObject reconTaskAfter = getTask(TASK_RECONCILE_DUMMY_UUID_OID); OperationResultType reconTaskResult = reconTaskAfter.asObjectable().getResult(); display("Recon task result", reconTaskResult); TestUtil.assertSuccess(reconTaskResult); - + PrismObject user = findUserByUsername(USER_AUGUSTUS_NAME); display("Augustus after recon", user); String newAugustusShadowOid = getSingleLinkOid(user); @@ -403,7 +403,7 @@ public void test230ReconcileDummyUuidDeleteAugustusAddAugustina() throws Excepti private void assertReconAuditModifications(int expectedModifications, String taskOid) { // Check audit display("Audit", dummyAuditService); - + List auditRecords = dummyAuditService.getRecords(); Iterator iterator = auditRecords.iterator(); @@ -439,14 +439,14 @@ private void assertReconAuditModifications(int expectedModifications, String tas // end of audit records; break; } - + 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); 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()); modifications++; @@ -479,13 +479,13 @@ private void assertImportedUserByOid(String userOid, String... resourceOids) thr assertNotNull("No user "+userOid, user); assertImportedUser(user, resourceOids); } - + private void assertImportedUserByUsername(String username, String... resourceOids) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject user = findUserByUsername(username); assertNotNull("No user "+username, user); assertImportedUser(user, resourceOids); } - + private void assertImportedUser(PrismObject user, String... resourceOids) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { assertLinks(user, resourceOids.length); for (String resourceOid: resourceOids) { 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 5a45bb1a9e0..222798f9b3c 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 @@ -64,7 +64,7 @@ /** * @author Radovan Semancik - * + * * @see TestActivation * */ @@ -76,10 +76,10 @@ public class TestValidityRecomputeTask extends AbstractInitializedModelIntegrati protected static final File ROLE_RED_JUDGE_FILE = new File(TEST_DIR, "role-red-judge.xml"); protected static final String ROLE_RED_JUDGE_OID = "12345111-1111-2222-1111-121212111222"; - + protected static final File ROLE_BIG_JUDGE_FILE = new File(TEST_DIR, "role-big-judge.xml"); protected static final String ROLE_BIG_JUDGE_OID = "12345111-1111-2222-1111-121212111224"; - + private static final XMLGregorianCalendar LONG_LONG_TIME_AGO = XmlTypeConverter.createXMLGregorianCalendar(1111, 1, 1, 12, 00, 00); private XMLGregorianCalendar drakeValidFrom; @@ -103,7 +103,7 @@ public void test100ImportValidityScannerTask() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // Pretend that the user was added a long time ago clock.override(LONG_LONG_TIME_AGO); addObject(USER_HERMAN_FILE); @@ -112,21 +112,21 @@ public void test100ImportValidityScannerTask() throws Exception { assertEffectiveActivation(userHermanBefore, ActivationStatusType.DISABLED); assertValidityStatus(userHermanBefore, TimeIntervalStatusType.BEFORE); clock.resetOverride(); - + XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); - + /// WHEN TestUtil.displayWhen(TEST_NAME); importObjectFromFile(TASK_VALIDITY_SCANNER_FILENAME); waitForTaskStart(TASK_VALIDITY_SCANNER_OID, false); waitForTaskFinish(TASK_VALIDITY_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); XMLGregorianCalendar endCal = clock.currentTimeXMLGregorianCalendar(); assertLastRecomputeTimestamp(TASK_VALIDITY_SCANNER_OID, startCal, endCal); - + PrismObject userHermanAfter = getUser(USER_HERMAN_OID); assertEffectiveActivation(userHermanAfter, ActivationStatusType.ENABLED); assertValidityStatus(userHermanAfter, TimeIntervalStatusType.IN); @@ -140,10 +140,10 @@ public void test110JackAssignJudgeDisabled() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ActivationType activationType = new ActivationType(); activationType.setAdministrativeStatus(ActivationStatusType.DISABLED); - + testJackAssignRoleJudgeInvalid(TEST_NAME, activationType, task, result); } @@ -155,15 +155,15 @@ public void test111JackAssignJudgeNotYetValid() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ActivationType activationType = new ActivationType(); XMLGregorianCalendar validFrom = clock.currentTimeXMLGregorianCalendar(); validFrom.add(XmlTypeConverter.createDuration(60*60*1000)); // one hour ahead activationType.setValidFrom(validFrom); - + testJackAssignRoleJudgeInvalid(TEST_NAME, activationType, task, result); } - + @Test public void test112JackAssignJudgeAfterValidity() throws Exception { final String TEST_NAME = "test112JackAssignJudgeAfterValidity"; @@ -172,15 +172,15 @@ public void test112JackAssignJudgeAfterValidity() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ActivationType activationType = new ActivationType(); XMLGregorianCalendar validTo = clock.currentTimeXMLGregorianCalendar(); validTo.add(XmlTypeConverter.createDuration(-60*60*1000)); // one hour ago activationType.setValidTo(validTo); - + testJackAssignRoleJudgeInvalid(TEST_NAME, activationType, task, result); } - + @Test public void test115JackAssignJudgeEnabled() throws Exception { final String TEST_NAME = "test115JackAssignJudgeEnabled"; @@ -189,13 +189,13 @@ public void test115JackAssignJudgeEnabled() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ActivationType activationType = new ActivationType(); activationType.setAdministrativeStatus(ActivationStatusType.ENABLED); - + testJackAssignRoleJudgeValid(TEST_NAME, activationType, task, result); } - + @Test public void test115JackAssignJudgeValid() throws Exception { final String TEST_NAME = "test115JackAssignJudgeValid"; @@ -204,7 +204,7 @@ public void test115JackAssignJudgeValid() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ActivationType activationType = new ActivationType(); XMLGregorianCalendar validFrom = clock.currentTimeXMLGregorianCalendar(); validFrom.add(XmlTypeConverter.createDuration(-60*60*1000)); // one hour ago @@ -212,25 +212,25 @@ public void test115JackAssignJudgeValid() throws Exception { XMLGregorianCalendar validTo = clock.currentTimeXMLGregorianCalendar(); validTo.add(XmlTypeConverter.createDuration(60*60*1000)); // one hour ahead activationType.setValidTo(validTo); - + testJackAssignRoleJudgeValid(TEST_NAME, activationType, task, result); } - + private void testJackAssignRoleJudgeValid(final String TEST_NAME, ActivationType activationType, Task task, OperationResult result) throws Exception { // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_BIG_JUDGE_OID, activationType, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(null, USER_JACK_USERNAME); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_JACK_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(null, USER_JACK_USERNAME); @@ -239,29 +239,29 @@ private void testJackAssignRoleJudgeValid(final String TEST_NAME, ActivationType display("User after", user); assertLinks(user, 2); assert11xUserOk(user); - + MidPointPrincipal principal = userProfileService.getPrincipal(user); assertAuthorized(principal, AUTZ_PUNISH_URL); - + // CLEANUP unassignAllRoles(USER_JACK_OID); assertNoDummyAccount(null, USER_JACK_USERNAME); } - + private void testJackAssignRoleJudgeInvalid(final String TEST_NAME, ActivationType activationType, Task task, OperationResult result) throws Exception { // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_BIG_JUDGE_OID, activationType, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertNoDummyAccount(null, USER_JACK_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertNoDummyAccount(null, USER_JACK_USERNAME); @@ -271,21 +271,21 @@ private void testJackAssignRoleJudgeInvalid(final String TEST_NAME, ActivationTy display("User after", user); assertNoLinkedAccount(user); assert11xUserOk(user); - + MidPointPrincipal principal = userProfileService.getPrincipal(user); assertNotAuthorized(principal, AUTZ_PUNISH_URL); - + // CLEANUP unassignAllRoles(USER_JACK_OID); assertNoDummyAccount(null, USER_JACK_USERNAME); } - + private void assert11xUserOk(PrismObject user) { assertAdministrativeStatusEnabled(user); assertEffectiveActivation(user, ActivationStatusType.ENABLED); } - + @Test public void test120JackDisableAssignmentJudge() throws Exception { final String TEST_NAME = "test120JackDisableAssignmentJudge"; @@ -294,30 +294,30 @@ public void test120JackDisableAssignmentJudge() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ActivationType activationType = new ActivationType(); activationType.setAdministrativeStatus(ActivationStatusType.ENABLED); assignRole(USER_JACK_OID, ROLE_BIG_JUDGE_OID, activationType, task, result); assertDummyAccount(null, USER_JACK_USERNAME); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_JACK_USERNAME); AssignmentType judgeAssignment = getJudgeAssignment(USER_JACK_OID); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyAssignmentAdministrativeStatus(USER_JACK_OID, judgeAssignment.getId(), + modifyAssignmentAdministrativeStatus(USER_JACK_OID, judgeAssignment.getId(), ActivationStatusType.DISABLED, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); PrismObject user = getUser(USER_JACK_OID); display("User after", user); assertNoDummyAccount(null, USER_JACK_USERNAME); - + assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_JACK_USERNAME, USER_JACK_FULL_NAME, false); - + assert11xUserOk(user); } - + @Test public void test122JackReplaceNullAdministrativeStatusAssignmentJudge() throws Exception { final String TEST_NAME = "test122JackReplaceNullAdministrativeStatusAssignmentJudge"; @@ -326,15 +326,15 @@ public void test122JackReplaceNullAdministrativeStatusAssignmentJudge() throws E // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + assertNoDummyAccount(null, USER_JACK_USERNAME); AssignmentType judgeAssignment = getJudgeAssignment(USER_JACK_OID); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyAssignmentAdministrativeStatus(USER_JACK_OID, judgeAssignment.getId(), + modifyAssignmentAdministrativeStatus(USER_JACK_OID, judgeAssignment.getId(), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); PrismObject user = getUser(USER_JACK_OID); @@ -342,7 +342,7 @@ public void test122JackReplaceNullAdministrativeStatusAssignmentJudge() throws E assertDummyAccount(null, USER_JACK_USERNAME); assert11xUserOk(user); } - + @Test public void test123JackDisableAssignmentJudge() throws Exception { final String TEST_NAME = "test123JackDisableAssignmentJudge"; @@ -351,15 +351,15 @@ public void test123JackDisableAssignmentJudge() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + assertDummyAccount(null, USER_JACK_USERNAME); AssignmentType judgeAssignment = getJudgeAssignment(USER_JACK_OID); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyAssignmentAdministrativeStatus(USER_JACK_OID, judgeAssignment.getId(), + modifyAssignmentAdministrativeStatus(USER_JACK_OID, judgeAssignment.getId(), ActivationStatusType.DISABLED, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); PrismObject user = getUser(USER_JACK_OID); @@ -367,7 +367,7 @@ public void test123JackDisableAssignmentJudge() throws Exception { assertNoDummyAccount(null, USER_JACK_USERNAME); assert11xUserOk(user); } - + @Test public void test124JackEnableAssignmentJudge() throws Exception { final String TEST_NAME = "test124JackEnableAssignmentJudge"; @@ -376,15 +376,15 @@ public void test124JackEnableAssignmentJudge() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + assertNoDummyAccount(null, USER_JACK_USERNAME); AssignmentType judgeAssignment = getJudgeAssignment(USER_JACK_OID); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyAssignmentAdministrativeStatus(USER_JACK_OID, judgeAssignment.getId(), + modifyAssignmentAdministrativeStatus(USER_JACK_OID, judgeAssignment.getId(), ActivationStatusType.ENABLED, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); PrismObject user = getUser(USER_JACK_OID); @@ -401,20 +401,20 @@ public void test125JackDeleteAdministrativeStatusAssignmentJudge() throws Except // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + assertDummyAccount(null, USER_JACK_USERNAME); AssignmentType judgeAssignment = getJudgeAssignment(USER_JACK_OID); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyObjectDeleteProperty(UserType.class, USER_JACK_OID, + modifyObjectDeleteProperty(UserType.class, USER_JACK_OID, new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(judgeAssignment.getId()), new NameItemPathSegment(AssignmentType.F_ACTIVATION), - new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), + new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), task, result, ActivationStatusType.ENABLED); - + // THEN TestUtil.displayThen(TEST_NAME); PrismObject user = getUser(USER_JACK_OID); @@ -422,7 +422,7 @@ public void test125JackDeleteAdministrativeStatusAssignmentJudge() throws Except assertDummyAccount(null, USER_JACK_USERNAME); assert11xUserOk(user); } - + @Test public void test126JackAddAdministrativeStatusAssignmentJudge() throws Exception { final String TEST_NAME = "test126JackAddAdministrativeStatusAssignmentJudge"; @@ -431,20 +431,20 @@ public void test126JackAddAdministrativeStatusAssignmentJudge() throws Exception // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + assertDummyAccount(null, USER_JACK_USERNAME); AssignmentType judgeAssignment = getJudgeAssignment(USER_JACK_OID); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyObjectAddProperty(UserType.class, USER_JACK_OID, + modifyObjectAddProperty(UserType.class, USER_JACK_OID, new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(judgeAssignment.getId()), new NameItemPathSegment(AssignmentType.F_ACTIVATION), - new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), + new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), task, result, ActivationStatusType.ENABLED); - + // THEN TestUtil.displayThen(TEST_NAME); PrismObject user = getUser(USER_JACK_OID); @@ -452,7 +452,7 @@ public void test126JackAddAdministrativeStatusAssignmentJudge() throws Exception assertDummyAccount(null, USER_JACK_USERNAME); assert11xUserOk(user); } - + @Test public void test127JackDeleteActivationAssignmentJudge() throws Exception { final String TEST_NAME = "test127JackDeleteActivationAssignmentJudge"; @@ -461,21 +461,21 @@ public void test127JackDeleteActivationAssignmentJudge() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + assertDummyAccount(null, USER_JACK_USERNAME); AssignmentType judgeAssignment = getJudgeAssignment(USER_JACK_OID); ActivationType activationType = new ActivationType(); activationType.setAdministrativeStatus(ActivationStatusType.ENABLED); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyObjectDeleteContainer(UserType.class, USER_JACK_OID, + modifyObjectDeleteContainer(UserType.class, USER_JACK_OID, new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(judgeAssignment.getId()), - new NameItemPathSegment(AssignmentType.F_ACTIVATION)), + new NameItemPathSegment(AssignmentType.F_ACTIVATION)), task, result, activationType); - + // THEN TestUtil.displayThen(TEST_NAME); PrismObject user = getUser(USER_JACK_OID); @@ -492,23 +492,23 @@ public void test128JackAssignmentJudgeValidToSetInvalid() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + assertDummyAccount(null, USER_JACK_USERNAME); AssignmentType judgeAssignment = getJudgeAssignment(USER_JACK_OID); ActivationType activationType = new ActivationType(); XMLGregorianCalendar validTo = clock.currentTimeXMLGregorianCalendar(); validTo.add(XmlTypeConverter.createDuration(-60*60*1000)); // one hour ago activationType.setValidTo(validTo); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyObjectReplaceContainer(UserType.class, USER_JACK_OID, + modifyObjectReplaceContainer(UserType.class, USER_JACK_OID, new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(judgeAssignment.getId()), - new NameItemPathSegment(AssignmentType.F_ACTIVATION)), + new NameItemPathSegment(AssignmentType.F_ACTIVATION)), task, result, activationType); - + // THEN TestUtil.displayThen(TEST_NAME); PrismObject user = getUser(USER_JACK_OID); @@ -525,30 +525,30 @@ public void test129JackAssignmentJudgeValidToSetValid() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + 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 - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyObjectReplaceProperty(UserType.class, USER_JACK_OID, + modifyObjectReplaceProperty(UserType.class, USER_JACK_OID, new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(judgeAssignment.getId()), new NameItemPathSegment(AssignmentType.F_ACTIVATION), - new NameItemPathSegment(ActivationType.F_VALID_TO)), + new NameItemPathSegment(ActivationType.F_VALID_TO)), task, result, validTo); - + // THEN TestUtil.displayThen(TEST_NAME); PrismObject user = getUser(USER_JACK_OID); display("User after", user); assertDummyAccount(null, USER_JACK_USERNAME); - + assert11xUserOk(user); - + // CLEANUP unassignAllRoles(USER_JACK_OID); assertNoDummyAccount(null, USER_JACK_USERNAME); @@ -560,7 +560,7 @@ private AssignmentType getJudgeAssignment(String userOid) throws ObjectNotFoundE assertEquals("Wrong num ass", 1, assignments.size()); return assignments.iterator().next(); } - + /** * The test13x works with two roles for the same resource, enabling/disabling them. */ @@ -572,44 +572,44 @@ public void test130BarbossaAssignJudgeEnabled() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // preconditions assertNoAssignments(USER_BARBOSSA_OID); assertNoDummyAccount(null, USER_BARBOSSA_USERNAME); - + ActivationType activationType = new ActivationType(); activationType.setAdministrativeStatus(ActivationStatusType.ENABLED); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_BARBOSSA_OID, ROLE_JUDGE_OID, activationType, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(null, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - + // WHEN TestUtil.displayWhen(TEST_NAME); waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(null, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, ROLE_JUDGE_TITLE); - assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_JUDGE_DRINK); PrismObject user = getUser(USER_BARBOSSA_OID); display("User after", user); assertLinks(user, 1); - + MidPointPrincipal principal = userProfileService.getPrincipal(user); assertAuthorized(principal, AUTZ_PUNISH_URL); } - + @Test public void test131BarbossaAssignSailorEnabled() throws Exception { final String TEST_NAME = "test131BarbossaAssignSailorEnabled"; @@ -618,40 +618,40 @@ public void test131BarbossaAssignSailorEnabled() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ActivationType activationType = new ActivationType(); activationType.setAdministrativeStatus(ActivationStatusType.ENABLED); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_BARBOSSA_OID, ROLE_SAILOR_OID, activationType, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(null, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - + // WHEN TestUtil.displayWhen(TEST_NAME); waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(null, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, ROLE_JUDGE_TITLE); - assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_JUDGE_DRINK, ROLE_SAILOR_DRINK); PrismObject user = getUser(USER_BARBOSSA_OID); display("User after", user); assertLinks(user, 1); - + MidPointPrincipal principal = userProfileService.getPrincipal(user); assertAuthorized(principal, AUTZ_PUNISH_URL); } - + @Test public void test132BarbossaDisableAssignmentJudge() throws Exception { final String TEST_NAME = "test132BarbossaDisableAssignmentJudge"; @@ -660,39 +660,39 @@ public void test132BarbossaDisableAssignmentJudge() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + AssignmentType assignment = getUserAssignment(USER_BARBOSSA_OID, ROLE_JUDGE_OID); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyAssignmentAdministrativeStatus(USER_BARBOSSA_OID, assignment.getId(), + modifyAssignmentAdministrativeStatus(USER_BARBOSSA_OID, assignment.getId(), ActivationStatusType.DISABLED, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(null, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - + // WHEN TestUtil.displayWhen(TEST_NAME); waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(null, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - assertNoDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, + assertNoDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME); - assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_SAILOR_DRINK); PrismObject user = getUser(USER_BARBOSSA_OID); display("User after", user); assertLinks(user, 1); - + MidPointPrincipal principal = userProfileService.getPrincipal(user); assertNotAuthorized(principal, AUTZ_PUNISH_URL); } - + @Test public void test133BarbossaDisableAssignmentSailor() throws Exception { final String TEST_NAME = "test133BarbossaDisableAssignmentSailor"; @@ -701,22 +701,22 @@ public void test133BarbossaDisableAssignmentSailor() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + AssignmentType assignment = getUserAssignment(USER_BARBOSSA_OID, ROLE_SAILOR_OID); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyAssignmentAdministrativeStatus(USER_BARBOSSA_OID, assignment.getId(), + modifyAssignmentAdministrativeStatus(USER_BARBOSSA_OID, assignment.getId(), ActivationStatusType.DISABLED, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertNoDummyAccount(null, USER_BARBOSSA_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertNoDummyAccount(null, USER_BARBOSSA_USERNAME); @@ -724,11 +724,11 @@ public void test133BarbossaDisableAssignmentSailor() throws Exception { PrismObject user = getUser(USER_BARBOSSA_OID); display("User after", user); assertLinks(user, 0); - + MidPointPrincipal principal = userProfileService.getPrincipal(user); assertNotAuthorized(principal, AUTZ_PUNISH_URL); } - + @Test public void test134BarbossaEnableAssignmentJudge() throws Exception { final String TEST_NAME = "test134BarbossaEnableAssignmentJudge"; @@ -737,36 +737,36 @@ public void test134BarbossaEnableAssignmentJudge() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + AssignmentType assignment = getUserAssignment(USER_BARBOSSA_OID, ROLE_JUDGE_OID); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyAssignmentAdministrativeStatus(USER_BARBOSSA_OID, assignment.getId(), + modifyAssignmentAdministrativeStatus(USER_BARBOSSA_OID, assignment.getId(), ActivationStatusType.ENABLED, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(null, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - + // WHEN TestUtil.displayWhen(TEST_NAME); assertDummyAccount(null, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, ROLE_JUDGE_TITLE); - assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_JUDGE_DRINK); PrismObject user = getUser(USER_BARBOSSA_OID); display("User after", user); assertLinks(user, 1); - + MidPointPrincipal principal = userProfileService.getPrincipal(user); assertAuthorized(principal, AUTZ_PUNISH_URL); } - + @Test public void test135BarbossaEnableAssignmentSailor() throws Exception { final String TEST_NAME = "test135BarbossaEnableAssignmentSailor"; @@ -775,36 +775,36 @@ public void test135BarbossaEnableAssignmentSailor() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + AssignmentType assignment = getUserAssignment(USER_BARBOSSA_OID, ROLE_SAILOR_OID); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyAssignmentAdministrativeStatus(USER_BARBOSSA_OID, assignment.getId(), + modifyAssignmentAdministrativeStatus(USER_BARBOSSA_OID, assignment.getId(), ActivationStatusType.ENABLED, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(null, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - + // WHEN TestUtil.displayWhen(TEST_NAME); assertDummyAccount(null, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, ROLE_JUDGE_TITLE); - assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_JUDGE_DRINK, ROLE_SAILOR_DRINK); PrismObject user = getUser(USER_BARBOSSA_OID); display("User after", user); assertLinks(user, 1); - + MidPointPrincipal principal = userProfileService.getPrincipal(user); assertAuthorized(principal, AUTZ_PUNISH_URL); } - + @Test public void test136BarbossaDisableBothAssignments() throws Exception { final String TEST_NAME = "test136BarbossaDisableBothAssignments"; @@ -813,18 +813,18 @@ public void test136BarbossaDisableBothAssignments() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + AssignmentType judgeAssignment = getUserAssignment(USER_BARBOSSA_OID, ROLE_JUDGE_OID); AssignmentType sailorAssignment = getUserAssignment(USER_BARBOSSA_OID, ROLE_SAILOR_OID); - - ObjectDelta objectDelta = - ObjectDelta.createModificationReplaceProperty(UserType.class, + + ObjectDelta objectDelta = + ObjectDelta.createModificationReplaceProperty(UserType.class, USER_BARBOSSA_OID, new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(judgeAssignment.getId()), new NameItemPathSegment(AssignmentType.F_ACTIVATION), - new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), + new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), prismContext, ActivationStatusType.DISABLED); objectDelta.addModificationReplaceProperty(new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), @@ -832,19 +832,19 @@ public void test136BarbossaDisableBothAssignments() throws Exception { new NameItemPathSegment(AssignmentType.F_ACTIVATION), new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), ActivationStatusType.DISABLED); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(objectDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertNoDummyAccount(null, USER_BARBOSSA_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertNoDummyAccount(null, USER_BARBOSSA_USERNAME); @@ -852,11 +852,11 @@ public void test136BarbossaDisableBothAssignments() throws Exception { PrismObject user = getUser(USER_BARBOSSA_OID); display("User after", user); assertLinks(user, 0); - + MidPointPrincipal principal = userProfileService.getPrincipal(user); assertNotAuthorized(principal, AUTZ_PUNISH_URL); } - + @Test public void test137BarbossaEnableBothAssignments() throws Exception { final String TEST_NAME = "test137BarbossaEnableBothAssignments"; @@ -865,18 +865,18 @@ public void test137BarbossaEnableBothAssignments() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + AssignmentType judgeAssignment = getUserAssignment(USER_BARBOSSA_OID, ROLE_JUDGE_OID); AssignmentType sailorAssignment = getUserAssignment(USER_BARBOSSA_OID, ROLE_SAILOR_OID); - - ObjectDelta objectDelta = - ObjectDelta.createModificationReplaceProperty(UserType.class, + + ObjectDelta objectDelta = + ObjectDelta.createModificationReplaceProperty(UserType.class, USER_BARBOSSA_OID, new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(judgeAssignment.getId()), new NameItemPathSegment(AssignmentType.F_ACTIVATION), - new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), + new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), prismContext, ActivationStatusType.ENABLED); objectDelta.addModificationReplaceProperty(new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), @@ -884,37 +884,37 @@ public void test137BarbossaEnableBothAssignments() throws Exception { new NameItemPathSegment(AssignmentType.F_ACTIVATION), new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), ActivationStatusType.ENABLED); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(objectDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(null, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - + // WHEN TestUtil.displayWhen(TEST_NAME); waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(null, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, ROLE_JUDGE_TITLE); - assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(null, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_JUDGE_DRINK, ROLE_SAILOR_DRINK); PrismObject user = getUser(USER_BARBOSSA_OID); display("User after", user); assertLinks(user, 1); - + MidPointPrincipal principal = userProfileService.getPrincipal(user); assertAuthorized(principal, AUTZ_PUNISH_URL); } - + /** * Unassign disabled assignments. */ @@ -926,22 +926,22 @@ public void test139BarbossaDisableBothAssignmentsUnassign() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + AssignmentType judgeAssignment = getUserAssignment(USER_BARBOSSA_OID, ROLE_JUDGE_OID); AssignmentType judgeAssignmentLight = new AssignmentType(); judgeAssignmentLight.setId(judgeAssignment.getId()); AssignmentType sailorAssignment = getUserAssignment(USER_BARBOSSA_OID, ROLE_SAILOR_OID); AssignmentType sailorAssignmentLight = new AssignmentType(); sailorAssignmentLight.setId(sailorAssignment.getId()); - - ObjectDelta objectDelta = - ObjectDelta.createModificationReplaceProperty(UserType.class, + + ObjectDelta objectDelta = + ObjectDelta.createModificationReplaceProperty(UserType.class, USER_BARBOSSA_OID, new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(judgeAssignment.getId()), new NameItemPathSegment(AssignmentType.F_ACTIVATION), - new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), + new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), prismContext, ActivationStatusType.DISABLED); objectDelta.addModificationReplaceProperty(new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), @@ -949,9 +949,9 @@ public void test139BarbossaDisableBothAssignmentsUnassign() throws Exception { new NameItemPathSegment(AssignmentType.F_ACTIVATION), new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), ActivationStatusType.DISABLED); - + modelService.executeChanges(MiscSchemaUtil.createCollection(objectDelta), null, task, result); - + assertNoDummyAccount(null, USER_BARBOSSA_USERNAME); waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); assertNoDummyAccount(null, USER_BARBOSSA_USERNAME); @@ -960,30 +960,30 @@ public void test139BarbossaDisableBothAssignmentsUnassign() throws Exception { assertLinks(user, 0); MidPointPrincipal principal = userProfileService.getPrincipal(user); assertNotAuthorized(principal, AUTZ_PUNISH_URL); - - objectDelta = - ObjectDelta.createModificationDeleteContainer(UserType.class, + + objectDelta = + ObjectDelta.createModificationDeleteContainer(UserType.class, USER_BARBOSSA_OID, - new ItemPath(new NameItemPathSegment(UserType.F_ASSIGNMENT)), + new ItemPath(new NameItemPathSegment(UserType.F_ASSIGNMENT)), prismContext, judgeAssignmentLight); objectDelta.addModificationDeleteContainer( new ItemPath(new NameItemPathSegment(UserType.F_ASSIGNMENT)), sailorAssignmentLight); - + display("Unassign delta", objectDelta); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(objectDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertNoDummyAccount(null, USER_BARBOSSA_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertNoDummyAccount(null, USER_BARBOSSA_USERNAME); @@ -991,13 +991,13 @@ public void test139BarbossaDisableBothAssignmentsUnassign() throws Exception { user = getUser(USER_BARBOSSA_OID); display("User after", user); assertLinks(user, 0); - + assertNoAssignments(user); - + principal = userProfileService.getPrincipal(user); assertNotAuthorized(principal, AUTZ_PUNISH_URL); } - + /** * The 14x tests are similar than test13x tests, they work with two roles for the same resource, enabling/disabling them. * The 14x work with the red dummy resource that does disable instead of account delete. @@ -1010,7 +1010,7 @@ public void test140BarbossaAssignRedJudgeEnabled() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // preconditions PrismObject user = getUser(USER_BARBOSSA_OID); display("User before", user); @@ -1018,40 +1018,40 @@ public void test140BarbossaAssignRedJudgeEnabled() throws Exception { assertNoAssignments(user); assertNoDummyAccount(null, USER_BARBOSSA_USERNAME); // just to be on the safe side assertNoDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME); - + ActivationType activationType = new ActivationType(); activationType.setAdministrativeStatus(ActivationStatusType.ENABLED); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_BARBOSSA_OID, ROLE_RED_JUDGE_OID, activationType, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - + // WHEN TestUtil.displayWhen(TEST_NAME); waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, ROLE_JUDGE_TITLE); - assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, ROLE_JUDGE_DRINK); user = getUser(USER_BARBOSSA_OID); display("User after", user); assertLinks(user, 1); - + MidPointPrincipal principal = userProfileService.getPrincipal(user); assertAuthorized(principal, AUTZ_PUNISH_URL); } - + @Test public void test141BarbossaAssignRedSailorEnabled() throws Exception { final String TEST_NAME = "test141BarbossaAssignRedSailorEnabled"; @@ -1060,40 +1060,40 @@ public void test141BarbossaAssignRedSailorEnabled() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ActivationType activationType = new ActivationType(); activationType.setAdministrativeStatus(ActivationStatusType.ENABLED); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_BARBOSSA_OID, ROLE_RED_SAILOR_OID, activationType, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - + // WHEN TestUtil.displayWhen(TEST_NAME); waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, ROLE_JUDGE_TITLE); - assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, ROLE_JUDGE_DRINK, ROLE_SAILOR_DRINK); PrismObject user = getUser(USER_BARBOSSA_OID); display("User after", user); assertLinks(user, 1); - + MidPointPrincipal principal = userProfileService.getPrincipal(user); assertAuthorized(principal, AUTZ_PUNISH_URL); } - + @Test public void test142BarbossaDisableAssignmentRedJudge() throws Exception { final String TEST_NAME = "test142BarbossaDisableAssignmentRedJudge"; @@ -1102,39 +1102,39 @@ public void test142BarbossaDisableAssignmentRedJudge() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + AssignmentType assignment = getUserAssignment(USER_BARBOSSA_OID, ROLE_RED_JUDGE_OID); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyAssignmentAdministrativeStatus(USER_BARBOSSA_OID, assignment.getId(), + modifyAssignmentAdministrativeStatus(USER_BARBOSSA_OID, assignment.getId(), ActivationStatusType.DISABLED, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - + // WHEN TestUtil.displayWhen(TEST_NAME); waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - assertNoDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, + assertNoDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, ROLE_SAILOR_DRINK); PrismObject user = getUser(USER_BARBOSSA_OID); display("User after", user); assertLinks(user, 1); - + MidPointPrincipal principal = userProfileService.getPrincipal(user); assertNotAuthorized(principal, AUTZ_PUNISH_URL); } - + @Test public void test143BarbossaDisableAssignmentRedSailor() throws Exception { final String TEST_NAME = "test143BarbossaDisableAssignmentRedSailor"; @@ -1143,38 +1143,38 @@ public void test143BarbossaDisableAssignmentRedSailor() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + AssignmentType assignment = getUserAssignment(USER_BARBOSSA_OID, ROLE_RED_SAILOR_OID); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyAssignmentAdministrativeStatus(USER_BARBOSSA_OID, assignment.getId(), + modifyAssignmentAdministrativeStatus(USER_BARBOSSA_OID, assignment.getId(), ActivationStatusType.DISABLED, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, false); - + // WHEN TestUtil.displayWhen(TEST_NAME); waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, false); - assertNoDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, + assertNoDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME); - assertNoDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, + assertNoDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME); PrismObject user = getUser(USER_BARBOSSA_OID); display("User after", user); assertLinks(user, 1); - + MidPointPrincipal principal = userProfileService.getPrincipal(user); assertNotAuthorized(principal, AUTZ_PUNISH_URL); } - + @Test public void test144BarbossaEnableAssignmentRedJudge() throws Exception { final String TEST_NAME = "test144BarbossaEnableAssignmentRedJudge"; @@ -1183,36 +1183,36 @@ public void test144BarbossaEnableAssignmentRedJudge() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + AssignmentType assignment = getUserAssignment(USER_BARBOSSA_OID, ROLE_RED_JUDGE_OID); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyAssignmentAdministrativeStatus(USER_BARBOSSA_OID, assignment.getId(), + modifyAssignmentAdministrativeStatus(USER_BARBOSSA_OID, assignment.getId(), ActivationStatusType.ENABLED, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - + // WHEN TestUtil.displayWhen(TEST_NAME); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, ROLE_JUDGE_TITLE); - assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, ROLE_JUDGE_DRINK); PrismObject user = getUser(USER_BARBOSSA_OID); display("User after", user); assertLinks(user, 1); - + MidPointPrincipal principal = userProfileService.getPrincipal(user); assertAuthorized(principal, AUTZ_PUNISH_URL); } - + @Test public void test145BarbossaEnableAssignmentRedSailor() throws Exception { final String TEST_NAME = "test145BarbossaEnableAssignmentRedSailor"; @@ -1221,36 +1221,36 @@ public void test145BarbossaEnableAssignmentRedSailor() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + AssignmentType assignment = getUserAssignment(USER_BARBOSSA_OID, ROLE_RED_SAILOR_OID); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyAssignmentAdministrativeStatus(USER_BARBOSSA_OID, assignment.getId(), + modifyAssignmentAdministrativeStatus(USER_BARBOSSA_OID, assignment.getId(), ActivationStatusType.ENABLED, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - + // WHEN TestUtil.displayWhen(TEST_NAME); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, ROLE_JUDGE_TITLE); - assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, ROLE_JUDGE_DRINK, ROLE_SAILOR_DRINK); PrismObject user = getUser(USER_BARBOSSA_OID); display("User after", user); assertLinks(user, 1); - + MidPointPrincipal principal = userProfileService.getPrincipal(user); assertAuthorized(principal, AUTZ_PUNISH_URL); } - + @Test public void test146BarbossaDisableBothRedAssignments() throws Exception { final String TEST_NAME = "test146BarbossaDisableBothRedAssignments"; @@ -1259,18 +1259,18 @@ public void test146BarbossaDisableBothRedAssignments() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + AssignmentType judgeAssignment = getUserAssignment(USER_BARBOSSA_OID, ROLE_RED_JUDGE_OID); AssignmentType sailorAssignment = getUserAssignment(USER_BARBOSSA_OID, ROLE_RED_SAILOR_OID); - - ObjectDelta objectDelta = - ObjectDelta.createModificationReplaceProperty(UserType.class, + + ObjectDelta objectDelta = + ObjectDelta.createModificationReplaceProperty(UserType.class, USER_BARBOSSA_OID, new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(judgeAssignment.getId()), new NameItemPathSegment(AssignmentType.F_ACTIVATION), - new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), + new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), prismContext, ActivationStatusType.DISABLED); objectDelta.addModificationReplaceProperty(new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), @@ -1278,35 +1278,35 @@ public void test146BarbossaDisableBothRedAssignments() throws Exception { new NameItemPathSegment(AssignmentType.F_ACTIVATION), new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), ActivationStatusType.DISABLED); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(objectDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, false); - + // WHEN TestUtil.displayWhen(TEST_NAME); waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, false); - assertNoDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, + assertNoDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME); - assertNoDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, + assertNoDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME); PrismObject user = getUser(USER_BARBOSSA_OID); display("User after", user); assertLinks(user, 1); - + MidPointPrincipal principal = userProfileService.getPrincipal(user); assertNotAuthorized(principal, AUTZ_PUNISH_URL); } - + @Test public void test147BarbossaEnableBothRedAssignments() throws Exception { final String TEST_NAME = "test147BarbossaEnableBothRedAssignments"; @@ -1315,18 +1315,18 @@ public void test147BarbossaEnableBothRedAssignments() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + AssignmentType judgeAssignment = getUserAssignment(USER_BARBOSSA_OID, ROLE_RED_JUDGE_OID); AssignmentType sailorAssignment = getUserAssignment(USER_BARBOSSA_OID, ROLE_RED_SAILOR_OID); - - ObjectDelta objectDelta = - ObjectDelta.createModificationReplaceProperty(UserType.class, + + ObjectDelta objectDelta = + ObjectDelta.createModificationReplaceProperty(UserType.class, USER_BARBOSSA_OID, new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(judgeAssignment.getId()), new NameItemPathSegment(AssignmentType.F_ACTIVATION), - new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), + new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), prismContext, ActivationStatusType.ENABLED); objectDelta.addModificationReplaceProperty(new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), @@ -1334,37 +1334,37 @@ public void test147BarbossaEnableBothRedAssignments() throws Exception { new NameItemPathSegment(AssignmentType.F_ACTIVATION), new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), ActivationStatusType.ENABLED); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(objectDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - + // WHEN TestUtil.displayWhen(TEST_NAME); waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, ROLE_JUDGE_TITLE); - assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, ROLE_JUDGE_DRINK, ROLE_SAILOR_DRINK); PrismObject user = getUser(USER_BARBOSSA_OID); display("User after", user); assertLinks(user, 1); - + MidPointPrincipal principal = userProfileService.getPrincipal(user); assertAuthorized(principal, AUTZ_PUNISH_URL); } - + /** * Unassign disabled assignments. */ @@ -1376,22 +1376,22 @@ public void test149BarbossaDisableBothRedAssignmentsUnassign() throws Exception // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + AssignmentType judgeAssignment = getUserAssignment(USER_BARBOSSA_OID, ROLE_RED_JUDGE_OID); AssignmentType judgeAssignmentLight = new AssignmentType(); judgeAssignmentLight.setId(judgeAssignment.getId()); AssignmentType sailorAssignment = getUserAssignment(USER_BARBOSSA_OID, ROLE_RED_SAILOR_OID); AssignmentType sailorAssignmentLight = new AssignmentType(); sailorAssignmentLight.setId(sailorAssignment.getId()); - - ObjectDelta objectDelta = - ObjectDelta.createModificationReplaceProperty(UserType.class, + + ObjectDelta objectDelta = + ObjectDelta.createModificationReplaceProperty(UserType.class, USER_BARBOSSA_OID, new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(judgeAssignment.getId()), new NameItemPathSegment(AssignmentType.F_ACTIVATION), - new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), + new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), prismContext, ActivationStatusType.DISABLED); objectDelta.addModificationReplaceProperty(new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), @@ -1399,9 +1399,9 @@ public void test149BarbossaDisableBothRedAssignmentsUnassign() throws Exception new NameItemPathSegment(AssignmentType.F_ACTIVATION), new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), ActivationStatusType.DISABLED); - + modelService.executeChanges(MiscSchemaUtil.createCollection(objectDelta), null, task, result); - + assertNoDummyAccount(null, USER_BARBOSSA_USERNAME); waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); assertNoDummyAccount(null, USER_BARBOSSA_USERNAME); @@ -1410,46 +1410,46 @@ public void test149BarbossaDisableBothRedAssignmentsUnassign() throws Exception assertLinks(user, 1); MidPointPrincipal principal = userProfileService.getPrincipal(user); assertNotAuthorized(principal, AUTZ_PUNISH_URL); - - objectDelta = - ObjectDelta.createModificationDeleteContainer(UserType.class, + + objectDelta = + ObjectDelta.createModificationDeleteContainer(UserType.class, USER_BARBOSSA_OID, - new ItemPath(new NameItemPathSegment(UserType.F_ASSIGNMENT)), + new ItemPath(new NameItemPathSegment(UserType.F_ASSIGNMENT)), prismContext, judgeAssignmentLight); objectDelta.addModificationDeleteContainer( new ItemPath(new NameItemPathSegment(UserType.F_ASSIGNMENT)), sailorAssignmentLight); - + display("Unassign delta", objectDelta); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(objectDelta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, false); assertNoDummyAccount(null, USER_BARBOSSA_USERNAME); // to be on the safe side - + // WHEN TestUtil.displayWhen(TEST_NAME); waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); assertDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, false); - assertNoDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, + assertNoDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME); - assertNoDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, + assertNoDummyAccountAttribute(RESOURCE_DUMMY_RED_NAME, USER_BARBOSSA_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME); assertNoDummyAccount(null, USER_BARBOSSA_USERNAME); // to be on the safe side user = getUser(USER_BARBOSSA_OID); display("User after", user); assertLinks(user, 1); - + assertNoAssignments(user); - + principal = userProfileService.getPrincipal(user); assertNotAuthorized(principal, AUTZ_PUNISH_URL); } @@ -1463,25 +1463,25 @@ public void test190HermanGoesInvalid() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); - + PrismObject userHermanBefore = getUser(USER_HERMAN_OID); XMLGregorianCalendar validTo = userHermanBefore.asObjectable().getActivation().getValidTo(); assertEffectiveActivation(userHermanBefore, ActivationStatusType.ENABLED); assertValidityStatus(userHermanBefore, TimeIntervalStatusType.IN); - - // Let's move the clock tiny bit after herman's validTo + + // Let's move the clock tiny bit after herman's validTo validTo.add(XmlTypeConverter.createDuration(100)); clock.override(validTo); - + /// WHEN TestUtil.displayWhen(TEST_NAME); waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); - + // THEN XMLGregorianCalendar endCal = clock.currentTimeXMLGregorianCalendar(); @@ -1491,7 +1491,7 @@ public void test190HermanGoesInvalid() throws Exception { assertLastRecomputeTimestamp(TASK_VALIDITY_SCANNER_OID, startCal, endCal); } - + @Test public void test200ImportTriggerScannerTask() throws Exception { final String TEST_NAME = "test200ImportTriggerScannerTask"; @@ -1500,23 +1500,23 @@ public void test200ImportTriggerScannerTask() throws Exception { // GIVEN Task task = createTask(TestTriggerTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); - + /// WHEN TestUtil.displayWhen(TEST_NAME); importObjectFromFile(TASK_TRIGGER_SCANNER_FILE); - + waitForTaskStart(TASK_TRIGGER_SCANNER_OID, false); waitForTaskFinish(TASK_TRIGGER_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); XMLGregorianCalendar endCal = clock.currentTimeXMLGregorianCalendar(); assertLastRecomputeTimestamp(TASK_TRIGGER_SCANNER_OID, startCal, endCal); - + } - + /** * Explicitly disable Elaine's red account. Do this at the beginning of the test. We will * move time ahead in later tests. This account should remain here exactly like this @@ -1530,19 +1530,19 @@ public void test205AccountRedElaineDisable() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN - modifyAccountShadowReplace(ACCOUNT_SHADOW_ELAINE_DUMMY_RED_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, + modifyAccountShadowReplace(ACCOUNT_SHADOW_ELAINE_DUMMY_RED_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.DISABLED); - + // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - + PrismObject accountShadow = getShadowModel(ACCOUNT_SHADOW_ELAINE_DUMMY_RED_OID); assertDisableReasonShadow(accountShadow, SchemaConstants.MODEL_DISABLE_REASON_EXPLICIT); } - + /** * Note: red resource disables account on unsassign, does NOT delete it. * Just the recompute trigger is set @@ -1555,41 +1555,41 @@ public void test210JackAssignAndUnassignAccountRed() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestMapping.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // assign Collection> deltas = new ArrayList>(); - ObjectDelta userDelta = createAccountAssignmentUserDelta(USER_JACK_OID, + ObjectDelta userDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_RED_OID, null, true); deltas.add(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", true); - + // unassign deltas = new ArrayList>(); userDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_RED_OID, null, false); deltas.add(userDelta); - + // WHEN modelService.executeChanges(deltas, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + // Let's wait for the task to give it a change to screw up waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); - + PrismObject userJack = getUser(USER_JACK_OID); display("Jack", userJack); assertUserJack(userJack, "Jack Sparrow", "Jack", "Sparrow"); - + String accountRedOid = getLinkRefOid(userJack, RESOURCE_DUMMY_RED_OID); PrismObject accountRed = getShadowModel(accountRedOid); - + XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); start.add(XmlTypeConverter.createDuration(true, 0, 0, 25, 0, 0, 0)); XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); @@ -1600,10 +1600,10 @@ public void test210JackAssignAndUnassignAccountRed() throws Exception { assertDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME, "Jack Sparrow", false); } - + /** * Move time a month ahead. The account that was disabled in a previous test should be - * deleted now. + * deleted now. */ @Test public void test215JackDummyAccountDeleteAfterMonth() throws Exception { @@ -1613,23 +1613,23 @@ public void test215JackDummyAccountDeleteAfterMonth() throws Exception { // 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)); - + // WHEN TestUtil.displayWhen(TEST_NAME); clock.override(time); - + waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); - + assertNoDummyAccount(RESOURCE_DUMMY_RED_NAME, ACCOUNT_JACK_DUMMY_USERNAME); } - + @Test public void test220AddDrake() throws Exception { final String TEST_NAME = "test220AddDrake"; @@ -1637,10 +1637,10 @@ public void test220AddDrake() throws Exception { XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); display("Start", start); - + PrismObject userDrake = PrismTestUtil.parseObject(USER_DRAKE_FILE); UserType userDrakeType = userDrake.asObjectable(); - + // Activation ActivationType activationType = new ActivationType(); userDrakeType.setActivation(activationType); @@ -1650,7 +1650,7 @@ public void test220AddDrake() throws Exception { drakeValidTo = clock.currentTimeXMLGregorianCalendar(); drakeValidTo.add(XmlTypeConverter.createDuration(true, 0, 0, 80, 0, 0, 0)); activationType.setValidTo(drakeValidTo); - + // Assignment: dummy red AssignmentType assignmentType = new AssignmentType(); userDrakeType.getAssignment().add(assignmentType); @@ -1675,27 +1675,27 @@ public void test220AddDrake() throws Exception { dummyAssignmentType2.setDescription("just to differentiate"); display("Drake before", userDrake); - + // WHEN TestUtil.displayWhen(TEST_NAME); - + addObject(userDrake); - + // THEN // Give the tasks a chance to screw up waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); - + // Make sure that it is effectivelly disabled PrismObject userDrakeAfter = getUser(USER_DRAKE_OID); display("Drake after", userDrakeAfter); assertEffectiveActivation(userDrakeAfter, ActivationStatusType.DISABLED); - + assertLinks(userDrakeAfter, 0); - + assertNoDummyAccount(RESOURCE_DUMMY_RED_NAME, "drake"); } - + @Test public void test222Drake4DaysBeforeValidFrom() throws Exception { final String TEST_NAME = "test222Drake4DaysBeforeValidFrom"; @@ -1705,25 +1705,25 @@ public void test222Drake4DaysBeforeValidFrom() throws Exception { start.add(XmlTypeConverter.createDuration(false, 0, 0, 4, 0, 0, 0)); clock.override(start); display("Start", start); - + // WHEN // just wait waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); - + // THEN // Make sure that it is effectivelly disabled PrismObject userDrakeAfter = getUser(USER_DRAKE_OID); display("Drake after", userDrakeAfter); assertEffectiveActivation(userDrakeAfter, ActivationStatusType.DISABLED); - + String accountRedOid = getLinkRefOid(userDrakeAfter, RESOURCE_DUMMY_RED_OID); PrismObject accountRed = getShadowModel(accountRedOid); display("Drake account RED after", accountRed); - + assertDummyAccount(RESOURCE_DUMMY_RED_NAME, "drake", "Francis Drake", false); } - + @Test public void test224Drake1DaysAfterValidFrom() throws Exception { final String TEST_NAME = "test224Drake1DaysAfterValidFrom"; @@ -1733,24 +1733,24 @@ public void test224Drake1DaysAfterValidFrom() throws Exception { start.add(XmlTypeConverter.createDuration(true, 0, 0, 1, 0, 0, 0)); clock.override(start); display("Start", start); - + // WHEN // just wait waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); - + // THEN PrismObject userDrakeAfter = getUser(USER_DRAKE_OID); display("Drake after", userDrakeAfter); assertEffectiveActivation(userDrakeAfter, ActivationStatusType.ENABLED); - + String accountRedOid = getLinkRefOid(userDrakeAfter, RESOURCE_DUMMY_RED_OID); PrismObject accountRed = getShadowModel(accountRedOid); display("Drake account RED after", accountRed); - + assertDummyAccount(RESOURCE_DUMMY_RED_NAME, "drake", "Francis Drake", true); } - + @Test public void test226Drake1DayBeforeValidTo() throws Exception { final String TEST_NAME = "test226Drake1DayBeforeValidTo"; @@ -1760,24 +1760,24 @@ public void test226Drake1DayBeforeValidTo() throws Exception { start.add(XmlTypeConverter.createDuration(false, 0, 0, 1, 0, 0, 0)); clock.override(start); display("Start", start); - + // WHEN // just wait waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); - + // THEN PrismObject userDrakeAfter = getUser(USER_DRAKE_OID); display("Drake after", userDrakeAfter); assertEffectiveActivation(userDrakeAfter, ActivationStatusType.ENABLED); - + String accountRedOid = getLinkRefOid(userDrakeAfter, RESOURCE_DUMMY_RED_OID); PrismObject accountRed = getShadowModel(accountRedOid); display("Drake account RED after", accountRed); - + assertDummyAccount(RESOURCE_DUMMY_RED_NAME, "drake", "Francis Drake", true); } - + @Test public void test228Drake1DayAfterValidTo() throws Exception { final String TEST_NAME = "test228Drake1DayAfterValidTo"; @@ -1787,25 +1787,25 @@ public void test228Drake1DayAfterValidTo() throws Exception { start.add(XmlTypeConverter.createDuration(true, 0, 0, 1, 0, 0, 0)); clock.override(start); display("Start", start); - + // WHEN // just wait waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); - + // THEN PrismObject userDrakeAfter = getUser(USER_DRAKE_OID); display("Drake after", userDrakeAfter); assertEffectiveActivation(userDrakeAfter, ActivationStatusType.DISABLED); - + String accountRedOid = getLinkRefOid(userDrakeAfter, RESOURCE_DUMMY_RED_OID); PrismObject accountRed = getShadowModel(accountRedOid); display("Drake account RED after", accountRed); assertDisableReasonShadow(accountRed, SchemaConstants.MODEL_DISABLE_REASON_MAPPED); - + assertDummyAccount(RESOURCE_DUMMY_RED_NAME, "drake", "Francis Drake", false); } - + @Test public void test230Drake20DaysAfterValidTo() throws Exception { final String TEST_NAME = "test230Drake20DaysAfterValidTo"; @@ -1815,22 +1815,22 @@ public void test230Drake20DaysAfterValidTo() throws Exception { start.add(XmlTypeConverter.createDuration(true, 0, 0, 20, 0, 0, 0)); clock.override(start); display("Start", start); - + // WHEN // just wait waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); - + // THEN PrismObject userDrakeAfter = getUser(USER_DRAKE_OID); display("Drake after", userDrakeAfter); assertEffectiveActivation(userDrakeAfter, ActivationStatusType.DISABLED); - + String accountRedOid = getLinkRefOid(userDrakeAfter, RESOURCE_DUMMY_RED_OID); PrismObject accountRed = getShadowModel(accountRedOid); display("Drake account RED after", accountRed); assertDisableReasonShadow(accountRed, SchemaConstants.MODEL_DISABLE_REASON_MAPPED); - + assertDummyAccount(RESOURCE_DUMMY_RED_NAME, "drake", "Francis Drake", false); } @@ -1843,22 +1843,22 @@ public void test232Drake40DaysAfterValidTo() throws Exception { start.add(XmlTypeConverter.createDuration(true, 0, 0, 40, 0, 0, 0)); clock.override(start); display("Start", start); - + // WHEN // just wait waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); - + // THEN PrismObject userDrakeAfter = getUser(USER_DRAKE_OID); display("Drake after", userDrakeAfter); assertEffectiveActivation(userDrakeAfter, ActivationStatusType.DISABLED); - + assertLinks(userDrakeAfter, 0); - + assertNoDummyAccount(RESOURCE_DUMMY_RED_NAME, "drake"); } - + /** * Elaine's red account was explicitly disabled. We have moved the time ahead in previous tests. * But this account should remain as it is. @@ -1869,19 +1869,19 @@ public void test250CheckAccountRedElaine() throws Exception { TestUtil.displayTestTitle(this, TEST_NAME); // GIVEN - + // WHEN // nothing to do - + // THEN - + PrismObject accountShadow = getShadowModel(ACCOUNT_SHADOW_ELAINE_DUMMY_RED_OID); assertDisableReasonShadow(accountShadow, SchemaConstants.MODEL_DISABLE_REASON_EXPLICIT); } - + private XMLGregorianCalendar judgeAssignmentValidFrom; private XMLGregorianCalendar judgeAssignmentValidTo; - + @Test public void test300HermanAssignJudgeNotYetValid() throws Exception { final String TEST_NAME = "test300HermanAssignJudgeNotYetValid"; @@ -1890,7 +1890,7 @@ public void test300HermanAssignJudgeNotYetValid() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ActivationType activationType = new ActivationType(); judgeAssignmentValidFrom = clock.currentTimeXMLGregorianCalendar(); judgeAssignmentValidFrom.add(XmlTypeConverter.createDuration(10*60*1000)); // 10 minutes ahead @@ -1900,16 +1900,16 @@ public void test300HermanAssignJudgeNotYetValid() throws Exception { activationType.setValidTo(judgeAssignmentValidTo); display("Assignment validFrom", judgeAssignmentValidFrom); display("Assignment validTo", judgeAssignmentValidTo); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_HERMAN_OID, ROLE_JUDGE_OID, activationType, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertNoDummyAccount(null, USER_HERMAN_USERNAME); } - + @Test public void test310HermanAssignJudgeBecomesValid() throws Exception { final String TEST_NAME = "test310HermanAssignJudgeBecomesValid"; @@ -1918,21 +1918,21 @@ public void test310HermanAssignJudgeBecomesValid() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject user = getUser(USER_HERMAN_OID); display("User before", user); XMLGregorianCalendar start = (XMLGregorianCalendar) judgeAssignmentValidFrom.clone(); start.add(XmlTypeConverter.createDuration(1*60*1000)); clock.override(start); display("Start", start); - + // WHEN // just wait waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); - + assertRoleJudgeValid(TEST_NAME, task, result); } - + @Test public void test315HermanAssignJudgeBecomesInValid() throws Exception { final String TEST_NAME = "test315HermanAssignJudgeBecomesInValid"; @@ -1941,27 +1941,27 @@ public void test315HermanAssignJudgeBecomesInValid() throws Exception { // GIVEN Task task = createTask(TestValidityRecomputeTask.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + XMLGregorianCalendar start = (XMLGregorianCalendar) judgeAssignmentValidTo.clone(); start.add(XmlTypeConverter.createDuration(1*60*1000)); clock.override(start); display("Start", start); - + // WHEN // just wait waitForTaskNextRunAssertSuccess(TASK_VALIDITY_SCANNER_OID, true); - + assertRoleJudgeInValid(TEST_NAME, task, result); } - - private void assertRoleJudgeValid(final String TEST_NAME, Task task, OperationResult result) throws Exception { + + private void assertRoleJudgeValid(final String TEST_NAME, Task task, OperationResult result) 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(final String TEST_NAME, Task task, OperationResult result) throws Exception { assertNoDummyAccount(null, USER_HERMAN_USERNAME); PrismObject user = getUser(USER_HERMAN_OID); display("User after", user); @@ -1970,20 +1970,20 @@ private void assertRoleJudgeInValid(final String TEST_NAME, Task task, Operation private void modifyAssignmentAdministrativeStatus(String userOid, long assignmentId, ActivationStatusType status, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { if (status == null) { - modifyObjectReplaceProperty(UserType.class, userOid, + modifyObjectReplaceProperty(UserType.class, userOid, new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(assignmentId), new NameItemPathSegment(AssignmentType.F_ACTIVATION), - new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), - task, result); + new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), + task, result); } else { - modifyObjectReplaceProperty(UserType.class, userOid, + modifyObjectReplaceProperty(UserType.class, userOid, new ItemPath( new NameItemPathSegment(UserType.F_ASSIGNMENT), new IdItemPathSegment(assignmentId), new NameItemPathSegment(AssignmentType.F_ACTIVATION), - new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), + new NameItemPathSegment(ActivationType.F_ADMINISTRATIVE_STATUS)), task, result, status); } } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/util/MockTaskHandler.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/util/MockTaskHandler.java index cf768ae2fb6..98747af2339 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/util/MockTaskHandler.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/util/MockTaskHandler.java @@ -38,9 +38,9 @@ /** * This task handler does nothing. Used in the tests. - * + * * @author Radovan Semancik - * + * */ @Component public class MockTaskHandler implements TaskHandler { @@ -68,13 +68,13 @@ public TaskRunResult run(Task task) { opResult.setStatus(OperationResultStatus.IN_PROGRESS); TaskRunResult runResult = new TaskRunResult(); runResult.setOperationResult(opResult); - + opResult.recordSuccess(); runResult.setRunResultStatus(TaskRunResultStatus.FINISHED); runResult.setProgress(1); LOGGER.trace("MockTaskHandler.run ending"); - + return runResult; } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/util/MockTriggerHandler.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/util/MockTriggerHandler.java index 8b8cf850849..a8ae0f8aa9f 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/util/MockTriggerHandler.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/util/MockTriggerHandler.java @@ -31,14 +31,14 @@ * */ public class MockTriggerHandler implements TriggerHandler { - + public static final String HANDLER_URI = SchemaConstants.NS_MIDPOINT_TEST + "/mock-trigger-handler"; - + protected static final Trace LOGGER = TraceManager.getTrace(MockTriggerHandler.class); - + private PrismObject lastObject; private int invocationCount; - + public PrismObject getLastObject() { return lastObject; } @@ -56,7 +56,7 @@ public void handle(PrismObject object, TriggerType tri lastObject = object.clone(); invocationCount++; } - + public void reset() { lastObject = null; invocationCount = 0; diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/util/ProfilingLensDebugListener.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/util/ProfilingLensDebugListener.java index 98e8265eaa9..7c82dbcd5cb 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/util/ProfilingLensDebugListener.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/util/ProfilingLensDebugListener.java @@ -32,7 +32,7 @@ import org.apache.commons.lang3.ObjectUtils; public class ProfilingLensDebugListener implements LensDebugListener { - + protected static final Trace LOGGER = TraceManager.getTrace(ProfilingLensDebugListener.class); private long projectorStartTime = 0; @@ -41,7 +41,7 @@ public class ProfilingLensDebugListener implements LensDebugListener { private long projectorMappingTotalMillis = 0; private long projectorMappingTotalCount = 0; private LensContext lastLensContext; - + @Override public void beforeSync(LensContext context) { // TODO Auto-generated method stub @@ -96,9 +96,9 @@ public void afterProjection(LensContext context) { changes = allDeltas.size(); } long projectorEtime = projectorEndTime - projectorStartTime; - LOGGER.trace("Projector finished ({}), {} changes, etime: {} ms ({} mapping evaluated, {} ms total)", + LOGGER.trace("Projector finished ({}), {} changes, etime: {} ms ({} mapping evaluated, {} ms total)", new Object[]{desc, changes, projectorEtime, projectorMappingTotalCount, projectorMappingTotalMillis}); - + lastLensContext = context; } diff --git a/model/model-intest/src/test/resources/manual/resource-semi-manual-slow-proposed.xml b/model/model-intest/src/test/resources/manual/resource-semi-manual-slow-proposed.xml index 2ebb0c6efb7..9ed37092916 100644 --- a/model/model-intest/src/test/resources/manual/resource-semi-manual-slow-proposed.xml +++ b/model/model-intest/src/test/resources/manual/resource-semi-manual-slow-proposed.xml @@ -145,6 +145,8 @@ light true + all + true PT15M 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 98a5f1c2d21..f6db15f9da0 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 @@ -191,6 +191,7 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.AuthorizationDecisionType; import com.evolveum.midpoint.xml.ns._public.common.common_3.AuthorizationPhaseType; import com.evolveum.midpoint.xml.ns._public.common.common_3.AuthorizationType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ConflictResolutionType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ConstructionType; import com.evolveum.midpoint.xml.ns._public.common.common_3.CredentialsPolicyType; import com.evolveum.midpoint.xml.ns._public.common.common_3.CredentialsType; @@ -225,36 +226,36 @@ * Abstract framework for an integration test that is placed on top of a model API. * This provides complete environment that the test should need, e.g model service instance, repository, provisioning, * dummy auditing, etc. It also implements lots of useful methods to make writing the tests easier. - * + * * @author Radovan Semancik * */ public abstract class AbstractModelIntegrationTest extends AbstractIntegrationTest { - + protected static final int DEFAULT_TASK_WAIT_TIMEOUT = 25000; protected static final long DEFAULT_TASK_SLEEP_TIME = 200; - + protected static final String CONNECTOR_DUMMY_TYPE = "com.evolveum.icf.dummy.connector.DummyConnector"; 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 = new ItemPath(UserType.F_ACTIVATION, + + protected static final ItemPath ACTIVATION_ADMINISTRATIVE_STATUS_PATH = new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS); - protected static final ItemPath ACTIVATION_VALID_FROM_PATH = new ItemPath(UserType.F_ACTIVATION, + protected static final ItemPath ACTIVATION_VALID_FROM_PATH = new ItemPath(UserType.F_ACTIVATION, ActivationType.F_VALID_FROM); - protected static final ItemPath ACTIVATION_VALID_TO_PATH = new ItemPath(UserType.F_ACTIVATION, + protected static final ItemPath ACTIVATION_VALID_TO_PATH = new ItemPath(UserType.F_ACTIVATION, ActivationType.F_VALID_TO); - + protected static final ItemPath PASSWORD_VALUE_PATH = new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE); - + private static final String DEFAULT_CHANNEL = SchemaConstants.CHANNEL_GUI_USER_URI; - + @Autowired protected ModelService modelService; @Autowired protected ModelInteractionService modelInteractionService; @Autowired protected ModelDiagnosticService modelDiagnosticService; @@ -266,29 +267,29 @@ public abstract class AbstractModelIntegrationTest extends AbstractIntegrationTe @Autowired protected HookRegistry hookRegistry; @Autowired protected Clock clock; @Autowired protected PrismContext prismContext; - @Autowired protected DummyTransport dummyTransport; + @Autowired protected DummyTransport dummyTransport; @Autowired protected SecurityEnforcer securityEnforcer; @Autowired protected MidpointFunctions libraryMidpointFunctions; @Autowired protected ValuePolicyProcessor valuePolicyProcessor; - + @Autowired(required = false) protected NotificationManager notificationManager; - + @Autowired(required = false) protected UserProfileService userProfileService; - + protected DummyResourceCollection dummyResourceCollection; - + protected DummyAuditService dummyAuditService; - + protected boolean verbose = false; - + private static final Trace LOGGER = TraceManager.getTrace(AbstractModelIntegrationTest.class); - + public AbstractModelIntegrationTest() { super(); } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { LOGGER.trace("initSystem"); @@ -304,7 +305,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti notificationManager.setDisabled(true); } } - + @Override public void postInitSystem(Task initTask, OperationResult initResult) throws Exception { super.postInitSystem(initTask, initResult); @@ -316,65 +317,65 @@ public void postInitSystem(Task initTask, OperationResult initResult) throws Exc protected void startResources() throws Exception { // Nothing to do by default } - + @AfterClass protected void cleanUpSecurity() { SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(null); } - - protected DummyResourceContoller initDummyResource(String name, File resourceFile, String resourceOid, + + protected DummyResourceContoller initDummyResource(String name, File resourceFile, String resourceOid, FailableProcessor controllerInitLambda, Task task, OperationResult result) throws Exception { return dummyResourceCollection.initDummyResource(name, resourceFile, resourceOid, controllerInitLambda, task, result); } - protected DummyResourceContoller initDummyResource(String name, File resourceFile, String resourceOid, + protected DummyResourceContoller initDummyResource(String name, File resourceFile, String resourceOid, Task task, OperationResult result) throws Exception { return dummyResourceCollection.initDummyResource(name, resourceFile, resourceOid, null, task, result); } - protected DummyResourceContoller initDummyResourcePirate(String name, File resourceFile, String resourceOid, + 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 getDummyResourceController(String name) { return dummyResourceCollection.get(name); } - + protected DummyResourceContoller getDummyResourceController() { return getDummyResourceController(null); } - + protected DummyResource getDummyResource(String name) { return dummyResourceCollection.getDummyResource(name); } - + protected DummyResource getDummyResource() { return getDummyResource(null); } - + protected PrismObject getDummyResourceObject(String name) { return dummyResourceCollection.getResourceObject(name); } - + protected PrismObject getDummyResourceObject() { return getDummyResourceObject(null); } - + protected ResourceType getDummyResourceType(String name) { return dummyResourceCollection.getResourceType(name); } - + protected ResourceType getDummyResourceType() { return getDummyResourceType(null); } - + protected void importObjectFromFile(String filename) throws FileNotFoundException { importObjectFromFile(new File(filename)); } - + protected void importObjectFromFile(File file) throws FileNotFoundException { OperationResult result = new OperationResult(AbstractModelIntegrationTest.class.getName() + ".importObjectFromFile"); importObjectFromFile(file, result); @@ -385,7 +386,7 @@ protected void importObjectFromFile(File file) throws FileNotFoundException { protected void importObjectFromFile(String filename, OperationResult result) throws FileNotFoundException { importObjectFromFile(new File(filename), result); } - + protected void importObjectFromFile(File file, OperationResult result) throws FileNotFoundException { OperationResult subResult = result.createSubresult(AbstractModelIntegrationTest.class+".importObjectFromFile"); subResult.addParam("filename", file.getPath()); @@ -399,12 +400,12 @@ protected void importObjectFromFile(File file, OperationResult result) throws Fi throw new SystemException("Import of file "+file+" failed: "+subResult.getMessage(), cause); } } - + protected void importObjectFromFile(File file, Task task, OperationResult result) throws FileNotFoundException { FileInputStream stream = new FileInputStream(file); modelService.importObjectsFromStream(stream, MiscSchemaUtil.getDefaultImportOptions(), task, result); } - + protected Throwable findCause(OperationResult result) { if (result.getCause() != null) { return result.getCause(); @@ -421,38 +422,42 @@ protected Throwable findCause(OperationResult result) { 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 { importObjectFromFile(file, result); OperationResult importResult = result.getLastSubresult(); TestUtil.assertSuccess("Import of "+file+" has failed", importResult); return modelService.getObject(type, oid, null, task, result); } - + /** - * This is not the real thing. It is just for the tests. + * This is not the real thing. It is just for the tests. */ protected void applyResourceSchema(ShadowType accountType, ResourceType resourceType) throws SchemaException { IntegrationTestTools.applyResourceSchema(accountType, resourceType, prismContext); } - - + + protected void assertUsers(int expectedNumberOfUsers) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { assertObjects(UserType.class, expectedNumberOfUsers); } - + protected void assertRoles(int expectedNumberOfUsers) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { assertObjects(RoleType.class, expectedNumberOfUsers); } - + protected void assertObjects(Class type, int expectedNumberOfUsers) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + assertEquals("Unexpected number of "+type.getSimpleName()+"s", expectedNumberOfUsers, getObjectCount(type)); + } + + protected int getObjectCount(Class type) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { Task task = taskManager.createTaskInstance(AbstractModelIntegrationTest.class.getName() + ".assertObjects"); OperationResult result = task.getResult(); List> users = modelService.searchObjects(type, null, null, task, result); if (verbose) display(type.getSimpleName()+"s", users); - assertEquals("Unexpected number of "+type.getSimpleName()+"s", expectedNumberOfUsers, users.size()); + return users.size(); } - + protected void searchObjectsIterative(Class type, ObjectQuery query, Consumer> handler, Integer expectedNumberOfObjects) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { Task task = taskManager.createTaskInstance(AbstractModelIntegrationTest.class.getName() + ".assertObjects"); OperationResult result = task.getResult(); @@ -486,10 +491,10 @@ protected void assertUserNoProperty(String userOid, QName propertyName) throws O protected void assertUserProperty(PrismObject user, QName propertyName, Object... expectedPropValues) { PrismProperty property = user.findProperty(propertyName); - assert property != null : "No property "+propertyName+" in "+user; + assert property != null : "No property "+propertyName+" in "+user; PrismAsserts.assertPropertyValue(property, expectedPropValues); } - + protected void assertUserNoProperty(PrismObject user, QName propertyName) { PrismProperty property = user.findProperty(propertyName); assert property == null : "Property "+propertyName+" present in "+user+": "+property; @@ -498,11 +503,11 @@ protected void assertUserNoProperty(PrismObject user, QName propertyNa protected void assertAdministrativeStatusEnabled(PrismObject user) { assertAdministrativeStatus(user, ActivationStatusType.ENABLED); } - + protected void assertAdministrativeStatusDisabled(PrismObject user) { assertAdministrativeStatus(user, ActivationStatusType.DISABLED); } - + protected void assertAdministrativeStatus(PrismObject object, ActivationStatusType expected) { PrismProperty statusProperty = object.findProperty(ACTIVATION_ADMINISTRATIVE_STATUS_PATH); if (expected == null && statusProperty == null) { @@ -516,23 +521,23 @@ protected void assertAdministrativeStatus(PrismObject obje assert status != null : "No status property is null in "+object; assert status == expected : "status property is "+status+", expected "+expected+" in "+object; } - + protected ObjectDelta createModifyUserReplaceDelta(String userOid, QName propertyName, Object... newRealValue) { return createModifyUserReplaceDelta(userOid, new ItemPath(propertyName), newRealValue); } - + protected ObjectDelta createModifyUserReplaceDelta(String userOid, ItemPath propertyName, Object... newRealValue) { return ObjectDelta.createModificationReplaceProperty(UserType.class, userOid, propertyName, prismContext, newRealValue); } - + protected ObjectDelta createModifyUserAddDelta(String userOid, ItemPath propertyName, Object... newRealValue) { return ObjectDelta.createModificationAddProperty(UserType.class, userOid, propertyName, prismContext, newRealValue); } - + protected ObjectDelta createModifyUserDeleteDelta(String userOid, ItemPath propertyName, Object... newRealValue) { return ObjectDelta.createModificationDeleteProperty(UserType.class, userOid, propertyName, prismContext, newRealValue); } - + protected ObjectDelta createModifyUserAddAccount(String userOid, PrismObject resource) throws SchemaException { PrismObject account = getAccountShadowDefinition().instantiate(); ObjectReferenceType resourceRef = new ObjectReferenceType(); @@ -540,55 +545,55 @@ protected ObjectDelta createModifyUserAddAccount(String userOid, Prism account.asObjectable().setResourceRef(resourceRef); RefinedResourceSchema refinedSchema = RefinedResourceSchemaImpl.getRefinedSchema(resource); account.asObjectable().setObjectClass(refinedSchema.getDefaultRefinedDefinition(ShadowKindType.ACCOUNT).getObjectClassDefinition().getTypeName()); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, userOid, prismContext); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account); ReferenceDelta accountDelta = ReferenceDelta.createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); userDelta.addModification(accountDelta); - + return userDelta; } - + protected ObjectDelta createModifyUserDeleteAccount(String userOid, PrismObject resource) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { String accountOid = getLinkRefOid(userOid, resource.getOid()); PrismObject account = getShadowModel(accountOid); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, userOid, prismContext); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account); ReferenceDelta accountDelta = ReferenceDelta.createModificationDelete(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); userDelta.addModification(accountDelta); - + return userDelta; } - + protected ObjectDelta createModifyUserUnlinkAccount(String userOid, PrismObject resource) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { String accountOid = getLinkRefOid(userOid, resource.getOid()); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, userOid, prismContext); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setOid(accountOid); ReferenceDelta accountDelta = ReferenceDelta.createModificationDelete(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); userDelta.addModification(accountDelta); - + return userDelta; } - + protected ObjectDelta createModifyAccountShadowEmptyDelta(String accountOid) { return ObjectDelta.createEmptyModifyDelta(ShadowType.class, accountOid, prismContext); } - - protected ObjectDelta createModifyAccountShadowReplaceAttributeDelta(String accountOid, + + protected ObjectDelta createModifyAccountShadowReplaceAttributeDelta(String accountOid, PrismObject resource, String attributeName, Object... newRealValue) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException { return createModifyAccountShadowReplaceAttributeDelta(accountOid, resource, getAttributeQName(resource, attributeName), newRealValue); } - - protected ObjectDelta createModifyAccountShadowReplaceAttributeDelta(String accountOid, + + protected ObjectDelta createModifyAccountShadowReplaceAttributeDelta(String accountOid, PrismObject resource, QName attributeName, Object... newRealValue) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException { return createModifyAccountShadowReplaceDelta(accountOid, resource, new ItemPath(ShadowType.F_ATTRIBUTES, attributeName), newRealValue); } - + protected ObjectDelta createModifyAccountShadowReplaceDelta(String accountOid, PrismObject resource, ItemPath itemPath, Object... newRealValue) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException { if (ShadowType.F_ATTRIBUTES.equals(ItemPath.getName(itemPath.first()))) { PropertyDelta attributeDelta = createAttributeReplaceDelta(resource, ((NameItemPathSegment)itemPath.last()).getName(), newRealValue); @@ -600,11 +605,11 @@ protected ObjectDelta createModifyAccountShadowReplaceDelta(String a return accountDelta; } } - + protected PropertyDelta createAttributeReplaceDelta(PrismObject resource, String attributeLocalName, T... newRealValue) throws SchemaException { return createAttributeReplaceDelta(resource, getAttributeQName(resource, attributeLocalName), newRealValue); } - + protected PropertyDelta createAttributeReplaceDelta(PrismObject resource, QName attributeQName, T... newRealValue) throws SchemaException { PrismPropertyDefinition attributeDefinition = getAttributeDefinition(resource, attributeQName); if (attributeDefinition == null) { @@ -613,11 +618,11 @@ protected PropertyDelta createAttributeReplaceDelta(PrismObject PropertyDelta createAttributeAddDelta(PrismObject resource, String attributeLocalName, T... newRealValue) throws SchemaException { return createAttributeAddDelta(resource, getAttributeQName(resource, attributeLocalName), newRealValue); } - + protected PropertyDelta createAttributeAddDelta(PrismObject resource, QName attributeQName, T... newRealValue) throws SchemaException { PrismPropertyDefinition attributeDefinition = getAttributeDefinition(resource, attributeQName); if (attributeDefinition == null) { @@ -626,11 +631,11 @@ protected PropertyDelta createAttributeAddDelta(PrismObject return PropertyDelta.createModificationAddProperty(new ItemPath(ShadowType.F_ATTRIBUTES, attributeQName), attributeDefinition, newRealValue); } - + protected PropertyDelta createAttributeDeleteDelta(PrismObject resource, String attributeLocalName, T... newRealValue) throws SchemaException { return createAttributeDeleteDelta(resource, getAttributeQName(resource, attributeLocalName), newRealValue); } - + protected PropertyDelta createAttributeDeleteDelta(PrismObject resource, QName attributeQName, T... newRealValue) throws SchemaException { PrismPropertyDefinition attributeDefinition = getAttributeDefinition(resource, attributeQName); if (attributeDefinition == null) { @@ -639,7 +644,7 @@ protected PropertyDelta createAttributeDeleteDelta(PrismObject resource, QName attributeName) throws SchemaException { RefinedResourceSchema refinedSchema = RefinedResourceSchemaImpl.getRefinedSchema(resource); if (refinedSchema == null) { @@ -652,13 +657,13 @@ protected ResourceAttributeDefinition getAttributeDefinition(PrismObject createModifyAccountShadowAddDelta(String accountOid, ItemPath propertyName, Object... newRealValue) { return ObjectDelta.createModificationAddProperty(ShadowType.class, accountOid, propertyName, prismContext, newRealValue); } - - protected void modifyUserReplace(String userOid, QName propertyName, Task task, OperationResult result, Object... newRealValue) - throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, + + protected void modifyUserReplace(String userOid, QName propertyName, Task task, OperationResult result, Object... newRealValue) + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyUserReplace(userOid, new ItemPath(propertyName), task, result, newRealValue); } - + protected void modifyUserReplace(String userOid, QName propertyName, ModelExecuteOptions options, Task task, OperationResult result, Object... newRealValue) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { @@ -666,33 +671,33 @@ protected void modifyUserReplace(String userOid, QName propertyName, ModelExecut } protected void modifyUserReplace(String userOid, ItemPath propertyPath, Task task, OperationResult result, Object... newRealValue) - throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyUserReplace(userOid, propertyPath, null, task, result, newRealValue); } - - protected void modifyUserReplace(String userOid, ItemPath propertyPath, ModelExecuteOptions options, Task task, OperationResult result, Object... newRealValue) - throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, + + protected void modifyUserReplace(String userOid, ItemPath propertyPath, ModelExecuteOptions options, Task task, OperationResult result, Object... newRealValue) + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { ObjectDelta objectDelta = createModifyUserReplaceDelta(userOid, propertyPath, newRealValue); Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); modelService.executeChanges(deltas, options, task, result); } - + protected void modifyObjectReplaceProperty(Class type, String oid, QName propertyName, Task task, OperationResult result, Object... newRealValue) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyObjectReplaceProperty(type, oid, new ItemPath(propertyName), task, result, newRealValue); } - + protected void modifyObjectReplaceProperty(Class type, String oid, QName propertyName, ModelExecuteOptions options, Task task, OperationResult result, Object... newRealValue) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyObjectReplaceProperty(type, oid, new ItemPath(propertyName), options, task, result, newRealValue); } protected void modifyObjectReplaceProperty(Class type, String oid, ItemPath propertyPath, Task task, OperationResult result, Object... newRealValue) - throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyObjectReplaceProperty(type, oid, propertyPath, null, task, result, newRealValue); } - + protected void modifyObjectReplaceProperty(Class type, String oid, ItemPath propertyPath, ModelExecuteOptions options, Task task, OperationResult result, Object... newRealValue) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { @@ -702,31 +707,31 @@ protected void modifyObjectReplaceProperty(Class type, } protected void modifyObjectDeleteProperty(Class type, String oid, ItemPath propertyPath, Task task, OperationResult result, Object... newRealValue) - throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { ObjectDelta objectDelta = ObjectDelta.createModificationDeleteProperty(type, oid, propertyPath, prismContext, newRealValue); Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); modelService.executeChanges(deltas, null, task, result); } - - protected void modifyObjectAddProperty(Class type, String oid, ItemPath propertyPath, Task task, OperationResult result, Object... newRealValue) - throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, + + protected void modifyObjectAddProperty(Class type, String oid, ItemPath propertyPath, Task task, OperationResult result, Object... newRealValue) + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { ObjectDelta objectDelta = ObjectDelta.createModificationAddProperty(type, oid, propertyPath, prismContext, newRealValue); Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); modelService.executeChanges(deltas, null, task, result); } - - protected void modifyObjectReplaceContainer(Class type, String oid, ItemPath propertyPath, Task task, OperationResult result, C... newRealValue) - throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, + + 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 = ObjectDelta.createModificationReplaceContainer(type, oid, propertyPath, prismContext, newRealValue); Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); modelService.executeChanges(deltas, null, task, result); } - - protected void modifyObjectAddContainer(Class type, String oid, ItemPath propertyPath, Task task, OperationResult result, C... newRealValue) - throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, + + 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 = ObjectDelta.createModificationAddContainer(type, oid, propertyPath, prismContext, newRealValue); Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); @@ -734,55 +739,55 @@ protected void modifyObjectAddCo } protected void modifyObjectDeleteContainer(Class type, String oid, ItemPath propertyPath, Task task, OperationResult result, C... newRealValue) - throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { ObjectDelta objectDelta = ObjectDelta.createModificationDeleteContainer(type, oid, propertyPath, prismContext, newRealValue); Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); modelService.executeChanges(deltas, null, task, result); } - + protected void modifyObjectReplaceReference(Class type, String oid, QName refName, Task task, OperationResult result, PrismReferenceValue... refVals) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyObjectReplaceReference(type, oid, new ItemPath(refName), task, result, refVals); } - - protected void modifyObjectReplaceReference(Class type, String oid, ItemPath refPath, Task task, OperationResult result, PrismReferenceValue... refVals) - throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, + + 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 = ObjectDelta.createModificationReplaceReference(type, oid, refPath, prismContext, refVals); Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); modelService.executeChanges(deltas, null, task, result); } - - protected void modifyUserAdd(String userOid, QName propertyName, Task task, OperationResult result, Object... newRealValue) - throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, + + protected void modifyUserAdd(String userOid, QName propertyName, Task task, OperationResult result, Object... newRealValue) + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyUserAdd(userOid, new ItemPath(propertyName), task, result, newRealValue); } - - protected void modifyUserAdd(String userOid, ItemPath propertyPath, Task task, OperationResult result, Object... newRealValue) - throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, + + protected void modifyUserAdd(String userOid, ItemPath propertyPath, Task task, OperationResult result, Object... newRealValue) + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { ObjectDelta objectDelta = createModifyUserAddDelta(userOid, propertyPath, newRealValue); Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); modelService.executeChanges(deltas, null, task, result); } - - protected void modifyUserDelete(String userOid, QName propertyName, Task task, OperationResult result, Object... newRealValue) - throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, + + protected void modifyUserDelete(String userOid, QName propertyName, Task task, OperationResult result, Object... newRealValue) + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyUserDelete(userOid, new ItemPath(propertyName), task, result, newRealValue); } - - protected void modifyUserDelete(String userOid, ItemPath propertyPath, Task task, OperationResult result, Object... newRealValue) - throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, + + protected void modifyUserDelete(String userOid, ItemPath propertyPath, Task task, OperationResult result, Object... newRealValue) + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { ObjectDelta objectDelta = createModifyUserDeleteDelta(userOid, propertyPath, newRealValue); Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); modelService.executeChanges(deltas, null, task, result); } - - protected void modifyAccountShadowReplace(String accountOid, ItemPath propertyPath, Task task, OperationResult result, Object... newRealValue) - throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, + + protected void modifyAccountShadowReplace(String accountOid, ItemPath propertyPath, Task task, OperationResult result, Object... newRealValue) + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { PrismObject shadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); String resourceOid = shadow.asObjectable().getResourceRef().getOid(); @@ -791,27 +796,27 @@ protected void modifyAccountShadowReplace(String accountOid, ItemPath propertyPa Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); modelService.executeChanges(deltas, null, task, result); } - + protected void modifyUserChangePassword(String userOid, String newPassword, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { ProtectedStringType userPasswordPs = new ProtectedStringType(); userPasswordPs.setClearValue(newPassword); modifyUserReplace(userOid, PASSWORD_VALUE_PATH, task, result, userPasswordPs); } - + protected void modifyAccountChangePassword(String accountOid, String newPassword, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { ProtectedStringType userPasswordPs = new ProtectedStringType(); userPasswordPs.setClearValue(newPassword); modifyAccountShadowReplace(accountOid, PASSWORD_VALUE_PATH, task, result, userPasswordPs); } - + protected void renameObject(Class type, String oid, String newName, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyObjectReplaceProperty(type, oid, ObjectType.F_NAME, task, result, createPolyString(newName)); } - + protected void recomputeUser(String userOid, Task task, OperationResult result) throws SchemaException, PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException, ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException { modelService.recompute(UserType.class, userOid, null, task, result); } - + protected void recomputeFocus(Class clazz, String userOid, Task task, OperationResult result) throws SchemaException, PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException, ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException { modelService.recompute(clazz, userOid, null, task, result); } @@ -819,7 +824,7 @@ protected void recomputeFocus(Class clazz, String userOid, protected void recomputeUser(String userOid, ModelExecuteOptions options, Task task, OperationResult result) throws SchemaException, PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException, ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException { modelService.recompute(UserType.class, userOid, options, task, result); } - + protected void assignRole(String userOid, String roleOid) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { Task task = taskManager.createTaskInstance(AbstractModelIntegrationTest.class+".assignRole"); OperationResult result = task.getResult(); @@ -827,13 +832,13 @@ protected void assignRole(String userOid, String roleOid) throws ObjectNotFoundE result.computeStatus(); TestUtil.assertSuccess(result); } - + protected void assignRole(String userOid, String roleOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { assignRole(UserType.class, userOid, roleOid, (ActivationType) null, task, result); } - + protected void assignRole(String userOid, String roleOid, ModelExecuteOptions options, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { @@ -851,7 +856,7 @@ protected void assignRole(String userOid, String roleOid, ActivationType activat PolicyViolationException, SecurityViolationException { modifyUserAssignment(userOid, roleOid, RoleType.COMPLEX_TYPE, null, task, null, activationType, true, result); } - + protected void unassignRole(String userOid, String roleOid, ActivationType activationType, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { @@ -881,7 +886,7 @@ protected void assignRole(String userOid, String roleOid, QName relation, Task t PolicyViolationException, SecurityViolationException { modifyUserAssignment(userOid, roleOid, RoleType.COMPLEX_TYPE, relation, task, null, null, true, result); } - + protected void assignRole(String userOid, String roleOid, QName relation, ModelExecuteOptions options, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { @@ -897,7 +902,7 @@ protected void assignRole(String userOid, String roleOid, QName relation) throws result.computeStatus(); TestUtil.assertSuccess(result); } - + protected void assignRole(String userOid, String roleOid, QName relation, Consumer modificationBlock, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { @@ -911,7 +916,7 @@ protected void unassignRole(String userOid, String roleOid) throws ObjectNotFoun result.computeStatus(); TestUtil.assertSuccess(result); } - + protected void unassignRole(String userOid, String roleOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { @@ -941,7 +946,7 @@ protected void unassignRole(String userOid, String roleOid, PrismContainer ex PolicyViolationException, SecurityViolationException { modifyUserAssignment(userOid, roleOid, RoleType.COMPLEX_TYPE, null, task, extension, false, result); } - + protected void unassignRole(String userOid, String roleOid, PrismContainer extension, ModelExecuteOptions options, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { @@ -953,7 +958,7 @@ protected void unassignRole(String userOid, String roleOid, QName relation, Task PolicyViolationException, SecurityViolationException { modifyUserAssignment(userOid, roleOid, RoleType.COMPLEX_TYPE, relation, task, null, null, false, result); } - + protected void unassignRole(String userOid, String roleOid, QName relation, ModelExecuteOptions options, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { @@ -965,7 +970,7 @@ protected void unassignRole(String userOid, String roleOid, QName relation, Cons PolicyViolationException, SecurityViolationException { modifyUserAssignment(userOid, roleOid, RoleType.COMPLEX_TYPE, relation, task, modificationBlock, false, result); } - + protected void unassignAllRoles(String userOid) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { @@ -1006,28 +1011,28 @@ protected void unassignAllRoles(String userOid, boolean useRawPlusRecompute) thr TestUtil.assertSuccess(result); } } - + protected void assignOrg(String userOid, String orgOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { assignOrg(userOid, orgOid, null, task, result); } - + protected void assignOrg(Class focusType, String focusOid, String orgOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { assignOrg(focusType, focusOid, orgOid, null, task, result); } - + protected void assignOrg(String userOid, String orgOid) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { assignOrg(userOid, orgOid, SchemaConstants.ORG_DEFAULT); } - - protected void assignOrg(String userOid, String orgOid, QName relation) - throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, - CommunicationException, ConfigurationException, ObjectAlreadyExistsException, + + protected void assignOrg(String userOid, String orgOid, QName relation) + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, + CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { Task task = createTask(AbstractIntegrationTest.class.getName()+".assignOrg"); OperationResult result = task.getResult(); @@ -1035,14 +1040,14 @@ protected void assignOrg(String userOid, String orgOid, QName relation) result.computeStatus(); TestUtil.assertSuccess(result); } - + protected void assignOrg(String userOid, String orgOid, QName relation, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyUserAssignment(userOid, orgOid, OrgType.COMPLEX_TYPE, relation, task, (Consumer)null, true, result); } - + protected void assignOrg(Class focusType, String focusOid, String orgOid, QName relation, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, @@ -1053,14 +1058,14 @@ protected void assignOrg(Class focusType, String focusO protected void unassignOrg(String userOid, String orgOid) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { unassignOrg(userOid, orgOid, SchemaConstants.ORG_DEFAULT); } - + protected void unassignOrg(String userOid, String orgOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { unassignOrg(userOid, orgOid, null, task, result); } - + protected void unassignOrg(String userOid, String orgOid, QName relation) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { Task task = taskManager.createTaskInstance(AbstractModelIntegrationTest.class+".unassignOrg"); OperationResult result = task.getResult(); @@ -1068,24 +1073,24 @@ protected void unassignOrg(String userOid, String orgOid, QName relation) throws result.computeStatus(); TestUtil.assertSuccess(result); } - - + + protected void unassignOrg(String userOid, String orgOid, QName relation, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyUserAssignment(userOid, orgOid, OrgType.COMPLEX_TYPE, relation, task, (Consumer)null, false, result); } - - protected void modifyUserAssignment(String userOid, String roleOid, QName refType, QName relation, Task task, + + protected void modifyUserAssignment(String userOid, String roleOid, QName refType, QName relation, Task task, PrismContainer extension, boolean add, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyUserAssignment(userOid, roleOid, refType, relation, task, extension, null, add, result); } - - protected void modifyUserAssignment(String userOid, String roleOid, QName refType, QName relation, Task task, - PrismContainer extension, ActivationType activationType, boolean add, OperationResult result) + + protected void modifyUserAssignment(String userOid, String roleOid, QName refType, QName relation, Task task, + PrismContainer extension, ActivationType activationType, boolean add, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { @@ -1102,7 +1107,7 @@ protected void modifyUserAssignment(String userOid, String roleOid, QName refTyp Collection> deltas = MiscSchemaUtil.createCollection(userDelta); modelService.executeChanges(deltas, options, task, result); } - + protected void modifyFocusAssignment(Class focusClass, String focusOid, String roleOid, QName refType, QName relation, Task task, PrismContainer extension, ActivationType activationType, boolean add, OperationResult result) throws ObjectNotFoundException, @@ -1122,11 +1127,11 @@ protected void modifyFocusAssignment(Class focusClass, } protected void modifyUserAssignment(String userOid, String roleOid, QName refType, QName relation, Task task, - Consumer modificationBlock, boolean add, OperationResult result) + Consumer modificationBlock, boolean add, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyFocusAssignment(UserType.class, userOid, roleOid, refType, relation, task, modificationBlock, add, result); } - + protected void modifyUserAssignment(String userOid, String roleOid, QName refType, QName relation, Task task, Consumer modificationBlock, boolean add, ModelExecuteOptions options, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { @@ -1134,11 +1139,11 @@ protected void modifyUserAssignment(String userOid, String roleOid, QName refTyp } protected void modifyFocusAssignment(Class focusClass, String focusOid, String roleOid, QName refType, QName relation, Task task, - Consumer modificationBlock, boolean add, OperationResult result) + Consumer modificationBlock, boolean add, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyFocusAssignment(focusClass, focusOid, roleOid, refType, relation, task, modificationBlock, add, null, result); } - + protected void modifyFocusAssignment(Class focusClass, String focusOid, String roleOid, QName refType, QName relation, Task task, Consumer modificationBlock, boolean add, ModelExecuteOptions options, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { @@ -1146,7 +1151,7 @@ protected void modifyFocusAssignment(Class focusClass, Collection> deltas = MiscSchemaUtil.createCollection(focusDelta); modelService.executeChanges(deltas, options, task, result); } - + /** * Executes unassign delta by removing each assignment individually by id. */ @@ -1165,11 +1170,11 @@ protected ObjectDelta createUnassignAllDelta(PrismObjec } return ObjectDelta.createModifyDelta(focusBefore.getOid(), modifications, focusBefore.getCompileTimeClass(), prismContext); } - + /** * Executes assignment replace delta with empty values. */ - protected void unassignAllReplace(String userOid, Task task, OperationResult result) + protected void unassignAllReplace(String userOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { @@ -1178,11 +1183,11 @@ protected void unassignAllReplace(String userOid, Task task, OperationResult res Collection> deltas = MiscSchemaUtil.createCollection(userDelta); modelService.executeChanges(deltas, null, task, result); } - - protected ContainerDelta createAssignmentModification(String roleOid, QName refType, QName relation, + + protected ContainerDelta createAssignmentModification(String roleOid, QName refType, QName relation, PrismContainer extension, ActivationType activationType, boolean add) throws SchemaException { try { - return createAssignmentModification(roleOid, refType, relation, + return createAssignmentModification(roleOid, refType, relation, assignment -> { if (extension != null) { try { @@ -1197,9 +1202,9 @@ protected ContainerDelta createAssignmentModification(String rol throw (SchemaException)te.getCause(); } } - - - protected ContainerDelta createAssignmentModification(String roleOid, QName refType, QName relation, + + + protected ContainerDelta createAssignmentModification(String roleOid, QName refType, QName relation, Consumer modificationBlock, boolean add) throws SchemaException { ContainerDelta assignmentDelta = ContainerDelta.createDelta(UserType.F_ASSIGNMENT, getUserDefinition()); PrismContainerValue cval = new PrismContainerValue(prismContext); @@ -1217,7 +1222,7 @@ protected ContainerDelta createAssignmentModification(String rol } return assignmentDelta; } - + protected ContainerDelta createAssignmentModification(long id, boolean add) throws SchemaException { ContainerDelta assignmentDelta = ContainerDelta.createDelta(UserType.F_ASSIGNMENT, getUserDefinition()); PrismContainerValue cval = new PrismContainerValue(prismContext); @@ -1229,15 +1234,15 @@ protected ContainerDelta createAssignmentModification(long id, b } return assignmentDelta; } - - protected ObjectDelta createAssignmentUserDelta(String userOid, String roleOid, QName refType, QName relation, + + protected ObjectDelta createAssignmentUserDelta(String userOid, String roleOid, QName refType, QName relation, PrismContainer extension, ActivationType activationType, boolean add) throws SchemaException { Collection> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(roleOid, refType, relation, extension, activationType, add))); ObjectDelta userDelta = ObjectDelta.createModifyDelta(userOid, modifications, UserType.class, prismContext); return userDelta; } - + protected ObjectDelta createAssignmentFocusDelta(Class focusClass, String focusOid, String roleOid, QName refType, QName relation, PrismContainer extension, ActivationType activationType, boolean add) throws SchemaException { Collection> modifications = new ArrayList<>(); @@ -1249,7 +1254,7 @@ protected ObjectDelta createAssignmentUserDelta(String userOid, String Consumer modificationBlock, boolean add) throws SchemaException { return createAssignmentFocusDelta(UserType.class, userOid, roleOid, refType, relation, modificationBlock, add); } - + protected ObjectDelta createAssignmentFocusDelta(Class focusClass, String userOid, String roleOid, QName refType, QName relation, Consumer modificationBlock, boolean add) throws SchemaException { Collection> modifications = new ArrayList<>(); @@ -1264,8 +1269,8 @@ protected ContainerDelta createAccountAssignmentModification(Str protected PropertyDelta createUserPropertyReplaceModification(QName propertyName, V... values) { return PropertyDelta.createReplaceDelta(getUserDefinition(), propertyName, values); } - - protected ContainerDelta createAssignmentModification(String resourceOid, ShadowKindType kind, + + protected ContainerDelta createAssignmentModification(String resourceOid, ShadowKindType kind, String intent, boolean add) throws SchemaException { AssignmentType assignmentType = createConstructionAssignment(resourceOid, kind, intent); return createAssignmentModification(assignmentType, add); @@ -1285,11 +1290,11 @@ protected ContainerDelta createAssignmentModification(Assignment return assignmentDelta; } - + protected AssignmentType createAccountAssignment(String resourceOid, String intent) { return createConstructionAssignment(resourceOid, ShadowKindType.ACCOUNT, intent); } - + protected AssignmentType createConstructionAssignment(String resourceOid, ShadowKindType kind, String intent) { AssignmentType assignmentType = new AssignmentType(); ConstructionType constructionType = new ConstructionType(); @@ -1302,7 +1307,7 @@ protected AssignmentType createConstructionAssignment(String resourceOid, Shadow constructionType.setIntent(intent); return assignmentType; } - + protected AssignmentType createTargetAssignment(String targetOid, QName targetType) { AssignmentType assignmentType = new AssignmentType(); ObjectReferenceType targetRef = new ObjectReferenceType(); @@ -1311,10 +1316,10 @@ protected AssignmentType createTargetAssignment(String targetOid, QName targetTy assignmentType.setTargetRef(targetRef); return assignmentType; } - + protected ObjectDelta createParametricAssignmentDelta(String userOid, String roleOid, String orgOid, String tenantOid, boolean adding) throws SchemaException { Collection> modifications = new ArrayList<>(); - + ContainerDelta assignmentDelta = ContainerDelta.createDelta(UserType.F_ASSIGNMENT, getUserDefinition()); PrismContainerValue cval = new PrismContainerValue(prismContext); if (adding) { @@ -1325,26 +1330,26 @@ protected ObjectDelta createParametricAssignmentDelta(String userOid, PrismReference targetRef = cval.findOrCreateReference(AssignmentType.F_TARGET_REF); targetRef.getValue().setOid(roleOid); targetRef.getValue().setTargetType(RoleType.COMPLEX_TYPE); - + if (orgOid != null) { PrismReference orgRef = cval.findOrCreateReference(AssignmentType.F_ORG_REF); orgRef.getValue().setOid(orgOid); } - + if (tenantOid != null) { PrismReference tenantRef = cval.findOrCreateReference(AssignmentType.F_TENANT_REF); tenantRef.getValue().setOid(tenantOid); } - - + + modifications.add(assignmentDelta); return ObjectDelta.createModifyDelta(userOid, modifications, UserType.class, prismContext); } - + protected void assignParametricRole(String userOid, String roleOid, String orgOid, String tenantOid, Task task, OperationResult result) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { assignParametricRole(userOid, roleOid, orgOid, tenantOid, null, task, result); } - + protected void assignParametricRole(String userOid, String roleOid, String orgOid, String tenantOid, ModelExecuteOptions options, Task task, OperationResult result) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { Collection> deltas = MiscSchemaUtil.createCollection( createParametricAssignmentDelta(userOid, roleOid, orgOid, tenantOid, true)); @@ -1354,7 +1359,7 @@ protected void assignParametricRole(String userOid, String roleOid, String orgOi protected void unassignParametricRole(String userOid, String roleOid, String orgOid, String tenantOid, Task task, OperationResult result) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { unassignParametricRole(userOid, roleOid, orgOid, tenantOid, null, task, result); } - + protected void unassignParametricRole(String userOid, String roleOid, String orgOid, String tenantOid, ModelExecuteOptions options, Task task, OperationResult result) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { Collection> deltas = MiscSchemaUtil.createCollection( createParametricAssignmentDelta(userOid, roleOid, orgOid, tenantOid, false)); @@ -1372,9 +1377,9 @@ protected void assertAssignees(String targetOid, QName relation, int expectedAss SearchResultList> assignees = listAssignees(targetOid, result); AssertJUnit.fail("Unexpected number of assignees of "+targetOid+" as '"+relation+"', expected "+expectedAssignees+", but was " + count+ ": "+assignees); } - + } - + protected int countAssignees(String targetOid, OperationResult result) throws SchemaException { return countAssignees(targetOid, SchemaConstants.ORG_DEFAULT, result); } @@ -1388,7 +1393,7 @@ protected int countAssignees(String targetOid, QName relation, OperationResult r .build(); return repositoryService.countObjects(FocusType.class, query, result); } - + protected SearchResultList> listAssignees(String targetOid, OperationResult result) throws SchemaException { ObjectQuery query = QueryBuilder.queryFor(FocusType.class, prismContext) .item(FocusType.F_ASSIGNMENT, AssignmentType.F_TARGET_REF).ref(targetOid) @@ -1420,11 +1425,11 @@ protected ObjectDelta createReplaceAccountConstructionUserDelta(String ObjectDelta userDelta = ObjectDelta.createModifyDelta(userOid, modifications, UserType.class, prismContext); return userDelta; } - + protected ObjectDelta createAccountAssignmentUserDelta(String userOid, String resourceOid, String intent, boolean add) throws SchemaException { return createAssignmentDelta(UserType.class, userOid, resourceOid, ShadowKindType.ACCOUNT, intent, add); } - + protected ObjectDelta createAssignmentDelta(Class type, String focusOid, String resourceOid, ShadowKindType kind, String intent, boolean add) throws SchemaException { Collection> modifications = new ArrayList<>(); @@ -1432,7 +1437,7 @@ protected ObjectDelta createAssignmentDelta(Class ty ObjectDelta userDelta = ObjectDelta.createModifyDelta(focusOid, modifications, type, prismContext); return userDelta; } - + protected Collection> executeChanges(ObjectDelta objectDelta, ModelExecuteOptions options, Task task, OperationResult result) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); return modelService.executeChanges(deltas, options, task, result); @@ -1452,19 +1457,19 @@ protected void assignAccount(String userOid, String resourceOid, String intent) result.computeStatus(); TestUtil.assertSuccess(result); } - + protected void assignAccount(String userOid, String resourceOid, String intent, Task task, OperationResult result) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { ObjectDelta userDelta = createAccountAssignmentUserDelta(userOid, resourceOid, intent, true); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); modelService.executeChanges(deltas, null, task, result); } - + protected void unassignAccount(String userOid, String resourceOid, String intent, Task task, OperationResult result) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { ObjectDelta userDelta = createAccountAssignmentUserDelta(userOid, resourceOid, intent, false); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); modelService.executeChanges(deltas, null, task, result); } - + protected PrismObject getUser(String userOid) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { Task task = taskManager.createTaskInstance(AbstractModelIntegrationTest.class.getName() + ".getUser"); OperationResult result = task.getResult(); @@ -1477,7 +1482,7 @@ protected PrismObject getUser(String userOid) throws ObjectNotFoundExc protected PrismObject getUserFromRepo(String userOid) throws ObjectNotFoundException, SchemaException { return repositoryService.getObject(UserType.class, userOid, null, new OperationResult("dummy")); } - + protected PrismObject findObjectByName(Class type, String name) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { Task task = taskManager.createTaskInstance(AbstractModelIntegrationTest.class.getName() + ".findObjectByName"); OperationResult result = task.getResult(); @@ -1488,11 +1493,11 @@ protected PrismObject findObjectByName(Class type, assert objects.size() == 1 : "Too many objects found for name "+name+": "+objects; return objects.iterator().next(); } - + protected ObjectQuery createNameQuery(String name) throws SchemaException { return ObjectQueryUtil.createNameQuery(PrismTestUtil.createPolyString(name), prismContext); } - + protected PrismObject findUserByUsername(String username) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { return findObjectByName(UserType.class, username); } @@ -1519,8 +1524,8 @@ protected PrismObject findAccountByUsername(String username, PrismOb OperationResult result = task.getResult(); return findAccountByUsername(username, resource, task, result); } - - protected PrismObject findAccountByUsername(String username, PrismObject resource, + + protected PrismObject findAccountByUsername(String username, PrismObject resource, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { ObjectQuery query = createAccountShadowQuery(username, resource); List> accounts = modelService.searchObjects(ShadowType.class, query, null, task, result); @@ -1530,10 +1535,10 @@ protected PrismObject findAccountByUsername(String username, PrismOb assert accounts.size() == 1 : "Too many accounts found for username "+username+" on "+resource+": "+accounts; return accounts.iterator().next(); } - - protected Collection> listAccounts(PrismObject resource, + + protected Collection> listAccounts(PrismObject resource, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { - + RefinedResourceSchema rSchema = RefinedResourceSchemaImpl.getRefinedSchema(resource); RefinedObjectClassDefinition rAccount = rSchema.getDefaultRefinedDefinition(ShadowKindType.ACCOUNT); Collection identifierDefs = rAccount.getPrimaryIdentifiers(); @@ -1546,15 +1551,15 @@ protected Collection> listAccounts(PrismObject> accounts = modelService.searchObjects(ShadowType.class, query, null, task, result); return accounts; } - + protected PrismObject getShadowModel(String accountOid) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { return getShadowModel(accountOid, false, true); } - + protected PrismObject getShadowModelNoFetch(String accountOid) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { return getShadowModel(accountOid, true, true); } - + protected PrismObject getShadowModel(String accountOid, boolean noFetch, boolean assertSuccess) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { Task task = taskManager.createTaskInstance(AbstractModelIntegrationTest.class.getName() + ".getAccount"); OperationResult result = task.getResult(); @@ -1580,15 +1585,15 @@ protected void assertNoObject(Class type, String oid) protected void assertNoObject(Class type, String oid, Task task, OperationResult result) throws SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { try { PrismObject object = modelService.getObject(type, oid, null, task, result); - + AssertJUnit.fail("Expected that "+object+" does not exist, but it does"); } catch (ObjectNotFoundException e) { // This is expected return; } } - - protected void assertNoShadow(String username, PrismObject resource, + + protected void assertNoShadow(String username, PrismObject resource, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException { ObjectQuery query = createAccountShadowQuery(username, resource); List> accounts = repositoryService.searchObjects(ShadowType.class, query, null, result); @@ -1598,8 +1603,8 @@ protected void assertNoShadow(String username, PrismObject resourc LOGGER.error("Found shadow for "+username+" on "+resource+" while not expecting it:\n"+accounts.get(0).debugDump()); assert false : "Found shadow for "+username+" on "+resource+" while not expecting it: "+accounts; } - - protected void assertHasShadow(String username, PrismObject resource, + + protected void assertHasShadow(String username, PrismObject resource, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException { ObjectQuery query = createAccountShadowQuery(username, resource); List> accounts = repositoryService.searchObjects(ShadowType.class, query, null, result); @@ -1640,19 +1645,19 @@ protected PrismReferenceValue getSingleLinkRef(PrismObject assertEquals("OID mismatch in linkRefValue", accountOid, accountRefValue.getOid()); return accountRefValue; } - + protected String getLinkRefOid(String userOid, String resourceOid) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { return getLinkRefOid(getUser(userOid), resourceOid); } - + protected String getLinkRefOid(PrismObject focus, String resourceOid) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismReferenceValue linkRef = getLinkRef(focus, resourceOid); if (linkRef == null) { return null; } - return linkRef.getOid(); + return linkRef.getOid(); } - + protected PrismReferenceValue getLinkRef(PrismObject focus, String resourceOid) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { F focusType = focus.asObjectable(); for (ObjectReferenceType linkRefType: focusType.getLinkRef()) { @@ -1665,9 +1670,9 @@ protected PrismReferenceValue getLinkRef(PrismObject fo } } AssertJUnit.fail("Account for resource "+resourceOid+" not found in "+focus); - return null; // Never reached. But compiler complains about missing return + return null; // Never reached. But compiler complains about missing return } - + protected String getLinkRefOid(PrismObject focus, String resourceOid, ShadowKindType kind, String intent) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { F focusType = focus.asObjectable(); for (ObjectReferenceType linkRefType: focusType.getLinkRef()) { @@ -1687,9 +1692,9 @@ protected String getLinkRefOid(PrismObject focus, Strin } } AssertJUnit.fail("Linked shadow for resource "+resourceOid+", kind "+kind+" and intent "+intent+" not found in "+focus); - return null; // Never reached. But compiler complains about missing return + return null; // Never reached. But compiler complains about missing return } - + protected void assertUserNoAccountRefs(PrismObject user) { UserType userJackType = user.asObjectable(); assertEquals("Unexpected number of accountRefs", 0, userJackType.getLinkRef().size()); @@ -1700,7 +1705,7 @@ protected String assertAccount(PrismObject user, String resourceOid) t assertNotNull("User " + user + " has no account on resource " + resourceOid, accountOid); return accountOid; } - + protected void assertAccounts(String userOid, int numAccounts) throws ObjectNotFoundException, SchemaException { OperationResult result = new OperationResult("assertAccounts"); PrismObject user = repositoryService.getObject(UserType.class, userOid, null, result); @@ -1717,7 +1722,7 @@ protected void assertNoShadow(String shadowOid) throws SchemaException { // This is OK } } - + protected AssignmentType getUserAssignment(String userOid, String roleOid) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject user = getUser(userOid); List assignments = user.asObjectable().getAssignment(); @@ -1729,7 +1734,7 @@ protected AssignmentType getUserAssignment(String userOid, String roleOid) throw } return null; } - + protected AssignmentType getUserAssignment(String userOid, String roleOid, QName relation) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject user = getUser(userOid); @@ -1747,17 +1752,17 @@ protected AssignmentType getUserAssignment(String userOid, String roleOid, QName protected void assertNoAssignments(PrismObject user) { MidPointAsserts.assertNoAssignments(user); } - + protected void assertNoAssignments(String userOid, OperationResult result) throws ObjectNotFoundException, SchemaException { PrismObject user = repositoryService.getObject(UserType.class, userOid, null, result); assertNoAssignments(user); } - + protected void assertNoAssignments(String userOid) throws ObjectNotFoundException, SchemaException { OperationResult result = new OperationResult(AbstractModelIntegrationTest.class.getName() + ".assertNoShadow"); assertNoAssignments(userOid, result); } - + protected void assertAssignedRole(String userOid, String roleOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException { PrismObject user = repositoryService.getObject(UserType.class, userOid, null, result); assertAssignedRole(user, roleOid); @@ -1770,11 +1775,11 @@ protected AssignmentType assertAssignedRole(PrismObject protected AssignmentType assertAssignedRole(PrismObject user, String roleOid) { return MidPointAsserts.assertAssignedRole(user, roleOid); } - + protected static void assertAssignedRoles(PrismObject user, String... roleOids) { MidPointAsserts.assertAssignedRoles(user, roleOids); } - + protected void assignDeputy(String userDeputyOid, String userTargetOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { assignDeputy(userDeputyOid, userTargetOid, null, task, result); } @@ -1786,21 +1791,21 @@ protected void assignDeputy(String userDeputyOid, String userTargetOid, Consumer protected void unassignDeputy(String userDeputyOid, String userTargetOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { unassignDeputy(userDeputyOid, userTargetOid, null, task, result); } - + protected void unassignDeputy(String userDeputyOid, String userTargetOid, Consumer modificationBlock, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyUserAssignment(userDeputyOid, userTargetOid, UserType.COMPLEX_TYPE, SchemaConstants.ORG_DEPUTY, task, modificationBlock, false, result); } - + protected void assignDeputyLimits(String userDeputyOid, String userTargetOid, Task task, OperationResult result, ObjectReferenceType... limitTargets) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyDeputyAssignmentLimits(userDeputyOid, userTargetOid, true, task, result, limitTargets); } - + protected void unassignDeputyLimits(String userDeputyOid, String userTargetOid, Task task, OperationResult result, ObjectReferenceType... limitTargets) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyDeputyAssignmentLimits(userDeputyOid, userTargetOid, false, task, result, limitTargets); } - + protected void modifyDeputyAssignmentLimits(String userDeputyOid, String userTargetOid, boolean add, Task task, OperationResult result, ObjectReferenceType... limitTargets) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { - modifyUserAssignment(userDeputyOid, userTargetOid, UserType.COMPLEX_TYPE, SchemaConstants.ORG_DEPUTY, task, + modifyUserAssignment(userDeputyOid, userTargetOid, UserType.COMPLEX_TYPE, SchemaConstants.ORG_DEPUTY, task, assignment -> { AssignmentSelectorType limitTargetContent = new AssignmentSelectorType(); assignment.setLimitTargetContent(limitTargetContent); @@ -1813,11 +1818,11 @@ protected void modifyDeputyAssignmentLimits(String userDeputyOid, String userTar protected void assertAssignedDeputy(PrismObject focus, String targetUserOid) { MidPointAsserts.assertAssigned(focus, targetUserOid, UserType.COMPLEX_TYPE, SchemaConstants.ORG_DEPUTY); } - + protected static void assertAssignedOrgs(PrismObject user, String... orgOids) { MidPointAsserts.assertAssignedOrgs(user, orgOids); } - + protected void assertObjectRefs(String contextDesc, Collection real, ObjectType... expected) { assertObjectRefs(contextDesc, real, objectsToOids(expected)); } @@ -1908,15 +1913,15 @@ protected void assertAssignedOrg(String userOid, String orgOid, Task task, Opera PrismObject user = repositoryService.getObject(UserType.class, userOid, null, result); assertAssignedOrg(user, orgOid); } - + protected void assertAssignedOrg(PrismObject focus, String orgOid, QName relation) { MidPointAsserts.assertAssignedOrg(focus, orgOid, relation); } - + protected void assertAssignedOrg(PrismObject focus, String orgOid) { MidPointAsserts.assertAssignedOrg(focus, orgOid); } - + protected void assertNotAssignedOrg(PrismObject focus, String orgOid) { MidPointAsserts.assertNotAssignedOrg(focus, orgOid); } @@ -1929,18 +1934,18 @@ protected void assertHasOrg(String userOid, String orgOid, Task task, OperationR PrismObject user = repositoryService.getObject(UserType.class, userOid, null, result); assertAssignedOrg(user, orgOid); } - + protected void assertHasOrgs(PrismObject user, String... orgOids) throws Exception { for (String orgOid: orgOids) { assertHasOrg(user, orgOid); } assertHasOrgs(user, orgOids.length); } - + protected void assertHasOrg(PrismObject focus, String orgOid) { MidPointAsserts.assertHasOrg(focus, orgOid); } - + protected void assertHasOrg(PrismObject user, String orgOid, QName relation) { MidPointAsserts.assertHasOrg(user, orgOid, relation); } @@ -1948,7 +1953,7 @@ protected void assertHasOrg(PrismObject user, String o protected void assertHasNoOrg(PrismObject user, String orgOid) { MidPointAsserts.assertHasNoOrg(user, orgOid, null); } - + protected void assertHasNoOrg(PrismObject user, String orgOid, QName relation) { MidPointAsserts.assertHasNoOrg(user, orgOid, relation); } @@ -1956,11 +1961,11 @@ protected void assertHasNoOrg(PrismObject user, String protected void assertHasNoOrg(PrismObject user) { MidPointAsserts.assertHasNoOrg(user); } - + protected void assertHasOrgs(PrismObject user, int expectedNumber) { MidPointAsserts.assertHasOrgs(user, expectedNumber); } - + protected void assertSubOrgs(String baseOrgOid, int expected) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { Task task = taskManager.createTaskInstance(AbstractModelIntegrationTest.class+".assertSubOrgs"); OperationResult result = task.getResult(); @@ -1985,7 +1990,7 @@ protected List> getSubOrgs(String baseOrgOid, Task task, Op .build(); return modelService.searchObjects(OrgType.class, query, null, task, result); } - + protected String dumpOrgTree(String topOrgOid) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { Task task = taskManager.createTaskInstance(AbstractModelIntegrationTest.class+".assertSubOrgs"); OperationResult result = task.getResult(); @@ -1995,7 +2000,7 @@ protected String dumpOrgTree(String topOrgOid) throws SchemaException, ObjectNot TestUtil.assertSuccess(result); return dump; } - + protected String dumpOrgTree(PrismObject topOrg, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { StringBuilder sb = new StringBuilder(); dumpOrg(sb, topOrg, 0); @@ -2012,14 +2017,14 @@ private void dumpSubOrgs(StringBuilder sb, String baseOrgOid, int indent, Task t dumpSubOrgs(sb, suborg.getOid(), indent + 1, task, result); } } - + private void dumpOrg(StringBuilder sb, PrismObject org, int indent) { DebugUtil.indentDebugDump(sb, indent); sb.append(org); List linkRefs = org.asObjectable().getLinkRef(); sb.append(": ").append(linkRefs.size()).append(" links"); } - + protected void displayUsers() throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { Task task = taskManager.createTaskInstance(AbstractModelIntegrationTest.class+".displayUsers"); OperationResult result = task.getResult(); @@ -2034,7 +2039,7 @@ public boolean handle(PrismObject user, OperationResult parentResult) result.computeStatus(); TestUtil.assertSuccess(result); } - + protected void dumpFocus(String message, PrismObject focus) throws ObjectNotFoundException, SchemaException { OperationResult result = new OperationResult(AbstractIntegrationTest.class.getName() + ".dumpFocus"); StringBuilder sb = new StringBuilder(); @@ -2090,41 +2095,41 @@ protected void dumpFocus(String message, PrismObject fo protected void assertAssignments(PrismObject user, int expectedNumber) { MidPointAsserts.assertAssignments(user, expectedNumber); } - + protected void assertInducements(PrismObject role, int expectedNumber) { MidPointAsserts.assertInducements(role, expectedNumber); } - + protected void assertAssignments(PrismObject user, Class expectedType, int expectedNumber) { MidPointAsserts.assertAssignments(user, expectedType, expectedNumber); } - + protected void assertAssigned(PrismObject user, String targetOid, QName refType) { 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) throws ObjectNotFoundException, SchemaException { assertAssignedNoRole(focus); } - + protected void assertAssignedNoRole(String userOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException { PrismObject user = repositoryService.getObject(UserType.class, userOid, null, result); assertAssignedNoRole(user); } - + protected void assertAssignedNoRole(PrismObject user) { assertAssignedNo(user, RoleType.COMPLEX_TYPE); } - + protected void assertAssignedNo(PrismObject user, QName refType) { F userType = user.asObjectable(); for (AssignmentType assignmentType: userType.getAssignment()) { @@ -2136,12 +2141,12 @@ protected void assertAssignedNo(PrismObject user, QName } } } - + protected void assertAssignedAccount(String userOid, String resourceOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException { PrismObject user = repositoryService.getObject(UserType.class, userOid, null, result); assertAssignedAccount(user, resourceOid); } - + protected AssignmentType assertAssignedAccount(PrismObject user, String resourceOid) throws ObjectNotFoundException, SchemaException { UserType userType = user.asObjectable(); for (AssignmentType assignmentType: userType.getAssignment()) { @@ -2158,7 +2163,7 @@ protected AssignmentType assertAssignedAccount(PrismObject user, Strin AssertJUnit.fail(user.toString() + " does not have account assignment for resource " + resourceOid); return null; // not reached } - + protected void assertAssignedNoAccount(PrismObject user, String resourceOid) throws ObjectNotFoundException, SchemaException { UserType userType = user.asObjectable(); for (AssignmentType assignmentType: userType.getAssignment()) { @@ -2173,11 +2178,11 @@ protected void assertAssignedNoAccount(PrismObject user, String resour } } } - + protected PrismObjectDefinition getRoleDefinition() { return prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(RoleType.class); } - + protected PrismObjectDefinition getShadowDefinition() { return prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(ShadowType.class); } @@ -2185,12 +2190,12 @@ protected PrismObjectDefinition getShadowDefinition() { protected PrismContainerDefinition getAssignmentDefinition() { return prismContext.getSchemaRegistry().findContainerDefinitionByType(AssignmentType.COMPLEX_TYPE); } - + protected PrismContainerDefinition getAssignmentExtensionDefinition() { PrismContainerDefinition assignmentDefinition = getAssignmentDefinition(); return assignmentDefinition.findContainerDefinition(AssignmentType.F_EXTENSION); } - + protected PrismContainer getAssignmentExtensionInstance() throws SchemaException { return getAssignmentExtensionDefinition().instantiate(); } @@ -2198,22 +2203,22 @@ protected PrismContainer getAssignmentExtensionInstance() throws SchemaExcept protected PrismObjectDefinition getResourceDefinition() { return prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(ResourceType.class); } - + protected PrismObjectDefinition getAccountShadowDefinition() { return prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(ShadowType.class); } - - + + protected PrismObject createObject(Class type, String name) throws SchemaException { PrismObject object = getObjectDefinition(type).instantiate(); object.asObjectable().setName(createPolyStringType(name)); return object; } - + protected PrismObject createUser(String name, String fullName) throws SchemaException { return createUser(name, fullName, null); } - + protected PrismObject createUser(String name, String fullName, Boolean enabled) throws SchemaException { PrismObject user = createObject(UserType.class, name); UserType userType = user.asObjectable(); @@ -2229,7 +2234,7 @@ protected PrismObject createUser(String name, String fullName, Boolean } return user; } - + protected PrismObject createUser(String name, String givenName, String familyName, Boolean enabled) throws SchemaException { PrismObject user = getUserDefinition().instantiate(); UserType userType = user.asObjectable(); @@ -2248,12 +2253,12 @@ 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(); @@ -2265,7 +2270,7 @@ protected void fillinUserAssignmentAccountConstruction(PrismObject use assignmentType.setConstruction(accountConstruntion); user.asObjectable().getAssignment().add(assignmentType); } - + protected PrismObject createAccount(PrismObject resource, String name, boolean enabled) throws SchemaException { PrismObject shadow = getShadowDefinition().instantiate(); ShadowType shadowType = shadow.asObjectable(); @@ -2290,7 +2295,7 @@ protected PrismObject createAccount(PrismObject resour } return shadow; } - + protected void addAttributeToShadow(PrismObject shadow, PrismObject resource, String attrName, T attrValue) throws SchemaException { ResourceAttributeContainer attrs = ShadowUtil.getAttributesContainer(shadow); ResourceAttributeDefinition attrSnDef = attrs.getDefinition().findAttributeDefinition( @@ -2299,11 +2304,11 @@ protected void addAttributeToShadow(PrismObject shadow, PrismObj attr.setRealValue(attrValue); attrs.add(attr); } - + protected void setDefaultUserTemplate(String userTemplateOid) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { setDefaultObjectTemplate(UserType.COMPLEX_TYPE, userTemplateOid); } - + protected void setDefaultObjectTemplate(QName objectType, String userTemplateOid) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { OperationResult result = new OperationResult(AbstractModelIntegrationTest.class.getName()+".setDefaultObjectTemplate"); @@ -2312,19 +2317,19 @@ protected void setDefaultObjectTemplate(QName objectType, String userTemplateOid result.computeStatus(); TestUtil.assertSuccess("Aplying default object template failed (result)", result); } - + protected void setDefaultObjectTemplate(QName objectType, String objectTemplateOid, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { setDefaultObjectTemplate(objectType, null, objectTemplateOid, parentResult); } - + protected void setDefaultObjectTemplate(QName objectType, String subType, String objectTemplateOid, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { PrismObject systemConfig = repositoryService.getObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, parentResult); - + PrismContainerValue oldValue = null; for (ObjectPolicyConfigurationType focusPolicyType: systemConfig.asObjectable().getDefaultObjectPolicyConfiguration()) { if (QNameUtil.match(objectType, focusPolicyType.getType()) && MiscUtil.equals(subType, focusPolicyType.getSubtype())) { @@ -2332,13 +2337,13 @@ protected void setDefaultObjectTemplate(QName objectType, String subType, String } } Collection modifications = new ArrayList<>(); - + if (oldValue != null) { - ContainerDelta deleteDelta = ContainerDelta.createModificationDelete(SystemConfigurationType.F_DEFAULT_OBJECT_POLICY_CONFIGURATION, + ContainerDelta deleteDelta = ContainerDelta.createModificationDelete(SystemConfigurationType.F_DEFAULT_OBJECT_POLICY_CONFIGURATION, SystemConfigurationType.class, prismContext, oldValue.clone()); ((Collection)modifications).add(deleteDelta); } - + if (objectTemplateOid != null) { ObjectPolicyConfigurationType newFocusPolicyType; ContainerDelta addDelta; @@ -2346,11 +2351,11 @@ protected void setDefaultObjectTemplate(QName objectType, String subType, String newFocusPolicyType = new ObjectPolicyConfigurationType(); newFocusPolicyType.setType(objectType); newFocusPolicyType.setSubtype(subType); - addDelta = ContainerDelta.createModificationAdd(SystemConfigurationType.F_DEFAULT_OBJECT_POLICY_CONFIGURATION, + addDelta = ContainerDelta.createModificationAdd(SystemConfigurationType.F_DEFAULT_OBJECT_POLICY_CONFIGURATION, SystemConfigurationType.class, prismContext, newFocusPolicyType); } else { PrismContainerValue newValue = oldValue.clone(); - addDelta = ContainerDelta.createModificationAdd(SystemConfigurationType.F_DEFAULT_OBJECT_POLICY_CONFIGURATION, + addDelta = ContainerDelta.createModificationAdd(SystemConfigurationType.F_DEFAULT_OBJECT_POLICY_CONFIGURATION, SystemConfigurationType.class, prismContext, newValue); newFocusPolicyType = newValue.asContainerable(); } @@ -2359,44 +2364,86 @@ protected void setDefaultObjectTemplate(QName objectType, String subType, String newFocusPolicyType.setObjectTemplateRef(templateRef); ((Collection)modifications).add(addDelta); } - + modifySystemObjectInRepo(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), modifications, parentResult); - + } - + + protected void setConflictResolution(QName objectType, String subType, ConflictResolutionType conflictResolution, OperationResult parentResult) + throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { + + PrismObject systemConfig = repositoryService.getObject(SystemConfigurationType.class, + SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, parentResult); + + PrismContainerValue oldValue = null; + for (ObjectPolicyConfigurationType focusPolicyType: systemConfig.asObjectable().getDefaultObjectPolicyConfiguration()) { + if (QNameUtil.match(objectType, focusPolicyType.getType()) && MiscUtil.equals(subType, focusPolicyType.getSubtype())) { + oldValue = focusPolicyType.asPrismContainerValue(); + } + } + Collection modifications = new ArrayList<>(); + + if (oldValue != null) { + ContainerDelta deleteDelta = ContainerDelta.createModificationDelete(SystemConfigurationType.F_DEFAULT_OBJECT_POLICY_CONFIGURATION, + SystemConfigurationType.class, prismContext, oldValue.clone()); + ((Collection)modifications).add(deleteDelta); + } + + ObjectPolicyConfigurationType newFocusPolicyType = new ObjectPolicyConfigurationType(); + newFocusPolicyType.setType(objectType); + newFocusPolicyType.setSubtype(subType); + if (oldValue != null) { + ObjectReferenceType oldObjectTemplateRef = oldValue.asContainerable().getObjectTemplateRef(); + if (oldObjectTemplateRef != null) { + newFocusPolicyType.setObjectTemplateRef(oldObjectTemplateRef.clone()); + } + } + + newFocusPolicyType.setConflictResolution(conflictResolution); + + ContainerDelta addDelta = ContainerDelta.createModificationAdd(SystemConfigurationType.F_DEFAULT_OBJECT_POLICY_CONFIGURATION, + SystemConfigurationType.class, prismContext, newFocusPolicyType); + + ((Collection)modifications).add(addDelta); + + modifySystemObjectInRepo(SystemConfigurationType.class, + SystemObjectsType.SYSTEM_CONFIGURATION.value(), modifications, parentResult); + + } + protected void setGlobalSecurityPolicy(String securityPolicyOid, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { Collection modifications = new ArrayList<>(); - - ReferenceDelta refDelta = ReferenceDelta.createModificationReplace(SystemConfigurationType.F_GLOBAL_SECURITY_POLICY_REF, + + ReferenceDelta refDelta = ReferenceDelta.createModificationReplace(SystemConfigurationType.F_GLOBAL_SECURITY_POLICY_REF, SystemConfigurationType.class, prismContext, securityPolicyOid); modifications.add(refDelta); - + modifySystemObjectInRepo(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), modifications, parentResult); - + } - + protected void modifySystemObjectInRepo(Class type, String oid, Collection modifications, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { repositoryService.modifyObject(type, oid, modifications, parentResult); invalidateSystemObjectsCache(); } - + @Override protected void invalidateSystemObjectsCache() { systemObjectCache.invalidateCaches(); } - + protected ItemPath getIcfsNameAttributePath() { return new ItemPath( ShadowType.F_ATTRIBUTES, SchemaTestConstants.ICFS_NAME); - + } - + protected void assertResolvedResourceRefs(ModelContext context) { for (ModelProjectionContext projectionContext: context.getProjectionContexts()) { assertResolvedResourceRefs(projectionContext.getObjectOld(), "objectOld in "+projectionContext); @@ -2441,18 +2488,18 @@ private void assertResolvedResourceRefs(Collection 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. + * existing user values. */ protected void breakAssignmentDelta(Collection> deltas) throws SchemaException { breakAssignmentDelta((ObjectDelta)deltas.iterator().next()); } - + /** * Breaks user assignment delta in the context by inserting some empty value. This may interfere with comparing the values to - * existing user values. + * existing user values. */ protected void breakAssignmentDelta(ObjectDelta userDelta) throws SchemaException { ContainerDelta assignmentDelta = userDelta.findContainerDelta(UserType.F_ASSIGNMENT); @@ -2465,31 +2512,31 @@ protected void breakAssignmentDelta(ObjectDelta userDel } PrismContainer activationContainer = assignmentDeltaValue.findOrCreateContainer(AssignmentType.F_ACTIVATION); PrismContainerValue emptyValue = new PrismContainerValue(prismContext); - activationContainer.add(emptyValue); + activationContainer.add(emptyValue); } - - + + protected void purgeResourceSchema(String resourceOid) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { Task task = taskManager.createTaskInstance(AbstractModelIntegrationTest.class.getName() + ".purgeResourceSchema"); OperationResult result = task.getResult(); - - ObjectDelta resourceDelta = ObjectDelta.createModificationReplaceContainer(ResourceType.class, + + ObjectDelta resourceDelta = ObjectDelta.createModificationReplaceContainer(ResourceType.class, resourceOid, ResourceType.F_SCHEMA, prismContext, new PrismContainerValue[0]); Collection> deltas = MiscSchemaUtil.createCollection(resourceDelta); - + modelService.executeChanges(deltas, null, task, result); - + result.computeStatus(); TestUtil.assertSuccess(result); } - + protected List> searchOrg(String baseOrgOid, OrgFilter.Scope scope, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { ObjectQuery query = QueryBuilder.queryFor(OrgType.class, prismContext) .isInScopeOf(baseOrgOid, scope) .build(); return modelService.searchObjects(OrgType.class, query, null, task, result); } - + protected PrismObject searchObjectByName(Class type, String name) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { Task task = taskManager.createTaskInstance(AbstractModelIntegrationTest.class.getName()+".searchObjectByName"); OperationResult result = task.getResult(); @@ -2498,7 +2545,7 @@ protected PrismObject searchObjectByName(Class type TestUtil.assertSuccess(result); return out; } - + protected PrismObject searchObjectByName(Class type, String name, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { ObjectQuery query = ObjectQueryUtil.createNameQuery(name, prismContext); List> foundObjects = modelService.searchObjects(type, query, null, task, result); @@ -2518,29 +2565,29 @@ protected void assertAccountShadowModel(PrismObject accountShadow, S protected void assertAccountShadowModel(PrismObject accountShadow, String oid, String username, ResourceType resourceType, MatchingRule matchingRule) throws SchemaException { assertShadowModel(accountShadow, oid, username, resourceType, getAccountObjectClass(resourceType), matchingRule); } - + protected void assertShadowModel(PrismObject accountShadow, String oid, String username, ResourceType resourceType, QName objectClass) throws SchemaException { assertShadowModel(accountShadow, oid, username, resourceType, objectClass, null); } - + protected void assertShadowModel(PrismObject accountShadow, String oid, String username, ResourceType resourceType, QName objectClass, MatchingRule nameMatchingRule) throws SchemaException { assertShadowCommon(accountShadow, oid, username, resourceType, objectClass, nameMatchingRule, false); IntegrationTestTools.assertProvisioningShadow(accountShadow, resourceType, RefinedAttributeDefinition.class, objectClass); } - + protected QName getAttributeQName(PrismObject resource, String attributeLocalName) { String resourceNamespace = ResourceTypeUtil.getResourceNamespace(resource); return new QName(resourceNamespace, attributeLocalName); } - + protected ItemPath getAttributePath(PrismObject resource, String attributeLocalName) { return new ItemPath(ShadowType.F_ATTRIBUTES, getAttributeQName(resource, attributeLocalName)); } - + // TASKS - + protected void waitForTaskFinish(Task task, boolean checkSubresult) throws Exception { waitForTaskFinish(task, checkSubresult, DEFAULT_TASK_WAIT_TIMEOUT); } @@ -2548,7 +2595,7 @@ protected void waitForTaskFinish(Task task, boolean checkSubresult) throws Excep protected void waitForTaskFinish(Task task, boolean checkSubresult, final int timeout) throws Exception { waitForTaskFinish(task, checkSubresult, timeout, DEFAULT_TASK_SLEEP_TIME); } - + protected void waitForTaskFinish(final Task task, final boolean checkSubresult, final int timeout, long sleepTime) throws Exception { final OperationResult waitResult = new OperationResult(AbstractIntegrationTest.class+".waitForTaskFinish"); Checker checker = new Checker() { @@ -2621,11 +2668,11 @@ public void timeout() { protected void waitForTaskFinish(String taskOid, boolean checkSubresult) throws CommonException { waitForTaskFinish(taskOid, checkSubresult, DEFAULT_TASK_WAIT_TIMEOUT); } - + protected void waitForTaskFinish(final String taskOid, final boolean checkSubresult, final int timeout) throws CommonException { waitForTaskFinish(taskOid, checkSubresult, timeout, false); } - + protected void waitForTaskFinish(final String taskOid, final boolean checkSubresult, final int timeout, final boolean errorOk) throws CommonException { final OperationResult waitResult = new OperationResult(AbstractIntegrationTest.class+".waitForTaskFinish"); Checker checker = new Checker() { @@ -2663,11 +2710,11 @@ public void timeout() { }; IntegrationTestTools.waitFor("Waiting for task " + taskOid + " finish", checker, timeout, DEFAULT_TASK_SLEEP_TIME); } - + protected void waitForTaskStart(String taskOid, boolean checkSubresult) throws Exception { waitForTaskStart(taskOid, checkSubresult, DEFAULT_TASK_WAIT_TIMEOUT); } - + protected void waitForTaskStart(final String taskOid, final boolean checkSubresult,final int timeout) throws Exception { final OperationResult waitResult = new OperationResult(AbstractIntegrationTest.class+".waitForTaskStart"); Checker checker = new Checker() { @@ -2698,15 +2745,15 @@ public void timeout() { }; IntegrationTestTools.waitFor("Waiting for task " + taskOid + " start", checker, timeout, DEFAULT_TASK_SLEEP_TIME); } - + protected OperationResult waitForTaskNextRunAssertSuccess(String taskOid, boolean checkSubresult) throws Exception { return waitForTaskNextRunAssertSuccess(taskOid, checkSubresult, DEFAULT_TASK_WAIT_TIMEOUT); } - + protected OperationResult waitForTaskNextRunAssertSuccess(Task origTask, boolean checkSubresult) throws Exception { return waitForTaskNextRunAssertSuccess(origTask, checkSubresult, DEFAULT_TASK_WAIT_TIMEOUT); } - + protected OperationResult waitForTaskNextRunAssertSuccess(final String taskOid, final boolean checkSubresult, final int timeout) throws Exception { OperationResult taskResult = waitForTaskNextRun(taskOid, checkSubresult, timeout); if (isError(taskResult, checkSubresult)) { @@ -2714,7 +2761,7 @@ protected OperationResult waitForTaskNextRunAssertSuccess(final String taskOid, } return taskResult; } - + protected OperationResult waitForTaskNextRunAssertSuccess(Task origTask, final boolean checkSubresult, final int timeout) throws Exception { OperationResult taskResult = waitForTaskNextRun(origTask, checkSubresult, timeout); if (isError(taskResult, checkSubresult)) { @@ -2722,7 +2769,7 @@ protected OperationResult waitForTaskNextRunAssertSuccess(Task origTask, final b } return taskResult; } - + protected OperationResult waitForTaskNextRun(final String taskOid, final boolean checkSubresult, final int timeout) throws Exception { return waitForTaskNextRun(taskOid, checkSubresult, timeout, false); } @@ -2732,7 +2779,7 @@ protected OperationResult waitForTaskNextRun(final String taskOid, final boolean Task origTask = taskManager.getTask(taskOid, waitResult); return waitForTaskNextRun(origTask, checkSubresult, timeout, waitResult, kickTheTask); } - + protected OperationResult waitForTaskNextRun(final Task origTask, final boolean checkSubresult, final int timeout) throws Exception { return waitForTaskNextRun(origTask, checkSubresult, timeout, false); } @@ -2741,7 +2788,7 @@ protected OperationResult waitForTaskNextRun(final Task origTask, final boolean final OperationResult waitResult = new OperationResult(AbstractIntegrationTest.class+".waitForTaskNextRun"); return waitForTaskNextRun(origTask, checkSubresult, timeout, waitResult, kickTheTask); } - + protected OperationResult waitForTaskNextRun(final Task origTask, final boolean checkSubresult, final int timeout, final OperationResult waitResult, boolean kickTheTask) throws Exception { final Long origLastRunStartTimestamp = origTask.getLastRunStartTimestamp(); final Long origLastRunFinishTimestamp = origTask.getLastRunFinishTimestamp(); @@ -2754,7 +2801,7 @@ protected OperationResult waitForTaskNextRun(final Task origTask, final boolean public boolean check() throws CommonException { Task freshTask = taskManager.getTask(origTask.getOid(), waitResult); OperationResult taskResult = freshTask.getResult(); -// display("Times", longTimeToString(origLastRunStartTimestamp) + "-" + longTimeToString(origLastRunStartTimestamp) +// display("Times", longTimeToString(origLastRunStartTimestamp) + "-" + longTimeToString(origLastRunStartTimestamp) // + " : " + longTimeToString(freshTask.getLastRunStartTimestamp()) + "-" + longTimeToString(freshTask.getLastRunFinishTimestamp())); if (verbose) display("Check result", taskResult); taskResultHolder.setValue(taskResult); @@ -2780,8 +2827,8 @@ public void timeout() { Task freshTask = taskManager.getTask(origTask.getOid(), waitResult); OperationResult result = freshTask.getResult(); LOGGER.debug("Timed-out task:\n{}", freshTask.debugDump()); - display("Times", "origLastRunStartTimestamp="+longTimeToString(origLastRunStartTimestamp) - + ", origLastRunFinishTimestamp=" + longTimeToString(origLastRunFinishTimestamp) + display("Times", "origLastRunStartTimestamp="+longTimeToString(origLastRunStartTimestamp) + + ", origLastRunFinishTimestamp=" + longTimeToString(origLastRunFinishTimestamp) + ", freshTask.getLastRunStartTimestamp()=" + longTimeToString(freshTask.getLastRunStartTimestamp()) + ", freshTask.getLastRunFinishTimestamp()=" + longTimeToString(freshTask.getLastRunFinishTimestamp())); assert false : "Timeout ("+timeout+") while waiting for "+freshTask+" next run. Last result "+result; @@ -2793,29 +2840,29 @@ public void timeout() { } }; IntegrationTestTools.waitFor("Waiting for task " + origTask + " next run", checker, timeout, DEFAULT_TASK_SLEEP_TIME); - + Task freshTask = taskManager.getTask(origTask.getOid(), waitResult); LOGGER.debug("Final task:\n{}", freshTask.debugDump()); - display("Times", "origLastRunStartTimestamp="+longTimeToString(origLastRunStartTimestamp) - + ", origLastRunFinishTimestamp=" + longTimeToString(origLastRunFinishTimestamp) + display("Times", "origLastRunStartTimestamp="+longTimeToString(origLastRunStartTimestamp) + + ", origLastRunFinishTimestamp=" + longTimeToString(origLastRunFinishTimestamp) + ", freshTask.getLastRunStartTimestamp()=" + longTimeToString(freshTask.getLastRunStartTimestamp()) + ", freshTask.getLastRunFinishTimestamp()=" + longTimeToString(freshTask.getLastRunFinishTimestamp())); - + return taskResultHolder.getValue(); } - + private String longTimeToString(Long longTime) { if (longTime == null) { return "null"; } return longTime.toString(); } - + private boolean isError(OperationResult result, boolean checkSubresult) { OperationResult subresult = getSubresult(result, checkSubresult); return subresult != null ? subresult.isError() : false; } - + private boolean isUnknown(OperationResult result, boolean checkSubresult) { OperationResult subresult = getSubresult(result, checkSubresult); return subresult != null ? subresult.isUnknown() : false; // TODO or return true? @@ -2832,9 +2879,9 @@ private OperationResult getSubresult(OperationResult result, boolean checkSubres } return result; } - + protected void restartTask(String taskOid) throws CommonException { - + // Wait at least 1ms here. We have the timestamp in the tasks with a millisecond granularity. If the tasks is started, // executed and then resstarted and excecuted within the same millisecond then the second execution will not be // detected and the wait for task finish will time-out. So waiting one millisecond here will make sure that the @@ -2844,7 +2891,7 @@ protected void restartTask(String taskOid) throws CommonException { } catch (InterruptedException e) { LOGGER.warn("Sleep interrupted: {}", e.getMessage(), e); } - + final OperationResult result = new OperationResult(AbstractIntegrationTest.class+".restartTask"); Task task = taskManager.getTask(taskOid, result); LOGGER.info("Restarting task {}", taskOid); @@ -2866,7 +2913,7 @@ protected void restartTask(String taskOid) throws CommonException { throw new IllegalStateException("Task " + task + " cannot be restarted, because its state is: " + task.getExecutionStatus()); } } - + protected void setSecurityContextUser(String userOid) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { Task task = taskManager.createTaskInstance("get administrator"); PrismObject object = modelService.getObject(UserType.class, userOid, null, task, task.getResult()); @@ -2880,7 +2927,7 @@ protected void setSecurityContextUser(String userOid) throws ObjectNotFoundExcep protected String getSecurityContextUserOid() { return ((MidPointPrincipal) (SecurityContextHolder.getContext().getAuthentication().getPrincipal())).getOid(); } - + protected void assertSideEffectiveDeltasOnly(String desc, ObjectDelta focusDelta) { if (focusDelta == null) { return; @@ -2923,7 +2970,7 @@ protected void assertSideEffectiveDeltasOnly(String desc, protected void assertSideEffectiveDeltasOnly(ObjectDelta focusDelta, String desc, ActivationStatusType expectedEfficientActivation) { assertEffectualDeltas(focusDelta, desc, expectedEfficientActivation, 0); } - + protected void assertEffectualDeltas(ObjectDelta focusDelta, String desc, ActivationStatusType expectedEfficientActivation, int expectedEffectualModifications) { if (focusDelta == null) { return; @@ -2961,11 +3008,11 @@ protected void assertEffectualDeltas(ObjectDelta focusD if (focusDelta.findItemDelta(new ItemPath(FocusType.F_ITERATION_TOKEN)) != null) { expectedModifications++; } - assertEquals("Unexpected modifications in "+desc+": "+focusDelta, expectedModifications, focusDelta.getModifications().size()); + assertEquals("Unexpected modifications in "+desc+": "+focusDelta, expectedModifications, focusDelta.getModifications().size()); } - + private boolean isSideEffectDelta(ItemDelta modification) { - if (modification.getPath().containsName(ObjectType.F_METADATA) || + if (modification.getPath().containsName(ObjectType.F_METADATA) || (modification.getPath().containsName(FocusType.F_ASSIGNMENT) && modification.getPath().containsName(ActivationType.F_EFFECTIVE_STATUS))) { return true; } else if (modification.getPath().containsName(FocusType.F_ASSIGNMENT) && modification.getPath().containsName(AssignmentType.F_ACTIVATION) && modification.isReplace() && (modification instanceof ContainerDelta)) { @@ -2984,15 +3031,15 @@ private boolean isSideEffectDelta(ItemDelta modification) { } protected void assertValidFrom(PrismObject obj, Date expectedDate) { - assertEquals("Wrong validFrom in "+obj, XmlTypeConverter.createXMLGregorianCalendar(expectedDate), + assertEquals("Wrong validFrom in "+obj, XmlTypeConverter.createXMLGregorianCalendar(expectedDate), getActivation(obj).getValidFrom()); } protected void assertValidTo(PrismObject obj, Date expectedDate) { - assertEquals("Wrong validTo in "+obj, XmlTypeConverter.createXMLGregorianCalendar(expectedDate), + assertEquals("Wrong validTo in "+obj, XmlTypeConverter.createXMLGregorianCalendar(expectedDate), getActivation(obj).getValidTo()); } - + protected ActivationType getActivation(PrismObject obj) { ObjectType objectType = obj.asObjectable(); ActivationType activation; @@ -3072,13 +3119,13 @@ protected void addObject(File file) throws ObjectAlreadyE PrismObject object = PrismTestUtil.parseObject(file); addObject(object); } - + protected PrismObject addObject(File file, Task task, OperationResult result) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException, IOException { PrismObject object = PrismTestUtil.parseObject(file); addObject(object, task, result); return object; } - + protected void addObject(PrismObject object) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { Task task = taskManager.createTaskInstance(AbstractModelIntegrationTest.class.getName() + ".addObject"); OperationResult result = task.getResult(); @@ -3086,7 +3133,7 @@ protected void addObject(PrismObject object) throws Ob result.computeStatus(); TestUtil.assertSuccess(result); } - + protected void addObject(PrismObject object, Task task, OperationResult result) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { addObject(object, null, task, result); } @@ -3096,7 +3143,7 @@ protected void addObject(PrismObject object, ModelExec modelService.executeChanges(MiscSchemaUtil.createCollection(addDelta), options, task, result); object.setOid(addDelta.getOid()); } - + protected void deleteObject(Class type, String oid, Task task, OperationResult result) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { ObjectDelta delta = ObjectDelta.createDeleteDelta(type, oid, prismContext); modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); @@ -3115,42 +3162,42 @@ protected void deleteObject(Class type, String oid) th result.computeStatus(); TestUtil.assertSuccess(result); } - + protected void addTrigger(String oid, XMLGregorianCalendar timestamp, String uri) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { Task task = taskManager.createTaskInstance(AbstractModelIntegrationTest.class.getName() + ".addTrigger"); OperationResult result = task.getResult(); TriggerType triggerType = new TriggerType(); triggerType.setTimestamp(timestamp); triggerType.setHandlerUri(uri); - ObjectDelta delta = ObjectDelta.createModificationAddContainer(ObjectType.class, oid, + ObjectDelta delta = ObjectDelta.createModificationAddContainer(ObjectType.class, oid, new ItemPath(ObjectType.F_TRIGGER), prismContext, triggerType); modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); result.computeStatus(); TestUtil.assertSuccess(result); } - + protected void assertTrigger(PrismObject object, String handlerUri, XMLGregorianCalendar start, XMLGregorianCalendar end) throws ObjectNotFoundException, SchemaException { for (TriggerType trigger: object.asObjectable().getTrigger()) { - if (handlerUri.equals(trigger.getHandlerUri()) + if (handlerUri.equals(trigger.getHandlerUri()) && MiscUtil.isBetween(trigger.getTimestamp(), start, end)) { return; } } AssertJUnit.fail("Expected that " + object + " will have a trigger but it has not"); } - + protected void assertTrigger(PrismObject object, String handlerUri, XMLGregorianCalendar mid, long tolerance) throws ObjectNotFoundException, SchemaException { XMLGregorianCalendar start = XmlTypeConverter.addMillis(mid, -tolerance); XMLGregorianCalendar end = XmlTypeConverter.addMillis(mid, tolerance); for (TriggerType trigger: object.asObjectable().getTrigger()) { - if (handlerUri.equals(trigger.getHandlerUri()) + if (handlerUri.equals(trigger.getHandlerUri()) && MiscUtil.isBetween(trigger.getTimestamp(), start, end)) { return; } } AssertJUnit.fail("Expected that "+object+" will have a trigger but it has not"); } - + protected void assertNoTrigger(Class type, String oid) throws ObjectNotFoundException, SchemaException { OperationResult result = new OperationResult(AbstractModelIntegrationTest.class.getName() + ".assertNoTrigger"); PrismObject object = repositoryService.getObject(type, oid, null, result); @@ -3158,7 +3205,7 @@ protected void assertNoTrigger(Class type, String oid) TestUtil.assertSuccess(result); assertNoTrigger(object); } - + protected void assertNoTrigger(PrismObject object) throws ObjectNotFoundException, SchemaException { List triggers = object.asObjectable().getTrigger(); if (triggers != null && !triggers.isEmpty()) { @@ -3188,7 +3235,7 @@ protected void checkDummyTransportMessages(String name, int expectedCount) { } } } - + protected void assertSingleDummyTransportMessage(String name, String expectedBody) { List messages = dummyTransport.getMessages("dummy:" + name); assertNotNull("No messages recorded in dummy transport '" + name + "'", messages); @@ -3198,13 +3245,13 @@ protected void assertSingleDummyTransportMessage(String name, String expectedBod Message message = messages.get(0); assertEquals("Unexpected notifier "+name+" message body", expectedBody, message.getBody()); } - + protected String getDummyTransportMessageBody(String name, int index) { List messages = dummyTransport.getMessages("dummy:" + name); Message message = messages.get(index); return message.getBody(); } - + protected void assertHasDummyTransportMessage(String name, String expectedBody) { List messages = dummyTransport.getMessages("dummy:" + name); assertNotNull("No messages recorded in dummy transport '" + name + "'", messages); @@ -3215,7 +3262,7 @@ protected void assertHasDummyTransportMessage(String name, String expectedBody) } fail("Notifier "+name+" message body " + expectedBody + " not found"); } - + protected void displayAllNotifications() { for (java.util.Map.Entry> entry: dummyTransport.getMessages().entrySet()) { List messages = entry.getValue(); @@ -3224,7 +3271,7 @@ protected void displayAllNotifications() { } } } - + protected void displayNotifications(String name) { List messages = dummyTransport.getMessages("dummy:" + name); display("Notification messages: "+name, messages); @@ -3244,7 +3291,7 @@ protected void checkDummyTransportMessagesAtLeast(String name, int expectedCount assertNotNull("No messages recorded in dummy transport '" + name + "'", messages); assertTrue("Number of messages recorded in dummy transport '" + name + "' (" + messages.size() + ") is not at least " + expectedCount, messages.size() >= expectedCount); } - + protected DummyAccount getDummyAccount(String dummyInstanceName, String username) throws SchemaViolationException, ConflictException { DummyResource dummyResource = DummyResource.getInstance(dummyInstanceName); try { @@ -3255,7 +3302,7 @@ protected DummyAccount getDummyAccount(String dummyInstanceName, String username throw new IllegalStateException(e.getMessage(),e); } } - + protected DummyAccount getDummyAccountById(String dummyInstanceName, String id) throws SchemaViolationException, ConflictException { DummyResource dummyResource = DummyResource.getInstance(dummyInstanceName); try { @@ -3266,11 +3313,11 @@ protected DummyAccount getDummyAccountById(String dummyInstanceName, String id) throw new IllegalStateException(e.getMessage(),e); } } - + protected void assertDefaultDummyAccount(String username, String fullname, boolean active) throws SchemaViolationException, ConflictException { assertDummyAccount(null, username, fullname, active); } - + protected DummyAccount assertDummyAccount(String dummyInstanceName, String username, String fullname, Boolean active) throws SchemaViolationException, ConflictException { DummyAccount account = getDummyAccount(dummyInstanceName, username); assertNotNull("No dummy("+dummyInstanceName+") account for username "+username, account); @@ -3278,23 +3325,23 @@ protected DummyAccount assertDummyAccount(String dummyInstanceName, String usern assertEquals("Wrong activation for dummy(" + dummyInstanceName + ") account " + username, active, account.isEnabled()); return account; } - + protected DummyAccount assertDummyAccount(String dummyInstanceName, String username) throws SchemaViolationException, ConflictException { DummyAccount account = getDummyAccount(dummyInstanceName, username); assertNotNull("No dummy(" + dummyInstanceName + ") account for username " + username, account); return account; } - + protected void assertDummyAccountById(String dummyInstanceName, String id) throws SchemaViolationException, ConflictException { DummyAccount account = getDummyAccountById(dummyInstanceName, id); assertNotNull("No dummy("+dummyInstanceName+") account for id "+id, account); } - + protected void assertNoDummyAccountById(String dummyInstanceName, String id) throws SchemaViolationException, ConflictException { DummyAccount account = getDummyAccountById(dummyInstanceName, id); assertNull("Dummy(" + dummyInstanceName + ") account for id " + id + " exists while not expecting it", account); } - + protected void assertDummyAccountActivation(String dummyInstanceName, String username, Boolean active) throws SchemaViolationException, ConflictException { DummyAccount account = getDummyAccount(dummyInstanceName, username); assertNotNull("No dummy("+dummyInstanceName+") account for username "+username, account); @@ -3304,16 +3351,16 @@ protected void assertDummyAccountActivation(String dummyInstanceName, String use protected void assertNoDummyAccount(String username) throws SchemaViolationException, ConflictException { assertNoDummyAccount(null, username); } - + protected void assertNoDummyAccount(String dummyInstanceName, String username) throws SchemaViolationException, ConflictException { DummyAccount account = getDummyAccount(dummyInstanceName, username); assertNull("Dummy account for username " + username + " exists while not expecting it (" + dummyInstanceName + ")", account); } - + protected void assertDefaultDummyAccountAttribute(String username, String attributeName, Object... expectedAttributeValues) throws SchemaViolationException, ConflictException { assertDummyAccountAttribute(null, username, attributeName, expectedAttributeValues); } - + protected void assertDummyAccountAttribute(String dummyInstanceName, String username, String attributeName, Object... expectedAttributeValues) throws SchemaViolationException, ConflictException { DummyAccount account = getDummyAccount(dummyInstanceName, username); assertNotNull("No dummy account for username "+username, account); @@ -3363,15 +3410,15 @@ protected DummyGroup getDummyGroup(String dummyInstanceName, String name) throws throw new IllegalStateException(e.getMessage(),e); } } - + protected void assertDummyGroup(String username, String description) throws SchemaViolationException, ConflictException { assertDummyGroup(null, username, description, null); } - + protected void assertDummyGroup(String username, String description, Boolean active) throws SchemaViolationException, ConflictException { assertDummyGroup(null, username, description, active); } - + protected void assertDummyGroup(String dummyInstanceName, String groupname, String description, Boolean active) throws SchemaViolationException, ConflictException { DummyGroup group = getDummyGroup(dummyInstanceName, groupname); assertNotNull("No dummy("+dummyInstanceName+") group for name "+groupname, group); @@ -3385,7 +3432,7 @@ protected void assertDummyGroup(String dummyInstanceName, String groupname, Stri protected void assertNoDummyGroup(String groupname) throws SchemaViolationException, ConflictException { assertNoDummyGroup(null, groupname); } - + protected void assertNoDummyGroup(String dummyInstanceName, String groupname) throws SchemaViolationException, ConflictException { DummyGroup group = getDummyGroup(dummyInstanceName, groupname); assertNull("Dummy group '" + groupname + "' exists while not expecting it (" + dummyInstanceName + ")", group); @@ -3414,7 +3461,7 @@ protected void assertDummyGroupMember(String dummyInstanceName, String dummyGrou assertNotNull("No dummy group "+dummyGroupName, group); IntegrationTestTools.assertGroupMember(group, accountId); } - + protected void assertDefaultDummyGroupMember(String dummyGroupName, String accountId) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { assertDummyGroupMember(null, dummyGroupName, accountId); } @@ -3424,18 +3471,18 @@ protected void assertNoDummyGroupMember(String dummyInstanceName, String dummyGr DummyGroup group = dummyResource.getGroupByName(dummyGroupName); IntegrationTestTools.assertNoGroupMember(group, accountId); } - + protected void assertNoDefaultDummyGroupMember(String dummyGroupName, String accountId) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { assertNoDummyGroupMember(null, dummyGroupName, accountId); } - + protected void assertDummyAccountNoAttribute(String dummyInstanceName, String username, String attributeName) throws SchemaViolationException, ConflictException { DummyAccount account = getDummyAccount(dummyInstanceName, username); assertNotNull("No dummy account for username "+username, account); Set values = account.getAttributeValues(attributeName, Object.class); assertTrue("Unexpected values for attribute " + attributeName + " of dummy account " + username + ": " + values, values == null || values.isEmpty()); } - + protected Entry assertOpenDjAccount(String uid, String cn, Boolean active) throws DirectoryException { Entry entry = openDJController.searchByUid(uid); assertNotNull("OpenDJ accoun with uid "+uid+" not found", entry); @@ -3445,22 +3492,22 @@ protected Entry assertOpenDjAccount(String uid, String cn, Boolean active) throw } return entry; } - + protected void assertNoOpenDjAccount(String uid) throws DirectoryException { Entry entry = openDJController.searchByUid(uid); assertNull("Expected that OpenDJ account with uid " + uid + " will be gone, but it is still there", entry); } - + protected void assertIteration(PrismObject shadow, Integer expectedIteration, String expectedIterationToken) { PrismAsserts.assertPropertyValue(shadow, ShadowType.F_ITERATION, expectedIteration); PrismAsserts.assertPropertyValue(shadow, ShadowType.F_ITERATION_TOKEN, expectedIterationToken); } - + protected void assertIterationDelta(ObjectDelta shadowDelta, Integer expectedIteration, String expectedIterationToken) { PrismAsserts.assertPropertyReplace(shadowDelta, ShadowType.F_ITERATION, expectedIteration); PrismAsserts.assertPropertyReplace(shadowDelta, ShadowType.F_ITERATION_TOKEN, expectedIterationToken); } - + protected void assertSituation(PrismObject shadow, SynchronizationSituationType expectedSituation) { if (expectedSituation == null) { PrismAsserts.assertNoItem(shadow, ShadowType.F_SYNCHRONIZATION_SITUATION); @@ -3468,42 +3515,42 @@ protected void assertSituation(PrismObject shadow, SynchronizationSi PrismAsserts.assertPropertyValue(shadow, ShadowType.F_SYNCHRONIZATION_SITUATION, expectedSituation); } } - - protected void assertEnableTimestampFocus(PrismObject focus, + + protected void assertEnableTimestampFocus(PrismObject focus, XMLGregorianCalendar startTime, XMLGregorianCalendar endTime) { XMLGregorianCalendar userDisableTimestamp = focus.asObjectable().getActivation().getEnableTimestamp(); - TestUtil.assertBetween("Wrong user enableTimestamp in "+focus, + TestUtil.assertBetween("Wrong user enableTimestamp in "+focus, startTime, endTime, userDisableTimestamp); } - protected void assertDisableTimestampFocus(PrismObject focus, + protected void assertDisableTimestampFocus(PrismObject focus, XMLGregorianCalendar startTime, XMLGregorianCalendar endTime) { XMLGregorianCalendar userDisableTimestamp = focus.asObjectable().getActivation().getDisableTimestamp(); - TestUtil.assertBetween("Wrong user disableTimestamp in "+focus, + TestUtil.assertBetween("Wrong user disableTimestamp in "+focus, startTime, endTime, userDisableTimestamp); } - - protected void assertEnableTimestampShadow(PrismObject shadow, + + protected void assertEnableTimestampShadow(PrismObject shadow, XMLGregorianCalendar startTime, XMLGregorianCalendar endTime) { ActivationType activationType = shadow.asObjectable().getActivation(); assertNotNull("No activation in "+shadow, activationType); XMLGregorianCalendar userDisableTimestamp = activationType.getEnableTimestamp(); - TestUtil.assertBetween("Wrong shadow enableTimestamp in "+shadow, + TestUtil.assertBetween("Wrong shadow enableTimestamp in "+shadow, startTime, endTime, userDisableTimestamp); } - protected void assertDisableTimestampShadow(PrismObject shadow, + protected void assertDisableTimestampShadow(PrismObject shadow, XMLGregorianCalendar startTime, XMLGregorianCalendar endTime) { XMLGregorianCalendar userDisableTimestamp = shadow.asObjectable().getActivation().getDisableTimestamp(); - TestUtil.assertBetween("Wrong shadow disableTimestamp in "+shadow, + TestUtil.assertBetween("Wrong shadow disableTimestamp in "+shadow, startTime, endTime, userDisableTimestamp); } - + protected void assertDisableReasonShadow(PrismObject shadow, String expectedReason) { String disableReason = shadow.asObjectable().getActivation().getDisableReason(); assertEquals("Wrong shadow disableReason in " + shadow, expectedReason, disableReason); } - + protected String getPassword(PrismObject user) throws EncryptionException { CredentialsType credentialsType = user.asObjectable().getCredentials(); assertNotNull("No credentials in "+user, credentialsType); @@ -3513,7 +3560,7 @@ protected String getPassword(PrismObject user) throws EncryptionExcept assertNotNull("No password value in "+user, protectedStringType); return protector.decryptString(protectedStringType); } - + protected void assertPassword(PrismObject user, String expectedPassword) throws EncryptionException { String decryptedUserPassword = getPassword(user); assertEquals("Wrong password in "+user, expectedPassword, decryptedUserPassword); @@ -3536,7 +3583,7 @@ protected void assertShadowLdapPassword(PrismObject shadow, String e ProtectedStringType protectedStringType = passwordType.getValue(); assertLdapPassword(protectedStringType, expectedPassword, shadow); } - + protected void assertLdapPassword(ProtectedStringType protectedStringType, String expectedPassword, PrismObject source) throws EncryptionException { assertNotNull("No password value in "+source, protectedStringType); String decryptedUserPassword = protector.decryptString(protectedStringType); @@ -3555,27 +3602,27 @@ protected void assertGroupMember(DummyGroup group, String accountId) { protected void assertNoGroupMember(DummyGroup group, String accountId) { IntegrationTestTools.assertNoGroupMember(group, accountId); } - + protected void assertNoGroupMembers(DummyGroup group) { IntegrationTestTools.assertNoGroupMembers(group); } - + protected void login(String principalName) throws ObjectNotFoundException, SchemaException { MidPointPrincipal principal = userProfileService.getPrincipal(principalName); login(principal); } - + protected void login(PrismObject user) throws SchemaException { MidPointPrincipal principal = userProfileService.getPrincipal(user); login(principal); } - + protected void login(MidPointPrincipal principal) { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = new UsernamePasswordAuthenticationToken(principal, null); securityContext.setAuthentication(authentication); } - + protected void loginSuperUser(String principalName) throws SchemaException, ObjectNotFoundException { MidPointPrincipal principal = userProfileService.getPrincipal(principalName); loginSuperUser(principal); @@ -3597,13 +3644,13 @@ protected void loginSuperUser(MidPointPrincipal principal) throws SchemaExceptio Authentication authentication = new UsernamePasswordAuthenticationToken(principal, null); securityContext.setAuthentication(authentication); } - + protected void loginAnonymous() { - Authentication authentication = new AnonymousAuthenticationToken("foo", + Authentication authentication = new AnonymousAuthenticationToken("foo", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); SecurityContextHolder.getContext().setAuthentication(authentication); } - + protected void assertLoggedInUser(String username) { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); @@ -3637,17 +3684,17 @@ protected void assertLoggedInUser(String username) { AssertJUnit.fail("Expected logged in user '"+username+"' but there was unknown principal in the spring security context: "+principal); } } - + protected void resetAuthentication() { SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(null); } - + protected void assertNoAuthentication() { SecurityContext securityContext = SecurityContextHolder.getContext(); assertNull("Unexpected authentication", securityContext.getAuthentication()); } - + protected void displayAllUsers() throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { Task task = taskManager.createTaskInstance(AbstractModelIntegrationTest.class.getName() + ".displayAllUsers"); OperationResult result = task.getResult(); @@ -3662,7 +3709,7 @@ public boolean handle(PrismObject object, OperationResult parentResult result.computeStatus(); TestUtil.assertSuccess(result); } - + /** * Returns appropriate object synchronization settings for the class. * Assumes single sync setting for now. @@ -3699,7 +3746,7 @@ protected ObjectSynchronizationType determineSynchronization(ResourceType resour } throw new IllegalArgumentException("Synchronization setting for "+type+" and name "+name+" not found in "+resource); } - + protected void assertShadowKindIntent(String shadowOid, ShadowKindType expectedKind, String expectedIntent) throws ObjectNotFoundException, SchemaException { OperationResult result = new OperationResult(AbstractIntegrationTest.class.getName()+".assertShadowKindIntent"); @@ -3708,17 +3755,17 @@ protected void assertShadowKindIntent(String shadowOid, ShadowKindType expectedK TestUtil.assertSuccess(result); assertShadowKindIntent(shadow, expectedKind, expectedIntent); } - + protected void assertShadowKindIntent(PrismObject shadow, ShadowKindType expectedKind, String expectedIntent) { assertEquals("Wrong kind in " + shadow, expectedKind, shadow.asObjectable().getKind()); assertEquals("Wrong intent in " + shadow, expectedIntent, shadow.asObjectable().getIntent()); } - + protected PrismObject getDefaultActor() { return null; } - + protected Task createTask(String operationName) { Task task = super.createTask(operationName); PrismObject defaultActor = getDefaultActor(); @@ -3728,7 +3775,7 @@ protected Task createTask(String operationName) { task.setChannel(DEFAULT_CHANNEL); return task; } - + protected void modifyRoleAddConstruction(String roleOid, long inducementId, String resourceOid) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { Task task = createTask(AbstractModelIntegrationTest.class.getName() + ".modifyRoleAddConstruction"); OperationResult result = task.getResult(); @@ -3736,7 +3783,7 @@ protected void modifyRoleAddConstruction(String roleOid, long inducementId, Stri ObjectReferenceType resourceRedRef = new ObjectReferenceType(); resourceRedRef.setOid(resourceOid); construction.setResourceRef(resourceRedRef); - ObjectDelta roleDelta = ObjectDelta.createModificationAddContainer(RoleType.class, roleOid, + ObjectDelta roleDelta = ObjectDelta.createModificationAddContainer(RoleType.class, roleOid, new ItemPath( new NameItemPathSegment(RoleType.F_INDUCEMENT), new IdItemPathSegment(inducementId), @@ -3746,7 +3793,7 @@ protected void modifyRoleAddConstruction(String roleOid, long inducementId, Stri result.computeStatus(); TestUtil.assertSuccess(result); } - + protected void modifyRoleAddInducementTarget(String roleOid, String targetOid, boolean reconcileAffected, ModelExecuteOptions defaultOptions, Task task) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { if (task == null) { @@ -3757,7 +3804,7 @@ protected void modifyRoleAddInducementTarget(String roleOid, String targetOid, b ObjectReferenceType targetRef = new ObjectReferenceType(); targetRef.setOid(targetOid); inducement.setTargetRef(targetRef); - ObjectDelta roleDelta = ObjectDelta.createModificationAddContainer(RoleType.class, roleOid, + ObjectDelta roleDelta = ObjectDelta.createModificationAddContainer(RoleType.class, roleOid, new ItemPath(new NameItemPathSegment(RoleType.F_INDUCEMENT)), prismContext, inducement); ModelExecuteOptions options = nullToEmpty(defaultOptions); @@ -3795,27 +3842,27 @@ protected AssignmentType findInducementByTarget(String roleOid, String targetOid } return null; } - + protected void modifyRoleDeleteInducementTarget(String roleOid, String targetOid, ModelExecuteOptions options) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { Task task = createTask(AbstractModelIntegrationTest.class.getName() + ".modifyRoleDeleteInducementTarget"); OperationResult result = task.getResult(); AssignmentType inducement = findInducementByTarget(roleOid, targetOid); - ObjectDelta roleDelta = ObjectDelta.createModificationDeleteContainer(RoleType.class, roleOid, + ObjectDelta roleDelta = ObjectDelta.createModificationDeleteContainer(RoleType.class, roleOid, new ItemPath(new NameItemPathSegment(RoleType.F_INDUCEMENT)), prismContext, inducement.asPrismContainerValue().clone()); modelService.executeChanges(MiscSchemaUtil.createCollection(roleDelta), options, task, result); result.computeStatus(); TestUtil.assertSuccess(result); } - + protected void modifyRoleDeleteInducement(String roleOid, long inducementId, boolean reconcileAffected, ModelExecuteOptions defaultOptions, Task task) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { if (task == null) { task = createTask(AbstractModelIntegrationTest.class.getName() + ".modifyRoleDeleteInducement"); } OperationResult result = task.getResult(); - + AssignmentType inducement = new AssignmentType(); inducement.setId(inducementId); ObjectDelta roleDelta = ObjectDelta.createModificationDeleteContainer(RoleType.class, roleOid, @@ -3838,17 +3885,17 @@ protected ModelExecuteOptions nullToEmpty(ModelExecuteOptions options) { protected void modifyUserAddAccount(String userOid, File accountFile, Task task, OperationResult result) throws SchemaException, IOException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { PrismObject account = PrismTestUtil.parseObject(accountFile); - + ObjectDelta userDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, userOid, prismContext); PrismReferenceValue accountRefVal = new PrismReferenceValue(); accountRefVal.setObject(account); ReferenceDelta accountDelta = ReferenceDelta.createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); userDelta.addModification(accountDelta); Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); - + modelService.executeChanges(deltas, null, task, result); } - + protected void assertAuthorized(MidPointPrincipal principal, String action) throws SchemaException { assertAuthorized(principal, action, null); assertAuthorized(principal, action, AuthorizationPhaseType.REQUEST); @@ -3859,23 +3906,23 @@ protected void assertAuthorized(MidPointPrincipal principal, String action, Auth SecurityContext origContext = SecurityContextHolder.getContext(); createSecurityContext(principal); try { - assertTrue("AuthorizationEvaluator.isAuthorized: Principal "+principal+" NOT authorized for action "+action, + assertTrue("AuthorizationEvaluator.isAuthorized: Principal "+principal+" NOT authorized for action "+action, securityEnforcer.isAuthorized(action, phase, null, null, null, null)); if (phase == null) { - securityEnforcer.decide(SecurityContextHolder.getContext().getAuthentication(), createSecureObject(), + securityEnforcer.decide(SecurityContextHolder.getContext().getAuthentication(), createSecureObject(), createConfigAttributes(action)); } } finally { SecurityContextHolder.setContext(origContext); } } - + protected void assertNotAuthorized(MidPointPrincipal principal, String action) throws SchemaException { assertNotAuthorized(principal, action, null); assertNotAuthorized(principal, action, AuthorizationPhaseType.REQUEST); assertNotAuthorized(principal, action, AuthorizationPhaseType.EXECUTION); } - + protected void assertNotAuthorized(MidPointPrincipal principal, String action, AuthorizationPhaseType phase) throws SchemaException { SecurityContext origContext = SecurityContextHolder.getContext(); createSecurityContext(principal); @@ -3883,13 +3930,13 @@ protected void assertNotAuthorized(MidPointPrincipal principal, String action, A SecurityContextHolder.setContext(origContext); assertFalse("AuthorizationEvaluator.isAuthorized: Principal " + principal + " IS authorized for action " + action + " (" + phase + ") but he should not be", isAuthorized); } - + protected void assertAuthorizations(PrismObject user, String... expectedAuthorizations) throws ObjectNotFoundException, SchemaException { MidPointPrincipal principal = userProfileService.getPrincipal(user); assertNotNull("No principal for "+user, principal); assertAuthorizations(principal, expectedAuthorizations); } - + protected void assertAuthorizations(MidPointPrincipal principal, String... expectedAuthorizations) { List actualAuthorizations = new ArrayList<>(); for (Authorization authorization: principal.getAuthorities()) { @@ -3898,29 +3945,29 @@ protected void assertAuthorizations(MidPointPrincipal principal, String... expec PrismAsserts.assertSets("Wrong authorizations in "+principal, actualAuthorizations, expectedAuthorizations); } - + protected void assertNoAuthorizations(PrismObject user) throws ObjectNotFoundException, SchemaException { MidPointPrincipal principal = userProfileService.getPrincipal(user); assertNotNull("No principal for "+user, principal); assertNoAuthorizations(principal); } - + protected void assertNoAuthorizations(MidPointPrincipal principal) { if (principal.getAuthorities() != null && !principal.getAuthorities().isEmpty()) { AssertJUnit.fail("Unexpected authorizations in "+principal+": "+principal.getAuthorities()); } } - - protected AdminGuiConfigurationType assertAdminGuiConfigurations(MidPointPrincipal principal, int expectedMenuLinks, + + protected AdminGuiConfigurationType assertAdminGuiConfigurations(MidPointPrincipal principal, int expectedMenuLinks, int expectedDashboardLinks, int expectedObjectLists, int expectedObjectForms, int expecteduserDashboardWidgets) { AdminGuiConfigurationType adminGuiConfiguration = principal.getAdminGuiConfiguration(); display("Admin GUI config for "+principal.getUsername(), adminGuiConfiguration); - assertAdminGuiConfigurations(adminGuiConfiguration, + assertAdminGuiConfigurations(adminGuiConfiguration, expectedMenuLinks, expectedDashboardLinks, expectedObjectLists, expectedObjectForms, expecteduserDashboardWidgets); return adminGuiConfiguration; } - - protected void assertAdminGuiConfigurations(AdminGuiConfigurationType adminGuiConfiguration, + + protected void assertAdminGuiConfigurations(AdminGuiConfigurationType adminGuiConfiguration, int expectedMenuLinks, int expectedDashboardLinks, int expectedObjectLists, int expectedObjectForms, int expecteduserDashboardWidgets) { assertNotNull("No admin GUI configuration", adminGuiConfiguration); assertEquals("Wrong number of menu links in", @@ -3955,17 +4002,17 @@ protected void createSecurityContext(MidPointPrincipal principal) { context.setAuthentication(authentication); SecurityContextHolder.setContext(context); } - + protected Object createSecureObject() { return new FilterInvocation("/midpoint", "whateverServlet", "doSomething"); } - + protected Collection createConfigAttributes(String action) { Collection attrs = new ArrayList(); attrs.add(new SecurityConfig(action)); return attrs; } - + protected PrismObjectDefinition getEditObjectDefinition(PrismObject object) throws SchemaException, ConfigurationException, ObjectNotFoundException { Task task = taskManager.createTaskInstance(AbstractModelIntegrationTest.class+".getEditObjectDefinition"); OperationResult result = task.getResult(); @@ -3974,11 +4021,11 @@ protected PrismObjectDefinition getEditObjectDefinitio TestUtil.assertSuccess(result); return editSchema; } - + protected void assertRoleTypes(PrismObject focus, String... expectedRoleTypes) throws ObjectNotFoundException, SchemaException, ConfigurationException { assertRoleTypes(getAssignableRoleSpecification(focus), expectedRoleTypes); } - + protected RoleSelectionSpecification getAssignableRoleSpecification(PrismObject focus) throws ObjectNotFoundException, SchemaException, ConfigurationException { OperationResult result = new OperationResult(AbstractIntegrationTest.class.getName()+".getAssignableRoleSpecification"); RoleSelectionSpecification spec = modelInteractionService.getAssignableRoleSpecification(focus, result); @@ -4011,16 +4058,16 @@ protected void assertRoleTypes(RoleSelectionSpecification roleSpec, String... ex } } } - + protected void assertAllowRequestItems(String userOid, String targetRoleOid, AuthorizationDecisionType expectedDefaultDecision, QName... expectedAllowedItemQNames) throws SchemaException, SecurityViolationException, CommunicationException, ObjectNotFoundException, ConfigurationException, ExpressionEvaluationException { PrismObject user = getUser(userOid); PrismObject target = getRole(targetRoleOid); - + ItemSecurityDecisions decisions = modelInteractionService.getAllowedRequestAssignmentItems(user, target); display("Request decisions for "+target, decisions); assertEquals("Wrong assign default decision", expectedDefaultDecision, decisions.getDefaultDecision()); assertEquals("Unexpected number of allowed items", expectedAllowedItemQNames.length, decisions.getItemDecisionMap().size()); - + decisions.getItemDecisionMap().forEach( (path,decision) -> { assertEquals("wrong item "+path+" decision", AuthorizationDecisionType.ALLOW, decision); @@ -4032,7 +4079,7 @@ protected void assertAllowRequestItems(String userOid, String targetRoleOid, Aut ); } - + protected void assertEncryptedUserPassword(String userOid, String expectedClearPassword) throws EncryptionException, ObjectNotFoundException, SchemaException { OperationResult result = new OperationResult(AbstractIntegrationTest.class.getName()+".assertEncryptedUserPassword"); PrismObject user = repositoryService.getObject(UserType.class, userOid, null, result); @@ -4040,7 +4087,7 @@ protected void assertEncryptedUserPassword(String userOid, String expectedClearP TestUtil.assertSuccess(result); assertEncryptedUserPassword(user, expectedClearPassword); } - + protected void assertEncryptedUserPassword(PrismObject user, String expectedClearPassword) throws EncryptionException { UserType userType = user.asObjectable(); ProtectedStringType protectedActualPassword = userType.getCredentials().getPassword().getValue(); @@ -4055,41 +4102,41 @@ protected void assertPasswordMetadata(PrismObject user, boolean create MetadataType metadataType = metadataContainer.getValue().asContainerable(); assertMetadata("password metadata in "+user, metadataType, create, false, start, end, actorOid, channel); } - + protected void assertPasswordMetadata(PrismObject user, QName credentialType, boolean create, XMLGregorianCalendar start, XMLGregorianCalendar end, String actorOid, String channel) { PrismContainer metadataContainer = user.findContainer(new ItemPath(UserType.F_CREDENTIALS, credentialType, PasswordType.F_METADATA)); assertNotNull("No password metadata in "+user, metadataContainer); MetadataType metadataType = metadataContainer.getValue().asContainerable(); assertMetadata("password metadata in "+user, metadataType, create, false, start, end, actorOid, channel); } - + protected void assertCreateMetadata(PrismObject object, XMLGregorianCalendar start, XMLGregorianCalendar end) { MetadataType metadataType = object.asObjectable().getMetadata(); PrismObject defaultActor = getDefaultActor(); - assertMetadata(object.toString(), metadataType, true, true, start, end, + assertMetadata(object.toString(), metadataType, true, true, start, end, defaultActor==null?null:defaultActor.getOid(), DEFAULT_CHANNEL); } - + protected void assertModifyMetadata(PrismObject object, XMLGregorianCalendar start, XMLGregorianCalendar end) { MetadataType metadataType = object.asObjectable().getMetadata(); PrismObject defaultActor = getDefaultActor(); - assertMetadata(object.toString(), metadataType, false, false, start, end, + assertMetadata(object.toString(), metadataType, false, false, start, end, defaultActor==null?null:defaultActor.getOid(), DEFAULT_CHANNEL); } - + protected void assertCreateMetadata(AssignmentType assignmentType, XMLGregorianCalendar start, XMLGregorianCalendar end) { MetadataType metadataType = assignmentType.getMetadata(); PrismObject defaultActor = getDefaultActor(); - assertMetadata(assignmentType.toString(), metadataType, true, true, start, end, + assertMetadata(assignmentType.toString(), metadataType, true, true, start, end, defaultActor==null?null:defaultActor.getOid(), DEFAULT_CHANNEL); } - + protected void assertDummyPassword(String instance, String userId, String expectedClearPassword) throws SchemaViolationException, ConflictException { DummyAccount account = getDummyAccount(instance, userId); assertNotNull("No dummy account "+userId, account); assertEquals("Wrong password in dummy '"+instance+"' account "+userId, expectedClearPassword, account.getPassword()); } - + protected void assertDummyPasswordNotEmpty(String instance, String userId) throws SchemaViolationException, ConflictException { DummyAccount account = getDummyAccount(instance, userId); assertNotNull("No dummy account "+userId, account); @@ -4102,7 +4149,7 @@ protected void assertDummyPasswordNotEmpty(String instance, String userId) throw protected void reconcileUser(String oid, Task task, OperationResult result) throws CommunicationException, ObjectAlreadyExistsException, ExpressionEvaluationException, PolicyViolationException, SchemaException, SecurityViolationException, ConfigurationException, ObjectNotFoundException { reconcileUser(oid, null, task, result); } - + protected void reconcileUser(String oid, ModelExecuteOptions options, Task task, OperationResult result) throws CommunicationException, ObjectAlreadyExistsException, ExpressionEvaluationException, PolicyViolationException, SchemaException, SecurityViolationException, ConfigurationException, ObjectNotFoundException { ObjectDelta emptyDelta = ObjectDelta.createEmptyModifyDelta(UserType.class, oid, prismContext); modelService.executeChanges(MiscSchemaUtil.createCollection(emptyDelta), ModelExecuteOptions.createReconcile(options), task, result); @@ -4122,25 +4169,25 @@ protected void assertRefEquals(String message, ObjectReferenceType expected, Obj } PrismAsserts.assertRefEquivalent(message, expected.asReferenceValue(), actual.asReferenceValue()); } - + protected void assertTaskClosed(PrismObject task) { assertEquals("Wrong executionStatus in "+task, TaskExecutionStatusType.CLOSED, task.asObjectable().getExecutionStatus()); } - + protected List getAllAuditRecords(OperationResult result) throws SecurityViolationException, SchemaException { Map params = new HashMap<>(); return modelAuditService.listRecords("from RAuditEventRecord as aer order by aer.timestamp asc", params, result); } - + protected List getObjectAuditRecords(String oid) throws SecurityViolationException, SchemaException { OperationResult result = new OperationResult("getObjectAuditRecords"); return getObjectAuditRecords(oid, result); } - + protected List getObjectAuditRecords(String oid, OperationResult result) throws SecurityViolationException, SchemaException { Map params = new HashMap<>(); params.put("targetOid", oid); - return modelAuditService.listRecords("from RAuditEventRecord as aer where (aer.targetOid = :targetOid) order by aer.timestamp asc", + return modelAuditService.listRecords("from RAuditEventRecord as aer where (aer.targetOid = :targetOid) order by aer.timestamp asc", params, result); } @@ -4156,12 +4203,12 @@ protected List getAuditRecordsFromTo(XMLGregorianCalendar from OperationResult result = new OperationResult("getAuditRecordsFromTo"); return getAuditRecordsFromTo(from, to, result); } - + protected List getAuditRecordsFromTo(XMLGregorianCalendar from, XMLGregorianCalendar to, OperationResult result) throws SecurityViolationException, SchemaException { Map params = new HashMap<>(); params.put("from", from); params.put("to", to); - return modelAuditService.listRecords("from RAuditEventRecord as aer where (aer.timestamp >= :from) and (aer.timestamp <= :to) order by aer.timestamp asc", + return modelAuditService.listRecords("from RAuditEventRecord as aer where (aer.timestamp >= :from) and (aer.timestamp <= :to) order by aer.timestamp asc", params, result); } @@ -4352,7 +4399,7 @@ protected void dumpAllUsers(OperationResult initResult) throws SchemaException { .searchObjects(UserType.class, null, null, initResult); display("Users", users); } - + protected PrismObject

    assertLinkedPersona(PrismObject focus, Class

    personaClass, String subtype) throws ObjectNotFoundException, SchemaException { OperationResult result = new OperationResult("assertLinkedPersona"); for (ObjectReferenceType personaRef: focus.asObjectable().getPersonaRef()) { @@ -4375,7 +4422,7 @@ protected boolean isTypeAndSubtype(PrismObject focus, C } return true; } - + protected PrismObject getOrg(String orgName) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject org = findObjectByName(OrgType.class, orgName); assertNotNull("The org "+orgName+" is missing!", org); @@ -4383,11 +4430,11 @@ protected PrismObject getOrg(String orgName) throws SchemaException, Ob PrismAsserts.assertPropertyValue(org, OrgType.F_NAME, PrismTestUtil.createPolyString(orgName)); return org; } - + protected void dumpOrgTree() throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { display("Org tree", dumpOrgTree(getTopOrgOid())); } - + protected String getTopOrgOid() { return null; } @@ -4407,15 +4454,15 @@ protected void transplantGlobalPolicyRulesAdd(File configWithGlobalRulesFile, Ta protected void displayProvisioningScripts() { displayProvisioningScripts(null); } - + protected void displayProvisioningScripts(String dummyName) { display("Provisioning scripts "+dummyName, getDummyResource(dummyName).getScriptHistory()); } - + protected void purgeProvisioningScriptHistory() { purgeProvisioningScriptHistory(null); } - + protected void purgeProvisioningScriptHistory(String dummyName) { getDummyResource(dummyName).purgeScriptHistory(); } @@ -4426,25 +4473,25 @@ protected void assertNoProvisioningScripts() { AssertJUnit.fail(getDummyResource().getScriptHistory().size()+" provisioning scripts were executed while not expected any"); } } - + protected void assertDummyProvisioningScriptsNone() { IntegrationTestTools.assertScripts(getDummyResource().getScriptHistory()); } - + protected void applyPasswordPolicy(String passwordPolicyOid, String securityPolicyOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { PrismReferenceValue passPolicyRef = new PrismReferenceValue(passwordPolicyOid, ValuePolicyType.COMPLEX_TYPE); modifyObjectReplaceReference(SecurityPolicyType.class, securityPolicyOid, new ItemPath(SecurityPolicyType.F_CREDENTIALS, CredentialsPolicyType.F_PASSWORD, PasswordCredentialsPolicyType.F_VALUE_POLICY_REF), task, result, passPolicyRef); } - + protected void assertPasswordCompliesWithPolicy(PrismObject user, String passwordPolicyOid) throws EncryptionException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException { Task task = createTask("assertPasswordCompliesWithPolicy"); OperationResult result = task.getResult(); assertPasswordCompliesWithPolicy(user, passwordPolicyOid, task, result); assertSuccess(result); } - + protected void assertPasswordCompliesWithPolicy(PrismObject user, String passwordPolicyOid, Task task, OperationResult result) throws EncryptionException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException { String password = getPassword(user); display("Password of "+user, password); @@ -4459,7 +4506,7 @@ protected void assertPasswordCompliesWithPolicy(PrismObject user, Stri protected XMLGregorianCalendar getTimestamp(String duration) { return XmlTypeConverter.addDuration(clock.currentTimeXMLGregorianCalendar(), duration); } - + protected void clockForward(String duration) { XMLGregorianCalendar before = clock.currentTimeXMLGregorianCalendar(); clock.overrideDuration(duration); diff --git a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/DummyResourceCollection.java b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/DummyResourceCollection.java index b24c2172f6f..71052469bce 100644 --- a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/DummyResourceCollection.java +++ b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/DummyResourceCollection.java @@ -38,10 +38,10 @@ public class DummyResourceCollection { private static final Trace LOGGER = TraceManager.getTrace(DummyResourceCollection.class); - + private Map map = new HashMap<>(); private ModelService modelService; - + public DummyResourceCollection(ModelService modelService) { super(); this.modelService = modelService; @@ -75,7 +75,7 @@ public DummyResourceContoller initDummyResource(String name, File resourceFile, map.put(name, controller); return controller; } - + public DummyResourceContoller get(String name) { DummyResourceContoller contoller = map.get(name); if (contoller == null) { @@ -95,11 +95,11 @@ public ResourceType getResourceType(String name) { public DummyResource getDummyResource(String name) { return get(name).getDummyResource(); } - + public void forEachResourceCtl(Consumer lambda) { map.forEach((k,v) -> lambda.accept(v)); } - + /** * Resets the blocking state, error simulation, etc. */ 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 51953de2d00..4e77580b24e 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 @@ -85,7 +85,7 @@ public void send(Message message, String name, Event event, Task task, Operation public List getMessages(String transportName) { return messages.get(transportName); } - + public Map> getMessages() { return messages; } diff --git a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/EventHandler.java b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/EventHandler.java index 278346baeb3..93e1ccac700 100644 --- a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/EventHandler.java +++ b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/EventHandler.java @@ -29,6 +29,6 @@ public interface EventHandler { // true if we should continue with processing, false otherwise - boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, + boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, Task task, OperationResult result) throws SchemaException; } diff --git a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/AccessCertificationEvent.java b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/AccessCertificationEvent.java index 6dce4af4fd9..4b94dc6f7d2 100644 --- a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/AccessCertificationEvent.java +++ b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/AccessCertificationEvent.java @@ -94,7 +94,7 @@ public AccessCertificationStageDefinitionType getCurrentStageDefinition() { } return CertCampaignTypeUtil.findStageDefinition(campaign, campaign.getStageNumber()); } - + @Override protected void debugDumpCommon(StringBuilder sb, int indent) { super.debugDumpCommon(sb, indent); diff --git a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/BaseEvent.java b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/BaseEvent.java index 2487069d8e6..6b76280adad 100644 --- a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/BaseEvent.java +++ b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/BaseEvent.java @@ -374,7 +374,7 @@ public String getStatusAsText() { public EventHandlerType getAdHocHandler() { return adHocHandler; } - + protected void debugDumpCommon(StringBuilder sb, int indent) { DebugUtil.debugDumpWithLabelToStringLn(sb, "id", getId(), indent + 1); DebugUtil.debugDumpWithLabelLn(sb, "requester", getRequester(), indent + 1); diff --git a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/CertReviewEvent.java b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/CertReviewEvent.java index 8526976dc4d..452ec5c6ebc 100644 --- a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/CertReviewEvent.java +++ b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/CertReviewEvent.java @@ -90,7 +90,7 @@ private boolean awaitsResponseFrom(AccessCertificationCaseType aCase, String rev public List getCases() { return cases; } - + @Override public String debugDump(int indent) { StringBuilder sb = DebugUtil.createTitleStringBuilderLn(this.getClass(), indent); diff --git a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/CustomEvent.java b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/CustomEvent.java index b9faac72183..84ff7d40346 100644 --- a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/CustomEvent.java +++ b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/CustomEvent.java @@ -103,7 +103,7 @@ public boolean isUserRelated() { return false; } } - + @Override public String debugDump(int indent) { StringBuilder sb = DebugUtil.createTitleStringBuilderLn(this.getClass(), indent); diff --git a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/ModelEvent.java b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/ModelEvent.java index dda2b347607..fe70f1809cf 100644 --- a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/ModelEvent.java +++ b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/ModelEvent.java @@ -64,7 +64,7 @@ public ModelContext getModelContext() { public ModelElementContext getFocusContext() { return modelContext.getFocusContext(); } - + public Collection getProjectionContexts() { return modelContext.getProjectionContexts(); } diff --git a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/PolicyRuleEvent.java b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/PolicyRuleEvent.java index 3978a6875ee..fa88a61a5ae 100644 --- a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/PolicyRuleEvent.java +++ b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/PolicyRuleEvent.java @@ -67,7 +67,7 @@ public EvaluatedPolicyRule getPolicyRule() { public String getRuleName() { return policyRule.getName(); } - + @Override public String debugDump(int indent) { StringBuilder sb = DebugUtil.createTitleStringBuilderLn(this.getClass(), indent); diff --git a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/ResourceObjectEvent.java b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/ResourceObjectEvent.java index d578b15fe40..f1399d007cc 100644 --- a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/ResourceObjectEvent.java +++ b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/ResourceObjectEvent.java @@ -177,7 +177,7 @@ public String getContentAsFormattedList() { public String getContentAsFormattedList(boolean showSynchronizationItems, boolean showAuxiliaryAttributes) { return getNotificationFunctions().getContentAsFormattedList(this, showSynchronizationItems, showAuxiliaryAttributes); } - + @Override public String debugDump(int indent) { StringBuilder sb = DebugUtil.createTitleStringBuilderLn(this.getClass(), indent); diff --git a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/TaskEvent.java b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/TaskEvent.java index 147ff2e8e08..7adb6fe863f 100644 --- a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/TaskEvent.java +++ b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/TaskEvent.java @@ -137,7 +137,7 @@ public String getMessage() { public long getProgress() { return taskRunResult != null ? taskRunResult.getProgress() : task.getProgress(); } - + @Override public String debugDump(int indent) { StringBuilder sb = DebugUtil.createTitleStringBuilderLn(this.getClass(), indent); diff --git a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/WorkflowProcessEvent.java b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/WorkflowProcessEvent.java index bd6ceef484e..f5d878d8fb9 100644 --- a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/WorkflowProcessEvent.java +++ b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/events/WorkflowProcessEvent.java @@ -49,7 +49,7 @@ public String toString() { '}'; } - + @Override public String debugDump(int indent) { StringBuilder sb = DebugUtil.createTitleStringBuilderLn(this.getClass(), indent); 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 cd135e2db57..f626ff8ec8c 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 @@ -100,7 +100,7 @@ public String getContentType() { public void setContentType(String contentType) { this.contentType = contentType; } - + public String getFrom() { return from; } @@ -138,7 +138,7 @@ public String debugDump(int indent) { DebugUtil.debugDumpWithLabel(rv, "From", from, indent+1); rv.append("\n"); } - + DebugUtil.debugDumpWithLabel(rv, "To", to, indent+1); rv.append("\n"); diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/NotificationFunctionsImpl.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/NotificationFunctionsImpl.java index 88d5cb24ab5..ccf3fd1a1b9 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/NotificationFunctionsImpl.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/NotificationFunctionsImpl.java @@ -119,11 +119,11 @@ public static SystemConfigurationType getSystemConfiguration(RepositoryService r return null; } } - + public SystemConfigurationType getSystemConfiguration(OperationResult result) { return getSystemConfiguration(cacheRepositoryService, result); } - + public static SecurityPolicyType getSecurityPolicyConfiguration(ObjectReferenceType securityPolicyRef, RepositoryService repositoryService, OperationResult result) { try { if (securityPolicyRef == null) { diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/NotificationManagerImpl.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/NotificationManagerImpl.java index 325ce2e44b8..ca727e999e9 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/NotificationManagerImpl.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/NotificationManagerImpl.java @@ -124,13 +124,13 @@ public void processEvent(@Nullable Event event, Task task, OperationResult resul if (systemConfigurationType == null) { // something really wrong happened (or we are doing initial import of objects) return; } - + // boolean specificSecurityPoliciesDefined = false; // if (systemConfigurationType.getGlobalSecurityPolicyRef() != null) { -// +// // SecurityPolicyType securityPolicyType = NotificationFuctionsImpl.getSecurityPolicyConfiguration(systemConfigurationType.getGlobalSecurityPolicyRef(), cacheRepositoryService, result); // if (securityPolicyType != null && securityPolicyType.getAuthentication() != null) { -// +// // for (MailAuthenticationPolicyType mailPolicy : securityPolicyType.getAuthentication().getMailAuthentication()) { // NotificationConfigurationType notificationConfigurationType = mailPolicy.getNotificationConfiguration(); // if (notificationConfigurationType != null) { @@ -138,7 +138,7 @@ public void processEvent(@Nullable Event event, Task task, OperationResult resul // processNotifications(notificationConfigurationType, event, task, result); // } // } -// +// // for (SmsAuthenticationPolicyType mailPolicy : securityPolicyType.getAuthentication().getSmsAuthentication()) { // NotificationConfigurationType notificationConfigurationType = mailPolicy.getNotificationConfiguration(); // if (notificationConfigurationType != null) { @@ -146,29 +146,29 @@ public void processEvent(@Nullable Event event, Task task, OperationResult resul // processNotifications(notificationConfigurationType, event, task, result); // } // } -// +// // return; // } // } -// +// // if (specificSecurityPoliciesDefined) { // LOGGER.trace("Specific policy for notifier set in security configuration, skupping notifiers defined in system configuration."); // return; // } - + if (systemConfigurationType.getNotificationConfiguration() == null) { LOGGER.trace("No notification configuration in repository, finished event processing."); return; } - - NotificationConfigurationType notificationConfigurationType = systemConfigurationType.getNotificationConfiguration(); + + NotificationConfigurationType notificationConfigurationType = systemConfigurationType.getNotificationConfiguration(); processNotifications(notificationConfigurationType, event, task, result); LOGGER.trace("NotificationManager successfully processed event {} ({} top level handler(s))", event, notificationConfigurationType.getHandler().size()); } - + private void processNotifications(NotificationConfigurationType notificationConfigurationType, Event event, Task task, OperationResult result){ - + for (EventHandlerType eventHandlerType : notificationConfigurationType.getHandler()) { processEvent(event, eventHandlerType, task, result); diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/SimpleObjectRefImpl.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/SimpleObjectRefImpl.java index 05104004848..9c348f8bae7 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/SimpleObjectRefImpl.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/SimpleObjectRefImpl.java @@ -30,7 +30,7 @@ * @author mederly */ public class SimpleObjectRefImpl implements SimpleObjectRef { - + private String oid; private ObjectType objectType; private NotificationFunctionsImpl functions; // used to resolve object refs diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/api/transports/MailTransport.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/api/transports/MailTransport.java index 1a6946026f8..532d86a1236 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/api/transports/MailTransport.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/api/transports/MailTransport.java @@ -88,14 +88,14 @@ public void send(Message mailMessage, String transportName, Event event, Task ta result.addParam("mailMessage subject", mailMessage.getSubject()); SystemConfigurationType systemConfiguration = NotificationFunctionsImpl.getSystemConfiguration(cacheRepositoryService, new OperationResult("dummy")); - + // if (systemConfiguration == null) { // String msg = "No notifications are configured. Mail notification to " + mailMessage.getTo() + " will not be sent."; // LOGGER.warn(msg) ; // result.recordWarning(msg); // return; // } -// +// // MailConfigurationType mailConfigurationType = null; // SecurityPolicyType securityPolicyType = NotificationFuctionsImpl.getSecurityPolicyConfiguration(systemConfiguration.getGlobalSecurityPolicyRef(), cacheRepositoryService, result); // if (securityPolicyType != null && securityPolicyType.getAuthentication() != null && securityPolicyType.getAuthentication().getMailAuthentication() != null) { @@ -105,7 +105,7 @@ public void send(Message mailMessage, String transportName, Event event, Task ta // } // } // } - + if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null || systemConfiguration.getNotificationConfiguration().getMail() == null) { String msg = "No notifications are configured. Mail notification to " + mailMessage.getTo() + " will not be sent."; @@ -191,7 +191,7 @@ public void send(Message mailMessage, String transportName, Event event, Task ta MimeMessage mimeMessage = new MimeMessage(session); String from = mailMessage.getFrom() != null ? mailMessage.getFrom() : defaultFrom; mimeMessage.setFrom(new InternetAddress(from)); - + for (String recipient : mailMessage.getTo()) { mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient)); } diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/api/transports/SimpleSmsTransport.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/api/transports/SimpleSmsTransport.java index ba3e27cd911..cc9cb543743 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/api/transports/SimpleSmsTransport.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/api/transports/SimpleSmsTransport.java @@ -163,7 +163,7 @@ public void send(Message message, String transportName, Event event, Task task, resultForGateway.addContext("gateway name", smsGatewayConfigurationType.getName()); try { - String url = evaluateExpressionChecked(smsGatewayConfigurationType.getUrl(), getDefaultVariables(from, to, message), + String url = evaluateExpressionChecked(smsGatewayConfigurationType.getUrl(), getDefaultVariables(from, to, message), "sms gateway url", task, result); LOGGER.debug("Sending SMS to URL " + url); @@ -209,7 +209,7 @@ private String formatToFile(Message mailMessage, String url) { return "================ " + new Date() + " ======= " + (url != null ? url : "") + "\n" + mailMessage.toString() + "\n\n"; } - private String evaluateExpressionChecked(ExpressionType expressionType, ExpressionVariables expressionVariables, + private String evaluateExpressionChecked(ExpressionType expressionType, ExpressionVariables expressionVariables, String shortDesc, Task task, OperationResult result) { Throwable failReason; @@ -228,7 +228,7 @@ private String evaluateExpressionChecked(ExpressionType expressionType, Expressi throw new SystemException(failReason); } - private String evaluateExpression(ExpressionType expressionType, ExpressionVariables expressionVariables, + private String evaluateExpression(ExpressionType expressionType, ExpressionVariables expressionVariables, String shortDesc, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException { QName resultName = new QName(SchemaConstants.NS_C, "result"); diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/handlers/BaseHandler.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/handlers/BaseHandler.java index 4cc62c645f3..99f1239f5ca 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/handlers/BaseHandler.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/handlers/BaseHandler.java @@ -87,10 +87,10 @@ protected void logStart(Trace LOGGER, Event event, EventHandlerType eventHandler getHumanReadableHandlerDescription(eventHandlerType) + "\n parameters: " + (additionalData != null ? ("\n parameters: " + additionalData) : ("\n configuration: " + eventHandlerType))); - + } } - + protected void logNotApplicable(Event event, String reason) { if (LOGGER.isTraceEnabled()) { LOGGER.trace( @@ -124,7 +124,7 @@ public void logEnd(Trace LOGGER, Event event, EventHandlerType eventHandlerType, // expressions // shortDesc = what is to be evaluated e.g. "event filter expression" - protected boolean evaluateBooleanExpressionChecked(ExpressionType expressionType, ExpressionVariables expressionVariables, + protected boolean evaluateBooleanExpressionChecked(ExpressionType expressionType, ExpressionVariables expressionVariables, String shortDesc, Task task, OperationResult result) { Throwable failReason; @@ -143,7 +143,7 @@ protected boolean evaluateBooleanExpressionChecked(ExpressionType expressionType throw new SystemException(failReason); } - protected boolean evaluateBooleanExpression(ExpressionType expressionType, ExpressionVariables expressionVariables, String shortDesc, + protected boolean evaluateBooleanExpression(ExpressionType expressionType, ExpressionVariables expressionVariables, String shortDesc, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException { QName resultName = new QName(SchemaConstants.NS_C, "result"); @@ -181,7 +181,7 @@ protected List evaluateExpressionChecked(ExpressionType expressionType, throw new SystemException(failReason); } - private List evaluateExpression(ExpressionType expressionType, ExpressionVariables expressionVariables, + private List evaluateExpression(ExpressionType expressionType, ExpressionVariables expressionVariables, String shortDesc, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException { QName resultName = new QName(SchemaConstants.NS_C, "result"); diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/BaseHelper.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/BaseHelper.java index 74fe9f64c93..f52f3c5f845 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/BaseHelper.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/BaseHelper.java @@ -100,7 +100,7 @@ public void logEnd(Trace LOGGER, Event event, EventHandlerType eventHandlerType, // expressions // shortDesc = what is to be evaluated e.g. "event filter expression" - protected boolean evaluateBooleanExpressionChecked(ExpressionType expressionType, ExpressionVariables expressionVariables, + protected boolean evaluateBooleanExpressionChecked(ExpressionType expressionType, ExpressionVariables expressionVariables, String shortDesc, Task task, OperationResult result) { Throwable failReason; @@ -119,7 +119,7 @@ protected boolean evaluateBooleanExpressionChecked(ExpressionType expressionType throw new SystemException(failReason); } - protected boolean evaluateBooleanExpression(ExpressionType expressionType, ExpressionVariables expressionVariables, String shortDesc, + protected boolean evaluateBooleanExpression(ExpressionType expressionType, ExpressionVariables expressionVariables, String shortDesc, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException { QName resultName = new QName(SchemaConstants.NS_C, "result"); @@ -139,7 +139,7 @@ protected boolean evaluateBooleanExpression(ExpressionType expressionType, Expre return boolResult != null ? boolResult : false; } - protected List evaluateExpressionChecked(ExpressionType expressionType, ExpressionVariables expressionVariables, + protected List evaluateExpressionChecked(ExpressionType expressionType, ExpressionVariables expressionVariables, String shortDesc, Task task, OperationResult result) { Throwable failReason; @@ -158,7 +158,7 @@ protected List evaluateExpressionChecked(ExpressionType expressionType, throw new SystemException(failReason); } - private List evaluateExpression(ExpressionType expressionType, ExpressionVariables expressionVariables, + private List evaluateExpression(ExpressionType expressionType, ExpressionVariables expressionVariables, String shortDesc, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException { QName resultName = new QName(SchemaConstants.NS_C, "result"); diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/CategoryFilterHelper.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/CategoryFilterHelper.java index 17b3018e8fb..864112e3443 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/CategoryFilterHelper.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/CategoryFilterHelper.java @@ -36,7 +36,7 @@ public class CategoryFilterHelper extends BaseHelper { private static final Trace LOGGER = TraceManager.getTrace(CategoryFilterHelper.class); @Override - public boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, + public boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, Task task, OperationResult result) { if (eventHandlerType.getCategory().isEmpty()) { diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/ChainHelper.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/ChainHelper.java index 14b3a92f654..5e02c61f542 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/ChainHelper.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/ChainHelper.java @@ -35,7 +35,7 @@ public class ChainHelper extends BaseHelper { private static final Trace LOGGER = TraceManager.getTrace(ChainHelper.class); @Override - public boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, + public boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, Task task, OperationResult result) { if (eventHandlerType.getChained().isEmpty()) { diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/ExpressionFilterHelper.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/ExpressionFilterHelper.java index 45753717da6..9a705e1a543 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/ExpressionFilterHelper.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/ExpressionFilterHelper.java @@ -36,7 +36,7 @@ public class ExpressionFilterHelper extends BaseHelper { private static final Trace LOGGER = TraceManager.getTrace(ExpressionFilterHelper.class); @Override - public boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, + public boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, Task task, OperationResult result) { if (eventHandlerType.getExpressionFilter().isEmpty()) { diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/FocusTypeFilterHelper.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/FocusTypeFilterHelper.java index 343ece6b195..01c209a6709 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/FocusTypeFilterHelper.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/FocusTypeFilterHelper.java @@ -37,7 +37,7 @@ public class FocusTypeFilterHelper extends BaseHelper { private static final Trace LOGGER = TraceManager.getTrace(FocusTypeFilterHelper.class); @Override - public boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, + public boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, Task task, OperationResult result) { if (eventHandlerType.getFocusType().isEmpty()) { diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/ForkHelper.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/ForkHelper.java index 66801ace463..cd28651fcc5 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/ForkHelper.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/ForkHelper.java @@ -35,7 +35,7 @@ public class ForkHelper extends BaseHelper { private static final Trace LOGGER = TraceManager.getTrace(ForkHelper.class); @Override - public boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, + public boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, Task task, OperationResult result) { if (eventHandlerType.getForked().isEmpty()) { diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/KindIntentFilterHelper.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/KindIntentFilterHelper.java index 43e434bb21e..b7a97cfc374 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/KindIntentFilterHelper.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/KindIntentFilterHelper.java @@ -37,7 +37,7 @@ public class KindIntentFilterHelper extends BaseHelper { private static final Trace LOGGER = TraceManager.getTrace(KindIntentFilterHelper.class); @Override - public boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, + public boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, Task task, OperationResult result) { if (eventHandlerType.getObjectKind().isEmpty() && eventHandlerType.getObjectIntent().isEmpty()) { diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/OperationFilterHelper.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/OperationFilterHelper.java index 9b3f0dd867d..87867dd84c9 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/OperationFilterHelper.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/OperationFilterHelper.java @@ -36,7 +36,7 @@ public class OperationFilterHelper extends BaseHelper { private static final Trace LOGGER = TraceManager.getTrace(OperationFilterHelper.class); @Override - public boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, + public boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, Task task, OperationResult result) { if (eventHandlerType.getOperation().isEmpty()) { diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/StatusFilterHelper.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/StatusFilterHelper.java index 88b9e651f78..00facac0149 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/StatusFilterHelper.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/helpers/StatusFilterHelper.java @@ -36,7 +36,7 @@ public class StatusFilterHelper extends BaseHelper { private static final Trace LOGGER = TraceManager.getTrace(StatusFilterHelper.class); @Override - public boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, + public boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, Task task, OperationResult result) { if (eventHandlerType.getStatus().isEmpty()) { diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/AccountActivationNotifier.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/AccountActivationNotifier.java index 0b461f240b7..b41d9cd8d1e 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/AccountActivationNotifier.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/AccountActivationNotifier.java @@ -36,14 +36,14 @@ @Component public class AccountActivationNotifier extends ConfirmationNotifier { - + private static final Trace LOGGER = TraceManager.getTrace(AccountActivationNotifier.class); - + @Override public void init() { register(AccountActivationNotifierType.class); } - + @Override protected Trace getLogger() { return LOGGER; @@ -62,19 +62,19 @@ protected boolean checkApplicability(Event event, GeneralNotifierType generalNot logNotApplicable(event, "no user deltas in event"); return false; } - + List shadows = getShadowsToActivate(modelEvent); - - if (shadows.isEmpty()) { + + if (shadows.isEmpty()) { logNotApplicable(event, "no shadows to activate found in model context"); return false; - } - + } + LOGGER.trace("Found shadows to activate: {}. Processing notifications.", shadows); return true; } - - + + @Override protected String getSubject(Event event, GeneralNotifierType generalNotifierType, String transport, Task task, OperationResult result) { @@ -84,24 +84,24 @@ protected String getSubject(Event event, GeneralNotifierType generalNotifierType @Override protected String getBody(Event event, GeneralNotifierType generalNotifierType, String transport, Task task, OperationResult result) throws SchemaException { - + String message = "Your accounts was successully created. To activate your accounts, please click on the link bellow."; - + String accountsToActivate = "Shadow to be activated: \n"; for (ShadowType shadow : getShadowsToActivate((ModelEvent) event)) { accountsToActivate = accountsToActivate + shadow.asPrismObject().debugDump() + "\n"; } - + String body = message + "\n\n" + createConfirmationLink(getUser(event), generalNotifierType, result) + "\n\n" + accountsToActivate; - + return body; } - + private List getShadowsToActivate(ModelEvent modelEvent) { Collection projectionContexts = modelEvent.getProjectionContexts(); return getMidpointFunctions().getShadowsToActivate(projectionContexts); } - + @Override public String getConfirmationLink(UserType userType) { return getMidpointFunctions().createAccountActivationLink(userType); diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/ConfirmationNotifier.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/ConfirmationNotifier.java index 4415b4d0dd1..c7a1e23f748 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/ConfirmationNotifier.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/ConfirmationNotifier.java @@ -51,7 +51,7 @@ public class ConfirmationNotifier extends GeneralNotifier { @Autowired private NotificationFunctionsImpl notificationsUtil; - + @PostConstruct public void init() { @@ -72,23 +72,23 @@ protected boolean quickCheckApplicability(Event event, GeneralNotifierType gener public String getConfirmationLink(UserType userType) { throw new UnsupportedOperationException("Please implement in concrete notifier"); } - + protected String createConfirmationLink(UserType userType, GeneralNotifierType generalNotifierType, OperationResult result) { - - + + ConfirmationNotifierType userRegistrationNotifier = (ConfirmationNotifierType) generalNotifierType; - + RegistrationConfirmationMethodType confirmationMethod = userRegistrationNotifier.getConfirmationMethod(); - + if (confirmationMethod == null) { return null; } ExpressionEnvironment expressionEnv = new ExpressionEnvironment(); expressionEnv.setCurrentResult(result); ModelExpressionThreadLocalHolder.pushExpressionEnvironment(expressionEnv); - + try { - + switch (confirmationMethod) { case LINK: String confirmationLink = getConfirmationLink(userType); @@ -99,23 +99,23 @@ protected String createConfirmationLink(UserType userType, GeneralNotifierType g default: break; } - + } finally { ModelExpressionThreadLocalHolder.popExpressionEnvironment(); } - + return null; - + } - + protected UserType getUser(Event event){ ModelEvent modelEvent = (ModelEvent) event; PrismObject newUser = modelEvent.getFocusContext().getObjectNew(); UserType userType = newUser.asObjectable(); return userType; } - - + + @Override protected Trace getLogger() { return LOGGER; diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/CustomNotifier.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/CustomNotifier.java index 9bf9e688ec4..2444a0be820 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/CustomNotifier.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/CustomNotifier.java @@ -89,7 +89,7 @@ public void init() { } @Override - public boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, + public boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, Task task, OperationResult parentResult) throws SchemaException { OperationResult result = parentResult.createMinorSubresult(CustomNotifier.class.getName() + ".processEvent"); diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/GeneralNotifier.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/GeneralNotifier.java index 01c9c666563..e7047f2daf9 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/GeneralNotifier.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/GeneralNotifier.java @@ -80,7 +80,7 @@ public void init() { } @Override - public boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, + public boolean processEvent(Event event, EventHandlerType eventHandlerType, NotificationManager notificationManager, Task task, OperationResult parentResult) throws SchemaException { OperationResult result = parentResult.createMinorSubresult(GeneralNotifier.class.getName() + ".processEvent"); @@ -200,7 +200,7 @@ protected Trace getLogger() { return DEFAULT_LOGGER; // in case a subclass does not provide its own logger } - protected List getRecipientsAddresses(Event event, GeneralNotifierType generalNotifierType, ExpressionVariables variables, + protected List getRecipientsAddresses(Event event, GeneralNotifierType generalNotifierType, ExpressionVariables variables, UserType defaultRecipient, String transportName, Transport transport, Task task, OperationResult result) { List addresses = new ArrayList<>(); if (!generalNotifierType.getRecipientExpression().isEmpty()) { @@ -239,10 +239,10 @@ protected List getCcBccAddresses(List expressions, Expre return addresses; } - protected String getSubjectFromExpression(Event event, GeneralNotifierType generalNotifierType, ExpressionVariables variables, + protected String getSubjectFromExpression(Event event, GeneralNotifierType generalNotifierType, ExpressionVariables variables, Task task, OperationResult result) { if (generalNotifierType.getSubjectExpression() != null) { - List subjectList = evaluateExpressionChecked(generalNotifierType.getSubjectExpression(), variables, "subject expression", + List subjectList = evaluateExpressionChecked(generalNotifierType.getSubjectExpression(), variables, "subject expression", task, result); if (subjectList == null || subjectList.isEmpty()) { getLogger().warn("Subject expression for event " + event.getId() + " returned nothing."); @@ -293,10 +293,10 @@ protected String getContentTypeFromExpression(Event event, GeneralNotifierType g } } - protected String getBodyFromExpression(Event event, GeneralNotifierType generalNotifierType, ExpressionVariables variables, + protected String getBodyFromExpression(Event event, GeneralNotifierType generalNotifierType, ExpressionVariables variables, Task task, OperationResult result) { if (generalNotifierType.getBodyExpression() != null) { - List bodyList = evaluateExpressionChecked(generalNotifierType.getBodyExpression(), variables, + List bodyList = evaluateExpressionChecked(generalNotifierType.getBodyExpression(), variables, "body expression", task, result); if (bodyList == null || bodyList.isEmpty()) { getLogger().warn("Body expression for event " + event.getId() + " returned nothing."); diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/PasswordResetNotifier.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/PasswordResetNotifier.java index 67161476250..fdabf59f0e3 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/PasswordResetNotifier.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/PasswordResetNotifier.java @@ -33,12 +33,12 @@ public class PasswordResetNotifier extends ConfirmationNotifier { private static final Trace LOGGER = TraceManager.getTrace(ConfirmationNotifier.class); - + @Override public void init() { register(PasswordResetNotifierType.class); } - + @Override protected boolean quickCheckApplicability(Event event, GeneralNotifierType generalNotifierType, OperationResult result) { @@ -73,22 +73,22 @@ protected boolean checkApplicability(Event event, GeneralNotifierType generalNot return false; } } - + @Override protected String getSubject(Event event, GeneralNotifierType generalNotifierType, String transport, Task task, OperationResult result) { return "Password reset"; } - + @Override protected String getBody(Event event, GeneralNotifierType generalNotifierType, String transport, Task task, OperationResult result) { - + UserType userType = getUser(event); - + return "Did you request password reset? If yes, click on the link bellow \n\n" + createConfirmationLink(userType, generalNotifierType, result); - + } - + @Override public String getConfirmationLink(UserType userType) { return getMidpointFunctions().createPasswordResetLink(userType); diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/RegistrationConfirmationNotifier.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/RegistrationConfirmationNotifier.java index 5c4f9d43634..446b32ac33a 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/RegistrationConfirmationNotifier.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/RegistrationConfirmationNotifier.java @@ -35,12 +35,12 @@ public class RegistrationConfirmationNotifier extends ConfirmationNotifier { private static final Trace LOGGER = TraceManager.getTrace(ConfirmationNotifier.class); - + @Override public void init() { register(RegistrationConfirmationNotifierType.class); } - + @Override protected boolean quickCheckApplicability(Event event, GeneralNotifierType generalNotifierType, OperationResult result) { @@ -76,25 +76,25 @@ protected boolean checkApplicability(Event event, GeneralNotifierType generalNot return false; } } - + @Override protected String getSubject(Event event, GeneralNotifierType generalNotifierType, String transport, Task task, OperationResult result) { return "Registration confirmation"; } - + @Override protected String getBody(Event event, GeneralNotifierType generalNotifierType, String transport, Task task, OperationResult result) { UserType userType = getUser(event); - + String plainTextPassword = "IhopeYouRememberYourPassword"; try { plainTextPassword = getMidpointFunctions().getPlaintextUserPassword(userType); } catch (EncryptionException e) { //ignore...???? } - + StringBuilder messageBuilder = new StringBuilder("Dear "); messageBuilder.append(userType.getGivenName()).append(",\n") .append("your account was successfully created. To activate your account click on the following confiramtion link. ") @@ -106,13 +106,13 @@ protected String getBody(Event event, GeneralNotifierType generalNotifierType, S .append(userType.getName().getOrig()) .append("password: ") .append(plainTextPassword); - + return messageBuilder.toString(); } - + @Override public String getConfirmationLink(UserType userType) { return getMidpointFunctions().createRegistrationConfirmationLink(userType); - + } } diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/TimeValidityNotifier.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/TimeValidityNotifier.java index c6ef0ccbec3..a605d68c31b 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/TimeValidityNotifier.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/TimeValidityNotifier.java @@ -52,10 +52,10 @@ protected boolean quickCheckApplicability(Event event, GeneralNotifierType gener return false; } PolicyRuleEvent modelEvent = (PolicyRuleEvent) event; - + return UserType.class.isAssignableFrom(modelEvent.getRequesteeObject().getClass()); } - + @Override protected boolean checkApplicability(Event event, GeneralNotifierType generalNotifierType, OperationResult result) { PolicyRuleEvent ruleEvent = (PolicyRuleEvent) event; @@ -64,29 +64,29 @@ protected boolean checkApplicability(Event event, GeneralNotifierType generalNot policyConstraints.getTimeValidity() != null && !policyConstraints.getTimeValidity().isEmpty(); } - + @Override protected String getSubject(Event event, GeneralNotifierType generalNotifierType, String transport, Task task, OperationResult result) { - - + + return "Planned deactivation of user " + getUserName(event); } - + @Override protected String getBody(Event event, GeneralNotifierType generalNotifierType, String transport, Task task, OperationResult result) throws SchemaException { - + return "User " + getUserName(event) + " is going to be deactivated on " + getUser(event).getActivation().getValidTo(); - + } - + private String getUserName(Event event){ UserType user = getUser(event); PolyStringType username = user.getName(); return username.getOrig(); } - + private UserType getUser(Event event){ PolicyRuleEvent taskEvent = (PolicyRuleEvent) event; UserType user = (UserType) taskEvent.getRequesteeObject(); diff --git a/model/report-api/src/main/java/com/evolveum/midpoint/report/api/ReportConstants.java b/model/report-api/src/main/java/com/evolveum/midpoint/report/api/ReportConstants.java index 82e862f2847..6315d650e47 100644 --- a/model/report-api/src/main/java/com/evolveum/midpoint/report/api/ReportConstants.java +++ b/model/report-api/src/main/java/com/evolveum/midpoint/report/api/ReportConstants.java @@ -5,9 +5,9 @@ import com.evolveum.midpoint.schema.constants.SchemaConstants; public class ReportConstants { - + public static final String NS_EXTENSION = SchemaConstants.NS_REPORT + "/extension-3"; - + public static final QName REPORT_PARAMS_PROPERTY_NAME = new QName(ReportConstants.NS_EXTENSION, "reportParam"); public static final QName REPORT_OUTPUT_OID_PROPERTY_NAME = new QName(ReportConstants.NS_EXTENSION, "reportOutputOid"); diff --git a/model/report-api/src/main/java/com/evolveum/midpoint/report/api/ReportManager.java b/model/report-api/src/main/java/com/evolveum/midpoint/report/api/ReportManager.java index 995232dbcb3..4b27eb35665 100644 --- a/model/report-api/src/main/java/com/evolveum/midpoint/report/api/ReportManager.java +++ b/model/report-api/src/main/java/com/evolveum/midpoint/report/api/ReportManager.java @@ -70,7 +70,7 @@ public interface ReportManager { InputStream getReportOutputData(String reportOutputOid, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException, IOException; - - + + void deleteReportOutput(ReportOutputType reportOutput, OperationResult parentResult) throws Exception; } diff --git a/model/report-api/src/main/java/com/evolveum/midpoint/report/api/ReportPort.java b/model/report-api/src/main/java/com/evolveum/midpoint/report/api/ReportPort.java index 0d90b64f36f..66295a2d75a 100644 --- a/model/report-api/src/main/java/com/evolveum/midpoint/report/api/ReportPort.java +++ b/model/report-api/src/main/java/com/evolveum/midpoint/report/api/ReportPort.java @@ -9,7 +9,7 @@ public interface ReportPort { String CLASS_NAME_WITH_DOT = ReportPort.class.getName() + "."; String PROCESS_REPORT = CLASS_NAME_WITH_DOT + "processReport"; - + public static final QName PARSE_QUERY_RESPONSE = new QName(SchemaConstants.NS_REPORT_WS, "parseQueryResponse"); public static final QName PROCESS_REPORT_RESPONSE = new QName(SchemaConstants.NS_REPORT_WS, "processReportResponse"); public static final QName EVALUATE_SCRIPT_RESPONSE = new QName(SchemaConstants.NS_REPORT_WS, "evaluateScriptResponse"); diff --git a/model/report-api/src/main/java/com/evolveum/midpoint/report/api/ReportService.java b/model/report-api/src/main/java/com/evolveum/midpoint/report/api/ReportService.java index 335e281bfac..0336ca36834 100644 --- a/model/report-api/src/main/java/com/evolveum/midpoint/report/api/ReportService.java +++ b/model/report-api/src/main/java/com/evolveum/midpoint/report/api/ReportService.java @@ -36,14 +36,14 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; public interface ReportService { - + String PARAMETER_REPORT_SERVICE = "reportService"; - + ObjectQuery parseQuery(String query, Map parameters) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException; - + Collection> searchObjects(ObjectQuery query, Collection> options) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException; - + Collection> evaluateScript(String script, Map parameters) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException; Collection evaluateAuditScript(String script, Map parameters) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException; diff --git a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/CustomDataWriter.java b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/CustomDataWriter.java index b93520a4263..61a1239b578 100644 --- a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/CustomDataWriter.java +++ b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/CustomDataWriter.java @@ -35,13 +35,13 @@ public class CustomDataWriter implements DataWriter{ private PrismContext prismContex; - - + + public CustomDataWriter(PrismContext prismContex) { this.prismContex = prismContex; } - + @Override public void write(Object obj, MessagePartInfo part, XMLStreamWriter output) { QName rootElement = part.getElementQName(); @@ -54,32 +54,32 @@ public void write(Object obj, MessagePartInfo part, XMLStreamWriter output) { // TODO Auto-generated catch block throw new Fault(e); } - - + + } @Override public void setAttachments(Collection arg0) { // TODO Auto-generated method stub - + } @Override public void setProperty(String arg0, Object arg1) { // TODO Auto-generated method stub - + } @Override public void setSchema(Schema arg0) { // TODO Auto-generated method stub - + } @Override public void write(Object arg0, XMLStreamWriter arg1) { // TODO Auto-generated method stub - + } } diff --git a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/CustomWrappedOutInterceptor.java b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/CustomWrappedOutInterceptor.java index 6e41bc20f6c..16260c91513 100644 --- a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/CustomWrappedOutInterceptor.java +++ b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/CustomWrappedOutInterceptor.java @@ -27,11 +27,11 @@ public class CustomWrappedOutInterceptor extends BareOutInterceptor{ private PrismContext prismContext; - + public CustomWrappedOutInterceptor(PrismContext prismContext) { this.prismContext = prismContext; } - + @Override public void handleMessage(Message message) { super.handleMessage(message); @@ -44,10 +44,10 @@ public void handleMessage(Message message) { } message.getInterceptorChain().remove(defaultInterceptor); } - + @Override - protected void writeParts(Message message, Exchange exchange, - BindingOperationInfo operation, MessageContentsList objs, + protected void writeParts(Message message, Exchange exchange, + BindingOperationInfo operation, MessageContentsList objs, List parts) { // TODO Auto-generated method stub OutputStream out = message.getContent(OutputStream.class); @@ -55,7 +55,7 @@ protected void writeParts(Message message, Exchange exchange, Service service = exchange.getService(); XMLStreamWriter xmlWriter = origXmlWriter; CachingXmlEventWriter cache = null; - + Object en = message.getContextualProperty(OUT_BUFFERING); boolean allowBuffer = true; boolean buffer = false; @@ -74,8 +74,8 @@ protected void writeParts(Message message, Exchange exchange, xmlWriter = cache; out = null; } - - if (out != null + + if (out != null && writeToOutputStream(message, operation.getBinding(), service) && !MessageUtils.isTrue(message.getContextualProperty(DISABLE_OUTPUTSTREAM_OPTIMIZATION))) { if (xmlWriter != null) { @@ -86,18 +86,18 @@ && writeToOutputStream(message, operation.getBinding(), service) throw new Fault(e); } } - + DataWriter osWriter = getDataWriter(message, service, OutputStream.class); for (MessagePartInfo part : parts) { if (objs.hasValue(part)) { Object o = objs.get(part); - osWriter.write(o, part, out); + osWriter.write(o, part, out); } } } else { DataWriter dataWriter = new CustomDataWriter(prismContext); - + for (MessagePartInfo part : parts) { if (objs.hasValue(part)) { Object o = objs.get(part); @@ -115,6 +115,6 @@ && writeToOutputStream(message, operation.getBinding(), service) } } } - - + + } diff --git a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/MidPointAbstractDataSource.java b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/MidPointAbstractDataSource.java index 9e500ab1432..5318a44d388 100644 --- a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/MidPointAbstractDataSource.java +++ b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/MidPointAbstractDataSource.java @@ -22,12 +22,12 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; public class MidPointAbstractDataSource implements JRDataSource{ - + List> resultList = null; Iterator> iterator = null; - PrismObject currentObject = null; - - + PrismObject currentObject = null; + + @Override public boolean next() throws JRException { // TODO Auto-generated method stub @@ -54,7 +54,7 @@ public Object getFieldValue(JRField jrField) throws JRException { if (i == null){ return null; } - + if (i instanceof PrismProperty){ if (i.isSingleValue()){ return ((PrismProperty) i).getRealValue(); @@ -64,7 +64,7 @@ public Object getFieldValue(JRField jrField) throws JRException { if (i.isSingleValue()){ return ((PrismReference) i).getValue().asReferencable(); } - + List refs = new ArrayList(); for (PrismReferenceValue refVal : ((PrismReference) i).getValues()){ refs.add(refVal.asReferencable()); @@ -81,7 +81,7 @@ public Object getFieldValue(JRField jrField) throws JRException { } } return containers; - + } else throw new JRException("Could not get value of the fileld: " + fieldName); } diff --git a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/MidPointDataSource.java b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/MidPointDataSource.java index 1419860a04f..04d536357c4 100644 --- a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/MidPointDataSource.java +++ b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/MidPointDataSource.java @@ -32,7 +32,7 @@ public class MidPointDataSource implements JRDataSource{ Collection> resultList = null; Iterator> iterator = null; PrismContainerValue currentObject = null; - + public MidPointDataSource(Collection> results) { this.resultList = results; if (results != null){ @@ -40,7 +40,7 @@ public MidPointDataSource(Collection refs = new ArrayList(); for (PrismReferenceValue refVal : ((PrismReference) i).getValues()){ refs.add(ObjectTypeUtil.createObjectRef(refVal)); @@ -111,18 +111,18 @@ public Object getFieldValue(JRField jrField) throws JRException { } } return containers; - + } else throw new JRException("Could not get value of the fileld: " + fieldName); -// return +// return // throw new UnsupportedOperationException("dataSource.getFiledValue() not supported"); } - + private Object normalize(Object realValue, Class fieldClass){ if (realValue instanceof PolyString && fieldClass.equals(String.class)){ return ((PolyString)realValue).getOrig(); } - + return realValue; } diff --git a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/MidPointLocalQueryExecutor.java b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/MidPointLocalQueryExecutor.java index b6c7156dfc4..94210edf58d 100644 --- a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/MidPointLocalQueryExecutor.java +++ b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/MidPointLocalQueryExecutor.java @@ -47,41 +47,41 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; public class MidPointLocalQueryExecutor extends MidPointQueryExecutor { - + private static final Trace LOGGER = TraceManager.getTrace(MidPointLocalQueryExecutor.class); private ObjectQuery query; private String script; private Class type; private ReportService reportService; - - + + public MidPointLocalQueryExecutor(JasperReportsContext jasperReportsContext, JRDataset dataset, Map parametersMap, ReportService reportService){ super(jasperReportsContext, dataset, parametersMap); } - + protected MidPointLocalQueryExecutor(JasperReportsContext jasperReportsContext, JRDataset dataset, Map parametersMap) { super(jasperReportsContext, dataset, parametersMap); - + //JRFillParameter fillparam = (JRFillParameter) parametersMap.get(JRParameter.REPORT_PARAMETERS_MAP); //Map reportParams = (Map) fillparam.getValue(); reportService = (ReportService) parametersMap.get(ReportService.PARAMETER_REPORT_SERVICE).getValue(); parseQuery(); } - - + + @Override protected Object getParsedQuery(String query, Map expressionParameters) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException { return reportService.parseQuery(query, expressionParameters); } - + @Override protected Collection> searchObjects(Object query, Collection> options) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException{ return reportService.searchObjects((ObjectQuery) query, SelectorOptions.createCollection(GetOperationOptions.createRaw())); } - + @Override protected Collection> evaluateScript(String script, @@ -95,7 +95,7 @@ protected Collection> searchObjects(Object que protected Collection searchAuditRecords(String script, Map parameters) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException { return reportService.evaluateAuditScript(script, parameters); } - + @Override protected JRDataSource createDataSourceFromObjects(Collection> results) { return new MidPointDataSource(toPcvList(results)); @@ -113,8 +113,8 @@ private Collection> toPcvList(Colle protected JRDataSource createDataSourceFromContainerValues(Collection> results) { return new MidPointDataSource(results); } - - + + public String getScript() { return script; } @@ -124,7 +124,7 @@ public ObjectQuery getQuery() { public Class getType() { return type; } - + // private Object getObjectQueryFromParameters(){ // JRParameter[] params = dataset.getParameters(); // Map expressionParameters = new HashMap(); @@ -135,24 +135,24 @@ public Class getType() { // } // return null; // } -// +// // private Map getParameters(){ // JRParameter[] params = dataset.getParameters(); // Map expressionParameters = new HashMap(); // for (JRParameter param : params){ // LOGGER.trace(((JRBaseParameter)param).getName()); // Object v = getParameterValue(param.getName()); -// try{ +// try{ // expressionParameters.put(new QName(param.getName()), new PrismPropertyValue(v)); // } catch (Exception e){ // //just skip properties that are not important for midpoint // } -// +// // LOGGER.trace("p.val: {}", v); // } // return expressionParameters; // } -// +// // private Map getPromptingParameters(){ // JRParameter[] params = dataset.getParameters(); // Map expressionParameters = new HashMap(); @@ -165,27 +165,27 @@ public Class getType() { // } // LOGGER.trace(((JRBaseParameter)param).getName()); // Object v = getParameterValue(param.getName()); -// try{ +// try{ // expressionParameters.put(new QName(param.getName()), new PrismPropertyValue(v)); // } catch (Exception e){ // //just skip properties that are not important for midpoint // } -// +// // LOGGER.trace("p.val: {}", v); // } // return expressionParameters; // } -// +// // @Override // protected void parseQuery() { // // TODO Auto-generated method stub -// -// -// +// +// +// // String s = dataset.getQuery().getText(); -// +// // JRBaseParameter p = (JRBaseParameter) dataset.getParameters()[0]; -// +// // Map expressionParameters = getParameters(); // LOGGER.info("query: " + s); // if (StringUtils.isEmpty(s)){ @@ -193,7 +193,7 @@ public Class getType() { // } else { // try { // if (s.startsWith("", ""); // script = normalized.replace("", ""); -// +// // } // } catch (SchemaException | ObjectNotFoundException | ExpressionEvaluationException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } -// +// // } // // @Override // public JRDataSource createDatasource() throws JRException { // Collection> results = new ArrayList<>(); -// +// // try { // if (query == null && script == null){ // throw new JRException("Neither query, nor script defined in the report."); // } -// +// // if (query != null){ // results = reportService.searchObjects(query, SelectorOptions.createCollection(GetOperationOptions.createRaw())); // } else { @@ -243,13 +243,13 @@ public Class getType() { // // TODO Auto-generated catch block // throw new JRException(e); // } -// +// // MidPointDataSource mds = new MidPointDataSource(results); -// +// // return mds; // } -// -// +// +// // @Override // public void close() { //// throw new UnsupportedOperationException("QueryExecutor.close() not supported"); @@ -266,9 +266,9 @@ public Class getType() { // throw new UnsupportedOperationException("QueryExecutor.getParameterReplacement() not supported"); // } - - - + + + } diff --git a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/MidPointQueryExecutor.java b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/MidPointQueryExecutor.java index 568ee8ec4a4..86582001d6a 100644 --- a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/MidPointQueryExecutor.java +++ b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/MidPointQueryExecutor.java @@ -54,13 +54,13 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; public abstract class MidPointQueryExecutor extends JRAbstractQueryExecuter { - + private static final Trace LOGGER = TraceManager.getTrace(MidPointLocalQueryExecutor.class); private Object query; private String script; private Class type; private ReportService reportService; - + public String getScript() { return script; } @@ -70,7 +70,7 @@ public Object getQuery() { public Class getType() { return type; } - + protected Map getParameters(){ JRParameter[] params = dataset.getParameters(); Map expressionParameters = new HashMap(); @@ -80,17 +80,17 @@ protected Map getParameters(){ } //LOGGER.trace(((JRBaseParameter)param).getName()); Object v = getParameterValue(param.getName()); - try{ + try{ expressionParameters.put(new QName(param.getName()), new PrismPropertyValue(v)); } catch (Exception e){ //just skip properties that are not important for midpoint } - + LOGGER.trace("p.val: {}", v); } return expressionParameters; } - + protected Map getPromptingParameters(){ JRParameter[] params = dataset.getParameters(); Map expressionParameters = new HashMap(); @@ -103,39 +103,39 @@ protected Map getPromptingParameters(){ } //LOGGER.trace(((JRBaseParameter)param).getName()); Object v = getParameterValue(param.getName()); - try{ + try{ expressionParameters.put(new QName(param.getName()), new PrismPropertyValue(v)); } catch (Exception e){ //just skip properties that are not important for midpoint } - + LOGGER.trace("p.val: {}", v); } return expressionParameters; } - + protected abstract Object getParsedQuery(String query, Map expressionParameters) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException; - + protected String getParsedScript(String script){ String normalized = script.replace("", ""); return normalized.replace("", ""); } - + protected MidPointQueryExecutor(JasperReportsContext jasperReportsContext, JRDataset dataset, Map parametersMap) { super(jasperReportsContext, dataset, parametersMap); } - + protected abstract Collection> searchObjects(Object query, Collection> options) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException; protected abstract Collection> evaluateScript(String script, Map parameters) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException; - + protected abstract Collection searchAuditRecords(String script, Map parameters) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException; - + protected abstract JRDataSource createDataSourceFromObjects(Collection> results); protected abstract JRDataSource createDataSourceFromContainerValues(Collection> results); - + @Override protected void parseQuery() { try { @@ -158,14 +158,14 @@ protected void parseQuery() { } } - + @Override public JRDataSource createDatasource() throws JRException { try { if (query == null && script == null){ throw new JRException("Neither query, nor script defined in the report."); } - + if (query != null) { Collection> results; results = searchObjects(query, SelectorOptions.createCollection(GetOperationOptions.createRaw())); @@ -207,7 +207,7 @@ public boolean cancelQuery() throws JRException { protected String getParameterReplacement(String parameterName) { throw new UnsupportedOperationException("QueryExecutor.getParameterReplacement() not supported"); } - - + + } diff --git a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/MidPointQueryExecutorFactory.java b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/MidPointQueryExecutorFactory.java index 411b1da324b..bfcf0c6a566 100644 --- a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/MidPointQueryExecutorFactory.java +++ b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/MidPointQueryExecutorFactory.java @@ -23,13 +23,13 @@ public class MidPointQueryExecutorFactory extends AbstractQueryExecuterFactory{ // public final static String PARAMETER_MIDPOINT_FUNCTION = "MIDPOINT_FUNCTION"; // public final static String PARAMETER_AUDIT_SERVICE = "AUDIT_SERVICE"; // public final static String PARAMETER_REPORT_FUNCTIONS = "reportFunctions"; - - + + private final static Object[] MIDPOINT_BUILTIN_PARAMETERS = { ReportService.PARAMETER_REPORT_SERVICE, "midpoint.connection" }; - - + + @Override public Object[] getBuiltinParameters() { return MIDPOINT_BUILTIN_PARAMETERS; @@ -38,7 +38,7 @@ public Object[] getBuiltinParameters() { @Override public JRQueryExecuter createQueryExecuter(JasperReportsContext jasperReportsContext, JRDataset dataset, Map parameters) throws JRException { - + return new MidPointLocalQueryExecutor(jasperReportsContext, dataset, parameters); } @@ -46,7 +46,7 @@ public JRQueryExecuter createQueryExecuter(JasperReportsContext jasperReportsCon public boolean supportsQueryParameterType(String className) { return true; } - - + + } diff --git a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportCreateTaskHandler.java b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportCreateTaskHandler.java index 405adbea692..5cdf806a5f6 100644 --- a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportCreateTaskHandler.java +++ b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportCreateTaskHandler.java @@ -150,7 +150,7 @@ public TaskRunResult run(Task task) { JasperReport jasperReport = ReportTypeUtil.loadJasperReport(parentReport); LOGGER.trace("compile jasper design, create jasper report : {}", jasperReport); - + PrismContainer reportParams = (PrismContainer) task.getExtensionItem(ReportConstants.REPORT_PARAMS_PROPERTY_NAME); if (reportParams != null) { PrismContainerValue reportParamsValues = reportParams.getValue(); @@ -165,14 +165,14 @@ public TaskRunResult run(Task task) { } else { value = pp.getRealValues(); } - + parameters.put(paramName, value); - + } } } - + String virtualizerS = parentReport.getVirtualizer(); Integer virtualizerKickOn = parentReport.getVirtualizerKickOn(); @@ -188,7 +188,7 @@ public TaskRunResult run(Task task) { if (timeout != null && timeout > 0) { LOGGER.trace("Setting timeout on report execution [ms]: " + timeout); jasperReport.setProperty(TimeoutGovernor.PROPERTY_TIMEOUT_ENABLED, Boolean.TRUE.toString()); - jasperReport.setProperty(TimeoutGovernor.PROPERTY_TIMEOUT, String.valueOf(timeout)); + jasperReport.setProperty(TimeoutGovernor.PROPERTY_TIMEOUT, String.valueOf(timeout)); } if (virtualizerS != null && virtualizerKickOn != null && virtualizerKickOn > 0) { @@ -249,7 +249,7 @@ public TaskRunResult run(Task task) { LOGGER.trace("CreateReportTaskHandler.run stopping"); return runResult; } - + private boolean isSingleValue(String paramName, JRParameter[] jrParams) { JRParameter param = Arrays.stream(jrParams).filter(p -> p.getName().equals(paramName)).findAny().get(); return !List.class.isAssignableFrom(param.getValueClass()); @@ -276,17 +276,17 @@ private Map completeReport(ReportType parentReport, JasperReport } // private JasperReport loadJasperReport(ReportType reportType) throws SchemaException{ -// +// // if (reportType.getTemplate() == null) { // throw new IllegalStateException("Could not create report. No jasper template defined."); // } // try { // byte[] reportTemplate = Base64.decodeBase64(reportType.getTemplate()); -// +// // InputStream inputStreamJRXML = new ByteArrayInputStream(reportTemplate); // JasperDesign jasperDesign = JRXmlLoader.load(inputStreamJRXML); // LOGGER.trace("load jasper design : {}", jasperDesign); -// +// // if (reportType.getTemplateStyle() != null){ // JRDesignReportTemplate templateStyle = new JRDesignReportTemplate(new JRDesignExpression("$P{" + PARAMETER_TEMPLATE_STYLES + "}")); // jasperDesign.addTemplate(templateStyle); @@ -295,15 +295,15 @@ private Map completeReport(ReportType parentReport, JasperReport // parameter.setValueClass(JRTemplate.class); // parameter.setForPrompting(false); // jasperDesign.addParameter(parameter); -// } +// } // JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign); // return jasperReport; -// } catch (JRException ex){ +// } catch (JRException ex){ // LOGGER.error("Couldn't create jasper report design {}", ex.getMessage()); // throw new SchemaException(ex.getMessage(), ex.getCause()); // } -// -// +// +// // } private Map prepareReportParameters(ReportType reportType, OperationResult parentResult) { Map params = new HashMap(); @@ -477,19 +477,19 @@ private void saveReportOutputType(String filePath, ReportType reportType, Task t reportOutputType.setName(new PolyStringType(reportOutputName)); reportOutputType.setDescription(reportType.getDescription() + " - " + reportType.getExport().value()); reportOutputType.setExportType(reportType.getExport()); - - + + SearchResultList> nodes = modelService.searchObjects(NodeType.class, QueryBuilder.queryFor(NodeType.class, prismContext).item(NodeType.F_NODE_IDENTIFIER).eq(task.getNode()).build(), null, task, parentResult); if (nodes == null || nodes.isEmpty()) { LOGGER.error("Could not found node for storing the report."); throw new ObjectNotFoundException("Could not find node where to save report"); } - + if (nodes.size() > 1) { LOGGER.error("Found more than one node with ID {}.", task.getNode()); throw new IllegalStateException("Found more than one node with ID " + task.getNode()); } - + reportOutputType.setNodeRef(ObjectTypeUtil.createObjectRef(nodes.iterator().next())); ObjectDelta objectDelta = null; diff --git a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportFunctions.java b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportFunctions.java index 818ce8aaf69..192bb2d5987 100644 --- a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportFunctions.java +++ b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportFunctions.java @@ -327,11 +327,11 @@ ObjectFilter createEqualFilter(ItemPath propertyPat // RefFilter createReferenceEqualFilter(QName propertyName, Class type, String... oids) { // return RefFilter.createReferenceEqual(propertyName, type, prismContext, oids); // } - + // RefFilter createReferenceEqualFilter(ItemPath propertyPath, Class type, String... oids) throws SchemaException { // return RefFilter.createReferenceEqual(propertyPath, type, prismContext, oids); // } - + // Object parseObjectFromXML (String xml) throws SchemaException { // return prismContext.parserFor(xml).xml().parseAnyData(); // } diff --git a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportManagerImpl.java b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportManagerImpl.java index 86bdfcefa62..0a9d50a2554 100644 --- a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportManagerImpl.java +++ b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportManagerImpl.java @@ -76,31 +76,31 @@ */ @Service(value = "reportManager") public class ReportManagerImpl implements ReportManager, ChangeHook, ReadHook { - + public static final String HOOK_URI = "http://midpoint.evolveum.com/model/report-hook-1"; - + private static final Trace LOGGER = TraceManager.getTrace(ReportManagerImpl.class); - + private static final String CLASS_NAME_WITH_DOT = ReportManagerImpl.class.getSimpleName() + "."; private static final String CLEANUP_REPORT_OUTPUTS = CLASS_NAME_WITH_DOT + "cleanupReportOutputs"; private static final String DELETE_REPORT_OUTPUT = CLASS_NAME_WITH_DOT + "deleteReportOutput"; private static final String REPORT_OUTPUT_DATA = CLASS_NAME_WITH_DOT + "getReportOutputData"; - + @Autowired private HookRegistry hookRegistry; @Autowired private TaskManager taskManager; - + @Autowired private PrismContext prismContext; - + @Autowired private ModelService modelService; @PostConstruct - public void init() { + public void init() { hookRegistry.registerChangeHook(HOOK_URI, this); hookRegistry.registerReadHook(HOOK_URI, this); } @@ -134,9 +134,9 @@ private boolean isRaw(Collection> options) * @param task * @param parentResult describes report which has to be created */ - + @Override - public void runReport(PrismObject object, PrismContainer paramContainer, Task task, OperationResult parentResult) { + public void runReport(PrismObject object, PrismContainer paramContainer, Task task, OperationResult parentResult) { task.setHandlerUri(ReportCreateTaskHandler.REPORT_CREATE_TASK_URI); task.setObjectRef(object.getOid(), ReportType.COMPLEX_TYPE); try { @@ -146,10 +146,10 @@ public void runReport(PrismObject object, PrismContainer object, PrismContainer object = null; - for (Object o : context.getProjectionContexts()) { + for (Object o : context.getProjectionContexts()) { boolean deletion = false; object = ((ModelElementContext) o).getObjectNew(); if (object == null) { @@ -189,7 +189,7 @@ public HookOperationMode invoke(@NotNull ModelContext context, @NotNull Task tas object = ((ModelElementContext) o).getObjectOld(); } if (object == null) { - LOGGER.warn("Probably invalid projection context: both old and new objects are null"); + LOGGER.warn("Probably invalid projection context: both old and new objects are null"); } else if (object.getCompileTimeClass().isAssignableFrom(ReportType.class)) { relatesToReport = true; isDeletion = deletion; @@ -204,7 +204,7 @@ public HookOperationMode invoke(@NotNull ModelContext context, @NotNull Task tas LOGGER.trace("invoke() EXITING: Changes not related to report"); return HookOperationMode.FOREGROUND; } - + if (isDeletion) { LOGGER.trace("invoke() EXITING because operation is DELETION"); return HookOperationMode.FOREGROUND; @@ -230,7 +230,7 @@ public HookOperationMode invoke(@NotNull ModelContext context, @NotNull Task tas // Compile template JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign); LOGGER.trace("compile jasper design, create jasper report : {}", jasperReport); - + //result.computeStatus(); result.recordSuccessIfUnknown(); @@ -239,18 +239,18 @@ public HookOperationMode invoke(@NotNull ModelContext context, @NotNull Task tas String message = "Cannot load or compile jasper report: " + ex.getMessage(); LOGGER.error(message); result.recordFatalError(message, ex); - } - + } + return HookOperationMode.FOREGROUND; } - - + + @Override public void invokeOnException(@NotNull ModelContext context, @NotNull Throwable throwable, @NotNull Task task, @NotNull OperationResult result) { - + } - + @Override public void cleanupReports(CleanupPolicyType cleanupPolicy, OperationResult parentResult) { OperationResult result = parentResult.createSubresult(CLEANUP_REPORT_OUTPUTS); @@ -270,7 +270,7 @@ public void cleanupReports(CleanupPolicyType cleanupPolicy, OperationResult pare new Object[]{deleteReportOutputsTo, duration}); XMLGregorianCalendar timeXml = XmlTypeConverter.createXMLGregorianCalendar(deleteReportOutputsTo.getTime()); - + List> obsoleteReportOutputs = new ArrayList>(); try { ObjectQuery obsoleteReportOutputsQuery = QueryBuilder.queryFor(ReportOutputType.class, prismContext) @@ -286,11 +286,11 @@ public void cleanupReports(CleanupPolicyType cleanupPolicy, OperationResult pare boolean interrupted = false; int deleted = 0; int problems = 0; - + for (PrismObject reportOutputPrism : obsoleteReportOutputs){ ReportOutputType reportOutput = reportOutputPrism.asObjectable(); - - LOGGER.trace("Removing report output {} along with {} file.", reportOutput.getName().getOrig(), + + LOGGER.trace("Removing report output {} along with {} file.", reportOutput.getName().getOrig(), reportOutput.getFilePath()); boolean problem = false; try { @@ -308,20 +308,20 @@ public void cleanupReports(CleanupPolicyType cleanupPolicy, OperationResult pare } result.computeStatusIfUnknown(); - LOGGER.info("Report cleanup procedure " + - (interrupted ? "was interrupted" : "finished") + + LOGGER.info("Report cleanup procedure " + + (interrupted ? "was interrupted" : "finished") + ". Successfully deleted {} report outputs; there were problems with deleting {} report ouptuts.", deleted, problems); String suffix = interrupted ? " Interrupted." : ""; if (problems == 0) { parentResult.createSubresult(CLEANUP_REPORT_OUTPUTS + ".statistics").recordStatus(OperationResultStatus.SUCCESS, "Successfully deleted " + deleted + " report output(s)." + suffix); } else { - parentResult.createSubresult(CLEANUP_REPORT_OUTPUTS + ".statistics").recordPartialError("Successfully deleted " + + parentResult.createSubresult(CLEANUP_REPORT_OUTPUTS + ".statistics").recordPartialError("Successfully deleted " + deleted + " report output(s), " + "there was problems with deleting " + problems + " report outputs."); } } - + @Override public void deleteReportOutput(ReportOutputType reportOutput, OperationResult parentResult) throws Exception { String oid = reportOutput.getOid(); @@ -356,8 +356,8 @@ public void deleteReportOutput(ReportOutputType reportOutput, OperationResult pa ObjectDelta delta = ObjectDelta.createDeleteDelta(ReportOutputType.class, oid, prismContext); Collection> deltas = MiscSchemaUtil.createCollection(delta); - modelService.executeChanges(deltas, null, task, result); - + modelService.executeChanges(deltas, null, task, result); + result.recordSuccessIfUnknown(); } catch (Exception e) { @@ -365,8 +365,8 @@ public void deleteReportOutput(ReportOutputType reportOutput, OperationResult pa throw e; } } - - + + //TODO re-throw exceptions? @Override public InputStream getReportOutputData(String reportOutputOid, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException, IOException { @@ -379,7 +379,7 @@ public InputStream getReportOutputData(String reportOutputOid, OperationResult p try { ReportOutputType reportOutput = modelService.getObject(ReportOutputType.class, reportOutputOid, null, task, result).asObjectable(); - + String filePath = reportOutput.getFilePath(); if (StringUtils.isEmpty(filePath)) { parentResult.recordFatalError("Report output file path is not defined."); diff --git a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportServiceImpl.java b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportServiceImpl.java index b2d2ae25531..d57a95f6db3 100644 --- a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportServiceImpl.java +++ b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportServiceImpl.java @@ -72,7 +72,7 @@ public class ReportServiceImpl implements ReportService { private static final transient Trace LOGGER = TraceManager.getTrace(ReportServiceImpl.class); - + @Autowired private ModelService model; @Autowired private TaskManager taskManager; @Autowired private PrismContext prismContext; @@ -105,10 +105,10 @@ public ObjectQuery parseQuery(String query, Map parameters) throw ObjectFilter subFilter = ((TypeFilter) f).getFilter(); ObjectQuery q = ObjectQuery.createObjectQuery(subFilter); - + ExpressionVariables variables = new ExpressionVariables(); variables.addVariableDefinitions(parameters); - + q = ExpressionUtil.evaluateQueryExpressions(q, variables, expressionFactory, prismContext, "parsing expression values for report", task, task.getResult()); ((TypeFilter) f).setFilter(q.getFilter()); @@ -296,7 +296,7 @@ private Collection createFunctionLibraries() { midPointLib.setNamespace("http://midpoint.evolveum.com/xml/ns/public/function/report-3"); ReportFunctions reportFunctions = new ReportFunctions(prismContext, model, taskManager, auditService); midPointLib.setGenericFunctions(reportFunctions); -// +// // MidpointFunctionsImpl mp = new MidpointFunctionsImpl(); // mp. diff --git a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportUtils.java b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportUtils.java index dfb47d153c2..cc2afcf0d3c 100644 --- a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportUtils.java +++ b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportUtils.java @@ -242,12 +242,12 @@ public static String getPropertyString(String key, String defaultValue) { } return val; } - + public static String getPropertyString(String key, Object values, String defaultValue) { if (key == null || values == null) { return defaultValue; } - + if (!List.class.isAssignableFrom(values.getClass())) { return getPropertyString((key.endsWith(".") ? key + values.toString() : key + "." + values.toString()), defaultValue); } @@ -282,7 +282,7 @@ public static String getPropertyString(String key, Object values, String default builder.append(", "); } } - + return builder.toString(); } @@ -322,11 +322,11 @@ public static String prettyPrintForReport(PrismContainerValue pcv) { sb.append(prettyPrintForReport(item2)); sb.append(", "); } - sb.setLength(Math.max(sb.length() - 2, 0)); // delete last delimiter + sb.setLength(Math.max(sb.length() - 2, 0)); // delete last delimiter sb.append("}"); sb.append(", "); } - sb.setLength(Math.max(sb.length() - 2, 0)); // delete last delimiter + sb.setLength(Math.max(sb.length() - 2, 0)); // delete last delimiter return sb.toString(); } @@ -403,7 +403,7 @@ public static String prettyPrintForReport(byte[] ba) { if (ba == null) { return "null"; } - return "[" + ((byte[]) ba).length + " bytes]"; //Jasper doesnt like byte[] + return "[" + ((byte[]) ba).length + " bytes]"; //Jasper doesnt like byte[] } public static String prettyPrintForReport(Collection prismValueList) { @@ -415,14 +415,14 @@ public static String prettyPrintForReport(Collection prismValueList) { sb.append("#"); } } - sb.setLength(Math.max(sb.length() - 1, 0)); // delete last # delimiter + sb.setLength(Math.max(sb.length() - 1, 0)); // delete last # delimiter return sb.toString(); } /* Multiplexer method for various input classes, using Reflection - Mostly Copied from com.evolveum.midpoint.util.PrettyPrinter - - Credit goes to Evolveum + - Credit goes to Evolveum */ public static String prettyPrintForReport(Object value) { if (value == null) { @@ -433,7 +433,7 @@ public static String prettyPrintForReport(Object value) { return ""; } - //special handling for byte[], some problems with jasper when printing + //special handling for byte[], some problems with jasper when printing if (byte[].class.equals(value.getClass())) { return prettyPrintForReport((byte[]) value); } @@ -475,7 +475,7 @@ private static String printItemDeltaValues(ItemDeltaType itemDelta) { sb.append(", "); } } - sb.setLength(Math.max(sb.length() - 2, 0)); // delete last delimiter + sb.setLength(Math.max(sb.length() - 2, 0)); // delete last delimiter return sb.toString(); } @@ -515,7 +515,7 @@ private static String printItemDeltaOldValues(ItemPathType itemPath, List values sb.append(", "); } } - sb.setLength(Math.max(sb.length() - 2, 0)); // delete last delimiter + sb.setLength(Math.max(sb.length() - 2, 0)); // delete last delimiter return sb.toString(); } @@ -725,20 +725,20 @@ public static String prettyPrintForReport(AccessCertificationResponseType respon public static String prettyPrintForReport(EvaluatedPolicyRuleTriggerType trigger) { return prettyPrintRuleTriggerForReport(trigger); - } - + } + public static String prettyPrintForReport(EvaluatedSituationTriggerType trigger) { return prettyPrintRuleTriggerForReport(trigger); - } - + } + public static String prettyPrintForReport(EvaluatedExclusionTriggerType trigger) { return prettyPrintRuleTriggerForReport(trigger); } - + public static String prettyPrintForReport(PrismObjectValue pov) { return prettyPrintForReport((PrismContainerValue) pov); } - + private static String prettyPrintRuleTriggerForReport(EvaluatedPolicyRuleTriggerType trigger) { if (trigger == null) { return ""; diff --git a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportWebService.java b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportWebService.java index dad5fd44060..db1d4d2d568 100644 --- a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportWebService.java +++ b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportWebService.java @@ -47,7 +47,7 @@ public class ReportWebService implements ReportPortType, ReportPort { @Autowired(required = true) private ReportService reportService; - + @Override public ObjectListType evaluateScript(String script, RemoteReportParametersType parameters) { try { @@ -101,7 +101,7 @@ private Map getParamsMap(RemoteReportParametersType parametersTyp } return parametersMap; - + } @@ -141,13 +141,13 @@ private AuditEventRecordListType createAuditEventRecordListType(Collection parametersMap = getParamsMap(parameters); ObjectQuery q = reportService.parseQuery(query, parametersMap); Collection> resultList = reportService.searchObjects(q, diff --git a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportWebServiceRaw.java b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportWebServiceRaw.java index 2f7e754815b..ac7974ee61c 100644 --- a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportWebServiceRaw.java +++ b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/ReportWebServiceRaw.java @@ -61,7 +61,7 @@ public class ReportWebServiceRaw implements Provider { @Autowired(required = true) private ReportWebService reportService; - + @Override public DOMSource invoke(DOMSource request) { try { @@ -144,7 +144,7 @@ public DOMSource invokeAllowingFaults(DOMSource request) throws FaultMessage { return new DOMSource(response); } - + private void serializeFaultMessage(Detail detail, FaultMessage faultMessage) { MiscSchemaUtil.serializeFaultMessage(detail, faultMessage, prismContext, LOGGER); } 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 b9c54911e76..2ce502d5915 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 @@ -50,7 +50,7 @@ @ContextConfiguration(locations = { "classpath:ctx-report-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestReport extends AbstractModelIntegrationTest{ - + // @Autowired(required=true) // private ModelService model; // @Autowired(required=true) @@ -59,48 +59,48 @@ public class TestReport extends AbstractModelIntegrationTest{ // private TaskManager taskManager; @Autowired(required=true) ExpressionFactory expressionFactory; - + private final static String TEST_DIR_COMMON = "src/test/resources/common"; - + private final static String USER_JACK_FILENAME = TEST_DIR_COMMON + "/user-jack.xml"; private final static String USER_JACK_OID = "c0c010c0-d34d-b33f-f00d-111111111111"; private final static File USER_JACK_FILE = new File(USER_JACK_FILENAME); - + private final static String SYSTEM_CONFIGURATION_FILENAME = TEST_DIR_COMMON + "/system-configuration.xml"; private final static File SYSTEM_CONFIGURATION_FILE = new File(SYSTEM_CONFIGURATION_FILENAME); - + private final static String RESOURCE_DUMMY_FILENAME = TEST_DIR_COMMON + "/resource-opendj.xml"; private final static String RESOURCE_DUMMY_OID = "ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff"; private final static File RESOURCE_DUMMY_FILE = new File(RESOURCE_DUMMY_FILENAME); - + private final static String CONNECTOR_DUMMY_FILENAME = TEST_DIR_COMMON + "/connector-ldap.xml"; private final static String CONNECTOR_DUMMY_OID = "ef2bc95b-76e0-59e2-86d6-3d4f02d3eedd"; private final static File CONNECTOR_DUMMY_FILE = new File(CONNECTOR_DUMMY_FILENAME); - + private final static String ROLE_SUPERUSER_FILENAME = TEST_DIR_COMMON +"/role-superuser.xml"; private final static File ROLE_SUPERUSER_FILE = new File(ROLE_SUPERUSER_FILENAME); - + private final static String USER_ADMINISTRATOR_FILENAME = TEST_DIR_COMMON+"/user-administrator.xml"; private final static File USER_ADMINISTRATOR_FILE = new File(USER_ADMINISTRATOR_FILENAME); - + protected static DummyResource dummyResource; protected static DummyResourceContoller dummyResourceCtl; protected ResourceType resourceDummyType; protected PrismObject resourceDummy; - + @Autowired(required = true) ReportCreateTaskHandler reportTaskHandler; - + @Override protected void startResources() throws Exception { openDJController.startCleanServer(); } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - - + + repoAddObjectFromFile(USER_JACK_FILE, true, initResult).asObjectable(); repoAddObjectFromFile(ROLE_SUPERUSER_FILE, initResult); // System Configuration @@ -111,27 +111,27 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti throw new ObjectAlreadyExistsException("System configuration already exists in repository;" + "looks like the previous test haven't cleaned it up", e); } - + // User administrator PrismObject userAdministrator = repoAddObjectFromFile(USER_ADMINISTRATOR_FILE, initResult); - + importObjectFromFile(RESOURCE_DUMMY_FILE, initResult); login(userAdministrator); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + // caseIgnoreMatchingRule = matchingRuleRegistry.getMatchingRule(StringIgnoreCaseMatchingRule.NAME, DOMUtil.XSD_STRING); - + // importSystemTasks(initResult); } - + @Test public void f() throws Exception{ OperationResult initResult = new OperationResult("generate report"); JasperDesign jd = JRXmlLoader.load(new File("src/test/resources/reports/report-users-ds.jrxml")); JasperReport jr = JasperCompileManager.compileReport(jd); - + Task task = taskManager.createTaskInstance(); Map params = new HashMap(); // params.put(MidPointQueryExecutorFactory.PARAMETER_MIDPOINT_CONNECTION, modelService); @@ -139,13 +139,13 @@ public void f() throws Exception{ // params.put(MidPointQueryExecutorFactory.PARAMETER_TASK_MANAGER, taskManager); // params.put(MidPointQueryExecutorFactory.PARAMETER_EXPRESSION_FACTORY, expressionFactory); params.put("userName", new PolyString("administrator")); - - + + reportTaskHandler.run(task); - + // byte[] reportTemplatebase64 = "".getBytes(); // byte[] reportTemplate = Base64.decodeBase64("UEdwaGMzQmxjbEpsY0c5eWRDQU5DaUFnSUNBSkNYaHRiRzV6UFNKb2RIUndPaTh2YW1GemNHVnljbVZ3YjNKMGN5NXpiM1Z5WTJWbWIzSm5aUzV1WlhRdmFtRnpjR1Z5Y21Wd2IzSjBjeUlnRFFvSkNRbDRiV3h1Y3pwNGMyazlJbWgwZEhBNkx5OTNkM2N1ZHpNdWIzSm5Mekl3TURFdldFMU1VMk5vWlcxaExXbHVjM1JoYm1ObElpQU5DZ2tKQ1hoemFUcHpZMmhsYldGTWIyTmhkR2x2YmowaWFIUjBjRG92TDJwaGMzQmxjbkpsY0c5eWRITXVjMjkxY21ObFptOXlaMlV1Ym1WMEwycGhjM0JsY25KbGNHOXlkSE1nYUhSMGNEb3ZMMnBoYzNCbGNuSmxjRzl5ZEhNdWMyOTFjbU5sWm05eVoyVXVibVYwTDNoelpDOXFZWE53WlhKeVpYQnZjblF1ZUhOa0lpQU5DZ2tKQ1c1aGJXVTlJbkpsY0c5eWRGVnpaWEpCWTJOdmRXNTBjeUlnRFFvSkNRbGpiMngxYlc1RGIzVnVkRDBpTWlJZ0RRb0pDUWx3WVdkbFYybGtkR2c5SWpFNE1DSWdEUW9KQ1Fsd1lXZGxTR1ZwWjJoMFBTSXhPQ0lnRFFvSkNRbDNhR1Z1VG05RVlYUmhWSGx3WlQwaVFXeHNVMlZqZEdsdmJuTk9iMFJsZEdGcGJDSWdEUW9KQ1FsamIyeDFiVzVYYVdSMGFEMGlPRGtpSUEwS0NRa0pZMjlzZFcxdVUzQmhZMmx1WnowaU1TSWdEUW9KQ1Fsc1pXWjBUV0Z5WjJsdVBTSXdJaUFOQ2drSkNYSnBaMmgwVFdGeVoybHVQU0l3SWlBTkNna0pDWFJ2Y0UxaGNtZHBiajBpTUNJZ0RRb0pDUWxpYjNSMGIyMU5ZWEpuYVc0OUlqQWlJQTBLQ1FrSmRYVnBaRDBpTmpkbE5EWTFZelV0TkRabFlTMDBNR1F5TFdKbFlUQXRORFk1WXpaalpqTTRPVE0zSWo0TkNna0pDVHh3Y205d1pYSjBlU0J1WVcxbFBTSnVaWFF1YzJZdWFtRnpjR1Z5Y21Wd2IzSjBjeTVoZDNRdWFXZHViM0psTG0xcGMzTnBibWN1Wm05dWRDSWdkbUZzZFdVOUluUnlkV1VpTHo0TkNna0pDVHh3Y205d1pYSjBlU0J1WVcxbFBTSnVaWFF1YzJZdWFtRnpjR1Z5Y21Wd2IzSjBjeTVsZUhCdmNuUXVjR1JtTG1admNtTmxMbXhwYm1WaWNtVmhheTV3YjJ4cFkza2lJSFpoYkhWbFBTSjBjblZsSWk4K0RRb0pDUWs4YzNSNWJHVWdabTl1ZEU1aGJXVTlJa1JsYW1GV2RTQlRZVzV6SWlCbWIyNTBVMmw2WlQwaU1UQWlJR2hCYkdsbmJqMGlUR1ZtZENJZ2FYTkVaV1poZFd4MFBTSjBjblZsSWlCcGMxQmtaa1Z0WW1Wa1pHVmtQU0owY25WbElpQU5DZ2tKQ1FrZ0lDQnVZVzFsUFNKQ1lYTmxJaUJ3WkdaRmJtTnZaR2x1WnowaVNXUmxiblJwZEhrdFNDSWdjR1JtUm05dWRFNWhiV1U5SWtSbGFtRldkVk5oYm5NdWRIUm1JaUIyUVd4cFoyNDlJazFwWkdSc1pTSStEUW9KQ1FrOEwzTjBlV3hsUGcwS0NRa0pQSE4wZVd4bElHbHpRbTlzWkQwaVptRnNjMlVpSUdselJHVm1ZWFZzZEQwaVptRnNjMlVpSUc1aGJXVTlJa1JsZEdGcGJDSWdjM1I1YkdVOUlrSmhjMlVpTHo0TkNna0pDVHh3WVhKaGJXVjBaWElnYm1GdFpUMGlkWE5sY2s5cFpDSWdZMnhoYzNNOUltcGhkbUV1YkdGdVp5NVRkSEpwYm1jaUx6NE5DZ2tKQ1R4d1lYSmhiV1YwWlhJZ2JtRnRaVDBpYUhGc1VYVmxjbmxCWTJOdmRXNTBjeUlnWTJ4aGMzTTlJbXBoZG1FdWJHRnVaeTVUZEhKcGJtY2lMejROQ2drSkNUeHhkV1Z5ZVZOMGNtbHVaeUJzWVc1bmRXRm5aVDBpYUhGc0lqNDhJVnREUkVGVVFWc2tVQ0Y3YUhGc1VYVmxjbmxCWTJOdmRXNTBjMzFkWFQ0OEwzRjFaWEo1VTNSeWFXNW5QZzBLQ1FrSlBHWnBaV3hrSUc1aGJXVTlJbUZqWTI5MWJuUk9ZVzFsSWlCamJHRnpjejBpYW1GMllTNXNZVzVuTGxOMGNtbHVaeUl2UGcwS0NRa0pQR1pwWld4a0lHNWhiV1U5SW5KbGMyOTFjbU5sVG1GdFpTSWdZMnhoYzNNOUltcGhkbUV1YkdGdVp5NVRkSEpwYm1jaUx6NE5DZ2tKQ1R4a1pYUmhhV3crRFFvSkNRa0pQR0poYm1RZ2FHVnBaMmgwUFNJeE9DSWdjM0JzYVhSVWVYQmxQU0pUZEhKbGRHTm9JajROQ2drSkNRa0pQR1p5WVcxbFBnMEtDUWtKQ1FrSlBISmxjRzl5ZEVWc1pXMWxiblFnZFhWcFpEMGlNMlU0Wm1Sa05tUXRZVFptWmkwME5EQTNMVGxoTVdVdE5XUTJZalEzTURZek1EQmhJaUJ3YjNOcGRHbHZibFI1Y0dVOUlrWnNiMkYwSWlCemRIbHNaVDBpUkdWMFlXbHNJaUJ0YjJSbFBTSlBjR0Z4ZFdVaUlIZzlJakFpSUhrOUlqRWlJSGRwWkhSb1BTSXhPREFpSUdobGFXZG9kRDBpTVRjaUx6NE5DZ2tKQ1FrSkNUeHNhVzVsUGcwS0NRa0pDUWtKQ1R4eVpYQnZjblJGYkdWdFpXNTBJSFYxYVdROUlqUTNaamt4T0RBeExXTm1OV1l0TkdKbFpDMWlNVGxqTFdOaE16a3pNV05pWmprNFpDSWdjRzl6YVhScGIyNVVlWEJsUFNKR2FYaFNaV3hoZEdsMlpWUnZWRzl3SWlCNFBTSXdJaUI1UFNJd0lpQjNhV1IwYUQwaU1UZ3dJaUJvWldsbmFIUTlJakVpSUdadmNtVmpiMnh2Y2owaUl6TXpNek16TXlJK0RRb0pDUWtKQ1FrSkNUeHdjbWx1ZEZkb1pXNUZlSEJ5WlhOemFXOXVQandoVzBORVFWUkJXMjVsZHlCcVlYWmhMbXhoYm1jdVFtOXZiR1ZoYmlnb2FXNTBLU1JXZTFKRlVFOVNWRjlEVDFWT1ZIMHVhVzUwVm1Gc2RXVW9LU0U5TVNsZFhUNDhMM0J5YVc1MFYyaGxia1Y0Y0hKbGMzTnBiMjQrRFFvSkNRa0pDUWtKUEM5eVpYQnZjblJGYkdWdFpXNTBQZzBLQ1FrSkNRa0pDVHhuY21Gd2FHbGpSV3hsYldWdWRENE5DZ2tKQ1FrSkNRa0pQSEJsYmlCc2FXNWxWMmxrZEdnOUlqQXVOU0lnYkdsdVpVTnZiRzl5UFNJak9UazVPVGs1SWk4K0RRb0pDUWtKQ1FrSlBDOW5jbUZ3YUdsalJXeGxiV1Z1ZEQ0TkNna0pDUWtKQ1R3dmJHbHVaVDROQ2drSkNRa0pDVHgwWlhoMFJtbGxiR1FnYVhOVGRISmxkR05vVjJsMGFFOTJaWEptYkc5M1BTSjBjblZsSWo0TkNna0pDUWtKQ1FrOGNtVndiM0owUld4bGJXVnVkQ0IxZFdsa1BTSmxZbUZsWmpFMlpDMHlPVEF6TFRRd01qa3RPV0UyWWkxa05HUXlORFExTlRoaFpUa2lJSEJ2YzJsMGFXOXVWSGx3WlQwaVJteHZZWFFpSUhOMGNtVjBZMmhVZVhCbFBTSlNaV3hoZEdsMlpWUnZWR0ZzYkdWemRFOWlhbVZqZENJZ2MzUjViR1U5SWtSbGRHRnBiQ0lnZUQwaU1DSWdlVDBpTWlJZ2QybGtkR2c5SWpFNE1DSWdhR1ZwWjJoMFBTSXhNeUl2UGcwS0NRa0pDUWtKQ1R4MFpYaDBSV3hsYldWdWRDQjJaWEowYVdOaGJFRnNhV2R1YldWdWREMGlUV2xrWkd4bElpOCtJQTBLQ1FrSkNRa0pDVHgwWlhoMFJtbGxiR1JGZUhCeVpYTnphVzl1UGp3aFcwTkVRVlJCV3lSR2UzSmxjMjkxY21ObFRtRnRaWDBySUNJNklDSWdLeUFrUm50aFkyTnZkVzUwVG1GdFpYMWRYVDQ4TDNSbGVIUkdhV1ZzWkVWNGNISmxjM05wYjI0K0RRb0pDUWtKQ1FrOEwzUmxlSFJHYVdWc1pENE5DZ2tKQ1FrSlBDOW1jbUZ0WlQ0TkNna0pDUWs4TDJKaGJtUStEUW9KQ1FrOEwyUmxkR0ZwYkQ0TkNna0pQQzlxWVhOd1pYSlNaWEJ2Y25RKw==".getBytes()); -// +// // byte[] decoded = Base64.decodeBase64(reportTemplate); // String s = new String(decoded); // System.out.println(s); @@ -154,7 +154,7 @@ public void f() throws Exception{ // fos.writeUTF(s); // fos.close(); JasperPrint jasperPrint = JasperFillManager.fillReport(jr, params); - + f = new File("src/test/resources/reports/report5.pdf"); JasperExportManager.exportReportToPdfFile(jasperPrint, f.getAbsolutePath()); // System.out.println("output: " + output); diff --git a/model/workflow-impl/src/main/java/com/evolveum/midpoint/wf/impl/processes/common/SpringApplicationContextHolder.java b/model/workflow-impl/src/main/java/com/evolveum/midpoint/wf/impl/processes/common/SpringApplicationContextHolder.java index 43a6bdbc0fd..8948934536a 100644 --- a/model/workflow-impl/src/main/java/com/evolveum/midpoint/wf/impl/processes/common/SpringApplicationContextHolder.java +++ b/model/workflow-impl/src/main/java/com/evolveum/midpoint/wf/impl/processes/common/SpringApplicationContextHolder.java @@ -39,9 +39,9 @@ public class SpringApplicationContextHolder implements ApplicationContextAware { private static ApplicationContext context; - public void setApplicationContext(ApplicationContext ctx) throws BeansException { + public void setApplicationContext(ApplicationContext ctx) throws BeansException { context = ctx; - } + } public static ApplicationContext getApplicationContext() { if (context == null) { @@ -121,4 +121,4 @@ public static ItemApprovalProcessInterface getItemApprovalProcessInterface() { } } - + diff --git a/model/workflow-impl/src/main/java/com/evolveum/midpoint/wf/impl/tasks/WfProcessInstanceShadowTaskHandler.java b/model/workflow-impl/src/main/java/com/evolveum/midpoint/wf/impl/tasks/WfProcessInstanceShadowTaskHandler.java index 2fb68faa413..0503ca356c2 100644 --- a/model/workflow-impl/src/main/java/com/evolveum/midpoint/wf/impl/tasks/WfProcessInstanceShadowTaskHandler.java +++ b/model/workflow-impl/src/main/java/com/evolveum/midpoint/wf/impl/tasks/WfProcessInstanceShadowTaskHandler.java @@ -68,29 +68,29 @@ public void init() { /* * There are two kinds of wf process-watching tasks: passive and active. - * + * * *Passive tasks* are used when wf processes are sophisticated enough to send events * about their state changes (using e.g. listeners or custom java tasks). In that case * we simply use midpoint tasks as holders of information coming within these events. - * + * * In the future, we will implement the original idea that when the workflow process - * instance finishes, the task status will be changed to RUNNABLE, and then this task + * instance finishes, the task status will be changed to RUNNABLE, and then this task * will be picked up by TaskManager to be run. This handler will be then called. * However, as for now, all processing (including post-processing after wf process * finish) is done within WorkflowHook.activiti2midpoint method. - * + * * As for *active tasks*, these are used to monitor simple wf processes, which do * not send any information to midpoint by themselves. These tasks are recurrent, * so their run() method is periodically executed. This method simply asks the * WfMS for the information about the particular process id. The response is asynchronous, * and is processed within WorkflowHook.activiti2midpoint method. - * + * */ @Override public TaskRunResult run(Task task) { if (wfConfiguration.isEnabled()) { - + // is this task already closed? (this flag is set by activiti2midpoint when it gets information about wf process termination) // todo: fixme this is a bit weird if (task.getExecutionStatus() == TaskExecutionStatus.CLOSED) { diff --git a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/policy/assignments/metarole/TestAssignmentsWithDifferentMetaroles.java b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/policy/assignments/metarole/TestAssignmentsWithDifferentMetaroles.java index 3b1661d6a00..627b65d21d6 100644 --- a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/policy/assignments/metarole/TestAssignmentsWithDifferentMetaroles.java +++ b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/policy/assignments/metarole/TestAssignmentsWithDifferentMetaroles.java @@ -529,7 +529,7 @@ private void previewAssignRolesToJack(String TEST_NAME, boolean immediate, boole } else { assertEquals("Wrong # of enforcement exception message", 0, enforcementMessages.size()); } - + // shortcuts final String l1 = userLead21Oid, l2 = userLead22Oid, l3 = userLead23Oid, l4 = userLead24Oid; @@ -555,13 +555,13 @@ private void previewAssignRolesToJack(String TEST_NAME, boolean immediate, boole new ExpectedStagePreview(8, set(l1, l2, l3, l4), set(), REJECT, AUTO_COMPLETION_CONDITION), new ExpectedStagePreview(9, set(l1, l2, l3, l4), set(l1, l2, l3, l4), true), new ExpectedStagePreview(10, set(), set(), REJECT, NO_ASSIGNEES_FOUND)); - + } private Set set(String... values) { return new HashSet<>(Arrays.asList(values)); } - + private void assertApprovalInfo(List infos, String targetOid, ExpectedStagePreview... expectedStagePreviews) { ApprovalSchemaExecutionInformationType found = null; @@ -765,7 +765,7 @@ private class ExpectedStagePreview { private final ApprovalLevelOutcomeType outcome; private final AutomatedCompletionReasonType reason; private final boolean hasError; - + ExpectedStagePreview(int number, Set definitionApproverOids, Set expectedApproverOids) { this(number, definitionApproverOids, expectedApproverOids, null, null, false); } diff --git a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/GenericConnectorException.java b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/GenericConnectorException.java index cfc66acb247..ff6f087f3d8 100644 --- a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/GenericConnectorException.java +++ b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/GenericConnectorException.java @@ -17,16 +17,16 @@ /** * Generic indistinguishable error of a connector framework. - * + * * Please do not use this exception if possible! * Only errors that cannot be categorized or that are not * expected at all should use this exception. - * + * * This is RUNTIME exception. As this error is generic and * we cannot distinguish any details, there is no hope that * an interface client can do anything with it. So don't even * bother catching it. - * + * * @author Radovan Semancik */ public class GenericConnectorException extends RuntimeException { diff --git a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ProvisioningListener.java b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ProvisioningListener.java index 795dc655dfa..a8195ffa330 100644 --- a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ProvisioningListener.java +++ b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ProvisioningListener.java @@ -21,7 +21,7 @@ */ @FunctionalInterface public interface ProvisioningListener { - + /** * Returns a short name of the listener for debugging purposes. * E.g. "model synchronization service". This name is used in log and error messages. diff --git a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ProvisioningService.java b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ProvisioningService.java index 9b3c32086e1..7b64985d77f 100644 --- a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ProvisioningService.java +++ b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ProvisioningService.java @@ -63,7 +63,7 @@ * @author Radovan Semancik *

    *

    - * This service retrieves information about resource objects and resources + * This service retrieves information about resource objects and resources * and handles changes to resource objects. Implementations of this interface * will apply the changes to accounts, groups and other similar objects to the * target resources. It also provides information about connectors and similar @@ -86,25 +86,25 @@ *

    */ public interface ProvisioningService { - + /** * Returns object for provided OID. - * + * * Must fail if object with the OID does not exists. - * + * * Resource Object Shadows: The resource object shadow attributes may be * retrieved from the local database, directly form the resource or a * combination of both. The retrieval may fail due to resource failure, * network failure or similar external cases. The retrieval may also take * relatively long time (e.g. until it times out). - * + * * @param type the type (class) of object to get * @param oid * OID of the object to get * @param parentResult * parent OperationResult (in/out) * @return Object fetched from repository and/or resource - * + * * @throws ObjectNotFoundException * requested object does not exist * @throws CommunicationException @@ -112,8 +112,8 @@ public interface ProvisioningService { * @throws SchemaException * error dealing with resource schema * @throws ConfigurationException - * Wrong resource or connector configuration - * @throws SecurityViolationException + * Wrong resource or connector configuration + * @throws SecurityViolationException * Security violation while communicating with the connector or processing provisioning policies * @throws IllegalArgumentException * wrong OID format, etc. @@ -121,30 +121,30 @@ public interface ProvisioningService { * unknown connector framework error */ PrismObject getObject(Class type, String oid, Collection> options, Task task, OperationResult parentResult) - throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, + throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException; - + /** * Add new object. - * + * * The OID provided in the input message may be empty. In that case the OID * will be assigned by the implementation of this method and it will be * provided as return value. - * + * * This operation should fail if such object already exists (if object with * the provided OID already exists). - * + * * The operation may fail if provided OID is in an unusable format for the * storage. Generating own OIDs and providing them to this method is not * recommended for normal operation. - * + * * Should be atomic. Should not allow creation of two objects with the same * OID (even if created in parallel). - * + * * The operation may fail if the object to be created does not conform to * the underlying schema of the storage system or the schema enforced by the * implementation. - * + * * @param object * object to create * @param scripts @@ -152,7 +152,7 @@ PrismObject getObject(Class type, String oid, Colle * @param parentResult * parent OperationResult (in/out) * @return OID assigned to the created object - * + * * @throws ObjectAlreadyExistsException * object with specified identifiers already exists, cannot add * @throws SchemaException @@ -160,27 +160,27 @@ PrismObject getObject(Class type, String oid, Colle * @throws CommunicationException * error communicating with the resource * @throws ObjectNotFoundException appropriate connector object was not found - * @throws ConfigurationException + * @throws ConfigurationException * @throws IllegalArgumentException * wrong OID format, etc. * @throws GenericConnectorException * unknown connector framework error - * @throws SecurityViolationException + * @throws SecurityViolationException * Security violation while communicating with the connector or processing provisioning policies */ String addObject(PrismObject object, OperationProvisioningScriptsType scripts, ProvisioningOperationOptions options, Task task, OperationResult parentResult) - throws ObjectAlreadyExistsException, SchemaException, CommunicationException, ObjectNotFoundException, + throws ObjectAlreadyExistsException, SchemaException, CommunicationException, ObjectNotFoundException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException; /** * Collect external changes on a resource and call the business logic with * the accumulated change data. - * + * * This method will be invoked by scheduler/sync thread. - * + * * TODO: Better description - * + * * @param resourceOid * OID of the resource for which to attempt synchronization * @param parentResult @@ -192,26 +192,26 @@ String addObject(PrismObject object, OperationProvisio * error communicating with the resource * @throws SchemaException * error dealing with resource schema - * @throws ConfigurationException - * @throws SecurityViolationException + * @throws ConfigurationException + * @throws SecurityViolationException * Security violation while communicating with the connector or processing provisioning policies * @throws GenericConnectorException * unknown connector framework error */ - int synchronize(ResourceShadowDiscriminator shadowCoordinates, Task task, OperationResult parentResult) throws ObjectNotFoundException, + int synchronize(ResourceShadowDiscriminator shadowCoordinates, Task task, OperationResult parentResult) throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException; /** * Search for objects. Searches through all object types. Returns a list of - * objects that match search criteria. - * + * objects that match search criteria. + * * Returns empty list if object type is correct but there are no objects of * that type. - * + * * Should fail if object type is wrong. Should fail if unknown property is * specified in the query. - * + * * @param paging * paging specification to limit operation result (optional) * @param query @@ -220,19 +220,19 @@ int synchronize(ResourceShadowDiscriminator shadowCoordinates, Task task, Operat *@param parentResult * parent OperationResult (in/out) @return all objects of specified type that match search criteria (subject * to paging) - * + * * @throws IllegalArgumentException * wrong object type * @throws GenericConnectorException * unknown connector framework error * @throws SchemaException * unknown property used in search query - * @throws ConfigurationException - * @throws SecurityViolationException + * @throws ConfigurationException + * @throws SecurityViolationException * Security violation while communicating with the connector or processing provisioning policies */ SearchResultList> searchObjects(Class type, ObjectQuery query, Collection> options, Task task, OperationResult parentResult) - throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, + throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException; /** @@ -241,16 +241,16 @@ SearchResultList> searchObjects(Class t Integer countObjects(Class type, ObjectQuery query, Collection> options, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException; - + /** * Search for objects iteratively. Searches through all object types. Calls a * specified handler for each object found. - * + * * If nothing is found the handler is not called and the operation returns. - * + * * Should fail if object type is wrong. Should fail if unknown property is * specified in the query. - * + * * @param query * search query * @param handler @@ -265,8 +265,8 @@ Integer countObjects(Class type, ObjectQuery query, Co * @throws SchemaException * unknown property used in search query * @throws ObjectNotFoundException appropriate connector object was not found - * @throws ConfigurationException - * @throws SecurityViolationException + * @throws ConfigurationException + * @throws SecurityViolationException * Security violation while communicating with the connector or processing provisioning policies */ SearchResultMetadata searchObjectsIterative(Class type, ObjectQuery query, Collection> options, @@ -277,23 +277,23 @@ SearchResultMetadata searchObjectsIterative(Class type * Modifies object using relative change description. Must fail if user with * provided OID does not exists. Must fail if any of the described changes * cannot be applied. Should be atomic. - * + * * If two or more modify operations are executed in parallel, the operations * should be merged. In case that the operations are in conflict (e.g. one * operation adding a value and the other removing the same value), the * result is not deterministic. - * + * * The operation may fail if the modified object does not conform to the * underlying schema of the storage system or the schema enforced by the * implementation. - * + * * TODO: optimistic locking - * + * * @param scripts * scripts that should be executed before of after operation * @param parentResult * parent OperationResult (in/out) - * + * * @throws ObjectNotFoundException * specified object does not exist * @throws SchemaException @@ -302,13 +302,13 @@ SearchResultMetadata searchObjectsIterative(Class type * wrong OID format, described change is not applicable * @throws GenericConnectorException * unknown connector framework error - * @throws SecurityViolationException + * @throws SecurityViolationException * Security violation while communicating with the connector or processing provisioning policies * @throws ObjectAlreadyExistsException * if resulting object would have name which already exists in another object of the same type */ String modifyObject(Class type, String oid, Collection modifications, - OperationProvisioningScriptsType scripts, ProvisioningOperationOptions options, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, + OperationProvisioningScriptsType scripts, ProvisioningOperationOptions options, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ObjectAlreadyExistsException, ExpressionEvaluationException; /** @@ -317,18 +317,18 @@ String modifyObject(Class type, String oid, Collection * Must fail if object with specified OID * does not exists. Should be atomic. *

    - * + * * @param oid * OID of object to delete * @param scripts * scripts that should be executed before of after operation * @param parentResult * parent OperationResult (in/out) - * + * * @throws ObjectNotFoundException * specified object does not exist - * @throws ConfigurationException - * @throws SecurityViolationException + * @throws ConfigurationException + * @throws SecurityViolationException * Security violation while communicating with the connector or processing provisioning policies * @throws IllegalArgumentException * wrong OID format, described change is not applicable @@ -340,12 +340,12 @@ void deleteObject(Class type, String oid, Provisioning /** * Executes a single provisioning script. - * + * * @param script * script to execute * @param parentResult * parent OperationResult (in/out) - * + * * @throws ObjectNotFoundException * specified object does not exist * @throws SchemaException @@ -354,71 +354,71 @@ void deleteObject(Class type, String oid, Provisioning * wrong OID format, described change is not applicable * @throws GenericConnectorException * unknown connector framework error - * @throws SecurityViolationException + * @throws SecurityViolationException * Security violation while communicating with the connector or processing provisioning policies * @throws ObjectAlreadyExistsException * if resulting object would have name which already exists in another object of the same type */ - void executeScript(String resourceOid, ProvisioningScriptType script, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, + void executeScript(String resourceOid, ProvisioningScriptType script, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ObjectAlreadyExistsException, ExpressionEvaluationException; - + /** * Test the resource connection and basic resource connector functionality. - * + * * This operation will NOT throw exception in case the resource connection * fails. It such case it will indicate the failure in the return message, * but the operation itself succeeds. The operations fails only if the * provided arguments are wrong, in case of system error, system * misconfiguration, etc. - * + * * The operation codes in the return value are defined by ConnectorTestOperation enumeration class. - * + * * @param resourceOid * OID of resource to test * @return results of executed tests - * + * * @throws ObjectNotFoundException * specified object does not exist * @throws IllegalArgumentException * wrong OID format * @throws GenericConnectorException * unknown connector framework error - * + * * @see ConnectorTestOperation */ OperationResult testResource(String resourceOid, Task task) throws ObjectNotFoundException; /** * Discovers local or remote connectors. - * + * * The operation will try to search for new connectors. It works either on local host (hostType is null) * or on a remote host (hostType is not null). All discovered connectors are stored in the repository. - * + * * It returns connectors that were discovered: those that were not in the repository before invocation - * of this operation. - * + * of this operation. + * * @param hostType definition of a connector host or null * @param parentResult parentResult parent OperationResult (in/out) * @return discovered connectors * @throws CommunicationException error connecting to a remote host */ Set discoverConnectors(ConnectorHostType hostType, OperationResult parentResult) throws CommunicationException; - + List getConnectorOperationalStatus(String resourceOid, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException; - + /** * Lists resource objects. - * + * * This method differs from other method in this interface as it works with resource objects directly. * It returns resource objects in a form of "detached shadow", that means fully-populated shadow objects * with no OID. The results of this method may not be stored in the repository. - * + * * The purpose of this method is to work directly with the resource without the potential problems of * provisioning implementation. E.g. it may be used to test resource connectivity or correctness of resource * setup. It may also be used to reach object types that are not directly supported as "shadows" by the provisioning * implementation. - * + * * @param resourceOid OID of the resource to fetch objects from * @param objectClass Object class of the objects to fetch * @param paging paging specification to limit operation result (optional) @@ -431,10 +431,10 @@ List getConnectorOperationalStatus(String resourceOi */ @Deprecated List> listResourceObjects(String resourceOid, QName objectClass, ObjectPaging paging, - Task task, OperationResult parentResult) + Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException; - - + + /** * Makes sure that the shadow is in accord with the reality. If there are any unfinished operations associated with the shadow * then this method will try to finish them. If there are pending (async) operations then this method will update their status. @@ -448,7 +448,7 @@ void refreshShadow(PrismObject shadow, ProvisioningOperationOptions /** * Applies appropriate definition to the shadow/resource delta. */ - void applyDefinition(ObjectDelta delta, Task task, OperationResult parentResult) + void applyDefinition(ObjectDelta delta, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException; /** @@ -462,13 +462,13 @@ void applyDefinition(ObjectDelta delta, Objectable obj */ void applyDefinition(PrismObject object, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException; - + /** * Applies appropriate definition to the query. */ - void applyDefinition(Class type, ObjectQuery query, Task task, OperationResult parentResult) + void applyDefinition(Class type, ObjectQuery query, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException; - + /** * Runs a short, non-destructive internal provisioning test. It tests provisioning framework and * general setup. Use ModelService.testResource for testing individual resource configurations. @@ -484,7 +484,7 @@ void applyDefinition(Class type, ObjectQuery query, Ta /** * Finish initialization of provisioning system. - * + * * The implementation may execute resource-intensive tasks in this method. All the dependencies should be already * constructed, properly wired and initialized. Also logging and other infrastructure should be already set up. */ @@ -496,7 +496,7 @@ ConstraintsCheckingResult checkConstraints(RefinedObjectClassDefinition shadowDe String shadowOid, ResourceShadowDiscriminator resourceShadowDiscriminator, ConstraintViolationConfirmer constraintViolationConfirmer, - Task task, OperationResult parentResult) + Task task, OperationResult parentResult) throws CommunicationException, ObjectAlreadyExistsException, SchemaException, SecurityViolationException, ConfigurationException, ObjectNotFoundException, ExpressionEvaluationException; void enterConstraintsCheckerCache(); 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 29011ff69d4..eaa72ee4634 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 @@ -10,49 +10,49 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; public class ResourceEventDescription implements Serializable, DebugDumpable{ - + private PrismObject oldShadow; private PrismObject currentShadow; private ObjectDelta delta; private String sourceChannel; // private PrismObject resource; - - + + public PrismObject getCurrentShadow() { return currentShadow; } - + public PrismObject getOldShadow() { return oldShadow; } - + public ObjectDelta getDelta() { return delta; } - + public String getSourceChannel() { return sourceChannel; } // public PrismObject getResource() { // return resource; // } - + public void setDelta(ObjectDelta delta) { this.delta = delta; } - + public void setOldShadow(PrismObject oldShadow) { this.oldShadow = oldShadow; } - + public void setCurrentShadow(PrismObject currentShadow) { this.currentShadow = currentShadow; } - + public void setSourceChannel(String sourceChannel) { this.sourceChannel = sourceChannel; } - + public boolean isProtected() { if ((currentShadow != null && ShadowUtil.isProtected(currentShadow)) || (oldShadow != null && ShadowUtil.isProtected(oldShadow))) { @@ -63,14 +63,14 @@ public boolean isProtected() { } return false; } - + @Override public String toString() { return "ResourceEventDescription(delta=" + delta + ", currentShadow=" + SchemaDebugUtil.prettyPrint(currentShadow) + ", oldShadow=" + SchemaDebugUtil.prettyPrint(oldShadow) + ", sourceChannel=" + sourceChannel + ")"; } - + /* (non-Javadoc) * @see com.evolveum.midpoint.util.DebugDumpable#debugDump() */ @@ -89,9 +89,9 @@ public String debugDump(int indent) { sb.append("ResourceEventDescription("); sb.append(sourceChannel); sb.append(")\n"); - + SchemaDebugUtil.indentDebugDump(sb, indent+1); - + sb.append("Delta:"); if (delta == null) { sb.append(" null"); @@ -100,17 +100,17 @@ public String debugDump(int indent) { } sb.append("\n"); SchemaDebugUtil.indentDebugDump(sb, indent+1); - + sb.append("oldShadow:"); if (oldShadow == null) { sb.append(" null"); } else { sb.append(oldShadow.debugDump(indent+2)); } - + sb.append("\n"); SchemaDebugUtil.indentDebugDump(sb, indent+1); - + sb.append("currentShadow:"); if (currentShadow == null) { sb.append(" null\n"); @@ -124,8 +124,8 @@ public String debugDump(int indent) { // public void setResource(PrismObject resource) { // this.resource = resource; // } -// -// +// +// public PrismObject getShadow() { PrismObject shadow; diff --git a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceEventListener.java b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceEventListener.java index ecb1af1eb95..73b19fd2ea2 100644 --- a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceEventListener.java +++ b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceEventListener.java @@ -28,5 +28,5 @@ public interface ResourceEventListener extends ProvisioningListener { public void notifyEvent(ResourceEventDescription eventDescription, Task task, OperationResult parentResult) throws SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ObjectNotFoundException, GenericConnectorException, ObjectAlreadyExistsException, ExpressionEvaluationException; - + } diff --git a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceObjectChangeListener.java b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceObjectChangeListener.java index 20f0370cce7..0bc2d4dc124 100644 --- a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceObjectChangeListener.java +++ b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceObjectChangeListener.java @@ -20,7 +20,7 @@ /** * @author Radovan Semancik - * + * */ public interface ResourceObjectChangeListener extends ProvisioningListener { @@ -31,18 +31,18 @@ public interface ResourceObjectChangeListener extends ProvisioningListener { /** * Submits notification about a specific change that happened on the * resource. - * + * * This describes the change that has already happened on the resource. The upper layers are * notified to take that change into an account (synchronize it). - * + * * The call should return without a major delay. It means that the * implementation can do calls to repository, but it should not * (synchronously) initiate a long-running process or provisioning request. - * + * * This operation may be called multiple times with the same change, e.g. in * case of failures in IDM or on the resource. The implementation must be * able to handle such duplicates. - * + * * @param change * change description */ 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 385f5b3abff..40807cac05b 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 @@ -45,16 +45,16 @@ public class ResourceObjectShadowChangeDescription implements DebugDumpable, Ser private PrismObject oldShadow; private String sourceChannel; private PrismObject resource; - + /** * If set to true then this change is not related to the primary goal of * the running task. E.g. it may be a change in entitlement that is discovered * when reading an account. Or it may be ordinary creation of a new shadow during * search. - * + * * On the other hand, related change is a change in the object that is being processed. * E.g. discovering that the object is missing, or a conflicting object already exists. - * + * * It is expected that reactions to the unrelated changes will be lighter, faster, * with lower overhead and without abmition to provide full synchronization. */ @@ -99,7 +99,7 @@ public PrismObject getResource() { public void setResource(PrismObject resource) { this.resource = resource; } - + public boolean isUnrelatedChange() { return unrelatedChange; } @@ -146,14 +146,14 @@ public boolean isProtected() { } return false; } - + @Override public String toString() { return "ResourceObjectShadowChangeDescription(objectDelta=" + objectDelta + ", currentShadow=" + SchemaDebugUtil.prettyPrint(currentShadow) + ", oldShadow=" + SchemaDebugUtil.prettyPrint(oldShadow) + ", sourceChannel=" + sourceChannel + ", resource=" + resource + (unrelatedChange ? " UNRELATED" : "") +")"; } - + /* (non-Javadoc) * @see com.evolveum.midpoint.util.DebugDumpable#debugDump() */ @@ -172,7 +172,7 @@ public String debugDump(int indent) { sb.append("ResourceObjectShadowChangeDescription("); sb.append(sourceChannel); sb.append(")\n"); - + SchemaDebugUtil.indentDebugDump(sb, indent+1); sb.append("resource:"); if (resource == null) { @@ -180,10 +180,10 @@ public String debugDump(int indent) { } else { sb.append(resource); } - + sb.append("\n"); SchemaDebugUtil.indentDebugDump(sb, indent+1); - + sb.append("objectDelta:"); if (objectDelta == null) { sb.append(" null"); @@ -192,17 +192,17 @@ public String debugDump(int indent) { } sb.append("\n"); SchemaDebugUtil.indentDebugDump(sb, indent+1); - + sb.append("oldShadow:"); if (oldShadow == null) { sb.append(" null"); } else { sb.append(oldShadow.debugDump(indent+2)); } - + sb.append("\n"); SchemaDebugUtil.indentDebugDump(sb, indent+1); - + sb.append("currentShadow:"); if (currentShadow == null) { sb.append(" null\n"); @@ -210,7 +210,7 @@ public String debugDump(int indent) { sb.append("\n"); sb.append(currentShadow.debugDump(indent+2)); } - + sb.append("\n"); SchemaDebugUtil.indentDebugDump(sb, indent+1); sb.append("unrelatedChange: ").append(unrelatedChange); 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 c252a7c7a17..f662992c7fd 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 @@ -78,7 +78,7 @@ public PrismObject getResource() { public void setResource(PrismObject resource) { this.resource = resource; } - + /** * Result of the failed operation. */ @@ -95,10 +95,10 @@ public void setResult(OperationResult result) { * cannot provide direct return value and therefore the invocation of * the listener is the only way how to pass operation return value to * the upper layers. - * + * * This may be useful e.g. for decided whether log the message and what * log level to use (it can be assumed that the error gets logged at least - * once for synchronous operations, but this may be the only chance to + * once for synchronous operations, but this may be the only chance to * properly log it for asynchronous operations). */ public boolean isAsynchronous() { @@ -148,12 +148,12 @@ public void checkConsistence() { public String toString() { return "ResourceOperationDescription(objectDelta=" + objectDelta + ", currentShadow=" + SchemaDebugUtil.prettyPrint(currentShadow) + ", sourceChannel=" + sourceChannel - + ", resource=" + resource + + + ", resource=" + resource + (asynchronous ? ", ASYNC" : "") + (attemptNumber != 0 ? ", attemptNumber="+attemptNumber : "") + ", result=" + result + ")"; } - + /* (non-Javadoc) * @see com.evolveum.midpoint.util.DebugDumpable#debugDump() */ @@ -172,7 +172,7 @@ public String debugDump(int indent) { sb.append("ResourceOperationDescription("); sb.append(sourceChannel); sb.append(")\n"); - + SchemaDebugUtil.indentDebugDump(sb, indent+1); sb.append("resource:"); if (resource == null) { @@ -180,7 +180,7 @@ public String debugDump(int indent) { } else { sb.append(resource); } - + sb.append("\n"); SchemaDebugUtil.indentDebugDump(sb, indent+1); sb.append("objectDelta:"); @@ -189,7 +189,7 @@ public String debugDump(int indent) { } else { sb.append(objectDelta.debugDump(indent+2)); } - + sb.append("\n"); SchemaDebugUtil.indentDebugDump(sb, indent+1); sb.append("currentShadow:"); @@ -199,7 +199,7 @@ public String debugDump(int indent) { sb.append("\n"); sb.append(currentShadow.debugDump(indent+2)); } - + sb.append("\n"); DebugUtil.debugDumpLabel(sb, "Asynchronous", indent+1); sb.append(asynchronous); @@ -209,7 +209,7 @@ public String debugDump(int indent) { sb.append(attemptNumber); sb.append("\n"); - SchemaDebugUtil.indentDebugDump(sb, indent+1); + SchemaDebugUtil.indentDebugDump(sb, indent+1); sb.append("result:"); if (result == null) { sb.append(" null\n"); diff --git a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceOperationListener.java b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceOperationListener.java index 379f56a68cc..f5958d5feec 100644 --- a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceOperationListener.java +++ b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceOperationListener.java @@ -19,18 +19,18 @@ import com.evolveum.midpoint.task.api.Task; /** - * + * * This is an additional processing of the * result. Even if no listener instance ever handled the event then the system * will function normally. This is meant for - * + * * (e.g. notify the administrator). - * + * * * The call should return without a major delay. It means that the * implementation can do calls to repository, but it should not * (synchronously) initiate a long-running process or provisioning request. - * + * * @author Radovan Semancik * */ @@ -38,30 +38,30 @@ public interface ResourceOperationListener extends ProvisioningListener { /** * Submits notification about a success of a provisioning operation. - * + * * This describes the operation that was executed on the resource and it - * was successful. The upper layers are notified to post-process the result. - * + * was successful. The upper layers are notified to post-process the result. + * * It should be called for both synchronous and asynchronous operations. * For synchronous operations it should provide the same result as is * returned from the operation. - * + * * @param parentResult the result that can be used to collect subresults of the listener execution. * It is NOT the result of the operation that succeeded. That result is inside the * operationDescription structure. */ public void notifySuccess(ResourceOperationDescription operationDescription, Task task, OperationResult parentResult); - + /** * Submits notification about a failure of provisioning operation. - * + * * This describes the operation that was executed on the resource and it * failed. The upper layers are notified to handle that failure. - * + * * This should be called for operations that were executed and failed * to execute. - * + * * This should be called only for the FINAL result. E.g. if the system will * never again try the operation. If the operation has been just tried and * there is an intermediary failure (e.g. a timeout) then this operation @@ -69,32 +69,32 @@ public interface ResourceOperationListener extends ProvisioningListener { * However, this operation should be called even for timeout-like errors * if the system stops trying and will no longer attempt to retry the operation * (e.g. if the attempt counter hits the maximum attempts limit). - * + * * It should be called for both synchronous and asynchronous operations. * For synchronous operations it should provide the same result as is * returned from the operation. - * + * * @param parentResult the result that can be used to collect subresults of the listener execution. * It is NOT the result of the operation that failed. That result is inside the * operationDescription structure. */ public void notifyFailure(ResourceOperationDescription operationDescription, Task task, OperationResult parentResult); - + /** * Submits notification about provisioning operation that is in progress. - * + * * This describes the operation that was tried to be executed on the resource * but cannot be executed immediately. This may be caused by the resource being * down (communication error), it may be caused by the mode of resource operation * (e.g. asynchronous processing) or by any similar cause. - * + * * This should be called after each attempt that the operation was tried. The number * of attempts already tried in indicated inside operationDescription structure. This * can be used e.g. to detect a first attempt to send mail to admin only once. - * + * * This should NOT be called for the final result of the operation. Methods notifySuccess * and notifyFailure should be used instead. - * + * * @param parentResult the result that can be used to collect subresults of the listener execution. * It is NOT the result of the operation that is in progress. That result is inside the * operationDescription structure. diff --git a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/SynchronizationProcessManager.java b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/SynchronizationProcessManager.java index 1d820dc139b..8dcf64a0849 100644 --- a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/SynchronizationProcessManager.java +++ b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/SynchronizationProcessManager.java @@ -16,9 +16,9 @@ package com.evolveum.midpoint.provisioning.api; /** - * + * * @author lazyman - * + * */ public interface SynchronizationProcessManager { diff --git a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/AccessChecker.java b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/AccessChecker.java index a3b0b42707b..adaaa88a052 100644 --- a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/AccessChecker.java +++ b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/AccessChecker.java @@ -51,11 +51,11 @@ */ @Component public class AccessChecker { - + public static final String OPERATION_NAME = AccessChecker.class.getName()+".accessCheck"; private static final Trace LOGGER = TraceManager.getTrace(AccessChecker.class); - public void checkAdd(ProvisioningContext ctx, PrismObject shadow, OperationResult parentResult) + public void checkAdd(ProvisioningContext ctx, PrismObject shadow, OperationResult parentResult) throws SchemaException, SecurityViolationException, ConfigurationException, ObjectNotFoundException, CommunicationException, ExpressionEvaluationException { OperationResult result = parentResult.createMinorSubresult(OPERATION_NAME); ResourceAttributeContainer attributeCont = ShadowUtil.getAttributesContainer(shadow); @@ -99,7 +99,7 @@ public void checkAdd(ProvisioningContext ctx, PrismObject shadow, Op public void checkModify(ResourceType resource, PrismObject shadow, Collection modifications, RefinedObjectClassDefinition objectClassDefinition, OperationResult parentResult) throws SecurityViolationException, SchemaException { - + OperationResult result = parentResult.createMinorSubresult(OPERATION_NAME); for (ItemDelta modification: modifications) { if (!(modification instanceof PropertyDelta)) { @@ -140,13 +140,13 @@ public void checkModify(ResourceType resource, PrismObject shadow, } } result.recordSuccess(); - + } public void filterGetAttributes(ResourceAttributeContainer attributeContainer, RefinedObjectClassDefinition objectClassDefinition, OperationResult parentResult) throws SchemaException { OperationResult result = parentResult.createMinorSubresult(OPERATION_NAME); - - + + for (ResourceAttribute attribute: attributeContainer.getAttributes()) { QName attrName = attribute.getElementName(); RefinedAttributeDefinition attrDef = objectClassDefinition.findAttributeDefinition(attrName); @@ -156,7 +156,7 @@ public void filterGetAttributes(ResourceAttributeContainer attributeContainer, R throw new SchemaException(message); } // Need to check model layer, not schema. Model means IDM logic which can be overridden in schemaHandling, - // schema layer is the original one. + // schema layer is the original one. PropertyLimitations limitations = attrDef.getLimitations(LayerType.MODEL); if (limitations == null) { continue; @@ -181,7 +181,7 @@ public void filterGetAttributes(ResourceAttributeContainer attributeContainer, R } result.recordSuccess(); } - - + + } diff --git a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ChangeNotificationDispatcherImpl.java b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ChangeNotificationDispatcherImpl.java index 23afe920d25..2d79ee8fdc1 100644 --- a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ChangeNotificationDispatcherImpl.java +++ b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ChangeNotificationDispatcherImpl.java @@ -48,14 +48,14 @@ */ @Component public class ChangeNotificationDispatcherImpl implements ChangeNotificationDispatcher { - + private boolean filterProtectedObjects = true; private List changeListeners = new ArrayList(); private List operationListeners = new ArrayList(); private List eventListeners = new ArrayList(); - + private static final Trace LOGGER = TraceManager.getTrace(ChangeNotificationDispatcherImpl.class); - + public boolean isFilterProtectedObjects() { return filterProtectedObjects; } @@ -78,7 +78,7 @@ public synchronized void registerNotificationListener(ResourceObjectChangeListen } } - + /* (non-Javadoc) * @see com.evolveum.midpoint.provisioning.api.ResourceObjectChangeNotificationManager#registerNotificationListener(com.evolveum.midpoint.provisioning.api.ResourceObjectChangeListener) */ @@ -108,10 +108,10 @@ public synchronized void registerNotificationListener(ResourceEventListener list @Override public void unregisterNotificationListener(ResourceEventListener listener) { eventListeners.remove(listener); - + } - + /* (non-Javadoc) * @see com.evolveum.midpoint.provisioning.api.ResourceObjectChangeNotificationManager#unregisterNotificationListener(com.evolveum.midpoint.provisioning.api.ResourceObjectChangeListener) */ @@ -119,7 +119,7 @@ public void unregisterNotificationListener(ResourceEventListener listener) { public synchronized void unregisterNotificationListener(ResourceOperationListener listener) { changeListeners.remove(listener); } - + /* (non-Javadoc) * @see com.evolveum.midpoint.provisioning.api.ResourceObjectChangeNotificationManager#unregisterNotificationListener(com.evolveum.midpoint.provisioning.api.ResourceObjectChangeListener) */ @@ -132,13 +132,13 @@ public synchronized void unregisterNotificationListener(ResourceObjectChangeList @Override public void notifyChange(ResourceObjectShadowChangeDescription change, Task task, OperationResult parentResult) { Validate.notNull(change, "Change description of resource object shadow must not be null."); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("SYNCHRONIZATION change notification\n{} ", change.debugDump()); } - + if (InternalsConfig.consistencyChecks) change.checkConsistence(); - + if ((null != changeListeners) && (!changeListeners.isEmpty())) { for (ResourceObjectChangeListener listener : new ArrayList<>(changeListeners)) { // sometimes there is registration/deregistration from within //LOGGER.trace("Listener: {}", listener.getClass().getSimpleName()); @@ -155,7 +155,7 @@ public void notifyChange(ResourceObjectShadowChangeDescription change, Task task LOGGER.warn("Change notification received but listener list is empty, there is nobody to get the message"); } } - + /* (non-Javadoc) * @see com.evolveum.midpoint.provisioning.api.ResourceObjectChangeListener#notifyFailure(com.evolveum.midpoint.provisioning.api.ResourceObjectShadowFailureDescription, com.evolveum.midpoint.task.api.Task, com.evolveum.midpoint.schema.result.OperationResult) */ @@ -163,13 +163,13 @@ public void notifyChange(ResourceObjectShadowChangeDescription change, Task task public void notifyFailure(ResourceOperationDescription failureDescription, Task task, OperationResult parentResult) { Validate.notNull(failureDescription, "Operation description of resource object shadow must not be null."); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Resource operation failure notification\n{} ", failureDescription.debugDump()); } - + failureDescription.checkConsistence(); - + if ((null != changeListeners) && (!changeListeners.isEmpty())) { for (ResourceOperationListener listener : new ArrayList<>(operationListeners)) { // sometimes there is registration/deregistration from within //LOGGER.trace("Listener: {}", listener.getClass().getSimpleName()); @@ -185,7 +185,7 @@ public void notifyFailure(ResourceOperationDescription failureDescription, LOGGER.debug("Operation failure received but listener list is empty, there is nobody to get the message"); } } - + /* (non-Javadoc) * @see com.evolveum.midpoint.provisioning.api.ResourceObjectChangeListener#notifyFailure(com.evolveum.midpoint.provisioning.api.ResourceObjectShadowFailureDescription, com.evolveum.midpoint.task.api.Task, com.evolveum.midpoint.schema.result.OperationResult) */ @@ -193,13 +193,13 @@ public void notifyFailure(ResourceOperationDescription failureDescription, public void notifySuccess(ResourceOperationDescription failureDescription, Task task, OperationResult parentResult) { Validate.notNull(failureDescription, "Operation description of resource object shadow must not be null."); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Resource operation success notification\n{} ", failureDescription.debugDump()); } - + failureDescription.checkConsistence(); - + if ((null != changeListeners) && (!changeListeners.isEmpty())) { for (ResourceOperationListener listener : new ArrayList<>(operationListeners)) { // sometimes there is registration/deregistration from within //LOGGER.trace("Listener: {}", listener.getClass().getSimpleName()); @@ -223,13 +223,13 @@ public void notifySuccess(ResourceOperationDescription failureDescription, public void notifyInProgress(ResourceOperationDescription failureDescription, Task task, OperationResult parentResult) { Validate.notNull(failureDescription, "Operation description of resource object shadow must not be null."); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Resource operation in-progress notification\n{} ", failureDescription.debugDump()); } - + failureDescription.checkConsistence(); - + if ((null != changeListeners) && (!changeListeners.isEmpty())) { for (ResourceOperationListener listener : new ArrayList<>(operationListeners)) { // sometimes there is registration/deregistration from within //LOGGER.trace("Listener: {}", listener.getClass().getSimpleName()); @@ -261,18 +261,18 @@ public void notifyEvent(ResourceEventDescription eventDescription, SecurityViolationException, ObjectNotFoundException, GenericConnectorException, ObjectAlreadyExistsException, ExpressionEvaluationException { Validate.notNull(eventDescription, "Event description must not be null."); - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("SYNCHRONIZATION change notification\n{} ", eventDescription.debugDump()); } - + if (filterProtectedObjects && eventDescription.isProtected()) { LOGGER.trace("Skipping dispatching of {} because it is protected", eventDescription); return; } - + // if (InternalsConfig.consistencyChecks) eventDescription.checkConsistence(); - + if ((null != eventListeners) && (!eventListeners.isEmpty())) { for (ResourceEventListener listener : new ArrayList<>(eventListeners)) { // sometimes there is registration/deregistration from within //LOGGER.trace("Listener: {}", listener.getClass().getSimpleName()); @@ -288,8 +288,8 @@ public void notifyEvent(ResourceEventDescription eventDescription, } else { LOGGER.warn("Event notification received but listener list is empty, there is nobody to get the message"); } - + } - + } diff --git a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ConfiguredConnectorCacheKey.java b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ConfiguredConnectorCacheKey.java index 7b40245e581..ae1232c6bfa 100644 --- a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ConfiguredConnectorCacheKey.java +++ b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ConfiguredConnectorCacheKey.java @@ -20,10 +20,10 @@ * */ public class ConfiguredConnectorCacheKey { - + private String resourceOid; private String connectorName; - + public ConfiguredConnectorCacheKey(String resourceOid, String connectorName) { super(); this.resourceOid = resourceOid; @@ -73,6 +73,6 @@ public boolean equals(Object obj) { public String toString() { return "ConfiguredConnectorCacheKey(" + resourceOid + ":" + connectorName + ")"; } - - + + } diff --git a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ConnectorManager.java b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ConnectorManager.java index 61450ea8ca5..6ff88f59bef 100644 --- a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ConnectorManager.java +++ b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ConnectorManager.java @@ -79,25 +79,25 @@ /** * Class that manages the ConnectorType objects in repository. - * + * * It creates new ConnectorType objects when a new local connector is * discovered, takes care of remote connector discovery, etc. - * + * * @author Radovan Semancik - * + * */ @Component public class ConnectorManager { - + private static final String USER_DATA_KEY_PARSED_CONNECTOR_SCHEMA = ConnectorManager.class.getName()+".parsedSchema"; - + @Autowired @Qualifier("cacheRepositoryService") private RepositoryService repositoryService; - + @Autowired(required = true) ApplicationContext springContext; - + @Autowired(required = true) private PrismContext prismContext; @@ -126,14 +126,14 @@ public Collection getConnectorFactories() { } return connectorFactories; } - + private ConnectorFactory determineConnectorFactory(ConnectorType connectorType) { if (connectorType == null) { return null; } return determineConnectorFactory(connectorType.getFramework()); } - + private ConnectorFactory determineConnectorFactory(String frameworkIdentifier) { for (ConnectorFactory connectorFactory: getConnectorFactories()) { if (connectorFactory.supportsFramework(frameworkIdentifier)) { @@ -142,7 +142,7 @@ private ConnectorFactory determineConnectorFactory(String frameworkIdentifier) { } return null; } - + public ConnectorInstance getConfiguredConnectorInstance(ConnectorSpec connectorSpec, boolean forceFresh, OperationResult result) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException { ConfiguredConnectorCacheKey cacheKey = connectorSpec.getCacheKey(); @@ -184,14 +184,14 @@ public ConnectorInstance getConfiguredConnectorInstance(ConnectorSpec connectorS return configuredConnectorInstance; } - + // should only be used by this class and testConnection in Resource manager void cacheConfifuredConnector(ConnectorSpec connectorSpec, ConnectorInstance connectorInstance) { ConfiguredConnectorCacheKey cacheKey = connectorSpec.getCacheKey(); if (connectorInstanceCache.containsKey(cacheKey)) { connectorInstanceCache.remove(cacheKey); } - + ConfiguredConnectorInstanceEntry cacheEntry = new ConfiguredConnectorInstanceEntry(); cacheEntry.connectorOid = connectorSpec.getConnectorOid(); cacheEntry.configuration = connectorSpec.getConnectorConfiguration(); @@ -202,16 +202,16 @@ void cacheConfifuredConnector(ConnectorSpec connectorSpec, ConnectorInstance con // should only be used by this class and testConnection in Resource manager ConnectorInstance createConnectorInstance(ConnectorSpec connectorSpec, OperationResult result) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException { - + ConnectorType connectorType = getConnectorTypeReadOnly(connectorSpec, result); - + ConnectorFactory connectorFactory = determineConnectorFactory(connectorType); - + ConnectorInstance connector = null; try { InternalMonitor.recordCount(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT); - + connector = connectorFactory.createConnectorInstance(connectorType, ResourceTypeUtil.getResourceNamespace(connectorSpec.getResource()), connectorSpec.toString()); @@ -219,7 +219,7 @@ ConnectorInstance createConnectorInstance(ConnectorSpec connectorSpec, Operation result.recordFatalError(e.getMessage(), e); throw new ObjectNotFoundException(e.getMessage(), e); } - + // This log message should be INFO level. It happens only occasionally. // If it happens often, it may be an // indication of a problem. Therefore it is good for admin to see it. @@ -227,14 +227,14 @@ ConnectorInstance createConnectorInstance(ConnectorSpec connectorSpec, Operation connectorSpec, connectorType.getConnectorType(), connectorType.getConnectorVersion()); return connector; - + } - + private ConnectorInstance createConfiguredConnectorInstance(ConnectorSpec connectorSpec, OperationResult result) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException { - + ConnectorInstance connector = createConnectorInstance(connectorSpec, result); - + PrismContainerValue connectorConfigurationVal = connectorSpec.getConnectorConfiguration() != null ? connectorSpec.getConnectorConfiguration().getValue() : null; if (connectorConfigurationVal == null) { @@ -244,12 +244,12 @@ private ConnectorInstance createConfiguredConnectorInstance(ConnectorSpec connec } try { connector.configure(connectorConfigurationVal, result); - + ResourceSchema resourceSchema = RefinedResourceSchemaImpl.getResourceSchema(connectorSpec.getResource(), prismContext); Collection capabilities = ResourceTypeUtil.getNativeCapabilitiesCollection(connectorSpec.getResource().asObjectable()); - + connector.initialize(resourceSchema, capabilities, ResourceTypeUtil.isCaseIgnoreAttributeNames(connectorSpec.getResource().asObjectable()), result); - + } catch (GenericFrameworkException e) { // Not expected. Transform to system exception result.recordFatalError("Generic provisioning framework error", e); @@ -261,7 +261,7 @@ private ConnectorInstance createConfiguredConnectorInstance(ConnectorSpec connec result.recordFatalError(e); throw e; } - + return connector; } @@ -275,7 +275,7 @@ public ConnectorType getConnectorTypeReadOnly(ConnectorSpec connectorSpec, Opera ConnectorType connectorType = connectorTypeCache.get(connOid); if (connectorType == null) { Collection> options = SelectorOptions.createCollection(GetOperationOptions.createReadOnly()); - PrismObject repoConnector = repositoryService.getObject(ConnectorType.class, connOid, + PrismObject repoConnector = repositoryService.getObject(ConnectorType.class, connOid, options, result); connectorType = repoConnector.asObjectable(); connectorTypeCache.put(connOid, connectorType); @@ -302,11 +302,11 @@ public ConnectorType getConnectorTypeReadOnly(ConnectorSpec connectorSpec, Opera if (connectorSchema == null) { throw new SchemaException("No connector schema in "+connectorType); } - connector.setUserData(USER_DATA_KEY_PARSED_CONNECTOR_SCHEMA, connectorSchema); + connector.setUserData(USER_DATA_KEY_PARSED_CONNECTOR_SCHEMA, connectorSchema); } return connectorType; } - + public PrismSchema getConnectorSchema(ConnectorType connectorType) throws SchemaException { PrismObject connector = connectorType.asPrismObject(); PrismSchema connectorSchema; @@ -317,7 +317,7 @@ public PrismSchema getConnectorSchema(ConnectorType connectorType) throws Schema if (connectorSchema == null) { throw new SchemaException("No connector schema in "+connectorType); } - connector.setUserData(USER_DATA_KEY_PARSED_CONNECTOR_SCHEMA, connectorSchema); + connector.setUserData(USER_DATA_KEY_PARSED_CONNECTOR_SCHEMA, connectorSchema); } else { if (userDataEntry instanceof PrismSchema) { connectorSchema = (PrismSchema)userDataEntry; @@ -343,11 +343,11 @@ public Set discoverLocalConnectors(OperationResult parentResult) /** * Lists local connectors and makes sure that appropriate ConnectorType * objects for them exist in repository. - * + * * It will never delete any repository object, even if the corresponding * connector cannot be found. The connector may temporarily removed, may be * present on a different node, manual upgrade may be needed etc. - * + * * @return set of discovered connectors (new connectors found) * @throws CommunicationException */ @@ -367,32 +367,32 @@ public Set discoverConnectors(ConnectorHostType hostType, Operati } Set discoveredConnectors = new HashSet(); - + for (ConnectorFactory connectorFactory: getConnectorFactories()) { - + Set foundConnectors; try { - + foundConnectors = connectorFactory.listConnectors(hostType, result); - + } catch (CommunicationException ex) { result.recordFatalError("Discovery failed: " + ex.getMessage(), ex); throw new CommunicationException("Discovery failed: " + ex.getMessage(), ex); } - + if (foundConnectors == null) { LOGGER.trace("Connector factory {} discovered null connectors, skipping", connectorFactory); continue; } - + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Got {} connectors from {}: {}", new Object[] { foundConnectors.size(), hostType, foundConnectors }); } - + for (ConnectorType foundConnector : foundConnectors) { - + LOGGER.trace("Found connector {}", foundConnector); - + boolean inRepo = true; try { inRepo = isInRepo(foundConnector, result); @@ -406,9 +406,9 @@ public Set discoverConnectors(ConnectorHostType hostType, Operati // But continue otherwise ... } if (!inRepo) { - + LOGGER.trace("Connector {} not in the repository, \"dicovering\" it", foundConnector); - + // First of all we need to "embed" connectorHost to the // connectorType. The UCF does not // have access to repository, therefore it cannot resolve it for @@ -416,18 +416,18 @@ public Set discoverConnectors(ConnectorHostType hostType, Operati if (hostType != null && foundConnector.getConnectorHost() == null) { foundConnector.setConnectorHost(hostType); } - + if (foundConnector.getSchema() == null) { LOGGER.warn("Connector {} haven't provided configuration schema", foundConnector); } - + // Sanitize framework-supplied OID if (StringUtils.isNotEmpty(foundConnector.getOid())) { LOGGER.warn("Provisioning framework " + foundConnector.getFramework() + " supplied OID for connector " + ObjectTypeUtil.toShortString(foundConnector)); foundConnector.setOid(null); } - + // Store the connector object String oid; try { @@ -469,7 +469,7 @@ private boolean isInRepo(ConnectorType connectorType, OperationResult result) th if (LOGGER.isTraceEnabled()) { LOGGER.trace("Looking for connector in repository:\n{}", query.debugDump()); } - + List> foundConnectors; try { foundConnectors = repositoryService.searchObjects(ConnectorType.class, query, null, result); @@ -564,7 +564,7 @@ public void shutdown() { connectorFactory.shutdown(); } } - + @FunctionalInterface private interface ConnectorFactoryConsumer { void process(ConnectorFactory connectorFactory) throws CommunicationException; diff --git a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ConnectorSpec.java b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ConnectorSpec.java index 9ddd54ffa06..d3d45f839e7 100644 --- a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ConnectorSpec.java +++ b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ConnectorSpec.java @@ -25,12 +25,12 @@ * */ public class ConnectorSpec { - + private PrismObject resource; private String connectorName; private String connectorOid; private PrismContainer connectorConfiguration; - + public ConnectorSpec(PrismObject resource, String connectorName, String connectorOid, PrismContainer connectorConfiguration) { super(); @@ -59,7 +59,7 @@ public PrismContainer getConnectorConfiguration() { public ConfiguredConnectorCacheKey getCacheKey() { return new ConfiguredConnectorCacheKey(resource.getOid(), connectorName); } - + @Override public String toString() { return "ConnectorSpec(" + resource + ", name=" + connectorName + ", oid=" diff --git a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ConstraintsChecker.java b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ConstraintsChecker.java index c89b449a363..06659ed7083 100644 --- a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ConstraintsChecker.java +++ b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ConstraintsChecker.java @@ -155,7 +155,7 @@ public ConstraintsCheckingResult check(Task task, OperationResult result) throws constraintsCheckingResult.setMessages(messageBuilder.toString()); return constraintsCheckingResult; } - + private boolean checkAttributeUniqueness(PrismProperty identifier, RefinedObjectClassDefinition accountDefinition, ResourceType resourceType, String oid, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { diff --git a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/EntitlementConverter.java b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/EntitlementConverter.java index 4a08d07f9ed..d3e100eceaf 100644 --- a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/EntitlementConverter.java +++ b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/EntitlementConverter.java @@ -75,30 +75,30 @@ /** * Class that collects the entitlement-related methods used by ResourceObjectConverter - * + * * Should NOT be used by any class other than ResourceObjectConverter. - * + * * @author Radovan Semancik * */ @Component class EntitlementConverter { - + private static final Trace LOGGER = TraceManager.getTrace(EntitlementConverter.class); - + @Autowired(required=true) private ResourceObjectReferenceResolver resourceObjectReferenceResolver; - + @Autowired(required=true) private PrismContext prismContext; - + @Autowired(required = true) private MatchingRuleRegistry matchingRuleRegistry; ////////// // GET ///////// - + public void postProcessEntitlementsRead(ProvisioningContext subjectCtx, PrismObject resourceObject, OperationResult parentResult) throws SchemaException, CommunicationException, ObjectNotFoundException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { ResourceType resourceType = subjectCtx.getResource(); @@ -107,10 +107,10 @@ public void postProcessEntitlementsRead(ProvisioningContext subjectCtx, Collection entitlementAssociationDefs = objectClassDefinition.getAssociationDefinitions(); if (entitlementAssociationDefs != null) { ResourceAttributeContainer attributesContainer = ShadowUtil.getAttributesContainer(resourceObject); - + PrismContainerDefinition associationDef = resourceObject.getDefinition().findContainerDefinition(ShadowType.F_ASSOCIATION); PrismContainer associationContainer = associationDef.instantiate(); - + for (RefinedAssociationDefinition assocDefType: entitlementAssociationDefs) { ShadowKindType entitlementKind = assocDefType.getKind(); if (entitlementKind == null) { @@ -125,11 +125,11 @@ public void postProcessEntitlementsRead(ProvisioningContext subjectCtx, } ResourceObjectAssociationDirectionType direction = assocDefType.getResourceObjectAssociationType().getDirection(); if (direction == ResourceObjectAssociationDirectionType.SUBJECT_TO_OBJECT) { - postProcessEntitlementSubjectToEntitlement(resourceType, resourceObject, objectClassDefinition, assocDefType, entitlementDef, attributesContainer, associationContainer, parentResult); + postProcessEntitlementSubjectToEntitlement(resourceType, resourceObject, objectClassDefinition, assocDefType, entitlementDef, attributesContainer, associationContainer, parentResult); } else if (direction == ResourceObjectAssociationDirectionType.OBJECT_TO_SUBJECT) { if (assocDefType.getResourceObjectAssociationType().getShortcutAssociationAttribute() != null) { - postProcessEntitlementSubjectToEntitlement(resourceType, resourceObject, objectClassDefinition, - assocDefType, entitlementDef, attributesContainer, associationContainer, + postProcessEntitlementSubjectToEntitlement(resourceType, resourceObject, objectClassDefinition, + assocDefType, entitlementDef, attributesContainer, associationContainer, assocDefType.getResourceObjectAssociationType().getShortcutAssociationAttribute(), assocDefType.getResourceObjectAssociationType().getShortcutValueAttribute(), parentResult); } else { @@ -140,27 +140,27 @@ public void postProcessEntitlementsRead(ProvisioningContext subjectCtx, } } } - + if (!associationContainer.isEmpty()) { resourceObject.add(associationContainer); } } } - - private void postProcessEntitlementSubjectToEntitlement(ResourceType resourceType, PrismObject resourceObject, + + private void postProcessEntitlementSubjectToEntitlement(ResourceType resourceType, PrismObject resourceObject, RefinedObjectClassDefinition objectClassDefinition, RefinedAssociationDefinition assocDefType, RefinedObjectClassDefinition entitlementDef, ResourceAttributeContainer attributesContainer, PrismContainer associationContainer, OperationResult parentResult) throws SchemaException { QName assocAttrName = assocDefType.getResourceObjectAssociationType().getAssociationAttribute(); QName valueAttrName = assocDefType.getResourceObjectAssociationType().getValueAttribute(); - postProcessEntitlementSubjectToEntitlement(resourceType, resourceObject, objectClassDefinition, - assocDefType, entitlementDef, attributesContainer, associationContainer, assocAttrName, + postProcessEntitlementSubjectToEntitlement(resourceType, resourceObject, objectClassDefinition, + assocDefType, entitlementDef, attributesContainer, associationContainer, assocAttrName, valueAttrName, parentResult); } - - private void postProcessEntitlementSubjectToEntitlement(ResourceType resourceType, - PrismObject resourceObject, + + private void postProcessEntitlementSubjectToEntitlement(ResourceType resourceType, + PrismObject resourceObject, RefinedObjectClassDefinition objectClassDefinition, RefinedAssociationDefinition assocDefType, RefinedObjectClassDefinition entitlementDef, ResourceAttributeContainer attributesContainer, PrismContainer associationContainer, @@ -188,7 +188,7 @@ private void postProcessEntitlementSubjectToEntitlement if (valueAttrName == null) { throw new SchemaException("No value attribute defined in entitlement association '"+associationName+"' in "+resourceType); } - + RefinedAttributeDefinition valueAttrDef = entitlementDef.findAttributeDefinition(valueAttrName); for (PrismPropertyValue assocAttrPVal : assocAttr.getValues()) { @@ -205,8 +205,8 @@ private void postProcessEntitlementSubjectToEntitlement LOGGER.trace("Assocciation attribute value resolved to valueAtrribute {} and identifiers container {}", valueAttribute, identifiersContainer); } } - - private void postProcessEntitlementEntitlementToSubject(ProvisioningContext subjectCtx, final PrismObject resourceObject, + + private void postProcessEntitlementEntitlementToSubject(ProvisioningContext subjectCtx, final PrismObject resourceObject, RefinedAssociationDefinition assocDefType, final ProvisioningContext entitlementCtx, ResourceAttributeContainer attributesContainer, final PrismContainer associationContainer, OperationResult parentResult) throws SchemaException, CommunicationException, ObjectNotFoundException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { @@ -216,19 +216,19 @@ private void postProcessEntitlementEntitlementToSubject if (associationName == null) { throw new SchemaException("No name in entitlement association "+assocDefType+" in "+resourceType); } - + QName associationAuxiliaryObjectClass = assocDefType.getAuxiliaryObjectClass(); - if (associationAuxiliaryObjectClass != null && associationAuxiliaryObjectClass.getNamespaceURI() != null && + if (associationAuxiliaryObjectClass != null && associationAuxiliaryObjectClass.getNamespaceURI() != null && !associationAuxiliaryObjectClass.getNamespaceURI().equals(ResourceTypeUtil.getResourceNamespace(resourceType))) { - LOGGER.warn("Auxiliary object class {} in association {} does not have namespace that matches {}", + LOGGER.warn("Auxiliary object class {} in association {} does not have namespace that matches {}", associationAuxiliaryObjectClass, assocDefType.getName(), resourceType); } if (associationAuxiliaryObjectClass != null && !subjectCtx.getObjectClassDefinition().hasAuxiliaryObjectClass(associationAuxiliaryObjectClass)) { - LOGGER.trace("Ignoring association {} because subject does not have auxiliary object class {}, it has {}", + LOGGER.trace("Ignoring association {} because subject does not have auxiliary object class {}, it has {}", associationName, associationAuxiliaryObjectClass, subjectCtx.getObjectClassDefinition().getAuxiliaryObjectClassDefinitions()); return; } - + QName assocAttrName = assocDefType.getResourceObjectAssociationType().getAssociationAttribute(); if (assocAttrName == null) { throw new SchemaException("No association attribute defined in entitlement association '"+associationName+"' in "+resourceType); @@ -237,7 +237,7 @@ private void postProcessEntitlementEntitlementToSubject if (assocAttrDef == null) { throw new SchemaException("Association attribute '"+assocAttrName+"'defined in entitlement association '"+associationName+"' was not found in schema for "+resourceType); } - + QName valueAttrName = assocDefType.getResourceObjectAssociationType().getValueAttribute(); if (valueAttrName == null) { throw new SchemaException("No value attribute defined in entitlement association '"+associationName+"' in "+resourceType); @@ -250,23 +250,23 @@ private void postProcessEntitlementEntitlementToSubject if (valueAttr.size() > 1) { throw new SchemaException("Value attribute "+valueAttrName+" has no more than one value; attribute defined in entitlement association '"+associationName+"' in "+resourceType); } - + ObjectQuery query = createQuery(assocDefType, assocAttrDef, valueAttr); - + AttributesToReturn attributesToReturn = ProvisioningUtil.createAttributesToReturn(entitlementCtx); - + SearchHierarchyConstraints searchHierarchyConstraints = null; ResourceObjectReferenceType baseContextRef = entitlementDef.getBaseContext(); if (baseContextRef != null) { // TODO: this should be done once per search. Not in every run of postProcessEntitlementEntitlementToSubject // this has to go outside of this method - PrismObject baseContextShadow = resourceObjectReferenceResolver.resolve(subjectCtx, baseContextRef, + PrismObject baseContextShadow = resourceObjectReferenceResolver.resolve(subjectCtx, baseContextRef, null, "base context specification in "+entitlementDef, parentResult); RefinedObjectClassDefinition baseContextObjectClassDefinition = subjectCtx.getRefinedSchema().determineCompositeObjectClassDefinition(baseContextShadow); ResourceObjectIdentification baseContextIdentification = ShadowUtil.getResourceObjectIdentification(baseContextShadow, baseContextObjectClassDefinition); searchHierarchyConstraints = new SearchHierarchyConstraints(baseContextIdentification, null); } - + ShadowResultHandler handler = new ShadowResultHandler() { @Override public boolean handle(PrismObject entitlementShadow) { @@ -278,8 +278,8 @@ public boolean handle(PrismObject entitlementShadow) { ShadowAssociationType.F_IDENTIFIERS, entitlementDef.toResourceAttributeContainerDefinition(), prismContext); associationCVal.add(identifiersContainer); identifiersContainer.getValue().addAll(ResourceAttribute.cloneCollection(entitlementIdentifiers)); - - // Remember the full shadow in user data. This is used later as an optimization to create the shadow in repo + + // Remember the full shadow in user data. This is used later as an optimization to create the shadow in repo identifiersContainer.setUserData(ResourceObjectConverter.FULL_SHADOW_KEY, entitlementShadow); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Processed entitlement-to-subject association for account {} and entitlement {}", @@ -291,7 +291,7 @@ public boolean handle(PrismObject entitlementShadow) { return true; } }; - + ConnectorInstance connector = subjectCtx.getConnector(ReadCapabilityType.class, parentResult); try { if (LOGGER.isTraceEnabled()) { @@ -307,7 +307,7 @@ public boolean handle(PrismObject entitlementShadow) { } catch (TunnelException e) { throw (SchemaException)e.getCause(); } - + } // precondition: valueAttr has exactly one value @@ -324,11 +324,11 @@ private ObjectQuery createQuery(RefinedAssociationDefinition assocDefTyp query.setAllowPartialResults(true); return query; } - + ////////// // ADD ///////// - + public void processEntitlementsAdd(ProvisioningContext ctx, PrismObject shadow) throws SchemaException, ConfigurationException, ObjectNotFoundException, CommunicationException, ExpressionEvaluationException { PrismContainer associationContainer = shadow.findContainer(ShadowType.F_ASSOCIATION); if (associationContainer == null || associationContainer.isEmpty()) { @@ -340,44 +340,44 @@ public void processEntitlementsAdd(ProvisioningContext ctx, PrismObject PrismObject collectEntitlementsAsObjectOperationInShadowAdd(ProvisioningContext ctx, Map roMap, - PrismObject shadow, OperationResult result) + PrismObject shadow, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, SecurityViolationException, ConfigurationException, ExpressionEvaluationException { PrismContainer associationContainer = shadow.findContainer(ShadowType.F_ASSOCIATION); if (associationContainer == null || associationContainer.isEmpty()) { return shadow; } - return collectEntitlementsAsObjectOperation(ctx, roMap, associationContainer.getValues(), null, shadow, + return collectEntitlementsAsObjectOperation(ctx, roMap, associationContainer.getValues(), null, shadow, ModificationType.ADD, result); } - + ////////// // MODIFY ///////// - + /** * Collects entitlement changes from the shadow to entitlement section into attribute operations. * NOTE: only collects SUBJECT_TO_ENTITLEMENT entitlement direction. */ - public void collectEntitlementChange(ProvisioningContext ctx, ContainerDelta itemDelta, + public void collectEntitlementChange(ProvisioningContext ctx, ContainerDelta itemDelta, Collection operations) throws SchemaException, ConfigurationException, ObjectNotFoundException, CommunicationException, ExpressionEvaluationException { Map operationsMap = new HashMap(); - + collectEntitlementToAttrsDelta(ctx, operationsMap, itemDelta.getValuesToAdd(), ModificationType.ADD); collectEntitlementToAttrsDelta(ctx, operationsMap, itemDelta.getValuesToDelete(), ModificationType.DELETE); collectEntitlementToAttrsDelta(ctx, operationsMap, itemDelta.getValuesToReplace(), ModificationType.REPLACE); operations.addAll(operationsMap.values()); } - + public PrismObject collectEntitlementsAsObjectOperation(ProvisioningContext ctx, Map roMap, ContainerDelta containerDelta, - PrismObject subjectShadowBefore, PrismObject subjectShadowAfter, + PrismObject subjectShadowBefore, PrismObject subjectShadowAfter, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, SecurityViolationException, ConfigurationException, ExpressionEvaluationException { - subjectShadowAfter = collectEntitlementsAsObjectOperation(ctx, roMap, containerDelta.getValuesToAdd(), + subjectShadowAfter = collectEntitlementsAsObjectOperation(ctx, roMap, containerDelta.getValuesToAdd(), subjectShadowBefore, subjectShadowAfter, ModificationType.ADD, result); subjectShadowAfter = collectEntitlementsAsObjectOperation(ctx, roMap, containerDelta.getValuesToDelete(), subjectShadowBefore, subjectShadowAfter, ModificationType.DELETE, result); @@ -385,18 +385,18 @@ public PrismObject collectEntitlementsAsObjectOperation(Provisio subjectShadowBefore, subjectShadowAfter, ModificationType.REPLACE, result); return subjectShadowAfter; } - + ///////// // DELETE ///////// - + /** * This is somehow different that all the other methods. We are not following the content of a shadow or delta. We are following * the definitions. This is to avoid the need to read the object that is going to be deleted. In fact, the object should not be there - * any more, but we still want to clean up entitlement membership based on the information from the shadow. + * any more, but we still want to clean up entitlement membership based on the information from the shadow. */ public void collectEntitlementsAsObjectOperationDelete(ProvisioningContext subjectCtx, final Map roMap, - PrismObject subjectShadow, OperationResult parentResult) + PrismObject subjectShadow, OperationResult parentResult) throws SchemaException, CommunicationException, ObjectNotFoundException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { Collection entitlementAssociationDefs = subjectCtx.getObjectClassDefinition().getAssociationDefinitions(); @@ -417,7 +417,7 @@ public void collectEntitlementsAsObjectOperationDelete(ProvisioningContext s LOGGER.trace("Ignoring association in deleted shadow because it does not require explicit referential integrity assurance"); continue; } - if (assocDefType.getAuxiliaryObjectClass() != null && + if (assocDefType.getAuxiliaryObjectClass() != null && !subjectCtx.getObjectClassDefinition().hasAuxiliaryObjectClass(assocDefType.getAuxiliaryObjectClass())) { LOGGER.trace("Ignoring association in deleted shadow because subject does not have {} auxiliary object class", assocDefType.getAuxiliaryObjectClass()); continue; @@ -436,7 +436,7 @@ public void collectEntitlementsAsObjectOperationDelete(ProvisioningContext s if (entitlementOcDef == null) { throw new SchemaException("No definition for entitlement intent(s) '"+assocDefType.getIntents()+"' defined in entitlement association "+associationName+" in "+subjectCtx.getResource()); } - + final QName assocAttrName = assocDefType.getResourceObjectAssociationType().getAssociationAttribute(); if (assocAttrName == null) { throw new SchemaException("No association attribute defined in entitlement association '"+associationName+"' in "+subjectCtx.getResource()); @@ -445,7 +445,7 @@ public void collectEntitlementsAsObjectOperationDelete(ProvisioningContext s if (assocAttrDef == null) { throw new SchemaException("Association attribute '"+assocAttrName+"'defined in entitlement association '"+associationName+"' was not found in schema for "+subjectCtx.getResource()); } - + QName valueAttrName = assocDefType.getResourceObjectAssociationType().getValueAttribute(); if (valueAttrName == null) { throw new SchemaException("No value attribute defined in entitlement association '"+associationName+"' in "+subjectCtx.getResource()); @@ -460,21 +460,21 @@ public void collectEntitlementsAsObjectOperationDelete(ProvisioningContext s if (valueAttr.size() > 1) { throw new SchemaException("Value attribute "+valueAttrName+" has no more than one value; attribute defined in entitlement association '"+associationName+"' in "+subjectCtx.getResource()); } - + ObjectQuery query = createQuery(assocDefType, assocAttrDef, valueAttr); - + AttributesToReturn attributesToReturn = ProvisioningUtil.createAttributesToReturn(entitlementCtx); - + SearchHierarchyConstraints searchHierarchyConstraints = null; ResourceObjectReferenceType baseContextRef = entitlementOcDef.getBaseContext(); if (baseContextRef != null) { - PrismObject baseContextShadow = resourceObjectReferenceResolver.resolve(subjectCtx, + PrismObject baseContextShadow = resourceObjectReferenceResolver.resolve(subjectCtx, baseContextRef, null, "base context specification in "+entitlementOcDef, parentResult); RefinedObjectClassDefinition baseContextObjectClassDefinition = subjectCtx.getRefinedSchema().determineCompositeObjectClassDefinition(baseContextShadow); ResourceObjectIdentification baseContextIdentification = ShadowUtil.getResourceObjectIdentification(baseContextShadow, baseContextObjectClassDefinition); searchHierarchyConstraints = new SearchHierarchyConstraints(baseContextIdentification, null); } - + ShadowResultHandler handler = new ShadowResultHandler() { @Override public boolean handle(PrismObject entitlementShadow) { @@ -488,7 +488,7 @@ public boolean handle(PrismObject entitlementShadow) { Collection> allIdentifiers = ShadowUtil.getAllIdentifiers(entitlementShadow); operations.setAllIdentifiers(allIdentifiers); } - + PropertyDelta attributeDelta = null; for(Operation operation: operations.getOperations()) { if (operation instanceof PropertyModificationOperation) { @@ -504,12 +504,12 @@ public boolean handle(PrismObject entitlementShadow) { attributeModification.setMatchingRuleQName(assocDefType.getMatchingRule()); operations.add(attributeModification); } - + attributeDelta.addValuesToDelete(valueAttr.getClonedValues()); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Association in deleted shadow delta:\n{}", attributeDelta.debugDump()); } - + return true; } }; @@ -523,15 +523,15 @@ public boolean handle(PrismObject entitlementShadow) { throw new GenericConnectorException(e.getMessage(), e); } } - + } - + } - + ///////// // common ///////// - + private void collectEntitlementToAttrsDelta(ProvisioningContext subjectCtx, Map operationMap, Collection> set, ModificationType modificationType) throws SchemaException, ConfigurationException, ObjectNotFoundException, CommunicationException, ExpressionEvaluationException { if (set == null) { @@ -541,7 +541,7 @@ private void collectEntitlementToAttrsDelta(ProvisioningContext subjectCtx, collectEntitlementToAttrDelta(subjectCtx, operationMap, associationCVal, modificationType); } } - + /** * Collects entitlement changes from the shadow to entitlement section into attribute operations. * Collects a single value. @@ -550,7 +550,7 @@ private void collectEntitlementToAttrsDelta(ProvisioningContext subjectCtx, private void collectEntitlementToAttrDelta(ProvisioningContext ctx, Map operationMap, PrismContainerValue associationCVal, ModificationType modificationType) throws SchemaException, ConfigurationException, ObjectNotFoundException, CommunicationException, ExpressionEvaluationException { RefinedObjectClassDefinition objectClassDefinition = ctx.getObjectClassDefinition(); - + ShadowAssociationType associationType = associationCVal.asContainerable(); QName associationName = associationType.getName(); if (associationName == null) { @@ -560,14 +560,14 @@ private void collectEntitlementToAttrDelta(ProvisioningContext ctx, Map void collectEntitlementToAttrDelta(ProvisioningContext ctx, Map valueAttr = identifiersContainer.findProperty(valueAttrName); if (valueAttr == null) { throw new SchemaException("No value attribute "+valueAttrName+" present in entitlement association '"+associationName+"' in shadow for "+ctx.getResource()); } - + if (modificationType == ModificationType.ADD) { attributeOperation.getPropertyDelta().addValuesToAdd(valueAttr.getClonedValues()); } else if (modificationType == ModificationType.DELETE) { @@ -603,10 +603,10 @@ private void collectEntitlementToAttrDelta(ProvisioningContext ctx, Map PrismObject collectEntitlementsAsObjectOperation(ProvisioningContext ctx, Map PrismObject collectEntitlementsAsObjectOperation(ProvisioningContext ctx, Map roMap, Collection> set, - PrismObject subjectShadowBefore, PrismObject subjectShadowAfter, + PrismObject subjectShadowBefore, PrismObject subjectShadowAfter, ModificationType modificationType, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, SecurityViolationException, ConfigurationException, ExpressionEvaluationException { if (set == null) { @@ -618,10 +618,10 @@ private PrismObject collectEntitlementsAsObjectOperation(Provisi } return subjectShadowAfter; } - - private PrismObject collectEntitlementAsObjectOperation(ProvisioningContext subjectCtx, Map PrismObject collectEntitlementAsObjectOperation(ProvisioningContext subjectCtx, Map roMap, PrismContainerValue associationCVal, - PrismObject subjectShadowBefore, PrismObject subjectShadowAfter, + PrismObject subjectShadowBefore, PrismObject subjectShadowAfter, ModificationType modificationType, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, SecurityViolationException, ConfigurationException, ExpressionEvaluationException { ResourceType resource = subjectCtx.getResource(); @@ -634,13 +634,13 @@ private PrismObject collectEntitlementAsObjectOperation(Prov if (assocDefType == null) { throw new SchemaException("No entitlement association with name "+assocDefType+" in schema of "+resource); } - + ResourceObjectAssociationDirectionType direction = assocDefType.getResourceObjectAssociationType().getDirection(); if (direction != ResourceObjectAssociationDirectionType.OBJECT_TO_SUBJECT) { // Process just this one direction. The other direction was processed before return subjectShadowAfter; } - + Collection entitlementIntents = assocDefType.getIntents(); if (entitlementIntents == null || entitlementIntents.isEmpty()) { throw new SchemaException("No entitlement intent specified in association "+associationCVal+" in "+resource); @@ -655,21 +655,21 @@ private PrismObject collectEntitlementAsObjectOperation(Prov if (entitlementOcDef == null) { throw new SchemaException("No definition of entitlement intent(s) '"+entitlementIntents+"' specified in association "+associationCVal+" in "+resource); } - + QName assocAttrName = assocDefType.getResourceObjectAssociationType().getAssociationAttribute(); if (assocAttrName == null) { throw new SchemaException("No association attribute defined in entitlement association in "+resource); } - + RefinedAttributeDefinition assocAttrDef = entitlementOcDef.findAttributeDefinition(assocAttrName); if (assocAttrDef == null) { throw new SchemaException("Association attribute '"+assocAttrName+"'defined in entitlement association was not found in entitlement intent(s) '"+entitlementIntents+"' in schema for "+resource); } - - ResourceAttributeContainer identifiersContainer = + + ResourceAttributeContainer identifiersContainer = ShadowUtil.getAttributesContainer(associationCVal, ShadowAssociationType.F_IDENTIFIERS); Collection> entitlementIdentifiersFromAssociation = identifiersContainer.getAttributes(); - + ResourceObjectDiscriminator disc = new ResourceObjectDiscriminator(entitlementOcDef.getTypeName(), entitlementIdentifiersFromAssociation); ResourceObjectOperations operations = roMap.get(disc); if (operations == null) { @@ -677,12 +677,12 @@ private PrismObject collectEntitlementAsObjectOperation(Prov operations.setResourceObjectContext(entitlementCtx); roMap.put(disc, operations); } - + QName valueAttrName = assocDefType.getResourceObjectAssociationType().getValueAttribute(); if (valueAttrName == null) { throw new SchemaException("No value attribute defined in entitlement association in "+resource); } - + // Which shadow would we use - shadowBefore or shadowAfter? // // If the operation is ADD or REPLACE, we use current version of the shadow (shadowAfter), because we want @@ -705,7 +705,7 @@ private PrismObject collectEntitlementAsObjectOperation(Prov subjectShadow = subjectShadowAfter; } } - + ResourceAttribute valueAttr = ShadowUtil.getAttribute(subjectShadow, valueAttrName); if (valueAttr == null) { if (!ShadowUtil.isFullShadow(subjectShadow)) { @@ -721,7 +721,7 @@ private PrismObject collectEntitlementAsObjectOperation(Prov throw new SchemaException("No value attribute "+valueAttrName+" in " + subjectShadow); } } - + PropertyDelta attributeDelta = null; for(Operation operation: operations.getOperations()) { if (operation instanceof PropertyModificationOperation) { @@ -734,9 +734,9 @@ private PrismObject collectEntitlementAsObjectOperation(Prov if (attributeDelta == null) { attributeDelta = assocAttrDef.createEmptyDelta(new ItemPath(ShadowType.F_ATTRIBUTES, assocAttrName)); } - + PrismProperty changedAssocAttr = PrismUtil.convertProperty(valueAttr, assocAttrDef); - + if (modificationType == ModificationType.ADD) { attributeDelta.addValuesToAdd(changedAssocAttr.getClonedValues()); } else if (modificationType == ModificationType.DELETE) { @@ -745,7 +745,7 @@ private PrismObject collectEntitlementAsObjectOperation(Prov // TODO: check if already exists attributeDelta.setValuesToReplace(changedAssocAttr.getClonedValues()); } - + if (ResourceTypeUtil.isAvoidDuplicateValues(resource)) { PrismObject currentObjectShadow = operations.getCurrentShadow(); if (currentObjectShadow == null) { @@ -762,17 +762,17 @@ private PrismObject collectEntitlementAsObjectOperation(Prov } attributeDelta = attributeDeltaAfterNarrow; } - + if (attributeDelta != null && !attributeDelta.isEmpty()) { PropertyModificationOperation attributeModification = new PropertyModificationOperation(attributeDelta); attributeModification.setMatchingRuleQName(assocDefType.getMatchingRule()); LOGGER.trace("Collecting entitlement object operations ({}) association {}: {}", modificationType, associationName.getLocalPart(), attributeModification); operations.add(attributeModification); } - + } return subjectShadowAfter; } - + } diff --git a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ProvisioningContext.java b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ProvisioningContext.java index f14cad3e52e..ca442e411c1 100644 --- a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ProvisioningContext.java +++ b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ProvisioningContext.java @@ -51,34 +51,34 @@ public class ProvisioningContext extends StateReporter { private static final Trace LOGGER = TraceManager.getTrace(ProvisioningContext.class); - + private ResourceManager resourceManager; private OperationResult parentResult; private Collection> getOperationOptions; - + private PrismObject originalShadow; private ResourceShadowDiscriminator shadowCoordinates; private Collection additionalAuxiliaryObjectClassQNames; private boolean useRefinedDefinition = true; - + private RefinedObjectClassDefinition objectClassDefinition; private ResourceType resource; private Map,ConnectorInstance> connectorMap; private RefinedResourceSchema refinedSchema; - + public ProvisioningContext(ResourceManager resourceManager, OperationResult parentResult) { this.resourceManager = resourceManager; this.parentResult = parentResult; } - + public void setResourceOid(String resourceOid) { super.setResourceOid(resourceOid); this.resource = null; this.connectorMap = null; this.refinedSchema = null; } - + public Collection> getGetOperationOptions() { return getOperationOptions; } @@ -90,7 +90,7 @@ public void setGetOperationOptions(Collection getOriginalShadow() { public void setOriginalShadow(PrismObject originalShadow) { this.originalShadow = originalShadow; } - + public Collection getAdditionalAuxiliaryObjectClassQNames() { return additionalAuxiliaryObjectClassQNames; } @@ -151,7 +151,7 @@ public RefinedResourceSchema getRefinedSchema() throws SchemaException, Configur } return refinedSchema; } - + public RefinedObjectClassDefinition getObjectClassDefinition() throws SchemaException, ConfigurationException, ObjectNotFoundException, CommunicationException, ExpressionEvaluationException { if (objectClassDefinition == null) { if (useRefinedDefinition) { @@ -202,7 +202,7 @@ public RefinedObjectClassDefinition computeCompositeObjectClassDefinition(PrismO public String getChannel() { return getTask()==null?null:getTask().getChannel(); } - + public ConnectorInstance getConnector(Class operationCapabilityClass, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException { if (connectorMap == null) { connectorMap = new HashMap<>(); @@ -214,11 +214,11 @@ public ConnectorInstance getConnector(Class operat } return connector; } - + public boolean isWildcard() { return (shadowCoordinates == null && originalShadow == null) || (shadowCoordinates != null && shadowCoordinates.isWildcard()); } - + /** * Creates a context for a different object class on the same resource. */ @@ -227,7 +227,7 @@ public ProvisioningContext spawn(ShadowKindType kind, String intent) { ctx.shadowCoordinates = new ResourceShadowDiscriminator(getResourceOid(), kind, intent); return ctx; } - + /** * Creates a context for a different object class on the same resource. */ @@ -237,7 +237,7 @@ public ProvisioningContext spawn(QName objectClassQName) throws SchemaException ctx.shadowCoordinates.setObjectClass(objectClassQName); return ctx; } - + /** * Creates a context for a different object class on the same resource. */ @@ -246,7 +246,7 @@ public ProvisioningContext spawn(PrismObject shadow) throws SchemaEx ctx.setOriginalShadow(shadow); return ctx; } - + // /** // * Creates a context for a different object class on the same resource. // */ @@ -255,7 +255,7 @@ public ProvisioningContext spawn(PrismObject shadow) throws SchemaEx // ctx.setObjectClassDefinition(objectClassDefinition); // return ctx; // } - + private ProvisioningContext spawnSameResource() { ProvisioningContext ctx = new ProvisioningContext(resourceManager, parentResult); ctx.setTask(this.getTask()); @@ -272,11 +272,11 @@ public void assertDefinition(String message) throws SchemaException, Configurati throw new SchemaException(message + " " + getDesc()); } } - + public void assertDefinition() throws SchemaException, ConfigurationException, ObjectNotFoundException, CommunicationException, ExpressionEvaluationException { assertDefinition("Cannot locate object class definition"); } - + public String getDesc() { if (originalShadow != null) { return "for " + originalShadow + " in " + (resource==null?("resource "+getResourceOid()):resource); @@ -306,11 +306,11 @@ private ConnectorInstance getConnectorInstance(Class< throw e; } } - + public CapabilitiesType getConnectorCapabilities(Class operationCapabilityClass) { return resourceManager.getConnectorCapabilities(resource.asPrismObject(), operationCapabilityClass); } - + @Override public String toString() { return "ProvisioningContext("+getDesc()+")"; diff --git a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ProvisioningContextFactory.java b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ProvisioningContextFactory.java index e9d902e5f9f..df7afcc0045 100644 --- a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ProvisioningContextFactory.java +++ b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ProvisioningContextFactory.java @@ -42,7 +42,7 @@ public class ProvisioningContextFactory { @Autowired(required = true) private ResourceManager resourceManager; - + public ProvisioningContext create(PrismObject shadow, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException { ProvisioningContext ctx = new ProvisioningContext(resourceManager, parentResult); ctx.setTask(task); @@ -51,7 +51,7 @@ public ProvisioningContext create(PrismObject shadow, Task task, Ope ctx.setResourceOid(resourceOid); return ctx; } - + public ProvisioningContext create(PrismObject shadow, Collection additionalAuxiliaryObjectClassQNames, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException { ProvisioningContext ctx = new ProvisioningContext(resourceManager, parentResult); ctx.setTask(task); @@ -61,7 +61,7 @@ public ProvisioningContext create(PrismObject shadow, Collection resourceObjectShadowDefinition; - + + private PrismObjectDefinition resourceObjectShadowDefinition; + private static final Trace LOGGER = TraceManager.getTrace(ProvisioningServiceImpl.class); private static final String DETAILS_CONNECTOR_FRAMEWORK_VERSION = "ConnId framework version"; // TODO generalize @@ -130,7 +130,7 @@ public ShadowCache getShadowCache(ShadowCacheFactory.Mode mode){ /** * Get the value of repositoryService. - * + * * @return the value of repositoryService */ public RepositoryService getCacheRepositoryService() { @@ -139,9 +139,9 @@ public RepositoryService getCacheRepositoryService() { /** * Set the value of repositoryService - * + * * Expected to be injected. - * + * * @param repositoryService * new value of repositoryService */ @@ -164,12 +164,12 @@ public PrismObject getObject(Class type, String oid result.addParam(OperationResult.PARAM_TYPE, type); result.addArbitraryObjectCollectionAsParam("options", options); result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class); - + GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options); PrismObject resultingObject = null; if (ResourceType.class.isAssignableFrom(type)) { - + if (GetOperationOptions.isRaw(rootOptions)) { try { resultingObject = (PrismObject) cacheRepositoryService.getObject(ResourceType.class, oid, @@ -223,22 +223,22 @@ public PrismObject getObject(Class type, String oid throw ex; } } - + } else { // Not resource - + PrismObject repositoryObject = getRepoObject(type, oid, rootOptions, result); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Retrieved repository object:\n{}", repositoryObject.debugDump()); } - + if (repositoryObject.canRepresent(ShadowType.class)) { - + try { - + resultingObject = (PrismObject) getShadowCache(Mode.STANDARD).getShadow(oid, (PrismObject) (repositoryObject), options, task, result); - + } catch (ObjectNotFoundException e) { if (!GetOperationOptions.isAllowNotFound(rootOptions)){ ProvisioningUtil.recordFatalError(LOGGER, result, "Error getting object OID=" + oid + ": " + e.getMessage(), e); @@ -267,20 +267,20 @@ public PrismObject getObject(Class type, String oid ProvisioningUtil.recordFatalError(LOGGER, result, "Error getting object OID=" + oid + ": " + e.getMessage(), e); throw new SystemException(e); } - - + + } else { resultingObject = repositoryObject; } } - + result.computeStatus(); if (!GetOperationOptions.isRaw(rootOptions)) { resultingObject = resultingObject.cloneIfImmutable(); resultingObject.asObjectable().setFetchResult(result.createOperationResultType()); } result.cleanupResult(); - + return resultingObject; } @@ -289,10 +289,10 @@ public PrismObject getObject(Class type, String oid public String addObject(PrismObject object, OperationProvisioningScriptsType scripts, ProvisioningOperationOptions options, Task task, OperationResult parentResult) throws ObjectAlreadyExistsException, SchemaException, CommunicationException, ObjectNotFoundException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { - + Validate.notNull(object, "Object to add must not be null."); Validate.notNull(parentResult, "Operation result must not be null."); - + if (InternalsConfig.encryptionChecks) { CryptoUtil.checkEncrypted(object); } @@ -453,10 +453,10 @@ private PrismProperty getTokenProperty(ResourceShadowDiscriminator shadowCoordin } return tokenProperty; } - + @Override public SearchResultList> searchObjects(Class type, ObjectQuery query, - Collection> options, Task task, OperationResult parentResult) + Collection> options, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { @@ -466,7 +466,7 @@ public SearchResultList> searchObjects(Cla result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class); final SearchResultList> objListType = new SearchResultList<>(new ArrayList>()); - + SearchResultMetadata metadata; try { if (!ShadowType.class.isAssignableFrom(type)) { @@ -477,16 +477,16 @@ public SearchResultList> searchObjects(Cla // validateObjects(objects); return objects; } - + final ResultHandler handler = (object, parentResult1) -> objListType.add(object); - + metadata = searchObjectsIterative(type, query, options, handler, task, result); - + } catch (ConfigurationException | SecurityViolationException | CommunicationException | ObjectNotFoundException | SchemaException | ExpressionEvaluationException | RuntimeException | Error e) { ProvisioningUtil.recordFatalError(LOGGER, result, "Could not search objects: " + e.getMessage(), e); throw e; } - + result.computeStatus(); result.cleanupResult(); // validateObjects(objListType); @@ -496,7 +496,7 @@ public SearchResultList> searchObjects(Cla @SuppressWarnings("unchecked") - private SearchResultList> searchRepoObjects(Class type, ObjectQuery query, + private SearchResultList> searchRepoObjects(Class type, ObjectQuery query, Collection> options, Task task, OperationResult result) throws SchemaException { List> repoObjects = null; @@ -549,21 +549,21 @@ private SearchResultList> searchRepoObject repoObject.asObjectable().setFetchResult(objResult.createOperationResultType()); newObjListType.add(repoObject); result.addSubresult(objResult); - result.recordPartialError(e); + result.recordPartialError(e); } } return newObjListType; } - + // TODO: move to ResourceManager and ConnectorManager // the shadow-related code is already in the ShadowCache - private PrismObject completeObject(Class type, PrismObject inObject, + private PrismObject completeObject(Class type, PrismObject inObject, Collection> options, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException { if (ResourceType.class.equals(type)) { - PrismObject completeResource = resourceManager.getResource((PrismObject) inObject, + PrismObject completeResource = resourceManager.getResource((PrismObject) inObject, SelectorOptions.findRootOptions(options), task, result); return (PrismObject) completeResource; } else if (ShadowType.class.equals(type)) { @@ -571,7 +571,7 @@ private PrismObject completeObject(Class type, Pris throw new IllegalStateException("BOOOM!"); } else { //TODO: connectors etc.. - + } return inObject; @@ -592,7 +592,7 @@ public Integer countObjects(Class type, ObjectQuery qu query = query.cloneEmpty(); query.setFilter(filter); } - + if (filter != null && filter instanceof NoneFilter) { result.recordSuccessIfUnknown(); result.cleanupResult(); @@ -612,18 +612,18 @@ public Integer countObjects(Class type, ObjectQuery qu Integer count; try { - + count = getShadowCache(Mode.STANDARD).countObjects(query, task, result); - + result.computeStatus(); - + } catch (ConfigurationException | CommunicationException | ObjectNotFoundException | SchemaException | ExpressionEvaluationException | RuntimeException | Error e) { ProvisioningUtil.recordFatalError(LOGGER, result, null, e); throw e; } finally { result.cleanupResult(); } - + return count; } @@ -637,11 +637,11 @@ public String modifyObject(Class type, String oid, Validate.notNull(oid, "OID must not be null."); Validate.notNull(modifications, "Modifications must not be null."); Validate.notNull(parentResult, "Operation result must not be null."); - + if (InternalsConfig.encryptionChecks) { CryptoUtil.checkEncrypted(modifications); } - + if (InternalsConfig.consistencyChecks) { ItemDelta.checkConsistence(modifications); } @@ -665,15 +665,18 @@ public String modifyObject(Class type, String oid, } try { - + if (ShadowType.class.isAssignableFrom(type)) { // calling shadow cache to modify object - oid = getShadowCache(Mode.STANDARD).modifyShadow((PrismObject)repoShadow, oid, modifications, scripts, options, task, + oid = getShadowCache(Mode.STANDARD).modifyShadow((PrismObject)repoShadow, oid, modifications, scripts, options, task, result); } else { cacheRepositoryService.modifyObject(type, oid, modifications, result); } - result.computeStatus(); + if (!result.isInProgress()) { + // This is the case when there is already a conflicting pending operation. + result.computeStatus(); + } } catch (CommunicationException e) { ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't modify object: communication problem: " + e.getMessage(), e); @@ -733,9 +736,9 @@ public void deleteObject(Class type, String oid, Provi if (object.canRepresent(ShadowType.class) && !ProvisioningOperationOptions.isRaw(options)) { try { - + getShadowCache(Mode.STANDARD).deleteShadow((PrismObject)object, options, scripts, task, result); - + } catch (CommunicationException e) { ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't delete object: communication problem: " + e.getMessage(), e); throw new CommunicationException(e.getMessage(), e); @@ -761,9 +764,9 @@ public void deleteObject(Class type, String oid, Provi } } else if (object.canRepresent(ResourceType.class)) { - + resourceManager.deleteResource(oid, options, task, result); - + } else { try { @@ -785,7 +788,7 @@ public void deleteObject(Class type, String oid, Provi } result.cleanupResult(); } - + /* (non-Javadoc) * @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) */ @@ -800,19 +803,19 @@ public void executeScript(String resourceOid, Provisionin result.addParam("oid", resourceOid); result.addArbitraryObjectAsParam("script", script); result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class); - + try { - + resourceManager.executeScript(resourceOid, script, task, result); - + } catch (CommunicationException | SchemaException | ConfigurationException | SecurityViolationException | ExpressionEvaluationException | RuntimeException | Error e) { ProvisioningUtil.recordFatalError(LOGGER, result, null, e); throw e; } - + result.computeStatus(); result.cleanupResult(); - + } @@ -832,7 +835,7 @@ public OperationResult testResource(String resourceOid, Task task) throws Object testResult.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class); PrismObject resource = null; - + try { resource = getRepoObject(ResourceType.class, resourceOid, null, testResult); resourceManager.testConnection(resource, task, testResult); @@ -867,9 +870,9 @@ public List> listResourceObjects(String resour if (objectClass == null) { throw new IllegalArgumentException("Objectclass not defined in a search query"); } - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(resourceOid, objectClass, prismContext); - + final List> objectList = new ArrayList>(); final ResultHandler shadowHandler = new ResultHandler() { @Override @@ -884,9 +887,9 @@ public boolean handle(PrismObject shadow, OperationResult objResult) }; try { - + getShadowCache(Mode.STANDARD).searchObjectsIterative(query, null, shadowHandler, false, task, result); - + } catch (SchemaException | ObjectNotFoundException | CommunicationException | ConfigurationException | SecurityViolationException | ExpressionEvaluationException | RuntimeException | Error ex) { result.recordFatalError(ex.getMessage(), ex); @@ -896,44 +899,44 @@ public boolean handle(PrismObject shadow, OperationResult objResult) result.cleanupResult(); return objectList; } - + @Override public void refreshShadow(PrismObject shadow, ProvisioningOperationOptions options, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, SecurityViolationException, ExpressionEvaluationException { Validate.notNull(shadow, "Shadow for refresh must not be null."); OperationResult result = parentResult.createSubresult(ProvisioningServiceImpl.class.getName() +".finishOperation"); - + LOGGER.debug("Refreshing shadow {}", shadow); - + try { - + getShadowCache(Mode.RECON).refreshShadow(shadow, task, result); - + refreshShadowLegacy(shadow, options, task, result); - + } catch (GenericFrameworkException e) { ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't refresh shadow: " + e.getClass().getSimpleName() + ": "+ e.getMessage(), e); throw new CommunicationException(e.getMessage(), e); - - } catch (CommunicationException | SchemaException | ObjectNotFoundException | ConfigurationException + + } catch (CommunicationException | SchemaException | ObjectNotFoundException | ConfigurationException | SecurityViolationException | ObjectAlreadyExistsException | ExpressionEvaluationException | RuntimeException | Error e) { ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't refresh shadow: " + e.getClass().getSimpleName() + ": "+ e.getMessage(), e); throw e; } - + result.computeStatus(); result.cleanupResult(); - + LOGGER.debug("Finished refreshing shadow {}: ", shadow, result); } - + private void refreshShadowLegacy(PrismObject shadow, ProvisioningOperationOptions options, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, SecurityViolationException, GenericFrameworkException, ExpressionEvaluationException { - + ShadowType shadowType = shadow.asObjectable(); - + if (shadowType.getFailedOperationType() == null) { return; } else if (FailedOperationTypeType.ADD == shadowType.getFailedOperationType()) { @@ -945,20 +948,20 @@ private void refreshShadowLegacy(PrismObject shadow, ProvisioningOp } else { result.recordWarning("Missing or unknown type of operation to finish: " + shadowType.getFailedOperationType()); } - + } - + // TODO: move to ResourceManager and ConnectorManager // the shadow-related code is already in the ShadowCache private boolean handleRepoObject(final Class type, PrismObject object, final Collection> options, final ResultHandler handler, Task task, final OperationResult objResult) { - + PrismObject completeObject; try { - + completeObject = completeObject(type, object, options, task, objResult); - + } catch (SchemaException | ObjectNotFoundException | CommunicationException | ConfigurationException | ExpressionEvaluationException e) { LOGGER.error("Error while completing {}: {}. Using non-complete object.", new Object[] { object, e.getMessage(), e }); @@ -966,15 +969,15 @@ private boolean handleRepoObject(final Class type, Pri object.asObjectable().setFetchResult(objResult.createOperationResultType()); completeObject = object; } - + objResult.computeStatus(); objResult.recordSuccessIfUnknown(); - + if (!objResult.isSuccess()) { OperationResultType resultType = objResult.createOperationResultType(); completeObject.asObjectable().setFetchResult(resultType); } - + return handler.handle(completeObject, objResult); } @@ -1008,12 +1011,12 @@ public SearchResultMetadata searchObjectsIterative(final query = query.cloneEmpty(); query.setFilter(filter); } - + if (InternalsConfig.consistencyChecks && filter != null) { // We may not have all the definitions here. We will apply the definitions later filter.checkConsistence(false); } - + if (filter != null && filter instanceof NoneFilter) { result.recordSuccessIfUnknown(); result.cleanupResult(); @@ -1022,53 +1025,53 @@ public SearchResultMetadata searchObjectsIterative(final metadata.setApproxNumberOfAllResults(0); return metadata; } - + final GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options); - + if (ShadowType.class.isAssignableFrom(type)) { - + SearchResultMetadata metadata; try { - + metadata = getShadowCache(Mode.STANDARD).searchObjectsIterative(query, options, (ResultHandler)handler, true, task, result); - + result.computeStatus(); - + } catch (ConfigurationException | CommunicationException | ObjectNotFoundException | SchemaException | ExpressionEvaluationException | RuntimeException | Error e) { ProvisioningUtil.recordFatalError(LOGGER, result, null, e); throw e; } finally { result.cleanupResult(); } - + return metadata; - + } else { - + ResultHandler internalHandler = (object, objResult) -> handleRepoObject(type, object, options, handler, task, objResult); - + Collection> repoOptions = null; if (GetOperationOptions.isReadOnly(rootOptions)) { repoOptions = SelectorOptions.createCollection(GetOperationOptions.createReadOnly()); } - + SearchResultMetadata metadata = null; try { - + metadata = getCacheRepositoryService().searchObjectsIterative(type, query, internalHandler, repoOptions, false, result); // TODO think about strictSequential flag - + result.computeStatus(); result.recordSuccessIfUnknown(); } catch (SchemaException | RuntimeException | Error e) { ProvisioningUtil.recordFatalError(LOGGER, result, null, e); } - + result.cleanupResult(); - + return metadata; - } - + } + } @Override @@ -1091,9 +1094,9 @@ public Set discoverConnectors(ConnectorHostType hostType, Operati result.cleanupResult(); return discoverConnectors; } - + @Override - public List getConnectorOperationalStatus(String resourceOid, Task task, OperationResult parentResult) + public List getConnectorOperationalStatus(String resourceOid, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException { OperationResult result = parentResult.createMinorSubresult(ProvisioningService.class.getName() + ".getConnectorOperationalStatus"); @@ -1102,14 +1105,14 @@ public List getConnectorOperationalStatus(String res PrismObject resource; try { - + resource = resourceManager.getResource(resourceOid, null, task, result); } catch (SchemaException | ObjectNotFoundException | ExpressionEvaluationException ex) { ProvisioningUtil.recordFatalError(LOGGER, result, ex.getMessage(), ex); throw ex; } - + List stats; try { stats = resourceManager.getConnectorOperationalStatus(resource, result); @@ -1127,7 +1130,7 @@ public List getConnectorOperationalStatus(String res @Override public void applyDefinition(ObjectDelta delta, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException { - + applyDefinition(delta, null, task, parentResult); } @@ -1135,13 +1138,13 @@ public void applyDefinition(ObjectDelta delta, Task ta @Override public void applyDefinition(ObjectDelta delta, Objectable object, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException { - + OperationResult result = parentResult.createMinorSubresult(ProvisioningService.class.getName() + ".applyDefinition"); result.addParam("delta", delta); result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class); - + try { - + if (ShadowType.class.isAssignableFrom(delta.getObjectTypeClass())){ getShadowCache(Mode.STANDARD).applyDefinition((ObjectDelta) delta, (ShadowType) object, result); } else if (ResourceType.class.isAssignableFrom(delta.getObjectTypeClass())){ @@ -1149,38 +1152,38 @@ public void applyDefinition(ObjectDelta delta, Objecta } else { throw new IllegalArgumentException("Could not apply definition to deltas for object type: " + delta.getObjectTypeClass()); } - + result.recordSuccessIfUnknown(); result.cleanupResult(); - + } catch (ObjectNotFoundException | CommunicationException | ConfigurationException | SchemaException | ExpressionEvaluationException | RuntimeException | Error e) { ProvisioningUtil.recordFatalError(LOGGER, result, null, e); throw e; - } + } } @Override @SuppressWarnings("unchecked") public void applyDefinition(PrismObject object, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException { - + OperationResult result = parentResult.createMinorSubresult(ProvisioningService.class.getName() + ".applyDefinition"); result.addParam(OperationResult.PARAM_OBJECT, object); result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class); - + try { - - if (ShadowType.class.isAssignableFrom(object.getCompileTimeClass())){ + + if (ShadowType.class.isAssignableFrom(object.getCompileTimeClass())){ getShadowCache(Mode.STANDARD).applyDefinition((PrismObject) object, result); } else if (ResourceType.class.isAssignableFrom(object.getCompileTimeClass())){ resourceManager.applyDefinition((PrismObject) object, task, result); } else { throw new IllegalArgumentException("Could not apply definition to object type: " + object.getCompileTimeClass()); } - + result.computeStatus(); result.recordSuccessIfUnknown(); - + } catch (ObjectNotFoundException | CommunicationException | ConfigurationException | SchemaException | ExpressionEvaluationException | RuntimeException | Error e) { ProvisioningUtil.recordFatalError(LOGGER, result, null, e); throw e; @@ -1188,8 +1191,8 @@ public void applyDefinition(PrismObject object, Task t result.cleanupResult(); } } - - private void setProtectedShadow(PrismObject shdaow, OperationResult result) + + private void setProtectedShadow(PrismObject shdaow, OperationResult result) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException { getShadowCache(Mode.STANDARD).setProtectedShadow(shdaow, result); } @@ -1197,29 +1200,29 @@ private void setProtectedShadow(PrismObject shdaow, OperationResult @Override public void applyDefinition(Class type, ObjectQuery query, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException { - + OperationResult result = parentResult.createMinorSubresult(ProvisioningService.class.getName() + ".applyDefinition"); result.addParam(OperationResult.PARAM_TYPE, type); result.addParam(OperationResult.PARAM_QUERY, query); result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class); - + try { - + if (ObjectQueryUtil.hasAllDefinitions(query)) { return; } - - if (ShadowType.class.isAssignableFrom(type)){ + + if (ShadowType.class.isAssignableFrom(type)){ getShadowCache(Mode.STANDARD).applyDefinition(query, result); } else if (ResourceType.class.isAssignableFrom(type)){ resourceManager.applyDefinition(query, result); } else { throw new IllegalArgumentException("Could not apply definition to query for object type: " + type); } - + result.computeStatus(); result.recordSuccessIfUnknown(); - + } catch (ObjectNotFoundException | CommunicationException | ConfigurationException | SchemaException | ExpressionEvaluationException | RuntimeException | Error e) { ProvisioningUtil.recordFatalError(LOGGER, result, null, e); throw e; @@ -1227,7 +1230,7 @@ public void applyDefinition(Class type, ObjectQuery qu result.cleanupResult(); } } - + @Override public void provisioningSelfTest(OperationResult parentTestResult, Task task) { CryptoUtil.securitySelfTest(parentTestResult); @@ -1267,7 +1270,7 @@ public void postInit(OperationResult parentResult) { result.computeStatus("Provisioning post-initialization failed"); result.cleanupResult(); } - + @PreDestroy public void shutdown() { connectorManager.shutdown(); @@ -1280,7 +1283,7 @@ public ConstraintsCheckingResult checkConstraints(RefinedObjectClassDefinition s String shadowOid, ResourceShadowDiscriminator resourceShadowDiscriminator, ConstraintViolationConfirmer constraintViolationConfirmer, - Task task, OperationResult parentResult) + Task task, OperationResult parentResult) throws CommunicationException, ObjectAlreadyExistsException, SchemaException, SecurityViolationException, ConfigurationException, ObjectNotFoundException, ExpressionEvaluationException { OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName() + ".checkConstraints"); ConstraintsChecker checker = new ConstraintsChecker(); @@ -1322,9 +1325,9 @@ private PrismObjectDefinition getResourceObjectShadowDefinition() { } return resourceObjectShadowDefinition; } - + private PrismObject getRepoObject(Class type, String oid, GetOperationOptions options, OperationResult result) throws ObjectNotFoundException, SchemaException{ - + try { return getCacheRepositoryService().getObject(type, oid, null, result); } catch (ObjectNotFoundException e) { @@ -1338,7 +1341,7 @@ private PrismObject getRepoObject(Class type, Strin } catch (SchemaException ex) { ProvisioningUtil.recordFatalError(LOGGER, result, "Can't get object with oid " + oid + ". Reason " + ex.getMessage(), ex); throw ex; - } + } } - + } diff --git a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceCache.java b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceCache.java index 944a33df49e..0217211b759 100644 --- a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceCache.java +++ b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceCache.java @@ -29,7 +29,7 @@ /** * Class for caching ResourceType instances with a parsed schemas. - * + * * @author Radovan Semancik * */ @@ -41,18 +41,18 @@ public class ResourceCache { ResourceCache() { cache = new HashMap<>(); } - + public synchronized void put(PrismObject resource) throws SchemaException { String oid = resource.getOid(); if (oid == null) { throw new SchemaException("Attempt to cache "+resource+" without an OID"); } - + String version = resource.getVersion(); if (version == null) { throw new SchemaException("Attempt to cache "+resource+" without version"); } - + PrismObject cachedResource = cache.get(oid); if (cachedResource == null) { cache.put(oid, resource.createImmutableClone()); @@ -78,12 +78,12 @@ private boolean compareVersion(String version1, String version2) { public synchronized PrismObject get(PrismObject resource, GetOperationOptions options) throws SchemaException { return get(resource.getOid(), resource.getVersion(), options); } - + public synchronized PrismObject get(String oid, String version, GetOperationOptions options) throws SchemaException { if (oid == null) { return null; } - + PrismObject cachedResource = cache.get(oid); if (cachedResource == null) { return null; @@ -92,7 +92,7 @@ public synchronized PrismObject get(String oid, String version, Ge if (!compareVersion(version, cachedResource.getVersion())) { return null; } - + if (GetOperationOptions.isReadOnly(options)) { cachedResource.checkImmutability(); return cachedResource; @@ -100,9 +100,9 @@ public synchronized PrismObject get(String oid, String version, Ge return cachedResource.clone(); } } - + /** - * Returns currently cached version. FOR DIAGNOSTICS ONLY. + * Returns currently cached version. FOR DIAGNOSTICS ONLY. */ public synchronized String getVersion(String oid) { if (oid == null) { diff --git a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceEventListenerImpl.java b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceEventListenerImpl.java index 1d26bffa8d5..4b7883efdbc 100644 --- a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceEventListenerImpl.java +++ b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceEventListenerImpl.java @@ -52,18 +52,18 @@ @Component public class ResourceEventListenerImpl implements ResourceEventListener { - + private static final Trace LOGGER = TraceManager.getTrace(ResourceEventListenerImpl.class); - + @Autowired(required = true) private ShadowCacheFactory shadowCacheFactory; - + @Autowired(required = true) private ProvisioningContextFactory provisioningContextFactory; - + @Autowired private ChangeNotificationDispatcher notificationManager; - + @PostConstruct public void registerForResourceObjectChangeNotifications() { notificationManager.registerNotificationListener(this); @@ -73,13 +73,13 @@ public void registerForResourceObjectChangeNotifications() { public void unregisterForResourceObjectChangeNotifications() { notificationManager.unregisterNotificationListener(this); } - + private ShadowCache getShadowCache(ShadowCacheFactory.Mode mode){ return shadowCacheFactory.getShadowCache(mode); } - - - + + + @Override public String getName() { // TODO Auto-generated method stub @@ -88,42 +88,42 @@ public String getName() { @Override public void notifyEvent(ResourceEventDescription eventDescription, Task task, OperationResult parentResult) throws SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ObjectNotFoundException, GenericConnectorException, ObjectAlreadyExistsException, ExpressionEvaluationException { - + Validate.notNull(eventDescription, "Event description must not be null."); Validate.notNull(task, "Task must not be null."); Validate.notNull(parentResult, "Operation result must not be null"); - + LOGGER.trace("Received event notification with the description: {}", eventDescription.debugDump()); - + if (eventDescription.getCurrentShadow() == null && eventDescription.getDelta() == null){ throw new IllegalStateException("Neither current shadow, nor delta specified. It is required to have at least one of them specified."); } - + applyDefinitions(eventDescription, parentResult); - + PrismObject shadow = null; shadow = eventDescription.getShadow(); ShadowCache shadowCache = getShadowCache(Mode.STANDARD); - + ProvisioningContext ctx = provisioningContextFactory.create(shadow, task, parentResult); ctx.assertDefinition(); - + Collection> identifiers = ShadowUtil.getPrimaryIdentifiers(shadow); - + Change change = new Change(identifiers, eventDescription.getCurrentShadow(), eventDescription.getOldShadow(), eventDescription.getDelta()); ObjectClassComplexTypeDefinition objectClassDefinition = ShadowUtil.getObjectClassDefinition(shadow); change.setObjectClassDefinition(objectClassDefinition); - + ShadowType shadowType = shadow.asObjectable(); - + LOGGER.trace("Start to precess change: {}", change.toString()); shadowCache.processChange(ctx, change, null, parentResult); - + LOGGER.trace("Change after processing {} . Start synchronizing.", change.toString()); shadowCache.processSynchronization(ctx, change, parentResult); - + } private void applyDefinitions(ResourceEventDescription eventDescription, @@ -132,11 +132,11 @@ private void applyDefinitions(ResourceEventDescription eventDescription, if (eventDescription.getCurrentShadow() != null){ shadowCache.applyDefinition(eventDescription.getCurrentShadow(), parentResult); } - + if (eventDescription.getOldShadow() != null){ shadowCache.applyDefinition(eventDescription.getOldShadow(), parentResult); } - + if (eventDescription.getDelta() != null){ shadowCache.applyDefinition(eventDescription.getDelta(), null, parentResult); } diff --git a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceObjectDiscriminator.java b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceObjectDiscriminator.java index bfc28820bb2..77c7522f682 100644 --- a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceObjectDiscriminator.java +++ b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceObjectDiscriminator.java @@ -30,16 +30,16 @@ * */ public class ResourceObjectDiscriminator { - + private QName objectClass; private Collection> primaryIdentifiers; - + public ResourceObjectDiscriminator(QName objectClass, Collection> primaryIdentifiers) { super(); this.objectClass = objectClass; this.primaryIdentifiers = primaryIdentifiers; } - + public QName getObjectClass() { return objectClass; } @@ -47,7 +47,7 @@ public QName getObjectClass() { public Collection> getPrimaryIdentifiers() { return primaryIdentifiers; } - + public boolean matches(PrismObject shadow) { ShadowType shadowType = shadow.asObjectable(); if (!objectClass.equals(shadowType.getObjectClass())) { diff --git a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceObjectOperations.java b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceObjectOperations.java index e8c84f7560f..6ddd445bbec 100644 --- a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceObjectOperations.java +++ b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceObjectOperations.java @@ -30,22 +30,22 @@ * */ public class ResourceObjectOperations { - + private static final Trace LOGGER = TraceManager.getTrace(ResourceObjectOperations.class); - + private Collection operations = new ArrayList<>(); private PrismObject currentShadow = null; private ProvisioningContext resourceObjectContext = null; private Collection> allIdentifiers; - + public PrismObject getCurrentShadow() { return currentShadow; } - + public void setCurrentShadow(PrismObject currentShadow) { this.currentShadow = currentShadow; } - + public ProvisioningContext getResourceObjectContext() { return resourceObjectContext; } @@ -57,7 +57,7 @@ public void setResourceObjectContext(ProvisioningContext resourceObjectContext) public Collection getOperations() { return operations; } - + public void add(Operation operation) { if (!operations.contains(operation)) { operations.add(operation); @@ -78,6 +78,6 @@ public String toString() { + ", ctx=" + resourceObjectContext + ")"; } - + } diff --git a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceObjectReferenceResolver.java b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceObjectReferenceResolver.java index d683181ad1a..5b2f25819ec 100644 --- a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceObjectReferenceResolver.java +++ b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ResourceObjectReferenceResolver.java @@ -72,33 +72,33 @@ */ @Component public class ResourceObjectReferenceResolver { - + private static final Trace LOGGER = TraceManager.getTrace(ResourceObjectReferenceResolver.class); - + @Autowired(required = true) private PrismContext prismContext; @Autowired(required = true) @Qualifier("cacheRepositoryService") private RepositoryService repositoryService; - + @Autowired(required = true) @Qualifier("shadowCacheProvisioner") private ShadowCache shadowCache; - + @Autowired(required = true) private ShadowManager shadowManager; - - PrismObject resolve(ProvisioningContext ctx, ResourceObjectReferenceType resourceObjectReference, - QName objectClass, final String desc, OperationResult result) - throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, + + PrismObject resolve(ProvisioningContext ctx, ResourceObjectReferenceType resourceObjectReference, + QName objectClass, final String desc, OperationResult result) + throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { if (resourceObjectReference == null) { return null; } ObjectReferenceType shadowRef = resourceObjectReference.getShadowRef(); if (shadowRef != null && shadowRef.getOid() != null) { - if (resourceObjectReference.getResolutionFrequency() == null + if (resourceObjectReference.getResolutionFrequency() == null || resourceObjectReference.getResolutionFrequency() == ResourceObjectReferenceResolutionFrequencyType.ONCE) { PrismObject shadow = repositoryService.getObject(ShadowType.class, shadowRef.getOid(), null, result); return shadow; @@ -116,16 +116,16 @@ PrismObject resolve(ProvisioningContext ctx, ResourceObjectReference // Use "raw" definitions from the original schema to avoid endless loops subctx.setUseRefinedDefinition(false); subctx.assertDefinition(); - + ObjectQuery refQuery = QueryJaxbConvertor.createObjectQuery(ShadowType.class, resourceObjectReference.getFilter(), prismContext); ObjectFilter baseFilter = ObjectQueryUtil.createResourceAndObjectClassFilter(ctx.getResource().getOid(), objectClass, prismContext); ObjectFilter filter = AndFilter.createAnd(baseFilter, refQuery.getFilter()); ObjectQuery query = ObjectQuery.createObjectQuery(filter); - + // TODO: implement "repo" search strategies - + Collection> options = null; - + final Holder> shadowHolder = new Holder<>(); ResultHandler handler = new ResultHandler() { @Override @@ -137,20 +137,20 @@ public boolean handle(PrismObject shadow, OperationResult objResult) return true; } }; - + shadowCache.searchObjectsIterative(subctx, query, options, handler, true, result); - + // TODO: implement storage of OID (ONCE search frequency) - + return shadowHolder.getValue(); } - + /** - * Resolve primary identifier from a collection of identifiers that may contain only secondary identifiers. + * Resolve primary identifier from a collection of identifiers that may contain only secondary identifiers. */ Collection> resolvePrimaryIdentifier(ProvisioningContext ctx, - Collection> identifiers, final String desc, OperationResult result) - throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, + Collection> identifiers, final String desc, OperationResult result) + throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { if (identifiers == null) { return null; @@ -169,7 +169,7 @@ Collection> resolvePrimaryIdentifier(Provisioning for (PrismProperty property: attributesContainer.getValue().getProperties()) { if (ocDef.isPrimaryIdentifier(property.getElementName())) { RefinedAttributeDefinition attrDef = ocDef.findAttributeDefinition(property.getElementName()); - ResourceAttribute primaryIdentifier = new ResourceAttribute<>(property.getElementName(), + ResourceAttribute primaryIdentifier = new ResourceAttribute<>(property.getElementName(), attrDef, prismContext); primaryIdentifier.setRealValue(property.getRealValue()); primaryIdentifiers.add(primaryIdentifier); @@ -178,13 +178,13 @@ Collection> resolvePrimaryIdentifier(Provisioning LOGGER.trace("Resolved identifiers {} to primary identifiers {} (object class {})", identifiers, primaryIdentifiers, ocDef); return primaryIdentifiers; } - + /** - * Resolve primary identifier from a collection of identifiers that may contain only secondary identifiers. + * Resolve primary identifier from a collection of identifiers that may contain only secondary identifiers. */ private ResourceObjectIdentification resolvePrimaryIdentifiers(ProvisioningContext ctx, - ResourceObjectIdentification identification, OperationResult result) - throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, + ResourceObjectIdentification identification, OperationResult result) + throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { if (identification == null) { return identification; @@ -207,33 +207,33 @@ private ResourceObjectIdentification resolvePrimaryIdentifiers(ProvisioningConte for (PrismProperty property: attributesContainer.getValue().getProperties()) { if (ocDef.isPrimaryIdentifier(property.getElementName())) { RefinedAttributeDefinition attrDef = ocDef.findAttributeDefinition(property.getElementName()); - ResourceAttribute primaryIdentifier = new ResourceAttribute<>(property.getElementName(), + ResourceAttribute primaryIdentifier = new ResourceAttribute<>(property.getElementName(), attrDef, prismContext); primaryIdentifier.setRealValue(property.getRealValue()); primaryIdentifiers.add(primaryIdentifier); } } LOGGER.trace("Resolved {} to primary identifiers {} (object class {})", identification, primaryIdentifiers, ocDef); - return new ResourceObjectIdentification(identification.getObjectClassDefinition(), primaryIdentifiers, + return new ResourceObjectIdentification(identification.getObjectClassDefinition(), primaryIdentifiers, identification.getSecondaryIdentifiers()); } - - + + public PrismObject fetchResourceObject(ProvisioningContext ctx, - Collection> identifiers, + Collection> identifiers, AttributesToReturn attributesToReturn, OperationResult parentResult) throws ObjectNotFoundException, CommunicationException, SchemaException, SecurityViolationException, ConfigurationException, ExpressionEvaluationException { ResourceType resource = ctx.getResource(); ConnectorInstance connector = ctx.getConnector(ReadCapabilityType.class, parentResult); RefinedObjectClassDefinition objectClassDefinition = ctx.getObjectClassDefinition(); - + try { - + if (!ResourceTypeUtil.isReadCapabilityEnabled(resource)){ throw new UnsupportedOperationException("Resource does not support 'read' operation"); } - + ResourceObjectIdentification identification = ResourceObjectIdentification.create(objectClassDefinition, identifiers); identification = resolvePrimaryIdentifiers(ctx, identification, parentResult); identification.validatePrimaryIdenfiers(); diff --git a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ShadowCache.java b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ShadowCache.java index d0a9410aec2..d9668a5d074 100644 --- a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ShadowCache.java +++ b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ShadowCache.java @@ -717,6 +717,12 @@ public String modifyShadow(PrismObject repoShadow, String oid, ProvisioningContext ctx = ctxFactory.create(repoShadow, additionalAuxiliaryObjectClassQNames, task, parentResult); + + PendingOperationType duplicateOperation = shadowManager.checkAndRecordPendingModifyOperationBeforeExecution(ctx, repoShadow, modifications, task, parentResult); + if (duplicateOperation != null) { + parentResult.recordInProgress(); + return repoShadow.getOid(); + } AsynchronousOperationReturnValue>> asyncReturnValue; try { @@ -1027,7 +1033,7 @@ private boolean expirePendingOperations(ProvisioningContext ctx, PrismObject r private void addPendingOperationModify(ProvisioningContext ctx, PrismObject shadow, Collection pendingModifications, OperationResult resourceOperationResult, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { - ObjectDelta pendingDelta = shadow.createModifyDelta(); - for (ItemDelta pendingModification: pendingModifications) { - pendingDelta.addModification(pendingModification.clone()); - } - + ObjectDelta pendingDelta = createModifyDelta(shadow, pendingModifications); addPendingOperationDelta(ctx, shadow, pendingDelta, OperationResultStatusType.IN_PROGRESS, resourceOperationResult, parentResult); } // returns conflicting operation (pending delta) if there is any public PendingOperationType checkAndRecordPendingDeleteOperationBeforeExecution(ProvisioningContext ctx, PrismObject shadow, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + + ObjectDelta proposedDelta = shadow.createDeleteDelta(); + return checkAndRecordPendingOperationBeforeExecution(ctx, shadow, proposedDelta, task, parentResult); + } + + private void recordPendingDeleteOperationAfterExecution(ProvisioningContext ctx, PrismObject oldRepoShadow, + OperationResult resourceOperationResult, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + + if (ResourceTypeUtil.getRecordPendingOperations(ctx.getResource()) == RecordPendingOperationsType.ALL) { + // We have to look for pending delta for this operation that may already exist. In that case update it + // instead creating a new one. + // We have to re-read the shadow from repository here. We need valid container IDs. + // Also there is some chance that the pending delta might have been created by a different thread. + PrismObject currentShadow = rereadShadow(oldRepoShadow, parentResult); + ObjectDelta proposedDelta = oldRepoShadow.createDeleteDelta(); + PendingOperationType existingPendingOperation = findExistingPendingOperation(currentShadow, proposedDelta, false); + if (existingPendingOperation != null) { + LOGGER.trace("Found existing pending operation for delete of {}, updating", currentShadow); + updatePendingOperationStatus(ctx, currentShadow, existingPendingOperation, OperationResultStatusType.IN_PROGRESS, resourceOperationResult, parentResult); + return; + } + } + + ObjectDelta pendingDelta = oldRepoShadow.createDeleteDelta(); + + addPendingOperationDelta(ctx, oldRepoShadow, pendingDelta, OperationResultStatusType.IN_PROGRESS, resourceOperationResult, parentResult); + } + + private PendingOperationType findExistingPendingOperation(PrismObject currentShadow, ObjectDelta proposedDelta, boolean processInProgress) throws SchemaException { + for (PendingOperationType pendingOperation: currentShadow.asObjectable().getPendingOperation()) { + OperationResultStatusType resultStatus = pendingOperation.getResultStatus(); + if (!isInProgressOrRequested(resultStatus, processInProgress)) { + continue; + } + ObjectDeltaType deltaType = pendingOperation.getDelta(); + if (deltaType == null) { + continue; + } + ObjectDelta delta = DeltaConvertor.createObjectDelta(deltaType, prismContext); + if (!matchPendingDelta(delta, proposedDelta)) { + continue; + } + return pendingOperation; + } + return null; + } + + private boolean isInProgressOrRequested(OperationResultStatusType resultStatus, boolean processInProgress) { + if (resultStatus == null) { + return true; + } + if (processInProgress && resultStatus == OperationResultStatusType.IN_PROGRESS) { + return true; + } + return false; + } + + public PendingOperationType checkAndRecordPendingModifyOperationBeforeExecution(ProvisioningContext ctx, + PrismObject repoShadow, Collection modifications, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + + ObjectDelta proposedDelta = createModifyDelta(repoShadow, modifications); + return checkAndRecordPendingOperationBeforeExecution(ctx, repoShadow, proposedDelta, task, parentResult); + } + + private ObjectDelta createModifyDelta(PrismObject repoShadow, Collection modifications) { + ObjectDelta delta = repoShadow.createModifyDelta(); + delta.addModifications(ItemDelta.cloneCollection(modifications)); + return delta; + } + + // returns conflicting operation (pending delta) if there is any + private PendingOperationType checkAndRecordPendingOperationBeforeExecution(ProvisioningContext ctx, + PrismObject repoShadow, ObjectDelta proposedDelta, + Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException { ResourceType resource = ctx.getResource(); ResourceConsistencyType consistencyType = resource.getConsistency(); if (consistencyType == null) { return null; } - OptimisticLockingRunner runner = new OptimisticLockingRunner.Builder() - .object(shadow) + .object(repoShadow) .result(parentResult) .repositoryService(repositoryService) .maxNumberOfAttempts(10) @@ -968,20 +1040,10 @@ public PendingOperationType checkAndRecordPendingDeleteOperationBeforeExecution( (object) -> { Boolean avoidDuplicateOperations = consistencyType.isAvoidDuplicateOperations(); if (BooleanUtils.isTrue(avoidDuplicateOperations)) { - for (PendingOperationType pendingOperation: object.asObjectable().getPendingOperation()) { - OperationResultStatusType resultStatus = pendingOperation.getResultStatus(); - if (resultStatus != null && resultStatus != OperationResultStatusType.IN_PROGRESS) { - continue; - } - ObjectDeltaType delta = pendingOperation.getDelta(); - if (delta == null) { - continue; - } - if (delta.getChangeType() != ChangeTypeType.DELETE) { - continue; - } - LOGGER.debug("Found duplicate operation for delete of {}: {}", object, pendingOperation); - return pendingOperation; + PendingOperationType existingPendingOperation = findExistingPendingOperation(object, proposedDelta, true); + if (existingPendingOperation != null) { + LOGGER.debug("Found duplicate operation for {} of {}: {}", proposedDelta.getChangeType(), object, existingPendingOperation); + return existingPendingOperation; } } @@ -989,9 +1051,9 @@ public PendingOperationType checkAndRecordPendingDeleteOperationBeforeExecution( return null; } - ObjectDelta pendingDelta = object.createDeleteDelta(); - - addPendingOperationDelta(ctx, object, pendingDelta, null, null, object.getVersion(), parentResult); + LOGGER.trace("Storing pending operation for {} of {}", proposedDelta.getChangeType(), object); + addPendingOperationDelta(ctx, object, proposedDelta, null, null, object.getVersion(), parentResult); + LOGGER.trace("Stored pending operation for {} of {}", proposedDelta.getChangeType(), object); // Yes, really return null. We are supposed to return conflicting operation (if found). // But in this case there is no conflict. This operation does not conflict with itself. @@ -1003,46 +1065,13 @@ public PendingOperationType checkAndRecordPendingDeleteOperationBeforeExecution( // should not happen throw new SystemException(e); } - + } - private void recordPendingDeleteOperationAfterExecution(ProvisioningContext ctx, PrismObject oldRepoShadow, - OperationResult resourceOperationResult, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException { - - if (ResourceTypeUtil.getRecordPendingOperations(ctx.getResource()) == RecordPendingOperationsType.ALL) { - // We have to look for pending delta for this operation that may already exist. In that case update it - // instead creating a new one. - // We have to re-read the shadow from repository here. We need valid container IDs. - // Also there is some chance that the pending delta might have been created by a different thread. - PrismObject currentShadow = rereadShadow(oldRepoShadow, parentResult); - - PendingOperationType existingPendingOperation = null; - for (PendingOperationType pendingOperation: currentShadow.asObjectable().getPendingOperation()) { - OperationResultStatusType resultStatus = pendingOperation.getResultStatus(); - if (resultStatus != null) { - continue; - } - ObjectDeltaType delta = pendingOperation.getDelta(); - if (delta == null) { - continue; - } - if (delta.getChangeType() != ChangeTypeType.DELETE) { - continue; - } - LOGGER.trace("Found existing pending operation for delete of {}, updating", currentShadow); - existingPendingOperation = pendingOperation; - break; - } - - if (existingPendingOperation != null) { - updatePendingOperationStatus(ctx, currentShadow, existingPendingOperation, OperationResultStatusType.IN_PROGRESS, resourceOperationResult, parentResult); - return; - } - } - - ObjectDelta pendingDelta = oldRepoShadow.createDeleteDelta(); - - addPendingOperationDelta(ctx, oldRepoShadow, pendingDelta, OperationResultStatusType.IN_PROGRESS, resourceOperationResult, parentResult); + + private boolean matchPendingDelta(ObjectDelta pendingDelta, ObjectDelta proposedDelta) { + // TODO: is this entirelly reliable? + return pendingDelta.equals(proposedDelta); } private PrismObject rereadShadow(PrismObject oldRepoShadow, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { @@ -1110,8 +1139,13 @@ private void updatePendingOperationStatus(ProvisioningContext ctx, PrismObject asyncRefDelta = PropertyDelta.createModificationReplaceProperty(asyncRefPath, shadow.getDefinition(), + PropertyDelta asyncRefDelta; + if (resourceOperationResult.getAsynchronousOperationReference() == null) { + asyncRefDelta = PropertyDelta.createModificationReplaceProperty(asyncRefPath, shadow.getDefinition() /*, no value */); + } else { + asyncRefDelta = PropertyDelta.createModificationReplaceProperty(asyncRefPath, shadow.getDefinition(), resourceOperationResult.getAsynchronousOperationReference()); + } repoDeltas.add(asyncRefDelta); } @@ -1227,14 +1261,34 @@ private PrismObject createRepositoryShadow(ProvisioningContext ctx, return repoShadow; } - public void modifyShadow(ProvisioningContext ctx, PrismObject shadow, Collection modifications, + public void modifyShadow(ProvisioningContext ctx, PrismObject oldRepoShadow, Collection modifications, OperationResult resourceOperationResult, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, ConfigurationException, CommunicationException, ExpressionEvaluationException { - LOGGER.trace("Updating repository shadow, resourceOperationResult={}, {} modifications", resourceOperationResult.getStatus(), modifications.size()); - if (resourceOperationResult.isInProgress()) { - addPendingOperationModify(ctx, shadow, modifications, resourceOperationResult, parentResult); + + PendingOperationType existingPendingOperation = null; + if (ResourceTypeUtil.getRecordPendingOperations(ctx.getResource()) == RecordPendingOperationsType.ALL) { + // We have to look for pending delta for this operation that may already exist. In that case update it + // instead creating a new one. + // We have to re-read the shadow from repository here. We need valid container IDs. + // Also there is some chance that the pending delta might have been created by a different thread. + PrismObject currentShadow = rereadShadow(oldRepoShadow, parentResult); + ObjectDelta proposedDelta = createModifyDelta(currentShadow, modifications); + existingPendingOperation = findExistingPendingOperation(currentShadow, proposedDelta, false); + } + + LOGGER.trace("Updating repository shadow, resourceOperationResult={}, {} modifications, existingPendingOperation={}", resourceOperationResult.getStatus(), modifications.size(), existingPendingOperation); + if (resourceOperationResult != null && resourceOperationResult.isInProgress()) { + if (existingPendingOperation == null) { + addPendingOperationModify(ctx, oldRepoShadow, modifications, resourceOperationResult, parentResult); + } else { + updatePendingOperationStatus(ctx, oldRepoShadow, existingPendingOperation, OperationResultStatusType.IN_PROGRESS, resourceOperationResult, parentResult); + } } else { - modifyShadowAttributes(ctx, shadow, modifications, parentResult); + if (existingPendingOperation == null) { + modifyShadowAttributes(ctx, oldRepoShadow, modifications, parentResult); + } else { + updatePendingOperationStatus(ctx, oldRepoShadow, existingPendingOperation, resourceOperationResult.getStatus().createStatusType(), resourceOperationResult, parentResult); + } } } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/AbstractProvisioningIntegrationTest.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/AbstractProvisioningIntegrationTest.java index 026236bbf55..e5fd4be46a0 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/AbstractProvisioningIntegrationTest.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/AbstractProvisioningIntegrationTest.java @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.provisioning.impl; @@ -42,21 +42,21 @@ public abstract class AbstractProvisioningIntegrationTest extends AbstractIntegrationTest { public static final File COMMON_DIR = ProvisioningTestUtil.COMMON_TEST_DIR_FILE; - + protected static final String CSV_CONNECTOR_TYPE = "com.evolveum.polygon.connector.csv.CsvConnector"; private static final Trace LOGGER = TraceManager.getTrace(AbstractProvisioningIntegrationTest.class); @Autowired(required=true) protected ProvisioningService provisioningService; - + @Autowired(required = true) protected SynchornizationServiceMock syncServiceMock; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { InternalsConfig.encryptionChecks = false; provisioningService.postInit(initResult); } - + } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/ProvisioningTestUtil.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/ProvisioningTestUtil.java index eb0d8cca4c6..8b5b906dfe7 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/ProvisioningTestUtil.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/ProvisioningTestUtil.java @@ -47,31 +47,31 @@ * */ public class ProvisioningTestUtil { - + public static final File COMMON_TEST_DIR_FILE = new File("src/test/resources/common/"); public static final File TEST_DIR_IMPL_FILE = new File("src/test/resources/impl/"); - + public static final File RESOURCE_OPENDJ_FILE = new File(COMMON_TEST_DIR_FILE, "resource-opendj.xml"); - + public static final String RESOURCE_DUMMY_NS = "http://midpoint.evolveum.com/xml/ns/public/resource/instance/ef2bc95b-76e0-59e2-86d6-9999dddddddd"; - + public static final String DOT_JPG_FILENAME = "src/test/resources/common/dot.jpg"; - + public static final File USER_ADMIN_FILE = new File(COMMON_TEST_DIR_FILE, "admin.xml"); - + public static final String CONNID_CONNECTOR_FACADE_CLASS_NAME = "org.identityconnectors.framework.api.ConnectorFacade"; public static final String CONNID_UID_NAME = "__UID__"; public static final String CONNID_NAME_NAME = "__NAME__"; public static final String CONNID_DESCRIPTION_NAME = "__DESCRIPTION__"; - + public static void checkRepoAccountShadow(PrismObject repoShadow) { checkRepoShadow(repoShadow, ShadowKindType.ACCOUNT); } - + public static void checkRepoEntitlementShadow(PrismObject repoShadow) { checkRepoShadow(repoShadow, ShadowKindType.ENTITLEMENT); } - + public static void checkRepoShadow(PrismObject repoShadow, ShadowKindType kind) { checkRepoShadow(repoShadow, kind, 2); } @@ -90,7 +90,7 @@ public static void checkRepoShadow(PrismObject repoShadow, ShadowKin assertEquals("Unexpected number of attributes in repo shadow "+repoShadow, (int)expectedNumberOfAttributes, attributes.size()); } } - + public static QName getDefaultAccountObjectClass(ResourceType resourceType) { String namespace = ResourceTypeUtil.getResourceNamespace(resourceType); return new QName(namespace, SchemaConstants.ACCOUNT_OBJECT_CLASS_LOCAL_NAME); 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 66a91aab5c7..b126ea46fc5 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 @@ -42,7 +42,7 @@ import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType; -/** +/** * @author Radovan Semancik * @author Katka Valalikova */ @@ -59,50 +59,50 @@ public class TestConnectorDiscovery extends AbstractIntegrationTest { public void initSystem(Task initTask, OperationResult initResult) throws Exception { provisioningService.postInit(initResult); } - - + + /** * Check whether the connectors were discovered correctly and were added to the repository. * @throws SchemaException - * + * */ @Test public void test001Connectors() throws Exception { final String TEST_NAME = "test001Connectors"; TestUtil.displayTestTitle(TEST_NAME); - + OperationResult result = new OperationResult(TestConnectorDiscovery.class.getName() + "." + TEST_NAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); List> connectors = repositoryService.searchObjects(ConnectorType.class, null, null, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertFalse("No connector found",connectors.isEmpty()); display("Found "+connectors.size()+" discovered connector"); - + result.computeStatus(); TestUtil.assertSuccess(result); - + for (PrismObject connector : connectors) { ConnectorType conn = connector.asObjectable(); display("Found connector " +conn, conn); IntegrationTestTools.assertConnectorSchemaSanity(conn, prismContext); } - + assertEquals("Unexpected number of connectors found", 7, connectors.size()); } - + @Test public void testListConnectors() throws Exception{ TestUtil.displayTestTitle("testListConnectors"); OperationResult result = new OperationResult(TestConnectorDiscovery.class.getName() + ".listConnectorsTest"); - + List> connectors = provisioningService.searchObjects(ConnectorType.class, null, null, null, result); assertNotNull(connectors); - + for (PrismObject connector : connectors){ ConnectorType conn = connector.asObjectable(); System.out.println(conn.toString()); @@ -110,22 +110,22 @@ public void testListConnectors() throws Exception{ System.out.println("connector type: "+ conn.getConnectorType()); System.out.println("-----\n"); } - + assertEquals("Unexpected number of connectors found", 7, connectors.size()); } - + @Test public void testSearchConnectorSimple() throws SchemaException{ final String TEST_NAME = "testSearchConnectorSimple"; TestUtil.displayTestTitle(TEST_NAME); OperationResult result = new OperationResult(TestConnectorDiscovery.class.getName() + "." + TEST_NAME); - + PrismObject ldapConnector = findConnectorByType(IntegrationTestTools.LDAP_CONNECTOR_TYPE, result); assertEquals("Type does not match", IntegrationTestTools.LDAP_CONNECTOR_TYPE, ldapConnector.asObjectable().getConnectorType()); } - - + + @Test public void testSearchConnectorAnd() throws SchemaException{ TestUtil.displayTestTitle("testSearchConnectorAnd"); @@ -140,7 +140,7 @@ public void testSearchConnectorAnd() throws SchemaException{ System.out.println("Query:\n"+query.debugDump()); List> connectors = repositoryService.searchObjects(ConnectorType.class, query, null, result); - + assertEquals("Unexpected number of results", 1, connectors.size()); PrismObject ldapConnector = connectors.get(0); 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 943ffbf322e..60238afab83 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 @@ -46,7 +46,7 @@ import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType; -/** +/** * @author Radovan Semancik */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @@ -57,7 +57,7 @@ public class TestConnectorManager extends AbstractIntegrationTest { @Autowired private ProvisioningService provisioningService; - + @Autowired private ConnectorManager connectorManager; @@ -69,18 +69,18 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti // we want to test the state before discovery // provisioningService.postInit(initResult); } - + @Test public void test100ListConnectorFactories() throws Exception { final String TEST_NAME = "test100ListConnectorFactories"; TestUtil.displayTestTitle(TEST_NAME); - + OperationResult result = new OperationResult(TestConnectorDiscovery.class.getName() + "." + TEST_NAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); Collection connectorFactories = connectorManager.getConnectorFactories(); - + // THEN TestUtil.displayThen(TEST_NAME); assertNotNull("Null connector factories", connectorFactories); @@ -90,46 +90,46 @@ public void test100ListConnectorFactories() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - + for (ConnectorFactory connectorFactory : connectorFactories) { display("Found connector factory " +connectorFactory, connectorFactory); } - - PrismAsserts.assertEqualsUnordered("Wrong connector factories", - connectorFactories.stream().map(x -> x.getClass().getName()), + + PrismAsserts.assertEqualsUnordered("Wrong connector factories", + connectorFactories.stream().map(x -> x.getClass().getName()), "com.evolveum.midpoint.provisioning.ucf.impl.connid.ConnectorFactoryConnIdImpl", "com.evolveum.midpoint.provisioning.ucf.impl.builtin.ConnectorFactoryBuiltinImpl"); } - + @Test public void test110SelfTest() throws Exception { final String TEST_NAME = "test100ListConnectorFactories"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = taskManager.createTaskInstance(TestConnectorDiscovery.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); connectorManager.connectorFrameworkSelfTest(result, task); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); } - + @Test public void test120FrameworkVersion() throws Exception { final String TEST_NAME = "test120FrameworkVersion"; TestUtil.displayTestTitle(TEST_NAME); - + // 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/TestDBTable.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestDBTable.java index 313f2357f04..773ede820eb 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestDBTable.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestDBTable.java @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.provisioning.impl; @@ -61,16 +61,16 @@ import static org.testng.AssertJUnit.*; /** - * + * * @author Radovan Semancik * */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext public class TestDBTable extends AbstractIntegrationTest { - + protected static final File TEST_DIR = new File("src/test/resources/db"); - + private static final File RESOURCE_DERBY_FILE = new File(TEST_DIR, "resource-derby.xml"); private static final String RESOURCE_DERBY_OID = "ef2bc95b-76e0-59e2-86d6-999902d3abab"; private static final File ACCOUNT_WILL_FILE = new File(TEST_DIR, "account-derby.xml"); @@ -79,25 +79,25 @@ public class TestDBTable extends AbstractIntegrationTest { private static final String ACCOUNT_WILL_FULLNAME = "Will Turner"; private static final String ACCOUNT_WILL_PASSWORD = "3lizab3th"; private static final String DB_TABLE_CONNECTOR_TYPE = "org.identityconnectors.databasetable.DatabaseTableConnector"; - + private static final Trace LOGGER = TraceManager.getTrace(TestDBTable.class); private static DerbyController derbyController = new DerbyController(); - + @Autowired private ProvisioningService provisioningService; - + // @Autowired // private TaskManager taskManager; - + @Autowired private SynchornizationServiceMock syncServiceMock; - - + + /* (non-Javadoc) * @see com.evolveum.midpoint.test.AbstractIntegrationTest#initSystem() */ - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { // We need to switch off the encryption checks. Some values cannot be encrypted as we do @@ -106,7 +106,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti provisioningService.postInit(initResult); addResourceFromFile(RESOURCE_DERBY_FILE, DB_TABLE_CONNECTOR_TYPE, initResult); } - + @BeforeClass public static void startDb() throws Exception { LOGGER.info("------------------------------------------------------------------------------"); @@ -123,37 +123,37 @@ public static void stopDb() throws Exception { LOGGER.info("------------------------------------------------------------------------------"); } - + @Test public void test000Integrity() throws ObjectNotFoundException, SchemaException { TestUtil.displayTestTitle("test000Integrity"); - + OperationResult result = new OperationResult(TestDBTable.class.getName()+".test000Integrity"); - + ResourceType resource = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, result).asObjectable(); String connectorOid = resource.getConnectorRef().getOid(); ConnectorType connector = repositoryService.getObject(ConnectorType.class, connectorOid, null, result).asObjectable(); assertNotNull(connector); display("DB Connector",connector); } - + @Test public void test001Connection() throws Exception { final String TEST_NAME = "test001Connection"; TestUtil.displayTestTitle(TEST_NAME); Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN OperationResult testResult = provisioningService.testResource(RESOURCE_DERBY_OID, task); - + display("Test result",testResult); TestUtil.assertSuccess("Test resource failed (result)", testResult); - + ResourceType resource = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, result).asObjectable(); display("Resource after test",resource); display("Resource after test (XML)", PrismTestUtil.serializeObjectToString(resource.asPrismObject(), PrismContext.LANG_XML)); - + List nativeCapabilities = resource.getCapabilities().getNative().getAny(); CredentialsCapabilityType credentialsCapabilityType = CapabilityUtil.getCapability(nativeCapabilities, CredentialsCapabilityType.class); assertNotNull("No credentials capability", credentialsCapabilityType); @@ -161,7 +161,7 @@ public void test001Connection() throws Exception { assertNotNull("No password in credentials capability", passwordCapabilityType); assertEquals("Wrong password capability ReturnedByDefault", Boolean.FALSE, passwordCapabilityType.isReturnedByDefault()); } - + @Test public void test002AddAccount() throws Exception { final String TEST_NAME = "test002AddAccount"; @@ -178,7 +178,7 @@ public void test002AddAccount() throws Exception { Task task = taskManager.createTaskInstance(); // WHEN String addedObjectOid = provisioningService.addObject(account.asPrismObject(), null, null, task, result); - + // THEN result.computeStatus(); display("add object result",result); @@ -192,25 +192,25 @@ public void test002AddAccount() throws Exception { ShadowType provisioningAccountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result).asObjectable(); PrismAsserts.assertEqualsPolyString("Name not equal.", ACCOUNT_WILL_USERNAME, provisioningAccountType.getName()); // assertEquals("will", provisioningAccountType.getName()); - + // Check database content - + Connection conn = derbyController.getConnection(); // Check if it empty Statement stmt = conn.createStatement(); stmt.execute("select * from users"); ResultSet rs = stmt.getResultSet(); - + assertTrue("The \"users\" table is empty",rs.next()); assertEquals(ACCOUNT_WILL_USERNAME,rs.getString(DerbyController.COLUMN_LOGIN)); assertEquals(ACCOUNT_WILL_PASSWORD,rs.getString(DerbyController.COLUMN_PASSWORD)); assertEquals(ACCOUNT_WILL_FULLNAME,rs.getString(DerbyController.COLUMN_FULL_NAME)); - + assertFalse("The \"users\" table has more than one record",rs.next()); rs.close(); stmt.close(); } - + // MID-1234 @Test(enabled=false) public void test005GetAccount() throws Exception { @@ -223,7 +223,7 @@ public void test005GetAccount() throws Exception { Task task = taskManager.createTaskInstance(); // WHEN PrismObject account = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + // THEN result.computeStatus(); display(result); @@ -239,6 +239,6 @@ public void test005GetAccount() throws Exception { String clearPassword = protector.decryptString(password); assertEquals("Wrong password", ACCOUNT_WILL_PASSWORD, clearPassword); } - - + + } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/AbstractCsvTest.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/AbstractCsvTest.java index dd0653cc033..fcffa84857d 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/AbstractCsvTest.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/AbstractCsvTest.java @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.provisioning.impl.csv; @@ -84,24 +84,24 @@ /** * The test of Provisioning service on the API level. The test is using CSV resource. - * + * * @author Radovan Semancik - * + * */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext public abstract class AbstractCsvTest extends AbstractProvisioningIntegrationTest { protected static final File TEST_DIR = new File("src/test/resources/csv/"); - + protected static final String RESOURCE_NS = MidPointConstants.NS_RI; - + public static final QName RESOURCE_CSV_ACCOUNT_OBJECTCLASS = new QName(RESOURCE_NS, "AccountObjectClass"); - + protected static final String CSV_CONNECTOR_TYPE = "com.evolveum.polygon.connector.csv.CsvConnector"; - + private static final File CSV_TARGET_FILE = new File("target/midpoint.csv"); - + protected static final String ACCOUNT_JACK_FIRSTNAME = "Jack"; protected static final String ACCOUNT_JACK_LASTNAME = "Sparrow"; @@ -109,38 +109,38 @@ public abstract class AbstractCsvTest extends AbstractProvisioningIntegrationTes protected static final String ATTR_FIRSTNAME = "firstname"; protected static final QName ATTR_FIRSTNAME_QNAME = new QName(RESOURCE_NS, ATTR_FIRSTNAME); - + protected static final String ATTR_LASTNAME = "lastname"; protected static final QName ATTR_LASTNAME_QNAME = new QName(RESOURCE_NS, ATTR_LASTNAME); protected PrismObject resource; protected ResourceType resourceType; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + resource = addResourceFromFile(getResourceFile(), CSV_CONNECTOR_TYPE, initResult); resourceType = resource.asObjectable(); - + FileUtils.copyFile(getSourceCsvFile(), CSV_TARGET_FILE); } protected abstract File getResourceFile(); - + protected abstract String getResourceOid(); - + protected abstract File getSourceCsvFile(); - + protected abstract File getAccountJackFile(); - + protected abstract String getAccountJackOid(); @Test public void test000Integrity() throws Exception { final String TEST_NAME = "test000Integrity"; TestUtil.displayTestTitle(TEST_NAME); - + assertNotNull("Resource is null", resource); assertNotNull("ResourceType is null", resourceType); @@ -154,14 +154,14 @@ public void test000Integrity() throws Exception { .getObject(ConnectorType.class, connectorOid, null, result).asObjectable(); assertNotNull(connector); display("CSVFile Connector", connector); - + // Check connector schema 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. @@ -193,14 +193,14 @@ public void test003Connection() throws Exception { TestUtil.assertSuccess("Test resource failed (result)", testResult); PrismObject resourceRepoAfter = repositoryService.getObject(ResourceType.class, getResourceOid(), null, result); - ResourceType resourceTypeRepoAfter = resourceRepoAfter.asObjectable(); + ResourceType resourceTypeRepoAfter = resourceRepoAfter.asObjectable(); display("Resource after test", resourceTypeRepoAfter); XmlSchemaType xmlSchemaTypeAfter = resourceTypeRepoAfter.getSchema(); assertNotNull("No schema after test connection", xmlSchemaTypeAfter); Element resourceXsdSchemaElementAfter = ResourceTypeUtil.getResourceXsdSchema(resourceTypeRepoAfter); assertNotNull("No schema after test connection", resourceXsdSchemaElementAfter); - + String resourceXml = prismContext.serializeObjectToString(resourceRepoAfter, PrismContext.LANG_XML); display("Resource XML", resourceXml); @@ -215,7 +215,7 @@ public void test003Connection() throws Exception { // schema will be checked in next test } - + @Test public void test004Configuration() throws Exception { final String TEST_NAME = "test004Configuration"; @@ -232,12 +232,12 @@ public void test004Configuration() throws Exception { assertNotNull("No configuration container", configurationContainer); PrismContainerDefinition confContDef = configurationContainer.getDefinition(); assertNotNull("No configuration container definition", confContDef); - PrismContainer confingurationPropertiesContainer = + PrismContainer confingurationPropertiesContainer = configurationContainer.findContainer(SchemaConstants.CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_QNAME); assertNotNull("No configuration properties container", confingurationPropertiesContainer); PrismContainerDefinition confPropDef = confingurationPropertiesContainer.getDefinition(); assertNotNull("No configuration properties container definition", confPropDef); - + } @Test @@ -251,7 +251,7 @@ public void test005ParsedSchema() throws Exception { // Also test if the utility method returns the same thing ResourceSchema resourceSchema = RefinedResourceSchemaImpl.getResourceSchema(resourceType, prismContext); - + display("Parsed resource schema", resourceSchema); assertNotNull("No resource schema", resourceSchema); @@ -263,20 +263,20 @@ public void test005ParsedSchema() throws Exception { assertFalse("No nativeObjectClass in account", StringUtils.isEmpty(accountDef.getNativeObjectClass())); assertAccountDefinition(accountDef); - + ResourceAttributeDefinition icfsNameDef = accountDef.findAttributeDefinition(SchemaConstants.ICFS_NAME); assertNull("ICFS NAME definition sneaked in", icfsNameDef); - + ResourceAttributeDefinition icfsUidDef = accountDef.findAttributeDefinition(SchemaConstants.ICFS_UID); assertNull("ICFS UID definition sneaked in", icfsUidDef); - + // 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)); } - + protected abstract void assertAccountDefinition(ObjectClassComplexTypeDefinition accountDef); @Test @@ -289,30 +289,30 @@ public void test006Capabilities() throws Exception { // WHEN ResourceType resource = provisioningService.getObject(ResourceType.class, getResourceOid(), null, null, result).asObjectable(); - + // THEN display("Resource from provisioninig", resource); display("Resource from provisioninig (XML)", PrismTestUtil.serializeObjectToString(resource.asPrismObject(), PrismContext.LANG_XML)); - + CapabilityCollectionType nativeCapabilities = resource.getCapabilities().getNative(); List nativeCapabilitiesList = nativeCapabilities.getAny(); assertFalse("Empty capabilities returned",nativeCapabilitiesList.isEmpty()); - + // Connector cannot do activation, this should be null ActivationCapabilityType capAct = CapabilityUtil.getCapability(nativeCapabilitiesList, ActivationCapabilityType.class); assertNull("Found activation capability while not expecting it" ,capAct); - + ScriptCapabilityType capScript = CapabilityUtil.getCapability(nativeCapabilitiesList, ScriptCapabilityType.class); assertNotNull("No script capability", capScript); List scriptHosts = capScript.getHost(); assertEquals("Wrong number of script hosts", 1, scriptHosts.size()); assertScriptHost(capScript, ProvisioningScriptHostType.CONNECTOR); - + List effectiveCapabilities = ResourceTypeUtil.getEffectiveCapabilities(resource); for (Object capability : effectiveCapabilities) { System.out.println("Capability: "+CapabilityUtil.getCapabilityDisplayName(capability)+" : "+capability); } - + } private void assertScriptHost(ScriptCapabilityType capScript, ProvisioningScriptHostType expectedHostType) { @@ -333,16 +333,16 @@ public void test100AddAccountJack() throws Exception { OperationResult result = task.getResult(); PrismObject shadowBefore = parseObject(getAccountJackFile()); - + // WHEN TestUtil.displayWhen(TEST_NAME); provisioningService.addObject(shadowBefore, null, null, task, result); // THEN TestUtil.displayThen(TEST_NAME); - assertSuccess(result); + assertSuccess(result); } - + @Test public void test110GetAccountJack() throws Exception { final String TEST_NAME = "test110GetAccountJack"; @@ -358,11 +358,11 @@ public void test110GetAccountJack() throws Exception { // THEN TestUtil.displayThen(TEST_NAME); assertSuccess(result); - + assertNotNull(shadow); display("Shadow after", shadow); - + ShadowType shadowType = shadow.asObjectable(); PrismAsserts.assertEqualsPolyString("Wrong name", "jack", shadow.getName()); assertNotNull(shadow.getOid()); @@ -372,17 +372,17 @@ public void test110GetAccountJack() throws Exception { assertNotNull("Missing activation", shadowType.getActivation()); assertNotNull("Missing activation status", shadowType.getActivation().getAdministrativeStatus()); assertEquals("Not enabled", ActivationStatusType.ENABLED, shadowType.getActivation().getAdministrativeStatus()); - + PrismObject repoShadow = repositoryService.getObject(ShadowType.class, shadow.getOid(), null, result); ShadowType repoShadowType = repoShadow.asObjectable(); assertEquals(RESOURCE_CSV_ACCOUNT_OBJECTCLASS, repoShadowType.getObjectClass()); assertEquals(getResourceOid(), repoShadowType.getResourceRef().getOid()); assertAccountJackAttributesRepo(shadowType); - + } protected abstract void assertAccountJackAttributes(ShadowType shadowType); - + protected abstract void assertAccountJackAttributesRepo(ShadowType shadowType); } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/TestCsvGuid.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/TestCsvGuid.java index 282b1ade604..4622a7600c6 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/TestCsvGuid.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/TestCsvGuid.java @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.provisioning.impl.csv; @@ -40,9 +40,9 @@ /** * The test of Provisioning service on the API level. The test is using CSV resource. - * + * * @author Radovan Semancik - * + * */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext @@ -50,17 +50,17 @@ public class TestCsvGuid extends AbstractCsvTest { private static final File RESOURCE_CSV_GUID_FILE = new File(TEST_DIR, "resource-csv-guid.xml"); private static final String RESOURCE_CSV_GUID_OID = "b39e0b10-2449-11e7-b0c1-73f52bb2a496"; - + private static final File ACCOUNT_JACK_FILE = new File(TEST_DIR, "account-jack-guid.xml");; private static final String ACCOUNT_JACK_OID = "2db718b6-243a-11e7-a9e5-bbb2545f80ed"; private static final String ACCOUNT_JACK_GUID = "007"; private static final String ACCOUNT_JACK_UNAME = "jack"; - + private static final File CSV_SOURCE_FILE = new File(TEST_DIR, "midpoint-guid.csv"); - + protected static final String ATTR_GUID = "guid"; protected static final QName ATTR_GUID_QNAME = new QName(RESOURCE_NS, ATTR_GUID); - + protected static final String ATTR_UNAME = "uname"; protected static final QName ATTR_UNAME_QNAME = new QName(RESOURCE_NS, ATTR_UNAME); @@ -80,7 +80,7 @@ protected String getResourceOid() { protected File getSourceCsvFile() { return CSV_SOURCE_FILE; } - + @Override protected File getAccountJackFile() { return ACCOUNT_JACK_FILE; @@ -89,13 +89,13 @@ protected File getAccountJackFile() { @Override protected String getAccountJackOid() { return ACCOUNT_JACK_OID; - } + } @Override protected void assertAccountDefinition(ObjectClassComplexTypeDefinition accountDef) { - + assertEquals("Unexpected number of definitions", 5, accountDef.getDefinitions().size()); - + ResourceAttributeDefinition guidDef = accountDef.findAttributeDefinition(ATTR_GUID); assertNotNull("No definition for guid", guidDef); assertEquals(1, guidDef.getMaxOccurs()); @@ -103,7 +103,7 @@ protected void assertAccountDefinition(ObjectClassComplexTypeDefinition accountD assertTrue("No guid create", guidDef.canAdd()); assertTrue("No guid update", guidDef.canModify()); assertTrue("No guid read", guidDef.canRead()); - + ResourceAttributeDefinition unameDef = accountDef.findAttributeDefinition(ATTR_UNAME); assertNotNull("No definition for uname", unameDef); assertEquals(1, unameDef.getMaxOccurs()); @@ -111,7 +111,7 @@ protected void assertAccountDefinition(ObjectClassComplexTypeDefinition accountD assertTrue("No uname create", unameDef.canAdd()); assertTrue("No uname update", unameDef.canModify()); assertTrue("No uname read", unameDef.canRead()); - + assertNotNull("Null secondary identifiers in account", accountDef.getSecondaryIdentifiers()); assertFalse("Empty secondary identifiers in account", accountDef.getSecondaryIdentifiers().isEmpty()); } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/TestCsvUsername.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/TestCsvUsername.java index cec0cf0e222..d0be9621676 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/TestCsvUsername.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/csv/TestCsvUsername.java @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.provisioning.impl.csv; @@ -39,9 +39,9 @@ /** * The test of Provisioning service on the API level. The test is using CSV resource. - * + * * @author Radovan Semancik - * + * */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext @@ -49,16 +49,16 @@ public class TestCsvUsername extends AbstractCsvTest { private static final File RESOURCE_CSV_USERNAME_FILE = new File(TEST_DIR, "resource-csv-username.xml"); private static final String RESOURCE_CSV_USERNAME_OID = "ef2bc95b-76e0-59e2-86d6-9999cccccccc"; - + private static final File ACCOUNT_JACK_FILE = new File(TEST_DIR, "account-jack-username.xml");; private static final String ACCOUNT_JACK_OID = "2db718b6-243a-11e7-a9e5-bbb2545f80ed"; private static final String ACCOUNT_JACK_USERNAME = "jack"; - + private static final File CSV_SOURCE_FILE = new File(TEST_DIR, "midpoint-username.csv"); protected static final String ATTR_USERNAME = "username"; protected static final QName ATTR_USERNAME_QNAME = new QName(RESOURCE_NS, ATTR_USERNAME); - + private static final Trace LOGGER = TraceManager.getTrace(TestCsvUsername.class); @Override @@ -75,7 +75,7 @@ protected String getResourceOid() { protected File getSourceCsvFile() { return CSV_SOURCE_FILE; } - + @Override protected File getAccountJackFile() { return ACCOUNT_JACK_FILE; @@ -84,13 +84,13 @@ protected File getAccountJackFile() { @Override protected String getAccountJackOid() { return ACCOUNT_JACK_OID; - } + } @Override protected void assertAccountDefinition(ObjectClassComplexTypeDefinition accountDef) { assertEquals("Unexpected number of definitions", 4, accountDef.getDefinitions().size()); - + ResourceAttributeDefinition usernameDef = accountDef.findAttributeDefinition(ATTR_USERNAME); assertNotNull("No definition for username", usernameDef); assertEquals(1, usernameDef.getMaxOccurs()); @@ -98,7 +98,7 @@ protected void assertAccountDefinition(ObjectClassComplexTypeDefinition accountD assertTrue("No username create", usernameDef.canAdd()); assertTrue("No username update", usernameDef.canModify()); assertTrue("No username read", usernameDef.canRead()); - + } @Override 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 897f0e959b2..23c20be4876 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 @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.provisioning.impl.dummy; @@ -125,7 +125,7 @@ /** * The test of Provisioning service on the API level. The test is using dummy * resource for speed and flexibility. - * + * * @author Radovan Semancik */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @@ -134,7 +134,7 @@ public class AbstractBasicDummyTest extends AbstractDummyTest { private static final Trace LOGGER = TraceManager.getTrace(AbstractBasicDummyTest.class); - + protected CachingMetadataType capabilitiesCachingMetadataType; protected String willIcfUid; protected XMLGregorianCalendar lastPasswordModifyStart; @@ -143,15 +143,15 @@ public class AbstractBasicDummyTest extends AbstractDummyTest { protected MatchingRule getUidMatchingRule() { return null; } - + protected boolean isAvoidDuplicateValues() { return false; } - + protected int getExpectedRefinedSchemaDefinitions() { return dummyResource.getNumberOfObjectclasses(); } - + @AfterClass public static void assertCleanShutdown() throws Exception { dummyResource.assertNoConnections(); @@ -176,14 +176,14 @@ public void test000Integrity() throws Exception { ConnectorType connector = repositoryService.getObject(ConnectorType.class, connectorOid, null, result).asObjectable(); assertNotNull(connector); display("Dummy Connector", connector); - + result.computeStatus(); display("getObject result", result); TestUtil.assertSuccess(result); - + // Check connector schema IntegrationTestTools.assertConnectorSchemaSanity(connector, prismContext); - + IntegrationTestTools.assertNoSchema(resource); } @@ -293,17 +293,17 @@ public void test015ListResourcesNoFetch() throws Exception { assertNull("Found schema in "+resource, xsdSchemaElement); } } - + assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 1); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); } - + /** * 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. @@ -315,17 +315,17 @@ public void test020Connection() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // Some connector initialization and other things might happen in previous tests. // The monitor is static, not part of spring context, it will not be cleared - + rememberCounter(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT); rememberCounter(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT); rememberCounter(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT); rememberCounter(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT); rememberCounter(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT); rememberResourceCacheStats(); - + // Check that there is no schema before test (pre-condition) PrismObject resourceBefore = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, result); ResourceType resourceTypeBefore = resourceBefore.asObjectable(); @@ -373,7 +373,7 @@ public void test020Connection() throws Exception { assertNotNull("No schema after parsing", parsedSchema); // schema will be checked in next test - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 1); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 1); @@ -381,7 +381,7 @@ public void test020Connection() throws Exception { assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 1); // One increment for availablity status, the other for schema assertResourceVersionIncrement(resourceRepoAfter, 2); - + } @Test @@ -394,7 +394,7 @@ public void test021Configuration() throws Exception { // WHEN resource = provisioningService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, null, result); resourceType = resource.asObjectable(); - + // THEN result.computeStatus(); display("getObject result", result); @@ -404,7 +404,7 @@ public void test021Configuration() throws Exception { // Schema for this version will not be re-parsed until getObject is tried assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 1); assertResourceCacheMissesIncrement(1); - + PrismContainer configurationContainer = resource.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); assertNotNull("No configuration container", configurationContainer); PrismContainerDefinition confContDef = configurationContainer.getDefinition(); @@ -422,16 +422,16 @@ public void test021Configuration() throws Exception { assertFalse("Configuration property " + confProp + " is raw", confProp.isRaw()); assertConfigurationProperty(confProp); } - + // The useless configuration variables should be reflected to the resource now assertEquals("Wrong useless string", "Shiver me timbers!", dummyResource.getUselessString()); assertEquals("Wrong guarded useless string", "Dead men tell no tales", dummyResource.getUselessGuardedString()); - + resource.checkConsistence(); - + rememberSchemaMetadata(resource); rememberConnectorInstance(resource); - + assertSteadyResource(); } @@ -462,7 +462,7 @@ public void test022ParsedSchema() throws Exception { returnedSchema == RefinedResourceSchemaImpl.getResourceSchema(resourceType, prismContext)); assertSchemaSanity(returnedSchema, resourceType); - + rememberResourceSchema(returnedSchema); assertSteadyResource(); } @@ -492,7 +492,7 @@ public void test023RefinedSchema() throws Exception { assertFalse("Empty secondary identifiers in account", accountDef.getSecondaryIdentifiers().isEmpty()); assertNotNull("No naming attribute in account", accountDef.getNamingAttribute()); assertFalse("No nativeObjectClass in account", StringUtils.isEmpty(accountDef.getNativeObjectClass())); - + assertEquals("Unexpected kind in account definition", ShadowKindType.ACCOUNT, accountDef.getKind()); assertTrue("Account definition in not default", accountDef.isDefaultInAKind()); assertEquals("Wrong intent in account definition", SchemaConstants.INTENT_DEFAULT, accountDef.getIntent()); @@ -535,20 +535,20 @@ public void test023RefinedSchema() throws Exception { assertNull("The _PASSSWORD_ attribute sneaked into schema", accountDef.findAttributeDefinition(new QName(SchemaConstants.NS_ICF_SCHEMA, "password"))); - + rememberRefinedResourceSchema(refinedSchema); - + for (Definition def: refinedSchema.getDefinitions()) { if (!(def instanceof RefinedObjectClassDefinition)) { fail("Non-refined definition sneaked into resource schema: "+def); } } - + assertEquals("Unexpected number of schema definitions", getExpectedRefinedSchemaDefinitions(), refinedSchema.getDefinitions().size()); - + assertSteadyResource(); } - + /** * Make sure that the refined schema haven't destroyed cached resource schema. * Also make sure that the caching in object's user data works well. @@ -568,11 +568,11 @@ public void test024ParsedSchemaAgain() throws Exception { display("Parsed resource schema", returnedSchema); assertSchemaSanity(returnedSchema, resourceType); - + assertResourceSchemaUnchanged(returnedSchema); assertSteadyResource(); } - + @Test public void test028Capabilities() throws Exception { final String TEST_NAME = "test028Capabilities"; @@ -600,7 +600,7 @@ public void test028Capabilities() throws Exception { CredentialsCapabilityType capCred = CapabilityUtil.getCapability(nativeCapabilitiesList, CredentialsCapabilityType.class); assertNativeCredentialsCapability(capCred); - + ActivationCapabilityType capAct = CapabilityUtil.getCapability(nativeCapabilitiesList, ActivationCapabilityType.class); if (supportsActivation()) { @@ -609,7 +609,7 @@ public void test028Capabilities() throws Exception { } else { assertNull("native activation capability sneaked in", capAct); } - + TestConnectionCapabilityType capTest = CapabilityUtil.getCapability(nativeCapabilitiesList, TestConnectionCapabilityType.class); assertNotNull("native test capability not present", capTest); @@ -619,7 +619,7 @@ public void test028Capabilities() throws Exception { assertNotNull("No host in native script capability", capScript.getHost()); assertFalse("No host in native script capability", capScript.getHost().isEmpty()); // TODO: better look inside - + capabilitiesCachingMetadataType = resourceType.getCapabilities().getCachingMetadata(); assertNotNull("No capabilities caching metadata", capabilitiesCachingMetadataType); assertNotNull("No capabilities caching metadata timestamp", capabilitiesCachingMetadataType.getRetrievalTimestamp()); @@ -639,10 +639,10 @@ public void test028Capabilities() throws Exception { System.out.println("Capability: " + CapabilityUtil.getCapabilityDisplayName(capability) + " : " + capability); } - + assertSteadyResource(); } - + protected void assertNativeCredentialsCapability(CredentialsCapabilityType capCred) { PasswordCapabilityType passwordCapabilityType = capCred.getPassword(); assertNotNull("password native capability not present", passwordCapabilityType); @@ -653,7 +653,7 @@ protected void assertNativeCredentialsCapability(CredentialsCapabilityType capCr } /** - * Check if the cached native capabilities were properly stored in the repo + * Check if the cached native capabilities were properly stored in the repo */ @Test public void test029CapabilitiesRepo() throws Exception { @@ -686,14 +686,14 @@ public void test029CapabilitiesRepo() throws Exception { assertNotNull("password native capability not present", capCred.getPassword()); ActivationCapabilityType capAct = CapabilityUtil.getCapability(nativeCapabilitiesList, ActivationCapabilityType.class); - + if (supportsActivation()) { assertNotNull("native activation capability not present", capAct); assertNotNull("native activation status capability not present", capAct.getStatus()); } else { assertNull("native activation capability sneaked in", capAct); } - + TestConnectionCapabilityType capTest = CapabilityUtil.getCapability(nativeCapabilitiesList, TestConnectionCapabilityType.class); assertNotNull("native test capability not present", capTest); @@ -708,9 +708,9 @@ public void test029CapabilitiesRepo() throws Exception { assertNotNull("No repo capabilities caching metadata", repoCapabilitiesCachingMetadataType); assertNotNull("No repo capabilities caching metadata timestamp", repoCapabilitiesCachingMetadataType.getRetrievalTimestamp()); assertNotNull("No repo capabilities caching metadata serial number", repoCapabilitiesCachingMetadataType.getSerialNumber()); - assertEquals("Repo capabilities caching metadata timestamp does not match previously returned value", + assertEquals("Repo capabilities caching metadata timestamp does not match previously returned value", capabilitiesCachingMetadataType.getRetrievalTimestamp(), repoCapabilitiesCachingMetadataType.getRetrievalTimestamp()); - assertEquals("Repo capabilities caching metadata serial does not match previously returned value", + assertEquals("Repo capabilities caching metadata serial does not match previously returned value", capabilitiesCachingMetadataType.getSerialNumber(), repoCapabilitiesCachingMetadataType.getSerialNumber()); assertSteadyResource(); @@ -751,19 +751,19 @@ public void test030ResourceAndConnectorCaching() throws Exception { ResourceSchema resourceSchemaAgain = RefinedResourceSchemaImpl.getResourceSchema(resourceAgain, prismContext); assertNotNull("No resource schema (again)", resourceSchemaAgain); assertTrue("Resource schema was not cached", resourceSchema == resourceSchemaAgain); - + // Check capabilities caching - + CapabilitiesType capabilitiesType = resourceType.getCapabilities(); assertNotNull("No capabilities fetched from provisioning", capabilitiesType); CachingMetadataType capCachingMetadataType = capabilitiesType.getCachingMetadata(); assertNotNull("No capabilities caching metadata fetched from provisioning", capCachingMetadataType); CachingMetadataType capCachingMetadataTypeAgain = resourceTypeAgain.getCapabilities().getCachingMetadata(); - assertEquals("Capabilities caching metadata serial number has changed", capCachingMetadataType.getSerialNumber(), + assertEquals("Capabilities caching metadata serial number has changed", capCachingMetadataType.getSerialNumber(), capCachingMetadataTypeAgain.getSerialNumber()); - assertEquals("Capabilities caching metadata timestamp has changed", capCachingMetadataType.getRetrievalTimestamp(), + assertEquals("Capabilities caching metadata timestamp has changed", capCachingMetadataType.getRetrievalTimestamp(), capCachingMetadataTypeAgain.getRetrievalTimestamp()); - + // Rough test if everything is fine resource.asObjectable().setFetchResult(null); resourceAgain.asObjectable().setFetchResult(null); @@ -785,14 +785,14 @@ public void test030ResourceAndConnectorCaching() throws Exception { configuredConnectorInstanceAgain.test(testResult); testResult.computeStatus(); TestUtil.assertSuccess("Connector test failed", testResult); - + // Test connection should also refresh the connector by itself. So check if it has been refreshed - + ConnectorInstance configuredConnectorInstanceAfterTest = resourceManager.getConfiguredConnectorInstance( resourceAgain, ReadCapabilityType.class, false, result); assertNotNull("No configuredConnectorInstance (again)", configuredConnectorInstanceAfterTest); assertTrue("Connector instance was not cached", configuredConnectorInstanceAgain == configuredConnectorInstanceAfterTest); - + assertSteadyResource(); } @@ -845,14 +845,14 @@ public void test031ResourceAndConnectorCachingForceFresh() throws Exception { configuredConnectorInstanceAgain.test(testResult); testResult.computeStatus(); TestUtil.assertSuccess("Connector test failed", testResult); - + assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 1); rememberConnectorInstance(configuredConnectorInstanceAgain); - + assertSteadyResource(); } - + @Test public void test040ApplyDefinitionShadow() throws Exception { final String TEST_NAME = "test040ApplyDefinitionShadow"; @@ -875,7 +875,7 @@ public void test040ApplyDefinitionShadow() throws Exception { account.checkConsistence(true, true); ShadowUtil.checkConsistence(account, TEST_NAME); TestUtil.assertSuccess("applyDefinition(account) result", result); - + assertSteadyResource(); } @@ -902,10 +902,10 @@ public void test041ApplyDefinitionAddShadowDelta() throws Exception { delta.checkConsistence(true, true, true); TestUtil.assertSuccess("applyDefinition(add delta) result", result); - + assertSteadyResource(); } - + @Test public void test042ApplyDefinitionResource() throws Exception { final String TEST_NAME = "test042ApplyDefinitionResource"; @@ -932,10 +932,10 @@ public void test042ApplyDefinitionResource() throws Exception { resource.checkConsistence(true, true); TestUtil.assertSuccess("applyDefinition(resource) result", result); - + assertSteadyResource(); } - + @Test public void test043ApplyDefinitionAddResourceDelta() throws Exception { final String TEST_NAME = "test043ApplyDefinitionAddResourceDelta"; @@ -963,22 +963,22 @@ public void test043ApplyDefinitionAddResourceDelta() throws Exception { delta.checkConsistence(true, true, true); TestUtil.assertSuccess("applyDefinition(add delta) result", result); - + assertSteadyResource(); } - + @Test public void test050SelfTest() throws Exception { final String TEST_NAME = "test050SelfTest"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult testResult = new OperationResult(AbstractBasicDummyTest.class + "." + TEST_NAME); - + // WHEN provisioningService.provisioningSelfTest(testResult, task); - + // THEN testResult.computeStatus(); IntegrationTestTools.display(testResult); @@ -1001,10 +1001,10 @@ public void test080TestAttributesToReturn() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(); OperationResult result = task.getResult(); - + ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, ShadowKindType.ENTITLEMENT, RESOURCE_DUMMY_INTENT_GROUP); ProvisioningContext ctx = provisioningContextFactory.create(coords, task, result); - + // WHEN AttributesToReturn attributesToReturn = ProvisioningUtil.createAttributesToReturn(ctx); @@ -1020,7 +1020,7 @@ public void test080TestAttributesToReturn() throws Exception { assertSteadyResource(); } - + @Test public void test090ConnectorStatsAfterSomeUse() throws Exception { final String TEST_NAME = "test090ConnectorStatsAfterSomeUse"; @@ -1040,7 +1040,7 @@ public void test090ConnectorStatsAfterSomeUse() throws Exception { assertNotNull("null operational status", operationalStatuses); assertEquals("Unexpected size of operational status", 1, operationalStatuses.size()); ConnectorOperationalStatus operationalStatus = operationalStatuses.get(0); - + assertEquals("Wrong connectorClassName", DummyConnector.class.getName(), operationalStatus.getConnectorClassName()); assertEquals("Wrong poolConfigMinSize", null, operationalStatus.getPoolConfigMinSize()); assertEquals("Wrong poolConfigMaxSize", (Integer)10, operationalStatus.getPoolConfigMaxSize()); @@ -1050,7 +1050,7 @@ public void test090ConnectorStatsAfterSomeUse() throws Exception { assertEquals("Wrong poolConfigMinEvictableIdleTime", (Long)120000L, operationalStatus.getPoolConfigMinEvictableIdleTime()); assertEquals("Wrong poolStatusNumIdle", (Integer)1, operationalStatus.getPoolStatusNumIdle()); assertEquals("Wrong poolStatusNumActive", (Integer)0, operationalStatus.getPoolStatusNumActive()); - + assertSteadyResource(); } @@ -1068,7 +1068,7 @@ public void test100AddAccountWill() throws Exception { account.checkConsistence(); display("Adding shadow", account); - + XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); // WHEN @@ -1078,9 +1078,9 @@ public void test100AddAccountWill() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); - + assertEquals(ACCOUNT_WILL_OID, addedObjectOid); account.checkConsistence(); @@ -1088,11 +1088,11 @@ public void test100AddAccountWill() throws Exception { PrismObject accountRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); // Added account is slightly different case. Even not-returned-by-default attributes are stored in the cache. checkRepoAccountShadowWill(accountRepo, start, end); - + willIcfUid = getIcfUid(accountRepo); display("Will ICF UID", willIcfUid); assertNotNull("No will ICF UID", willIcfUid); - + ActivationType activationRepo = accountRepo.asObjectable().getActivation(); if (supportsActivation()) { assertNotNull("No activation in "+accountRepo+" (repo)", activationRepo); @@ -1100,14 +1100,14 @@ public void test100AddAccountWill() throws Exception { } else { assertNull("Activation sneaked in (repo)", activationRepo); } - + syncServiceMock.assertNotifySuccessOnly(); PrismObject accountProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + XMLGregorianCalendar tsAfterRead = clock.currentTimeXMLGregorianCalendar(); - + display("Account provisioning", accountProvisioning); ShadowType accountTypeProvisioning = accountProvisioning.asObjectable(); display("account from provisioning", accountTypeProvisioning); @@ -1115,13 +1115,13 @@ public void test100AddAccountWill() throws Exception { assertEquals("Wrong kind (provisioning)", ShadowKindType.ACCOUNT, accountTypeProvisioning.getKind()); assertAttribute(accountProvisioning, SchemaConstants.ICFS_NAME, transformNameFromResource(ACCOUNT_WILL_USERNAME)); assertAttribute(accountProvisioning, getUidMatchingRule(), SchemaConstants.ICFS_UID, willIcfUid); - + ActivationType activationProvisioning = accountTypeProvisioning.getActivation(); if (supportsActivation()) { assertNotNull("No activation in "+accountProvisioning+" (provisioning)", activationProvisioning); - assertEquals("Wrong activation administrativeStatus in "+accountProvisioning+" (provisioning)", + assertEquals("Wrong activation administrativeStatus in "+accountProvisioning+" (provisioning)", ActivationStatusType.ENABLED, activationProvisioning.getAdministrativeStatus()); - TestUtil.assertEqualsTimestamp("Wrong activation enableTimestamp in "+accountProvisioning+" (provisioning)", + TestUtil.assertEqualsTimestamp("Wrong activation enableTimestamp in "+accountProvisioning+" (provisioning)", ACCOUNT_WILL_ENABLE_TIMESTAMP, activationProvisioning.getEnableTimestamp()); } else { assertNull("Activation sneaked in (provisioning)", activationProvisioning); @@ -1146,9 +1146,9 @@ public void test100AddAccountWill() throws Exception { display("Repository shadow", shadowFromRepo.debugDump()); checkRepoAccountShadow(shadowFromRepo); - + checkRepoAccountShadowWill(shadowFromRepo, end, tsAfterRead); - + // MID-3860 assertShadowPasswordMetadata(shadowFromRepo, true, start, end, null, null); assertNoShadowPassword(shadowFromRepo); @@ -1159,7 +1159,7 @@ public void test100AddAccountWill() throws Exception { assertSteadyResource(); } - protected void checkRepoAccountShadowWillBasic(PrismObject accountRepo, + protected void checkRepoAccountShadowWillBasic(PrismObject accountRepo, XMLGregorianCalendar start, XMLGregorianCalendar end, Integer expectedNumberOfAttributes) { display("Will account repo", accountRepo); ShadowType accountTypeRepo = accountRepo.asObjectable(); @@ -1169,12 +1169,12 @@ protected void checkRepoAccountShadowWillBasic(PrismObject accountRe if (isIcfNameUidSame() && !isProposedShadow(accountRepo)) { assertAttribute(accountRepo, SchemaConstants.ICFS_UID, getWillRepoIcfName()); } - + assertNumberOfAttributes(accountRepo, expectedNumberOfAttributes); - + assertRepoCachingMetadata(accountRepo, start, end); } - + private boolean isProposedShadow(PrismObject shadow) { String lifecycleState = shadow.asObjectable().getLifecycleState(); if (lifecycleState == null) { @@ -1198,11 +1198,11 @@ public void test102GetAccount() throws Exception { OperationResult result = new OperationResult(AbstractBasicDummyTest.class.getName() + "." + TEST_NAME); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); // WHEN - PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, null, + PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, null, result); // THEN @@ -1210,7 +1210,7 @@ public void test102GetAccount() throws Exception { display("getObject result", result); TestUtil.assertSuccess(result); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); display("Retrieved account shadow", shadow); @@ -1222,12 +1222,12 @@ public void test102GetAccount() throws Exception { checkRepoAccountShadowWill(shadowRepo, startTs, endTs); checkConsistency(shadow); - + assertCachingMetadata(shadow, false, startTs, endTs); - + // MID-3860 assertShadowPasswordMetadata(shadow, true, lastPasswordModifyStart, lastPasswordModifyEnd, null, null); - + assertSteadyResource(); } @@ -1243,11 +1243,11 @@ public void test103GetAccountNoFetch() throws Exception { GetOperationOptions rootOptions = new GetOperationOptions(); rootOptions.setNoFetch(true); Collection> options = SelectorOptions.createCollection(rootOptions); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); // WHEN - PrismObject shadow = provisioningService.getObject(ShadowType.class, + PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, options, null, result); // THEN @@ -1266,7 +1266,7 @@ public void test103GetAccountNoFetch() throws Exception { checkRepoAccountShadowWill(shadow, null, startTs); checkConsistency(shadow); - + assertSteadyResource(); } @@ -1294,10 +1294,10 @@ public void test105ApplyDefinitionModifyDelta() throws Exception { accountDelta.checkConsistence(true, true, true); TestUtil.assertSuccess("applyDefinition(modify delta) result", result); - + assertSteadyResource(); } - + /** * Make a native modification to an account and read it again. Make sure that * fresh data are returned - even though caching may be in effect. @@ -1310,12 +1310,12 @@ public void test106GetModifiedAccount() throws Exception { // GIVEN OperationResult result = new OperationResult(AbstractBasicDummyTest.class.getName() + "." + TEST_NAME); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + DummyAccount accountWill = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); accountWill.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Pirate"); accountWill.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "Black Pearl"); accountWill.setEnabled(false); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); // WHEN @@ -1328,7 +1328,7 @@ public void test106GetModifiedAccount() throws Exception { display("getObject result", result); TestUtil.assertSuccess(result); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); display("Retrieved account shadow", shadow); @@ -1341,10 +1341,10 @@ public void test106GetModifiedAccount() throws Exception { assertAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOOT_NAME, 42); Collection> attributes = ShadowUtil.getAttributes(shadow); assertEquals("Unexpected number of attributes", 7, attributes.size()); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); checkRepoAccountShadowWillBasic(shadowRepo, startTs, endTs, null); - + assertRepoShadowCachedAttributeValue(shadowRepo, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Pirate"); assertRepoShadowCachedAttributeValue(shadowRepo, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "Black Pearl"); assertRepoShadowCachedAttributeValue(shadowRepo, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, "sword", "love"); @@ -1352,20 +1352,20 @@ public void test106GetModifiedAccount() throws Exception { assertRepoShadowCacheActivation(shadowRepo, ActivationStatusType.DISABLED); checkConsistency(shadow); - + assertCachingMetadata(shadow, false, startTs, endTs); - + assertSteadyResource(); } - + @Test public void test999Shutdown() throws Exception { final String TEST_NAME = "test999Shutdown"; TestUtil.displayTestTitle(TEST_NAME); - + // WHEN provisioningService.shutdown(); - + // THEN dummyResource.assertNoConnections(); } @@ -1373,7 +1373,7 @@ public void test999Shutdown() throws Exception { protected void checkRepoAccountShadow(PrismObject shadowFromRepo) { ProvisioningTestUtil.checkRepoAccountShadow(shadowFromRepo); } - + protected void checkAccountWill(PrismObject shadow, OperationResult result, XMLGregorianCalendar startTs, XMLGregorianCalendar endTs) throws SchemaException, EncryptionException { checkAccountShadow(shadow, result, true, startTs, endTs); @@ -1383,15 +1383,15 @@ protected void checkAccountWill(PrismObject shadow, OperationResult assertAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOOT_NAME, 42); assertEquals("Unexpected number of attributes", 6, attributes.size()); } - - + + /** * We do not know what the timestamp should be */ protected void assertRepoCachingMetadata(PrismObject shadowRepo) { assertNull("Unexpected caching metadata in "+shadowRepo, shadowRepo.asObjectable().getCachingMetadata()); } - + protected void assertRepoCachingMetadata(PrismObject shadowRepo, XMLGregorianCalendar start, XMLGregorianCalendar end) { assertNull("Unexpected caching metadata in "+shadowRepo, shadowRepo.asObjectable().getCachingMetadata()); } @@ -1399,14 +1399,14 @@ protected void assertRepoCachingMetadata(PrismObject shadowRepo, XML protected void assertCachingMetadata(PrismObject shadow, boolean expectedCached, XMLGregorianCalendar startTs, XMLGregorianCalendar endTs) { assertNull("Unexpected caching metadata in "+shadow, shadow.asObjectable().getCachingMetadata()); } - + protected void checkAccountShadow(PrismObject shadowType, OperationResult parentResult, boolean fullShadow, XMLGregorianCalendar startTs, XMLGregorianCalendar endTs) throws SchemaException { ObjectChecker checker = createShadowChecker(fullShadow); ShadowUtil.checkConsistence(shadowType, parentResult.getOperation()); IntegrationTestTools.checkAccountShadow(shadowType.asObjectable(), resourceType, repositoryService, checker, getUidMatchingRule(), prismContext, parentResult); } - + protected ObjectChecker createShadowChecker(final boolean fullShadow) { return (shadow) -> { String icfName = ShadowUtil.getSingleStringAttributeValue(shadow, @@ -1427,17 +1427,17 @@ protected ObjectChecker createShadowChecker(final boolean fullShadow assertEquals("not enabled", ActivationStatusType.ENABLED, shadow.getActivation().getAdministrativeStatus()); } } - + assertProvisioningAccountShadow(shadow.asPrismObject(), resourceType, RefinedAttributeDefinition.class); } }; } - + protected void assertRepoShadowCachedAttributeValue(PrismObject shadowRepo, String attrName, T... attrValues) { - PrismAsserts.assertNoItem(shadowRepo, new ItemPath(ShadowType.F_ATTRIBUTES, + PrismAsserts.assertNoItem(shadowRepo, new ItemPath(ShadowType.F_ATTRIBUTES, new QName(ResourceTypeUtil.getResourceNamespace(resource), attrName))); } - + protected void assertRepoShadowCacheActivation(PrismObject shadowRepo, ActivationStatusType expectedAdministrativeStatus) { ActivationType activationType = shadowRepo.asObjectable().getActivation(); if (activationType == null) { 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 063152dee50..8605b2004a0 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 @@ -90,22 +90,22 @@ * */ public abstract class AbstractDummyTest extends AbstractProvisioningIntegrationTest { - + public static final File TEST_DIR_DUMMY = new File("src/test/resources/dummy/"); protected static final File TEST_DIR = TEST_DIR_DUMMY; - + public static final File RESOURCE_DUMMY_FILE = new File(TEST_DIR, "resource-dummy.xml"); public static final String RESOURCE_DUMMY_OID = "ef2bc95b-76e0-59e2-86d6-9999dddddddd"; public static final String RESOURCE_DUMMY_NS = "http://midpoint.evolveum.com/xml/ns/public/resource/instance/ef2bc95b-76e0-59e2-86d6-9999dddddddd"; public static final String RESOURCE_DUMMY_INTENT_GROUP = "group"; - + protected static final String RESOURCE_DUMMY_NONEXISTENT_OID = "ef2bc95b-000-000-000-009900dddddd"; protected static final File ACCOUNT_WILL_FILE = new File(TEST_DIR, "account-will.xml"); protected static final String ACCOUNT_WILL_OID = "c0c010c0-d34d-b44f-f11d-33322212dddd"; protected static final String ACCOUNT_WILL_USERNAME = "Will"; protected static final XMLGregorianCalendar ACCOUNT_WILL_ENABLE_TIMESTAMP = XmlTypeConverter.createXMLGregorianCalendar(2013, 5, 30, 12, 30, 42); - + protected static final File ACCOUNT_ELIZABETH_FILE = new File(TEST_DIR, "account-elizabeth.xml"); protected static final String ACCOUNT_ELIZABETH_OID = "ca42f312-3bc3-11e7-a32d-73a68a0f363b"; protected static final String ACCOUNT_ELIZABETH_USERNAME = "elizabeth"; @@ -119,15 +119,15 @@ public abstract class AbstractDummyTest extends AbstractProvisioningIntegrationT protected static final File ACCOUNT_MORGAN_FILE = new File(TEST_DIR, "account-morgan.xml"); protected static final String ACCOUNT_MORGAN_OID = "c0c010c0-d34d-b44f-f11d-444400008888"; protected static final String ACCOUNT_MORGAN_NAME = "morgan"; - + protected static final File ACCOUNT_LECHUCK_FILE = new File(TEST_DIR, "account-lechuck.xml"); protected static final String ACCOUNT_LECHUCK_OID = "c0c010c0-d34d-b44f-f11d-444400009aa9"; protected static final String ACCOUNT_LECHUCK_NAME = "lechuck"; - + protected static final File GROUP_PIRATES_FILE = new File(TEST_DIR, "group-pirates.xml"); protected static final String GROUP_PIRATES_OID = "c0c010c0-d34d-b44f-f11d-3332eeee0000"; protected static final String GROUP_PIRATES_NAME = "pirates"; - + protected static final File PRIVILEGE_PILLAGE_FILE = new File (TEST_DIR, "privilege-pillage.xml"); protected static final String PRIVILEGE_PILLAGE_OID = "c0c010c0-d34d-b44f-f11d-3332eeff0000"; protected static final String PRIVILEGE_PILLAGE_NAME = "pillage"; @@ -135,7 +135,7 @@ public abstract class AbstractDummyTest extends AbstractProvisioningIntegrationT protected static final File PRIVILEGE_BARGAIN_FILE = new File(TEST_DIR, "privilege-bargain.xml"); protected static final String PRIVILEGE_BARGAIN_OID = "c0c010c0-d34d-b44f-f11d-3332eeff0001"; protected static final String PRIVILEGE_BARGAIN_NAME = "bargain"; - + protected static final String PRIVILEGE_NONSENSE_NAME = "NoNsEnSe"; protected static final File ACCOUNT_SCRIPT_FILE = new File(TEST_DIR, "account-script.xml"); @@ -144,33 +144,33 @@ public abstract class AbstractDummyTest extends AbstractProvisioningIntegrationT protected static final File DISABLE_ACCOUNT_FILE = new File(TEST_DIR, "modify-will-disable.xml"); protected static final File MODIFY_ACCOUNT_FILE = new File(TEST_DIR, "modify-will-fullname.xml"); protected static final File SCRIPTS_FILE = new File(TEST_DIR, "scripts.xml"); - + protected static final String NOT_PRESENT_OID = "deaddead-dead-dead-dead-deaddeaddead"; - + protected static final String OBJECTCLAS_GROUP_LOCAL_NAME = "GroupObjectClass"; protected static final String OBJECTCLAS_PRIVILEGE_LOCAL_NAME = "CustomprivilegeObjectClass"; - + private static final Trace LOGGER = TraceManager.getTrace(AbstractDummyTest.class); protected static final QName ASSOCIATION_GROUP_NAME = new QName(RESOURCE_DUMMY_NS, "group"); protected static final QName ASSOCIATION_PRIV_NAME = new QName(RESOURCE_DUMMY_NS, "priv"); - + protected PrismObject resource; protected ResourceType resourceType; protected static DummyResource dummyResource; protected static DummyResourceContoller dummyResourceCtl; - + // Testing connector discovery @Autowired(required = true) protected ConnectorManager connectorManager; - + // Used to make sure that the connector is cached @Autowired(required = true) protected ResourceManager resourceManager; - + @Autowired(required = true) protected ProvisioningContextFactory provisioningContextFactory; - + // Values used to check if something is unchanged or changed properly private Long lastResourceVersion = null; private ConnectorInstance lastConfiguredConnectorInstance; @@ -207,7 +207,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti } repositoryService.addObject(shadowDaemon, null, initResult); } - + protected void extraDummyResourceInit() throws Exception { // nothing to do here } @@ -216,16 +216,16 @@ protected void setIcfUid(PrismObject shadow, String icfUid) { PrismProperty icfUidAttr = shadow.findProperty(new ItemPath(ShadowType.F_ATTRIBUTES, SchemaConstants.ICFS_UID)); icfUidAttr.setRealValue(icfUid); } - + protected String getIcfUid(ShadowType shadowType) { return getIcfUid(shadowType.asPrismObject()); } - + protected String getIcfUid(PrismObject shadow) { PrismProperty icfUidAttr = shadow.findProperty(new ItemPath(ShadowType.F_ATTRIBUTES, SchemaConstants.ICFS_UID)); return icfUidAttr.getRealValue(); } - + protected String getIcfName(PrismObject shadow) { PrismProperty icfUidAttr = shadow.findProperty(new ItemPath(ShadowType.F_ATTRIBUTES, SchemaConstants.ICFS_NAME)); return icfUidAttr.getRealValue(); @@ -234,19 +234,19 @@ protected String getIcfName(PrismObject shadow) { protected File getResourceDummyFilename() { return RESOURCE_DUMMY_FILE; } - + protected File getAccountWillFile() { return ACCOUNT_WILL_FILE; } - + protected String transformNameFromResource(String origName) { return origName; } - + protected String transformNameToResource(String origName) { return origName; } - + protected boolean supportsActivation() { return true; } @@ -256,41 +256,41 @@ protected void checkConsistency(Collection checkConsistency(shadow); } } - + protected void checkConsistency(PrismObject object) throws SchemaException { OperationResult result = new OperationResult(TestDummyNegative.class.getName() + ".checkConsistency"); - + PrismPropertyDefinition itemDef = ShadowUtil.getAttributesContainer(object).getDefinition().findAttributeDefinition(SchemaConstants.ICFS_NAME); - + LOGGER.info("item definition: {}", itemDef.debugDump()); //TODO: matching rule ObjectQuery query = QueryBuilder.queryFor(ShadowType.class, prismContext) .itemWithDef(itemDef, ShadowType.F_ATTRIBUTES, itemDef.getName()).eq(getWillRepoIcfName()) .build(); - + System.out.println("Looking for shadows of \"" + getWillRepoIcfName() + "\" with filter " + query.debugDump()); display("Looking for shadows of \"" + getWillRepoIcfName() + "\" with filter " + query.debugDump()); - + List> objects = repositoryService.searchObjects(ShadowType.class, query, null, result); - + assertEquals("Wrong number of repo shadows for ICF NAME \"" + getWillRepoIcfName() + "\"", 1, objects.size()); } - + protected void assertAttribute(PrismObject shadow, String attrName, T... expectedValues) { assertAttribute(resource, shadow.asObjectable(), attrName, expectedValues); } - + protected void assertAttribute(PrismObject shadow, QName attrName, T... expectedValues) { assertAttribute(resource, shadow.asObjectable(), attrName, expectedValues); } - + protected void assertAttribute(PrismObject shadow, MatchingRule matchingRule, QName attrName, T... expectedValues) throws SchemaException { assertAttribute(resource, shadow.asObjectable(), matchingRule, attrName, expectedValues); } @@ -298,11 +298,11 @@ protected void assertAttribute(PrismObject shadow, MatchingRule< protected void assertNoAttribute(PrismObject shadow, String attrName) { assertNoAttribute(resource, shadow.asObjectable(), attrName); } - + protected void assertSchemaSanity(ResourceSchema resourceSchema, ResourceType resourceType) throws Exception { dummyResourceCtl.assertDummyResourceSchemaSanityExtended(resourceSchema, resourceType, true); } - + protected DummyAccount getDummyAccount(String icfName, String icfUid) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { // if (isNameUnique()) { if (isIcfNameUidSame()) { @@ -311,7 +311,7 @@ protected DummyAccount getDummyAccount(String icfName, String icfUid) throws Con return dummyResource.getAccountById(icfUid); } } - + protected DummyAccount getDummyAccountAssert(String icfName, String icfUid) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { // if (isNameUnique()) { if (isIcfNameUidSame()) { @@ -323,7 +323,7 @@ protected DummyAccount getDummyAccountAssert(String icfName, String icfUid) thro return account; } } - + protected void assertNoDummyAccount(String icfName, String icfUid) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { DummyAccount account; if (isIcfNameUidSame()) { @@ -333,7 +333,7 @@ protected void assertNoDummyAccount(String icfName, String icfUid) throws Connec } assertNull("Unexpected dummy account with ICF UID "+icfUid+" (name "+icfName+")", account); } - + protected DummyGroup getDummyGroup(String icfName, String icfUid) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { // if (isNameUnique()) { if (isIcfNameUidSame()) { @@ -342,7 +342,7 @@ protected DummyGroup getDummyGroup(String icfName, String icfUid) throws Connect return dummyResource.getGroupById(icfUid); } } - + protected DummyGroup getDummyGroupAssert(String icfName, String icfUid) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { // if (isNameUnique()) { if (isIcfNameUidSame()) { @@ -354,7 +354,7 @@ protected DummyGroup getDummyGroupAssert(String icfName, String icfUid) throws C return group; } } - + protected DummyPrivilege getDummyPrivilege(String icfName, String icfUid) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException { // if (isNameUnique()) { if (isIcfNameUidSame()) { @@ -381,30 +381,30 @@ protected void assertDummyAccountAttributeValues(String accountName, String assertNotNull("No account '"+accountName+"'", dummyAccount); assertDummyAttributeValues(dummyAccount, attributeName, expectedValues); } - + protected void assertDummyAttributeValues(DummyObject object, String attributeName, T... expectedValues) { Set attributeValues = (Set) object.getAttributeValues(attributeName, expectedValues[0].getClass()); assertNotNull("No attribute "+attributeName+" in "+object.getShortTypeName()+" "+object, attributeValues); TestUtil.assertSetEquals("Wroung values of attribute "+attributeName+" in "+object.getShortTypeName()+" "+object, attributeValues, expectedValues); } - + protected void assertNoDummyAttribute(DummyObject object, String attributeName) { Set attributeValues = object.getAttributeValues(attributeName, Object.class); assertNotNull("Unexpected attribute "+attributeName+" in "+object.getShortTypeName()+" "+object+": "+attributeValues, attributeValues); } - + protected String getWillRepoIcfName() { return ACCOUNT_WILL_USERNAME; } - + protected boolean isIcfNameUidSame() { return true; } - + protected boolean isNameUnique() { return true; } - + protected void assertMember(DummyGroup group, String accountId) { IntegrationTestTools.assertGroupMember(group, accountId); } @@ -412,15 +412,15 @@ protected void assertMember(DummyGroup group, String accountId) { protected void assertNoMember(DummyGroup group, String accountId) { IntegrationTestTools.assertNoGroupMember(group, accountId); } - + protected void assertEntitlementGroup(PrismObject account, String entitlementOid) { assertAssociation(account, ASSOCIATION_GROUP_NAME, entitlementOid); } - + protected void assertEntitlementPriv(PrismObject account, String entitlementOid) { assertAssociation(account, ASSOCIATION_PRIV_NAME, entitlementOid); } - + protected void assertVersion(PrismObject object, String expectedVersion) { assertEquals("Wrong version of "+object, expectedVersion, object.asObjectable().getVersion()); } @@ -428,18 +428,18 @@ protected void assertVersion(PrismObject object, Strin protected void rememberResourceVersion(String version) { lastResourceVersion = parseVersion(version); } - + protected void assertResourceVersionIncrement(PrismObject resource, int expectedIncrement) { assertResourceVersionIncrement(resource.getVersion(), expectedIncrement); } - + protected void assertResourceVersionIncrement(String currentVersion, int expectedIncrement) { long currentVersionLong = parseVersion(currentVersion); long actualIncrement = currentVersionLong - lastResourceVersion; assertEquals("Unexpected increment in resource version", (long)expectedIncrement, actualIncrement); lastResourceVersion = currentVersionLong; } - + private long parseVersion(String stringVersion) { if (stringVersion == null) { AssertJUnit.fail("Version is null"); @@ -458,30 +458,30 @@ protected CachingMetadataType getSchemaCachingMetadata(PrismObject assertNotNull("No schema XSD element", resourceXsdSchemaElementAfter); return xmlSchemaTypeAfter.getCachingMetadata(); } - + protected void rememberSchemaMetadata(PrismObject resource) { lastCachingMetadata = getSchemaCachingMetadata(resource); } - + protected void assertSchemaMetadataUnchanged(PrismObject resource) { CachingMetadataType current = getSchemaCachingMetadata(resource); assertEquals("Schema caching metadata changed", lastCachingMetadata, current); } - + protected void rememberResourceSchema(ResourceSchema resourceSchema) { lastResourceSchema = resourceSchema; } - + protected void assertResourceSchemaUnchanged(ResourceSchema currentResourceSchema) { // We really want == there. We want to make sure that this is actually the same instance and that // it was properly cached assertTrue("Resource schema has changed", lastResourceSchema == currentResourceSchema); } - + protected void rememberRefinedResourceSchema(RefinedResourceSchema rResourceSchema) { lastRefinedResourceSchema = rResourceSchema; } - + protected void assertRefinedResourceSchemaUnchanged(RefinedResourceSchema currentRefinedResourceSchema) { // We really want == there. We want to make sure that this is actually the same instance and that // it was properly cached @@ -498,7 +498,7 @@ protected void assertHasSchema(PrismObject resource, String desc) assertNotNull("No schema XSD element in "+desc, resourceXsdSchemaElementAfter); String resourceXml = prismContext.serializeObjectToString(resource, PrismContext.LANG_XML); -// display("Resource XML", resourceXml); +// display("Resource XML", resourceXml); CachingMetadataType cachingMetadata = xmlSchemaTypeAfter.getCachingMetadata(); assertNotNull("No caching metadata in "+desc, cachingMetadata); @@ -515,11 +515,11 @@ protected void rememberConnectorInstance(PrismObject resource) thr + ".rememberConnectorInstance"); rememberConnectorInstance(resourceManager.getConfiguredConnectorInstance(resource, ReadCapabilityType.class, false, result)); } - + protected void rememberConnectorInstance(ConnectorInstance currentConnectorInstance) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException { lastConfiguredConnectorInstance = currentConnectorInstance; } - + protected void assertConnectorInstanceUnchanged(PrismObject resource) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException { OperationResult result = new OperationResult(TestDummyResourceAndSchemaCaching.class.getName() + ".rememberConnectorInstance"); @@ -527,7 +527,7 @@ protected void assertConnectorInstanceUnchanged(PrismObject resour resource, ReadCapabilityType.class, false, result); assertTrue("Connector instance has changed", lastConfiguredConnectorInstance == currentConfiguredConnectorInstance); } - + protected void assertConnectorInstanceChanged(PrismObject resource) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException { OperationResult result = new OperationResult(TestDummyResourceAndSchemaCaching.class.getName() + ".rememberConnectorInstance"); @@ -536,7 +536,7 @@ protected void assertConnectorInstanceChanged(PrismObject resource assertTrue("Connector instance has NOT changed", lastConfiguredConnectorInstance != currentConfiguredConnectorInstance); lastConfiguredConnectorInstance = currentConfiguredConnectorInstance; } - + protected void assertSteadyResource() throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException { assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); @@ -546,7 +546,7 @@ protected void assertSteadyResource() throws ObjectNotFoundException, SchemaExce assertResourceVersionIncrement(resource, 0); assertSchemaMetadataUnchanged(resource); assertConnectorInstanceUnchanged(resource); - + display("Resource cache", InternalMonitor.getResourceCacheStats()); // We do not assert hits, there may be a lot of them assertResourceCacheMissesIncrement(0); 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 58175c27d12..cc07c092c89 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 @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.provisioning.impl.dummy; @@ -123,9 +123,9 @@ /** * The test of Provisioning service on the API level. The test is using dummy * resource for speed and flexibility. - * + * * @author Radovan Semancik - * + * */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext @@ -139,13 +139,13 @@ public class TestDummy extends AbstractBasicDummyTest { protected static final long VALID_FROM_MILLIS = 12322342345435L; protected static final long VALID_TO_MILLIS = 3454564324423L; - + private static final String GROUP_CORSAIRS_NAME = "corsairs"; - + private static final Trace LOGGER = TraceManager.getTrace(TestDummy.class); - + private String drakeAccountOid; - + protected String morganIcfUid; private String williamIcfUid; protected String piratesIcfUid; @@ -157,19 +157,19 @@ public class TestDummy extends AbstractBasicDummyTest { private String corsairsIcfUid; private String corsairsShadowOid; private String meathookAccountOid; - + protected String getMurrayRepoIcfName() { return ACCOUNT_MURRAY_USERNAME; } - + protected String getBlackbeardRepoIcfName() { return BLACKBEARD_USERNAME; } - + protected String getDrakeRepoIcfName() { return DRAKE_USERNAME; } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -177,7 +177,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti } // test000-test100 in the superclasses - + @Test public void test101AddAccountWithoutName() throws Exception { final String TEST_NAME = "test101AddAccountWithoutName"; @@ -206,7 +206,7 @@ public void test101AddAccountWithoutName() throws Exception { .getObject(ShadowType.class, ACCOUNT_MORGAN_OID, null, result).asObjectable(); PrismAsserts.assertEqualsPolyString("Account name was not generated (repository)", ACCOUNT_MORGAN_NAME, accountType.getName()); morganIcfUid = getIcfUid(accountType); - + syncServiceMock.assertNotifySuccessOnly(); displayWhen(TEST_NAME); @@ -236,18 +236,18 @@ public void test101AddAccountWithoutName() throws Exception { checkRepoAccountShadow(shadowFromRepo); checkConsistency(account.asPrismObject()); - + assertSteadyResource(); } - + // test102-test106 in the superclasses - + /** * Make a native modification to an account and read it with max staleness option. * As there is no caching enabled this should throw an error. - * + * * Note: This test is overridden in TestDummyCaching - * + * * MID-3481 */ @Test @@ -257,25 +257,25 @@ public void test107AGetModifiedAccountFromCacheMax() throws Exception { // GIVEN OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + DummyAccount accountWill = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); accountWill.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Nice Pirate"); accountWill.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "Interceptor"); accountWill.setEnabled(true); - Collection> options = + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createMaxStaleness()); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); // WHEN displayWhen(TEST_NAME); - + try { - - ShadowType shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, options, null, + + ShadowType shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, options, null, result).asObjectable(); - + AssertJUnit.fail("Unexpected success"); } catch (ConfigurationException e) { // Caching is disabled, this is expected. @@ -284,10 +284,10 @@ public void test107AGetModifiedAccountFromCacheMax() throws Exception { result.computeStatus(); TestUtil.assertFailure(result); } - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); checkRepoAccountShadowWillBasic(shadowRepo, null, startTs, null); - + assertRepoShadowCachedAttributeValue(shadowRepo, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Pirate"); assertRepoShadowCachedAttributeValue(shadowRepo, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "Black Pearl"); assertRepoShadowCachedAttributeValue(shadowRepo, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, "Sword", "LOVE"); @@ -295,16 +295,16 @@ public void test107AGetModifiedAccountFromCacheMax() throws Exception { assertRepoShadowCacheActivation(shadowRepo, ActivationStatusType.DISABLED); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + assertSteadyResource(); } - + /** * Make a native modification to an account and read it with high staleness option. * In this test there is no caching enabled, so this should return fresh data. - * + * * Note: This test is overridden in TestDummyCaching - * + * * MID-3481 */ @Test @@ -314,21 +314,21 @@ public void test107BGetModifiedAccountFromCacheHighStaleness() throws Exception // GIVEN OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + DummyAccount accountWill = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); accountWill.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Very Nice Pirate"); accountWill.setEnabled(true); - Collection> options = + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createStaleness(1000000L)); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); // WHEN displayWhen(TEST_NAME); - + PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, options, null, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -336,15 +336,15 @@ public void test107BGetModifiedAccountFromCacheHighStaleness() throws Exception TestUtil.assertSuccess(result); assertAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Very Nice Pirate"); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); checkRepoAccountShadowWillBasic(shadowRepo, null, startTs, null); - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); - + assertSteadyResource(); } - + /** * Staleness of one millisecond is too small for the cache to work. * Fresh data should be returned - both in case the cache is enabled and disabled. @@ -357,10 +357,10 @@ public void test108GetAccountLowStaleness() throws Exception { // GIVEN OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - - Collection> options = + + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createStaleness(1L)); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); // WHEN @@ -373,7 +373,7 @@ public void test108GetAccountLowStaleness() throws Exception { display("getObject result", result); TestUtil.assertSuccess(result); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); display("Retrieved account shadow", shadow); @@ -387,22 +387,22 @@ public void test108GetAccountLowStaleness() throws Exception { assertAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOOT_NAME, 42); Collection> attributes = ShadowUtil.getAttributes(shadow); assertEquals("Unexpected number of attributes", 7, attributes.size()); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); checkRepoAccountShadowWillBasic(shadowRepo, startTs, endTs, null); - + assertRepoShadowCachedAttributeValue(shadowRepo, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Very Nice Pirate"); assertRepoShadowCachedAttributeValue(shadowRepo, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "Interceptor"); assertRepoShadowCachedAttributeValue(shadowRepo, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, "sword", "love"); assertRepoShadowCachedAttributeValue(shadowRepo, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOOT_NAME, 42); checkConsistency(shadow); - + assertCachingMetadata(shadow, false, startTs, endTs); - + assertSteadyResource(); } - + /** * Clean up after caching tests so we won't break subsequent tests. * MID-3481 @@ -411,7 +411,7 @@ public void test108GetAccountLowStaleness() throws Exception { public void test109ModifiedAccountCleanup() throws Exception { final String TEST_NAME = "test109ModifiedAccountCleanup"; displayTestTitle(TEST_NAME); - + // GIVEN OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); @@ -421,7 +421,7 @@ public void test109ModifiedAccountCleanup() throws Exception { accountWill.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "Flying Dutchman"); accountWill.replaceAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME); accountWill.setEnabled(true); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); // WHEN @@ -432,7 +432,7 @@ public void test109ModifiedAccountCleanup() throws Exception { display("getObject result", result); TestUtil.assertSuccess(result); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); display("Retrieved account shadow", shadow); @@ -444,9 +444,9 @@ public void test109ModifiedAccountCleanup() throws Exception { checkRepoAccountShadowWill(shadowRepo, startTs, endTs); checkConsistency(shadow); - + assertCachingMetadata(shadow, false, startTs, endTs); - + assertSteadyResource(); } @@ -470,12 +470,12 @@ public void test110SeachIterative() throws Exception { newAccount.setPassword("parrotMonster"); dummyResource.addAccount(newAccount); - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), - SchemaConstants.ACCOUNT_OBJECT_CLASS_LOCAL_NAME), prismContext); + SchemaConstants.ACCOUNT_OBJECT_CLASS_LOCAL_NAME), prismContext); final XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - + final Holder seenMeathookHolder = new Holder(false); final List> foundObjects = new ArrayList>(); ResultHandler handler = new ResultHandler() { @@ -484,7 +484,7 @@ public void test110SeachIterative() throws Exception { public boolean handle(PrismObject object, OperationResult parentResult) { foundObjects.add(object); display("Found", object); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); assertTrue(object.canRepresent(ShadowType.class)); @@ -493,9 +493,9 @@ public boolean handle(PrismObject object, OperationResult parentResu } catch (SchemaException e) { throw new SystemException(e.getMessage(), e); } - + assertCachingMetadata(object, false, startTs, endTs); - + if (object.asObjectable().getName().getOrig().equals("meathook")) { meathookAccountOid = object.getOid(); seenMeathookHolder.setValue(true); @@ -506,17 +506,17 @@ public boolean handle(PrismObject object, OperationResult parentResu throw new SystemException(e.getMessage(), e); } } - + return true; } }; rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN provisioningService.searchObjectsIterative(ShadowType.class, query, null, handler, null, result); // THEN - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); result.computeStatus(); display("searchObjectsIterative result", result); @@ -526,15 +526,15 @@ public boolean handle(PrismObject object, OperationResult parentResu assertEquals(4, foundObjects.size()); checkConsistency(foundObjects); assertProtected(foundObjects, 1); - + PrismObject shadowWillRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); - assertRepoShadowCachedAttributeValue(shadowWillRepo, + assertRepoShadowCachedAttributeValue(shadowWillRepo, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "Flying Dutchman"); checkRepoAccountShadowWill(shadowWillRepo, startTs, endTs); - + PrismObject shadowMeathook = repositoryService.getObject(ShadowType.class, meathookAccountOid, null, result); display("Meathook shadow", shadowMeathook); - assertRepoShadowCachedAttributeValue(shadowMeathook, + assertRepoShadowCachedAttributeValue(shadowMeathook, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, "hook"); assertRepoCachingMetadata(shadowMeathook, startTs, endTs); @@ -545,7 +545,7 @@ public boolean handle(PrismObject object, OperationResult parentResu rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); XMLGregorianCalendar startTs2 = clock.currentTimeXMLGregorianCalendar(); - + // WHEN provisioningService.searchObjectsIterative(ShadowType.class, query, null, handler, null, result); @@ -553,24 +553,24 @@ public boolean handle(PrismObject object, OperationResult parentResu XMLGregorianCalendar endTs2 = clock.currentTimeXMLGregorianCalendar(); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); - + display("Found shadows", foundObjects); - + assertEquals(4, foundObjects.size()); checkConsistency(foundObjects); assertProtected(foundObjects, 1); - + shadowWillRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); checkRepoAccountShadowWill(shadowWillRepo, startTs2, endTs2); - + shadowMeathook = repositoryService.getObject(ShadowType.class, meathookAccountOid, null, result); - assertRepoShadowCachedAttributeValue(shadowMeathook, + assertRepoShadowCachedAttributeValue(shadowMeathook, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, "hook"); assertRepoCachingMetadata(shadowMeathook, startTs2, endTs2); - + assertSteadyResource(); } - + @Test public void test111SeachIterativeNoFetch() throws Exception { final String TEST_NAME = "test111SeachIterativeNoFetch"; @@ -579,10 +579,10 @@ public void test111SeachIterativeNoFetch() throws Exception { OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), SchemaConstants.ACCOUNT_OBJECT_CLASS_LOCAL_NAME), prismContext); - + final XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); final List> foundObjects = new ArrayList>(); @@ -598,21 +598,21 @@ public boolean handle(PrismObject shadow, OperationResult parentResu } catch (SchemaException e) { throw new SystemException(e.getMessage(), e); } - + assertRepoCachingMetadata(shadow, null, startTs); - + if (shadow.asObjectable().getName().getOrig().equals("meathook")) { assertRepoShadowCachedAttributeValue(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "Sea Monkey"); } - + return true; } }; - Collection> options = + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createNoFetch()); - + rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN provisioningService.searchObjectsIterative(ShadowType.class, query, options, handler, null, result); @@ -623,14 +623,14 @@ public boolean handle(PrismObject shadow, OperationResult parentResu assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); display("Found shadows", foundObjects); - + assertEquals(4, foundObjects.size()); checkConsistency(foundObjects); assertProtected(foundObjects, 1); // MID-1640 - + assertSteadyResource(); } - + @Test public void test112SeachIterativeKindIntent() throws Exception { final String TEST_NAME = "test112SeachIterativeKindIntent"; @@ -639,7 +639,7 @@ public void test112SeachIterativeKindIntent() throws Exception { OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); - ObjectQuery query = ObjectQueryUtil.createResourceAndKindIntent(RESOURCE_DUMMY_OID, + ObjectQuery query = ObjectQueryUtil.createResourceAndKindIntent(RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, "default", prismContext); display("query", query); @@ -652,9 +652,9 @@ public boolean handle(PrismObject object, OperationResult parentResu return true; } }; - + rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + // WHEN provisioningService.searchObjectsIterative(ShadowType.class, query, null, handler, null, result); @@ -665,11 +665,11 @@ public boolean handle(PrismObject object, OperationResult parentResu assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); display("Found shadows", foundObjects); - + assertEquals(4, foundObjects.size()); checkConsistency(foundObjects); assertProtected(foundObjects, 1); // MID-1640 - + assertSteadyResource(); } @@ -700,18 +700,18 @@ public void test113SearchAllShadowsInRepository() throws Exception { // WHEN List> allShadows = repositoryService.searchObjects(ShadowType.class, query, null, result); - + // THEN result.computeStatus(); display("searchObjects result", result); TestUtil.assertSuccess(result); - + display("Found " + allShadows.size() + " shadows"); display("Found shadows", allShadows); assertFalse("No shadows found", allShadows.isEmpty()); assertEquals("Wrong number of results", 4, allShadows.size()); - + assertSteadyResource(); } @@ -729,20 +729,20 @@ public void test114SearchAllAccounts() throws Exception { // WHEN List> allShadows = provisioningService.searchObjects(ShadowType.class, query, null, null, result); - + // THEN result.computeStatus(); display("searchObjects result", result); TestUtil.assertSuccess(result); - + display("Found " + allShadows.size() + " shadows"); assertFalse("No shadows found", allShadows.isEmpty()); assertEquals("Wrong number of results", 4, allShadows.size()); - + checkConsistency(allShadows); assertProtected(allShadows, 1); - + assertSteadyResource(); } @@ -758,16 +758,16 @@ public void test115CountAllAccounts() throws Exception { // WHEN Integer count = provisioningService.countObjects(ShadowType.class, query, null, null, result); - + // THEN result.computeStatus(); display("countObjects result", result); TestUtil.assertSuccess(result); - + display("Found " + count + " shadows"); assertEquals("Wrong number of results", null, count); - + assertSteadyResource(); } @@ -782,17 +782,17 @@ public void test116SearchNullQueryResource() throws Exception { // WHEN List> allResources = provisioningService.searchObjects(ResourceType.class, new ObjectQuery(), null, null, result); - + // THEN result.computeStatus(); display("searchObjects result", result); TestUtil.assertSuccess(result); - + display("Found " + allResources.size() + " resources"); assertFalse("No resources found", allResources.isEmpty()); assertEquals("Wrong number of results", 1, allResources.size()); - + assertSteadyResource(); } @@ -805,16 +805,16 @@ public void test117CountNullQueryResource() throws Exception { // WHEN int count = provisioningService.countObjects(ResourceType.class, new ObjectQuery(), null, null, result); - + // THEN result.computeStatus(); display("countObjects result", result); TestUtil.assertSuccess(result); - + display("Counted " + count + " resources"); assertEquals("Wrong count", 1, count); - + assertSteadyResource(); } @@ -834,42 +834,42 @@ public void test118SearchAllAccountsLongStaleness() throws Exception { ObjectQuery query = IntegrationTestTools.createAllShadowsQuery(resourceType, SchemaTestConstants.ICF_ACCOUNT_OBJECT_CLASS_LOCAL_NAME, prismContext); display("All shadows query", query); - + rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - Collection> options = + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createStaleness(1000000L)); - + // WHEN List> allShadows = provisioningService.searchObjects(ShadowType.class, query, options, null, result); - + // THEN result.computeStatus(); display("searchObjects result", result); TestUtil.assertSuccess(result); - + display("Found " + allShadows.size() + " shadows"); assertFalse("No shadows found", allShadows.isEmpty()); assertEquals("Wrong number of results", 4, allShadows.size()); - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); - + checkConsistency(allShadows); assertProtected(allShadows, 1); - + assertSteadyResource(); } - + /** * Search for all accounts with maximum staleness option. * This is supposed to return only cached data. Therefore * repo search is performed. But as caching is * not enabled in this test only errors will be returned. - * + * * Note: This test is overridden in TestDummyCaching - * + * * MID-3481 */ @Test @@ -882,37 +882,37 @@ public void test119SearchAllAccountsMaxStaleness() throws Exception { ObjectQuery query = IntegrationTestTools.createAllShadowsQuery(resourceType, SchemaTestConstants.ICF_ACCOUNT_OBJECT_CLASS_LOCAL_NAME, prismContext); display("All shadows query", query); - + rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - Collection> options = + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createMaxStaleness()); - + // WHEN List> allShadows = provisioningService.searchObjects(ShadowType.class, query, options, null, result); - + // THEN display("searchObjects result", result); result.computeStatus(); TestUtil.assertFailure(result); - + display("Found " + allShadows.size() + " shadows"); assertFalse("No shadows found", allShadows.isEmpty()); assertEquals("Wrong number of results", 4, allShadows.size()); - + for (PrismObject shadow: allShadows) { display("Found shadow (error expected)", shadow); OperationResultType fetchResult = shadow.asObjectable().getFetchResult(); assertNotNull("No fetch result status in "+shadow, fetchResult); assertEquals("Wrong fetch result status in "+shadow, OperationResultStatusType.FATAL_ERROR, fetchResult.getStatus()); } - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); assertProtected(allShadows, 1); - + assertSteadyResource(); } @@ -926,10 +926,10 @@ public void test123ModifyObjectReplace() throws Exception { Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + syncServiceMock.reset(); - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, ACCOUNT_WILL_OID, dummyResourceCtl.getAttributeFullnamePath(), prismContext, "Pirate Will Turner"); display("ObjectDelta", delta); delta.checkConsistence(); @@ -942,13 +942,13 @@ public void test123ModifyObjectReplace() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); assertDummyAccountAttributeValues(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Pirate Will Turner"); - + syncServiceMock.assertNotifySuccessOnly(); - + assertSteadyResource(); } @@ -962,9 +962,9 @@ public void test124ModifyObjectAddPirate() throws Exception { + ".test124ModifyObjectAddPirate"); syncServiceMock.reset(); - ObjectDelta delta = ObjectDelta.createModificationAddProperty(ShadowType.class, - ACCOUNT_WILL_OID, - dummyResourceCtl.getAttributePath(DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME), + ObjectDelta delta = ObjectDelta.createModificationAddProperty(ShadowType.class, + ACCOUNT_WILL_OID, + dummyResourceCtl.getAttributePath(DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME), prismContext, "Pirate"); display("ObjectDelta", delta); delta.checkConsistence(); @@ -977,17 +977,17 @@ public void test124ModifyObjectAddPirate() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); // check if attribute was changed - assertDummyAccountAttributeValues(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid, + assertDummyAccountAttributeValues(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid, DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Pirate"); - + syncServiceMock.assertNotifySuccessOnly(); - + assertSteadyResource(); } - + @Test public void test125ModifyObjectAddCaptain() throws Exception { TestUtil.displayTestTitle("test125ModifyObjectAddCaptain"); @@ -998,8 +998,8 @@ public void test125ModifyObjectAddCaptain() throws Exception { + ".test125ModifyObjectAddCaptain"); syncServiceMock.reset(); - ObjectDelta delta = ObjectDelta.createModificationAddProperty(ShadowType.class, - ACCOUNT_WILL_OID, + ObjectDelta delta = ObjectDelta.createModificationAddProperty(ShadowType.class, + ACCOUNT_WILL_OID, dummyResourceCtl.getAttributePath(DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME), prismContext, "Captain"); display("ObjectDelta", delta); @@ -1013,14 +1013,14 @@ public void test125ModifyObjectAddCaptain() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); // check if attribute was changed - assertDummyAccountAttributeValues(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid, + assertDummyAccountAttributeValues(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid, DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Pirate", "Captain"); - + syncServiceMock.assertNotifySuccessOnly(); - + assertSteadyResource(); } @@ -1034,7 +1034,7 @@ public void test126ModifyObjectDeletePirate() throws Exception { + ".test126ModifyObjectDeletePirate"); syncServiceMock.reset(); - ObjectDelta delta = ObjectDelta.createModificationDeleteProperty(ShadowType.class, + ObjectDelta delta = ObjectDelta.createModificationDeleteProperty(ShadowType.class, ACCOUNT_WILL_OID, dummyResourceCtl.getAttributePath(DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME), prismContext, "Pirate"); display("ObjectDelta", delta); delta.checkConsistence(); @@ -1047,17 +1047,17 @@ public void test126ModifyObjectDeletePirate() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); // check if attribute was changed - assertDummyAccountAttributeValues(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid, + assertDummyAccountAttributeValues(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid, DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Captain"); - + syncServiceMock.assertNotifySuccessOnly(); - + assertSteadyResource(); } - + /** * Try to add the same value that the account attribute already has. Resources that do not tolerate this will fail * unless the mechanism to compensate for this works properly. @@ -1072,7 +1072,7 @@ public void test127ModifyObjectAddCaptainAgain() throws Exception { OperationResult result = task.getResult(); syncServiceMock.reset(); - ObjectDelta delta = ObjectDelta.createModificationAddProperty(ShadowType.class, + ObjectDelta delta = ObjectDelta.createModificationAddProperty(ShadowType.class, ACCOUNT_WILL_OID, dummyResourceCtl.getAttributePath(DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME), prismContext, "Captain"); display("ObjectDelta", delta); delta.checkConsistence(); @@ -1085,17 +1085,17 @@ public void test127ModifyObjectAddCaptainAgain() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); // check if attribute was changed - assertDummyAccountAttributeValues(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid, + assertDummyAccountAttributeValues(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid, DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Captain"); - + syncServiceMock.assertNotifySuccessOnly(); - + assertSteadyResource(); } - + /** * Set a null value to the (native) dummy attribute. The UCF layer should filter that out. */ @@ -1119,13 +1119,13 @@ public void test128NullAttributeValue() throws Exception { result.computeStatus(); display("getObject result", result); TestUtil.assertSuccess(result); - + ResourceAttributeContainer attributesContainer = ShadowUtil.getAttributesContainer(accountWill); ResourceAttribute titleAttribute = attributesContainer.findAttribute(new QName(ResourceTypeUtil.getResourceNamespace(resourceType), DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME)); assertNull("Title attribute sneaked in", titleAttribute); - + accountWill.checkConsistence(); - + assertSteadyResource(); } @@ -1158,7 +1158,7 @@ public void test131AddScript() throws Exception { ShadowType accountType = repositoryService.getObject(ShadowType.class, ACCOUNT_NEW_SCRIPT_OID, null, result).asObjectable(); assertShadowName(accountType, "william"); - + syncServiceMock.assertNotifySuccessOnly(); ShadowType provisioningAccountType = provisioningService.getObject(ShadowType.class, @@ -1173,14 +1173,14 @@ public void test131AddScript() throws Exception { assertEquals("Fullname is wrong", "William Turner", dummyAccount.getAttributeValue("fullname")); assertTrue("The account is not enabled", dummyAccount.isEnabled()); assertEquals("Wrong password", "3lizab3th123", dummyAccount.getPassword()); - + ProvisioningScriptSpec beforeScript = new ProvisioningScriptSpec("In the beginning ..."); beforeScript.addArgSingle("HOMEDIR", "jbond"); ProvisioningScriptSpec afterScript = new ProvisioningScriptSpec("Hello World"); afterScript.addArgSingle("which", "this"); afterScript.addArgSingle("when", "now"); IntegrationTestTools.assertScripts(dummyResource.getScriptHistory(), beforeScript, afterScript); - + assertSteadyResource(); } @@ -1198,14 +1198,14 @@ public void test132ModifyScript() throws Exception { OperationProvisioningScriptsType scriptsType = unmarshallValueFromFile(SCRIPTS_FILE, OperationProvisioningScriptsType.class); display("Provisioning scripts", PrismTestUtil.serializeAnyDataWrapped(scriptsType)); - - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, + + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, ACCOUNT_NEW_SCRIPT_OID, dummyResourceCtl.getAttributeFullnamePath(), prismContext, "Will Turner"); display("ObjectDelta", delta); delta.checkConsistence(); // WHEN - provisioningService.modifyObject(ShadowType.class, ACCOUNT_NEW_SCRIPT_OID, delta.getModifications(), + provisioningService.modifyObject(ShadowType.class, ACCOUNT_NEW_SCRIPT_OID, delta.getModifications(), scriptsType, null, task, result); // THEN @@ -1221,15 +1221,15 @@ public void test132ModifyScript() throws Exception { assertEquals("Fullname is wrong", "Will Turner", dummyAccount.getAttributeValue("fullname")); assertTrue("The account is not enabled", dummyAccount.isEnabled()); assertEquals("Wrong password", "3lizab3th123", dummyAccount.getPassword()); - + ProvisioningScriptSpec beforeScript = new ProvisioningScriptSpec("Where am I?"); ProvisioningScriptSpec afterScript = new ProvisioningScriptSpec("Still here"); afterScript.addArgMulti("status", "dead", "alive"); IntegrationTestTools.assertScripts(dummyResource.getScriptHistory(), beforeScript, afterScript); - + assertSteadyResource(); } - + /** * This test modifies account shadow property that does NOT result in account modification * on resource. The scripts must not be executed. @@ -1247,14 +1247,14 @@ public void test133ModifyScriptNoExec() throws Exception { OperationProvisioningScriptsType scriptsType = unmarshallValueFromFile(SCRIPTS_FILE, OperationProvisioningScriptsType.class); display("Provisioning scripts", PrismTestUtil.serializeAnyDataWrapped(scriptsType)); - - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, + + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, ACCOUNT_NEW_SCRIPT_OID, ShadowType.F_DESCRIPTION, prismContext, "Blah blah"); display("ObjectDelta", delta); delta.checkConsistence(); // WHEN - provisioningService.modifyObject(ShadowType.class, ACCOUNT_NEW_SCRIPT_OID, delta.getModifications(), + provisioningService.modifyObject(ShadowType.class, ACCOUNT_NEW_SCRIPT_OID, delta.getModifications(), scriptsType, null, task, result); // THEN @@ -1270,12 +1270,12 @@ public void test133ModifyScriptNoExec() throws Exception { assertEquals("Fullname is wrong", "Will Turner", dummyAccount.getAttributeValue("fullname")); assertTrue("The account is not enabled", dummyAccount.isEnabled()); assertEquals("Wrong password", "3lizab3th123", dummyAccount.getPassword()); - + IntegrationTestTools.assertScripts(dummyResource.getScriptHistory()); - + assertSteadyResource(); } - + @Test public void test134DeleteScript() throws Exception { final String TEST_NAME = "test134DeleteScript"; @@ -1289,7 +1289,7 @@ public void test134DeleteScript() throws Exception { OperationProvisioningScriptsType scriptsType = unmarshallValueFromFile(SCRIPTS_FILE, OperationProvisioningScriptsType.class); display("Provisioning scripts", PrismTestUtil.serializeAnyDataWrapped(scriptsType)); - + // WHEN provisioningService.deleteObject(ShadowType.class, ACCOUNT_NEW_SCRIPT_OID, null, scriptsType, task, result); @@ -1304,15 +1304,15 @@ public void test134DeleteScript() throws Exception { DummyAccount dummyAccount = getDummyAccount("william", williamIcfUid); assertNull("Dummy account not gone", dummyAccount); - + ProvisioningScriptSpec beforeScript = new ProvisioningScriptSpec("Goodbye World"); beforeScript.addArgMulti("what", "cruel"); ProvisioningScriptSpec afterScript = new ProvisioningScriptSpec("R.I.P."); IntegrationTestTools.assertScripts(dummyResource.getScriptHistory(), beforeScript, afterScript); - + assertSteadyResource(); } - + @Test public void test135ExecuteScript() throws Exception { final String TEST_NAME = "test135ExecuteScript"; @@ -1326,9 +1326,9 @@ public void test135ExecuteScript() throws Exception { OperationProvisioningScriptsType scriptsType = unmarshallValueFromFile(SCRIPTS_FILE, OperationProvisioningScriptsType.class); display("Provisioning scripts", PrismTestUtil.serializeAnyDataWrapped(scriptsType)); - + ProvisioningScriptType script = scriptsType.getScript().get(0); - + // WHEN provisioningService.executeScript(RESOURCE_DUMMY_OID, script, task, result); @@ -1336,14 +1336,14 @@ public void test135ExecuteScript() throws Exception { result.computeStatus(); display("executeScript result", result); TestUtil.assertSuccess("executeScript has failed (result)", result); - + ProvisioningScriptSpec expectedScript = new ProvisioningScriptSpec("Where to go now?"); expectedScript.addArgMulti("direction", "left", "right"); IntegrationTestTools.assertScripts(dummyResource.getScriptHistory(), expectedScript); - + assertSteadyResource(); } - + @Test public void test150DisableAccount() throws Exception { final String TEST_NAME = "test150DisableAccount"; @@ -1353,7 +1353,7 @@ public void test150DisableAccount() throws Exception { Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, + ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result).asObjectable(); assertNotNull(accountType); @@ -1361,7 +1361,7 @@ public void test150DisableAccount() throws Exception { DummyAccount dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); assertTrue(dummyAccount.isEnabled()); - + syncServiceMock.reset(); ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, @@ -1378,17 +1378,17 @@ public void test150DisableAccount() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); // check if activation was changed dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); assertFalse("Dummy account "+transformNameFromResource(ACCOUNT_WILL_USERNAME)+" is enabled, expected disabled", dummyAccount.isEnabled()); - + syncServiceMock.assertNotifySuccessOnly(); - + assertSteadyResource(); } - + @Test public void test151SearchDisabledAccounts() throws Exception { final String TEST_NAME = "test151SearchDisabledAccounts"; @@ -1403,7 +1403,7 @@ public void test151SearchDisabledAccounts() throws Exception { QueryBuilder.queryFor(ShadowType.class, prismContext) .item(ShadowType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS).eq(ActivationStatusType.DISABLED) .buildFilter()); - + syncServiceMock.reset(); // WHEN @@ -1413,15 +1413,15 @@ public void test151SearchDisabledAccounts() throws Exception { result.computeStatus(); display(result); TestUtil.assertSuccess(result); - + assertEquals("Unexpected number of search results", 1, resultList.size()); PrismObject shadow = resultList.get(0); display("Shadow", shadow); assertActivationAdministrativeStatus(shadow, ActivationStatusType.DISABLED); - + assertSteadyResource(); } - + @Test public void test152ActivationStatusUndefinedAccount() throws Exception { final String TEST_NAME = "test152ActivationStatusUndefinedAccount"; @@ -1431,14 +1431,14 @@ public void test152ActivationStatusUndefinedAccount() throws Exception { Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, + ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result).asObjectable(); assertNotNull(accountType); display("Retrieved account shadow", accountType); DummyAccount dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); assertFalse("Account is not disabled", dummyAccount.isEnabled()); - + syncServiceMock.reset(); ObjectDelta delta = ObjectDelta.createModificationDeleteProperty(ShadowType.class, @@ -1457,15 +1457,15 @@ public void test152ActivationStatusUndefinedAccount() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); // check if activation was changed dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); - assertEquals("Wrong dummy account "+transformNameFromResource(ACCOUNT_WILL_USERNAME)+" enabled flag", + assertEquals("Wrong dummy account "+transformNameFromResource(ACCOUNT_WILL_USERNAME)+" enabled flag", null, dummyAccount.isEnabled()); - + syncServiceMock.assertNotifySuccessOnly(); - + assertSteadyResource(); } @@ -1478,14 +1478,14 @@ public void test154EnableAccount() throws Exception { Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, + ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result).asObjectable(); assertNotNull(accountType); display("Retrieved account shadow", accountType); DummyAccount dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); assertEquals("Wrong dummy account enabled flag", null, dummyAccount.isEnabled()); - + syncServiceMock.reset(); ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, @@ -1502,17 +1502,17 @@ public void test154EnableAccount() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); // check if activation was changed dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); assertTrue("Dummy account "+transformNameFromResource(ACCOUNT_WILL_USERNAME)+" is disabled, expected enabled", dummyAccount.isEnabled()); - + syncServiceMock.assertNotifySuccessOnly(); - + assertSteadyResource(); } - + @Test public void test155SearchDisabledAccounts() throws Exception { final String TEST_NAME = "test155SearchDisabledAccounts"; @@ -1537,13 +1537,13 @@ public void test155SearchDisabledAccounts() throws Exception { result.computeStatus(); display(result); TestUtil.assertSuccess(result); - + assertEquals("Unexpected number of search results", 0, resultList.size()); - + assertSteadyResource(); } - - + + @Test public void test156SetValidFrom() throws Exception { final String TEST_NAME = "test156SetValidFrom"; @@ -1553,7 +1553,7 @@ public void test156SetValidFrom() throws Exception { Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, + ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result).asObjectable(); assertNotNull(accountType); @@ -1561,11 +1561,11 @@ public void test156SetValidFrom() throws Exception { DummyAccount dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); assertTrue(dummyAccount.isEnabled()); - + syncServiceMock.reset(); long millis = VALID_FROM_MILLIS; - + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, ACCOUNT_WILL_OID, SchemaConstants.PATH_ACTIVATION_VALID_FROM, prismContext, XmlTypeConverter.createXMLGregorianCalendar(VALID_FROM_MILLIS)); @@ -1579,18 +1579,18 @@ public void test156SetValidFrom() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); // check if activation was changed dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); assertEquals("Wrong account validFrom in account "+transformNameFromResource(ACCOUNT_WILL_USERNAME), new Date(VALID_FROM_MILLIS), dummyAccount.getValidFrom()); assertTrue("Dummy account "+transformNameFromResource(ACCOUNT_WILL_USERNAME)+" is disabled, expected enabled", dummyAccount.isEnabled()); - + syncServiceMock.assertNotifySuccessOnly(); - + assertSteadyResource(); } - + @Test public void test157SetValidTo() throws Exception { final String TEST_NAME = "test157SetValidTo"; @@ -1600,7 +1600,7 @@ public void test157SetValidTo() throws Exception { Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, + ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result).asObjectable(); assertNotNull(accountType); @@ -1608,11 +1608,11 @@ public void test157SetValidTo() throws Exception { DummyAccount dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); assertTrue(dummyAccount.isEnabled()); - + syncServiceMock.reset(); long millis = VALID_TO_MILLIS; - + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, ACCOUNT_WILL_OID, SchemaConstants.PATH_ACTIVATION_VALID_TO, prismContext, XmlTypeConverter.createXMLGregorianCalendar(VALID_TO_MILLIS)); @@ -1626,19 +1626,19 @@ public void test157SetValidTo() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); // check if activation was changed dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); assertEquals("Wrong account validFrom in account "+transformNameFromResource(ACCOUNT_WILL_USERNAME), new Date(VALID_FROM_MILLIS), dummyAccount.getValidFrom()); assertEquals("Wrong account validTo in account "+transformNameFromResource(ACCOUNT_WILL_USERNAME), new Date(VALID_TO_MILLIS), dummyAccount.getValidTo()); assertTrue("Dummy account "+transformNameFromResource(ACCOUNT_WILL_USERNAME)+" is disabled, expected enabled", dummyAccount.isEnabled()); - + syncServiceMock.assertNotifySuccessOnly(); - + assertSteadyResource(); } - + @Test public void test158DeleteValidToValidFrom() throws Exception { final String TEST_NAME = "test158DeleteValidToValidFrom"; @@ -1648,7 +1648,7 @@ public void test158DeleteValidToValidFrom() throws Exception { Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, + ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result).asObjectable(); assertNotNull(accountType); @@ -1656,18 +1656,18 @@ public void test158DeleteValidToValidFrom() throws Exception { DummyAccount dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); assertTrue(dummyAccount.isEnabled()); - + syncServiceMock.reset(); // long millis = VALID_TO_MILLIS; - + ObjectDelta delta = ObjectDelta.createModificationDeleteProperty(ShadowType.class, ACCOUNT_WILL_OID, SchemaConstants.PATH_ACTIVATION_VALID_TO, prismContext, XmlTypeConverter.createXMLGregorianCalendar(VALID_TO_MILLIS)); PrismObjectDefinition def = accountType.asPrismObject().getDefinition(); PropertyDelta validFromDelta = PropertyDelta.createModificationDeleteProperty( - SchemaConstants.PATH_ACTIVATION_VALID_FROM, - def.findPropertyDefinition(SchemaConstants.PATH_ACTIVATION_VALID_FROM), + SchemaConstants.PATH_ACTIVATION_VALID_FROM, + def.findPropertyDefinition(SchemaConstants.PATH_ACTIVATION_VALID_FROM), XmlTypeConverter.createXMLGregorianCalendar(VALID_FROM_MILLIS)); delta.addModification(validFromDelta); delta.checkConsistence(); @@ -1680,19 +1680,19 @@ public void test158DeleteValidToValidFrom() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); // check if activation was changed dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); assertNull("Unexpected account validTo in account "+transformNameFromResource(ACCOUNT_WILL_USERNAME) + ": " + dummyAccount.getValidTo(), dummyAccount.getValidTo()); assertNull("Unexpected account validFrom in account "+transformNameFromResource(ACCOUNT_WILL_USERNAME) + ": " + dummyAccount.getValidFrom(), dummyAccount.getValidFrom()); assertTrue("Dummy account "+transformNameFromResource(ACCOUNT_WILL_USERNAME)+" is disabled, expected enabled", dummyAccount.isEnabled()); - + syncServiceMock.assertNotifySuccessOnly(); - + assertSteadyResource(); } - + @Test public void test159GetLockedoutAccount() throws Exception { final String TEST_NAME = "test159GetLockedoutAccount"; @@ -1700,10 +1700,10 @@ public void test159GetLockedoutAccount() throws Exception { // GIVEN OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); - + DummyAccount dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); dummyAccount.setLockout(true); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); // WHEN @@ -1713,15 +1713,15 @@ public void test159GetLockedoutAccount() throws Exception { result.computeStatus(); display("getObject result", result); TestUtil.assertSuccess(result); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); display("Retrieved account shadow", shadow); assertNotNull("No dummy account", shadow); - + if (supportsActivation()) { - PrismAsserts.assertPropertyValue(shadow, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, + PrismAsserts.assertPropertyValue(shadow, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, LockoutStatusType.LOCKED); } else { PrismAsserts.assertNoItem(shadow, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS); @@ -1730,10 +1730,10 @@ public void test159GetLockedoutAccount() throws Exception { checkAccountWill(shadow, result, startTs, endTs); checkConsistency(shadow); - + assertSteadyResource(); } - + @Test public void test160SearchLockedAccounts() throws Exception { final String TEST_NAME = "test160SearchLockedAccounts"; @@ -1748,7 +1748,7 @@ public void test160SearchLockedAccounts() throws Exception { QueryBuilder.queryFor(ShadowType.class, prismContext) .item(ShadowType.F_ACTIVATION, ActivationType.F_LOCKOUT_STATUS).eq(LockoutStatusType.LOCKED) .buildFilter()); - + syncServiceMock.reset(); // WHEN @@ -1758,15 +1758,15 @@ public void test160SearchLockedAccounts() throws Exception { result.computeStatus(); display(result); TestUtil.assertSuccess(result); - + assertEquals("Unexpected number of search results", 1, resultList.size()); PrismObject shadow = resultList.get(0); display("Shadow", shadow); assertShadowLockout(shadow, LockoutStatusType.LOCKED); - + assertSteadyResource(); } - + @Test public void test162UnlockAccount() throws Exception { final String TEST_NAME = "test162UnlockAccount"; @@ -1776,14 +1776,14 @@ public void test162UnlockAccount() throws Exception { Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, + ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result).asObjectable(); assertNotNull(accountType); display("Retrieved account shadow", accountType); DummyAccount dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); assertTrue("Account is not locked", dummyAccount.isLockout()); - + syncServiceMock.reset(); ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, @@ -1802,14 +1802,14 @@ public void test162UnlockAccount() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); // check if activation was changed dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); assertFalse("Dummy account "+transformNameFromResource(ACCOUNT_WILL_USERNAME)+" is locked, expected unlocked", dummyAccount.isLockout()); - + syncServiceMock.assertNotifySuccessOnly(); - + assertSteadyResource(); } @@ -1820,7 +1820,7 @@ public void test163GetAccount() throws Exception { // GIVEN OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); // WHEN @@ -1832,15 +1832,15 @@ public void test163GetAccount() throws Exception { TestUtil.assertSuccess(result); XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - + display("Retrieved account shadow", shadow); assertNotNull("No dummy account", shadow); - + if (supportsActivation()) { - PrismAsserts.assertPropertyValue(shadow, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, + PrismAsserts.assertPropertyValue(shadow, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, ActivationStatusType.ENABLED); - PrismAsserts.assertPropertyValue(shadow, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, + PrismAsserts.assertPropertyValue(shadow, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, LockoutStatusType.NORMAL); } else { PrismAsserts.assertNoItem(shadow, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS); @@ -1850,10 +1850,10 @@ public void test163GetAccount() throws Exception { checkAccountWill(shadow, result, startTs, endTs); checkConsistency(shadow); - + assertSteadyResource(); } - + @Test public void test163SearchLockedAccounts() throws Exception { final String TEST_NAME = "test163SearchLockedAccounts"; @@ -1868,7 +1868,7 @@ public void test163SearchLockedAccounts() throws Exception { QueryBuilder.queryFor(ShadowType.class, prismContext) .item(ShadowType.F_ACTIVATION, ActivationType.F_LOCKOUT_STATUS).eq(LockoutStatusType.LOCKED) .buildFilter()); - + syncServiceMock.reset(); // WHEN @@ -1878,12 +1878,12 @@ public void test163SearchLockedAccounts() throws Exception { result.computeStatus(); display(result); TestUtil.assertSuccess(result); - + assertEquals("Unexpected number of search results", 0, resultList.size()); - + assertSteadyResource(); } - + @Test public void test170SearchNull() throws Exception { final String TEST_NAME = "test170SearchNull"; @@ -1891,31 +1891,31 @@ public void test170SearchNull() throws Exception { testSeachIterative(TEST_NAME, null, null, true, true, false, "meathook", "daemon", transformNameFromResource("morgan"), transformNameFromResource("Will")); } - + @Test public void test171SearchShipSeaMonkey() throws Exception { final String TEST_NAME = "test171SearchShipSeaMonkey"; displayTestTitle(TEST_NAME); - testSeachIterativeSingleAttrFilter(TEST_NAME, + testSeachIterativeSingleAttrFilter(TEST_NAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "Sea Monkey", null, true, "meathook"); } - + // See MID-1460 @Test(enabled=false) public void test172SearchShipNull() throws Exception { final String TEST_NAME = "test172SearchShipNull"; displayTestTitle(TEST_NAME); - testSeachIterativeSingleAttrFilter(TEST_NAME, + testSeachIterativeSingleAttrFilter(TEST_NAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, null, null, true, "daemon", "Will"); } - + @Test public void test173SearchWeaponCutlass() throws Exception { final String TEST_NAME = "test173SearchWeaponCutlass"; displayTestTitle(TEST_NAME); - + // Make sure there is an account on resource that the provisioning has // never seen before, so there is no shadow // for it yet. @@ -1927,12 +1927,12 @@ public void test173SearchWeaponCutlass() throws Exception { dummyResource.addAccount(newAccount); IntegrationTestTools.display("dummy", dummyResource.debugDump()); - - testSeachIterativeSingleAttrFilter(TEST_NAME, + + testSeachIterativeSingleAttrFilter(TEST_NAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, "cutlass", null, true, transformNameFromResource("morgan"), "carla"); } - + @Test public void test175SearchUidExact() throws Exception { final String TEST_NAME = "test175SearchUidExact"; @@ -1943,7 +1943,7 @@ public void test175SearchUidExact() throws Exception { transformNameFromResource("Will")); dummyResource.setDisableNameHintChecks(false); } - + @Test public void test176SearchUidExactNoFetch() throws Exception { final String TEST_NAME = "test176SearchUidExactNoFetch"; @@ -1961,7 +1961,7 @@ public void test177SearchIcfNameRepoized() throws Exception { SchemaConstants.ICFS_NAME, getWillRepoIcfName(), null, true, transformNameFromResource(ACCOUNT_WILL_USERNAME)); } - + @Test public void test180SearchIcfNameRepoizedNoFetch() throws Exception { final String TEST_NAME = "test180SearchIcfNameRepoizedNoFetch"; @@ -1979,7 +1979,7 @@ public void test181SearchIcfNameExact() throws Exception { SchemaConstants.ICFS_NAME, transformNameFromResource(ACCOUNT_WILL_USERNAME), null, true, transformNameFromResource(ACCOUNT_WILL_USERNAME)); } - + @Test public void test182SearchIcfNameExactNoFetch() throws Exception { final String TEST_NAME = "test182SearchIcfNameExactNoFetch"; @@ -2000,7 +2000,7 @@ public void test183SearchIcfNameAndUidExactNoFetch() throws Exception { transformNameFromResource(ACCOUNT_WILL_USERNAME)); } - + @Test public void test190SearchNone() throws Exception { final String TEST_NAME = "test190SearchNone"; @@ -2008,7 +2008,7 @@ public void test190SearchNone() throws Exception { ObjectFilter attrFilter = NoneFilter.createNone(); testSeachIterative(TEST_NAME, attrFilter, null, true, true, false); } - + /** * Search with query that queries both the repository and the resource. * We cannot do this. This should fail. @@ -2018,13 +2018,13 @@ public void test190SearchNone() throws Exception { public void test195SearchOnAndOffResource() throws Exception { final String TEST_NAME = "test195SearchOnAndOffResource"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = createOnOffQuery(); - + ResultHandler handler = new ResultHandler() { @Override public boolean handle(PrismObject object, OperationResult parentResult) { @@ -2032,25 +2032,25 @@ public boolean handle(PrismObject object, OperationResult parentResu return false; } }; - + try { // WHEN - provisioningService.searchObjectsIterative(ShadowType.class, query, + provisioningService.searchObjectsIterative(ShadowType.class, query, null, handler, task, result); - + AssertJUnit.fail("unexpected success"); - + } catch (SchemaException e) { // This is expected display("Expected exception", e); } - + // THEN result.computeStatus(); TestUtil.assertFailure(result); - + } - + /** * Search with query that queries both the repository and the resource. * NoFetch. This should go OK. @@ -2060,13 +2060,13 @@ public boolean handle(PrismObject object, OperationResult parentResu public void test196SearchOnAndOffResourceNoFetch() throws Exception { final String TEST_NAME = "test196SearchOnAndOffResourceNoFetch"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = createOnOffQuery(); - + ResultHandler handler = new ResultHandler() { @Override public boolean handle(PrismObject object, OperationResult parentResult) { @@ -2074,16 +2074,16 @@ public boolean handle(PrismObject object, OperationResult parentResu return false; } }; - + // WHEN - provisioningService.searchObjectsIterative(ShadowType.class, query, + provisioningService.searchObjectsIterative(ShadowType.class, query, SelectorOptions.createCollection(GetOperationOptions.createNoFetch()), handler, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + } private ObjectQuery createOnOffQuery() throws SchemaException { @@ -2104,11 +2104,11 @@ private ObjectQuery createOnOffQuery() throws SchemaException { protected void testSeachIterativeSingleAttrFilter(final String TEST_NAME, String attrName, T attrVal, GetOperationOptions rootOptions, boolean fullShadow, String... expectedAccountIds) throws Exception { - testSeachIterativeSingleAttrFilter(TEST_NAME, dummyResourceCtl.getAttributeQName(attrName), attrVal, + testSeachIterativeSingleAttrFilter(TEST_NAME, dummyResourceCtl.getAttributeQName(attrName), attrVal, rootOptions, fullShadow, expectedAccountIds); } - - protected void testSeachIterativeSingleAttrFilter(final String TEST_NAME, QName attrQName, T attrVal, + + protected void testSeachIterativeSingleAttrFilter(final String TEST_NAME, QName attrQName, T attrVal, GetOperationOptions rootOptions, boolean fullShadow, String... expectedAccountNames) throws Exception { ResourceSchema resourceSchema = RefinedResourceSchemaImpl.getResourceSchema(resource, prismContext); ObjectClassComplexTypeDefinition objectClassDef = resourceSchema.findObjectClassDefinition(SchemaTestConstants.ACCOUNT_OBJECT_CLASS_LOCAL_NAME); @@ -2153,10 +2153,10 @@ private void testSeachIterative(final String TEST_NAME, ObjectFilter attrFilter, query.setFilter(AndFilter.createAnd(query.getFilter(), attrFilter)); } } - + display("Query", query); - + final XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); final List> foundObjects = new ArrayList>(); @@ -2167,7 +2167,7 @@ public boolean handle(PrismObject shadow, OperationResult parentResu foundObjects.add(shadow); XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - + assertTrue(shadow.canRepresent(ShadowType.class)); if (!useRepo) { try { @@ -2181,8 +2181,8 @@ public boolean handle(PrismObject shadow, OperationResult parentResu }; Collection> options = SelectorOptions.createCollection(rootOptions); - - + + // WHEN if (useRepo) { repositoryService.searchObjectsIterative(ShadowType.class, query, handler, null, false, result); @@ -2194,7 +2194,7 @@ public boolean handle(PrismObject shadow, OperationResult parentResu result.computeStatus(); display("searchObjectsIterative result", result); TestUtil.assertSuccess(result); - + display("found shadows", foundObjects); for (String expectedAccountId: expectedAccountNames) { @@ -2209,14 +2209,14 @@ public boolean handle(PrismObject shadow, OperationResult parentResu AssertJUnit.fail("Account "+expectedAccountId+" was expected to be found but it was not found (found "+foundObjects.size()+", expected "+expectedAccountNames.length+")"); } } - + assertEquals("Wrong number of found objects ("+foundObjects+"): "+foundObjects, expectedAccountNames.length, foundObjects.size()); if (!useRepo) { checkConsistency(foundObjects); } assertSteadyResource(); } - + @Test public void test200AddGroup() throws Exception { final String TEST_NAME = "test200AddGroup"; @@ -2228,7 +2228,7 @@ public void test200AddGroup() throws Exception { PrismObject group = prismContext.parseObject(GROUP_PIRATES_FILE); group.checkConsistence(); - + rememberDummyResourceGroupMembersReadCount(null); display("Adding group", group); @@ -2250,7 +2250,7 @@ public void test200AddGroup() throws Exception { display("group from repo", groupRepoType); PrismAsserts.assertEqualsPolyString("Name not equal.", GROUP_PIRATES_NAME, groupRepoType.getName()); assertEquals("Wrong kind (repo)", ShadowKindType.ENTITLEMENT, groupRepoType.getKind()); - + syncServiceMock.assertNotifySuccessOnly(); assertDummyResourceGroupMembersReadCountIncrement(null, 0); @@ -2258,7 +2258,7 @@ public void test200AddGroup() throws Exception { display("group from provisioning", groupProvisioning); checkGroupPirates(groupProvisioning, result); piratesIcfUid = getIcfUid(groupRepoType); - + assertDummyResourceGroupMembersReadCountIncrement(null, 0); // Check if the group was created in the dummy resource @@ -2291,7 +2291,7 @@ public void test202GetGroup() throws Exception { + "." + TEST_NAME); rememberDummyResourceGroupMembersReadCount(null); - + // WHEN PrismObject shadow = provisioningService.getObject(ShadowType.class, GROUP_PIRATES_OID, null, null, result); @@ -2303,13 +2303,13 @@ public void test202GetGroup() throws Exception { display("Retrieved group shadow", shadow); assertNotNull("No dummy group", shadow); - + assertDummyResourceGroupMembersReadCountIncrement(null, 0); checkGroupPirates(shadow, result); checkConsistency(shadow); - + assertSteadyResource(); } @@ -2320,7 +2320,7 @@ private void checkGroupPirates(PrismObject shadow, OperationResult r assertAttribute(shadow, DummyResourceContoller.DUMMY_GROUP_ATTRIBUTE_DESCRIPTION, "Scurvy pirates"); Collection> attributes = ShadowUtil.getAttributes(shadow); assertEquals("Unexpected number of attributes", 3, attributes.size()); - + assertNull("The _PASSSWORD_ attribute sneaked into shadow", ShadowUtil.getAttributeValues( shadow, new QName(SchemaConstants.NS_ICF_SCHEMA, "password"))); } @@ -2338,7 +2338,7 @@ public void test203GetGroupNoFetch() throws Exception { Collection> options = SelectorOptions.createCollection(rootOptions); rememberDummyResourceGroupMembersReadCount(null); - + // WHEN PrismObject shadow = provisioningService.getObject(ShadowType.class, GROUP_PIRATES_OID, options, null, result); @@ -2350,16 +2350,16 @@ public void test203GetGroupNoFetch() throws Exception { display("Retrieved group shadow", shadow); assertNotNull("No dummy group", shadow); - + assertDummyResourceGroupMembersReadCountIncrement(null, 0); checkGroupShadow(shadow, result, false); checkConsistency(shadow); - + assertSteadyResource(); } - + @Test public void test205ModifyGroupReplace() throws Exception { final String TEST_NAME = "test205ModifyGroupReplace"; @@ -2368,12 +2368,12 @@ public void test205ModifyGroupReplace() throws Exception { Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + rememberDummyResourceGroupMembersReadCount(null); syncServiceMock.reset(); - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, - GROUP_PIRATES_OID, + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, + GROUP_PIRATES_OID, dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_GROUP_ATTRIBUTE_DESCRIPTION), prismContext, "Bloodthirsty pirates"); display("ObjectDelta", delta); @@ -2387,7 +2387,7 @@ public void test205ModifyGroupReplace() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); DummyGroup group = getDummyGroupAssert(GROUP_PIRATES_NAME, piratesIcfUid); assertDummyAttributeValues(group, DummyResourceContoller.DUMMY_GROUP_ATTRIBUTE_DESCRIPTION, "Bloodthirsty pirates"); @@ -2397,11 +2397,11 @@ public void test205ModifyGroupReplace() throws Exception { } else { assertDummyResourceGroupMembersReadCountIncrement(null, 0); } - + syncServiceMock.assertNotifySuccessOnly(); assertSteadyResource(); } - + @Test public void test210AddPrivilege() throws Exception { final String TEST_NAME = "test210AddPrivilege"; @@ -2431,7 +2431,7 @@ public void test210AddPrivilege() throws Exception { .asObjectable(); PrismAsserts.assertEqualsPolyString("Name not equal.", PRIVILEGE_PILLAGE_NAME, groupRepoType.getName()); assertEquals("Wrong kind (repo)", ShadowKindType.ENTITLEMENT, groupRepoType.getKind()); - + syncServiceMock.assertNotifySuccessOnly(); PrismObject privProvisioning = provisioningService.getObject(ShadowType.class, @@ -2481,10 +2481,10 @@ public void test212GetPriv() throws Exception { checkPrivPillage(shadow, result); checkConsistency(shadow); - + assertSteadyResource(); } - + private void checkPrivPillage(PrismObject shadow, OperationResult result) throws SchemaException { checkEntitlementShadow(shadow, result, OBJECTCLAS_PRIVILEGE_LOCAL_NAME, true); assertShadowName(shadow, PRIVILEGE_PILLAGE_NAME); @@ -2492,7 +2492,7 @@ private void checkPrivPillage(PrismObject shadow, OperationResult re Collection> attributes = ShadowUtil.getAttributes(shadow); assertEquals("Unexpected number of attributes", 3, attributes.size()); assertAttribute(shadow, DummyResourceContoller.DUMMY_PRIVILEGE_ATTRIBUTE_POWER, 100); - + assertNull("The _PASSSWORD_ attribute sneaked into shadow", ShadowUtil.getAttributeValues( shadow, new QName(SchemaConstants.NS_ICF_SCHEMA, "password"))); } @@ -2508,7 +2508,7 @@ public void test214AddPrivilegeBargain() throws Exception { PrismObject priv = prismContext.parseObject(PRIVILEGE_BARGAIN_FILE); priv.checkConsistence(); - + rememberDummyResourceGroupMembersReadCount(null); display("Adding priv", priv); @@ -2538,7 +2538,7 @@ public void test214AddPrivilegeBargain() throws Exception { display("priv from provisioning", privProvisioningType); checkPrivBargain(privProvisioningType, result); bargainIcfUid = getIcfUid(privProvisioningType); - + assertDummyResourceGroupMembersReadCountIncrement(null, 0); // Check if the group was created in the dummy resource @@ -2578,11 +2578,11 @@ public void test220EntitleAccountWillPirates() throws Exception { Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + rememberDummyResourceGroupMembersReadCount(null); syncServiceMock.reset(); - ObjectDelta delta = IntegrationTestTools.createEntitleDelta(ACCOUNT_WILL_OID, + ObjectDelta delta = IntegrationTestTools.createEntitleDelta(ACCOUNT_WILL_OID, dummyResourceCtl.getAttributeQName(DummyResourceContoller.DUMMY_ENTITLEMENT_GROUP_NAME), GROUP_PIRATES_OID, prismContext); display("ObjectDelta", delta); @@ -2598,22 +2598,22 @@ public void test220EntitleAccountWillPirates() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); if (isAvoidDuplicateValues()) { assertDummyResourceGroupMembersReadCountIncrement(null, 1); } else { assertDummyResourceGroupMembersReadCountIncrement(null, 0); } - + DummyGroup group = getDummyGroupAssert(GROUP_PIRATES_NAME, piratesIcfUid); assertMember(group, transformNameToResource(ACCOUNT_WILL_USERNAME)); - + syncServiceMock.assertNotifySuccessOnly(); assertDummyResourceGroupMembersReadCountIncrement(null, 0); assertSteadyResource(); } - + /** * Reads the will accounts, checks that the entitlement is there. */ @@ -2625,7 +2625,7 @@ public void test221GetPirateWill() throws Exception { Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + rememberDummyResourceGroupMembersReadCount(null); syncServiceMock.reset(); @@ -2635,21 +2635,21 @@ public void test221GetPirateWill() throws Exception { // THEN result.computeStatus(); display("Account", account); - + display(result); TestUtil.assertSuccess(result); - + assertDummyResourceGroupMembersReadCountIncrement(null, 0); assertEntitlementGroup(account, GROUP_PIRATES_OID); - + // Just make sure nothing has changed DummyGroup group = getDummyGroupAssert(GROUP_PIRATES_NAME, piratesIcfUid); assertMember(group, transformNameToResource(ACCOUNT_WILL_USERNAME)); - + assertDummyResourceGroupMembersReadCountIncrement(null, 0); assertSteadyResource(); } - + @Test public void test222EntitleAccountWillPillage() throws Exception { final String TEST_NAME = "test222EntitleAccountWillPillage"; @@ -2657,11 +2657,11 @@ public void test222EntitleAccountWillPillage() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + rememberDummyResourceGroupMembersReadCount(null); syncServiceMock.reset(); - ObjectDelta delta = IntegrationTestTools.createEntitleDelta(ACCOUNT_WILL_OID, + ObjectDelta delta = IntegrationTestTools.createEntitleDelta(ACCOUNT_WILL_OID, ASSOCIATION_PRIV_NAME, PRIVILEGE_PILLAGE_OID, prismContext); display("ObjectDelta", delta); delta.checkConsistence(); @@ -2674,35 +2674,35 @@ public void test222EntitleAccountWillPillage() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + assertDummyResourceGroupMembersReadCountIncrement(null, 0); - + DummyAccount dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); assertNotNull("Account will is gone!", dummyAccount); Set accountProvileges = dummyAccount.getAttributeValues(DummyAccount.ATTR_PRIVILEGES_NAME, String.class); PrismAsserts.assertSets("account privileges", accountProvileges, PRIVILEGE_PILLAGE_NAME); - + assertDummyResourceGroupMembersReadCountIncrement(null, 0); - + // Make sure that privilege object is still there DummyPrivilege priv = getDummyPrivilegeAssert(PRIVILEGE_PILLAGE_NAME, pillageIcfUid); assertNotNull("Privilege object is gone!", priv); - + delta.checkConsistence(); assertDummyResourceGroupMembersReadCountIncrement(null, 0); - + // Make sure that the groups is still there and will is a member DummyGroup group = getDummyGroupAssert(GROUP_PIRATES_NAME, piratesIcfUid); assertMember(group, transformNameToResource(ACCOUNT_WILL_USERNAME)); - + syncServiceMock.assertNotifySuccessOnly(); assertDummyResourceGroupMembersReadCountIncrement(null, 0); - + PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); display("Shadow after", shadow); assertEntitlementGroup(shadow, GROUP_PIRATES_OID); assertEntitlementPriv(shadow, PRIVILEGE_PILLAGE_OID); - + assertSteadyResource(); } @@ -2748,7 +2748,7 @@ public void test223EntitleAccountWillBargain() throws Exception { assertMember(group, transformNameToResource(ACCOUNT_WILL_USERNAME)); syncServiceMock.assertNotifySuccessOnly(); - + assertSteadyResource(); } @@ -2762,7 +2762,7 @@ public void test224GetPillagingPirateWill() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + rememberDummyResourceGroupMembersReadCount(null); syncServiceMock.reset(); @@ -2772,24 +2772,24 @@ public void test224GetPillagingPirateWill() throws Exception { // THEN result.computeStatus(); display("Account", account); - + display(result); TestUtil.assertSuccess(result); - + assertEntitlementGroup(account, GROUP_PIRATES_OID); assertEntitlementPriv(account, PRIVILEGE_PILLAGE_OID); assertEntitlementPriv(account, PRIVILEGE_BARGAIN_OID); assertDummyResourceGroupMembersReadCountIncrement(null, 0); - + // Just make sure nothing has changed DummyAccount dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); assertNotNull("Account will is gone!", dummyAccount); Set accountProvileges = dummyAccount.getAttributeValues(DummyAccount.ATTR_PRIVILEGES_NAME, String.class); PrismAsserts.assertSets("Wrong account privileges", accountProvileges, PRIVILEGE_PILLAGE_NAME, PRIVILEGE_BARGAIN_NAME); - + assertDummyResourceGroupMembersReadCountIncrement(null, 0); - + // Make sure that privilege object is still there DummyPrivilege priv = getDummyPrivilegeAssert(PRIVILEGE_PILLAGE_NAME, pillageIcfUid); assertNotNull("Privilege object is gone!", priv); @@ -2798,11 +2798,11 @@ public void test224GetPillagingPirateWill() throws Exception { DummyGroup group = getDummyGroupAssert(GROUP_PIRATES_NAME, piratesIcfUid); assertMember(group, transformNameToResource(ACCOUNT_WILL_USERNAME)); - + assertDummyResourceGroupMembersReadCountIncrement(null, 0); assertSteadyResource(); } - + /** * Create a fresh group directly on the resource. So we are sure there is no shadow * for it yet. Add will to this group. Get will account. Make sure that the group is @@ -2816,11 +2816,11 @@ public void test225GetFoolishPirateWill() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + DummyGroup groupFools = new DummyGroup("fools"); dummyResource.addGroup(groupFools); groupFools.addMember(transformNameFromResource(ACCOUNT_WILL_USERNAME)); - + syncServiceMock.reset(); rememberDummyResourceGroupMembersReadCount(null); rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); @@ -2831,23 +2831,23 @@ public void test225GetFoolishPirateWill() throws Exception { // THEN result.computeStatus(); display("Account", account); - + display(result); TestUtil.assertSuccess(result); assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 2); - + assertDummyResourceGroupMembersReadCountIncrement(null, 0); - + PrismObject foolsShadow = findShadowByName(new QName(RESOURCE_DUMMY_NS, OBJECTCLAS_GROUP_LOCAL_NAME), "fools", resource, result); assertNotNull("No shadow for group fools", foolsShadow); - + assertDummyResourceGroupMembersReadCountIncrement(null, 0); - + assertEntitlementGroup(account, GROUP_PIRATES_OID); assertEntitlementGroup(account, foolsShadow.getOid()); assertEntitlementPriv(account, PRIVILEGE_PILLAGE_OID); assertEntitlementPriv(account, PRIVILEGE_BARGAIN_OID); - + assertDummyResourceGroupMembersReadCountIncrement(null, 0); // Just make sure nothing has changed @@ -2855,7 +2855,7 @@ public void test225GetFoolishPirateWill() throws Exception { assertNotNull("Account will is gone!", dummyAccount); Set accountProvileges = dummyAccount.getAttributeValues(DummyAccount.ATTR_PRIVILEGES_NAME, String.class); PrismAsserts.assertSets("Wrong account privileges", accountProvileges, PRIVILEGE_PILLAGE_NAME, PRIVILEGE_BARGAIN_NAME); - + // Make sure that privilege object is still there DummyPrivilege priv = getDummyPrivilegeAssert(PRIVILEGE_PILLAGE_NAME, pillageIcfUid); assertNotNull("Privilege object is gone!", priv); @@ -2863,18 +2863,18 @@ public void test225GetFoolishPirateWill() throws Exception { assertNotNull("Privilege object (bargain) is gone!", priv2); assertDummyResourceGroupMembersReadCountIncrement(null, 0); - + DummyGroup group = getDummyGroupAssert(GROUP_PIRATES_NAME, piratesIcfUid); assertMember(group, transformNameToResource(ACCOUNT_WILL_USERNAME)); - + String foolsIcfUid = getIcfUid(foolsShadow); groupFools = getDummyGroupAssert("fools", foolsIcfUid); assertMember(groupFools, transformNameToResource(ACCOUNT_WILL_USERNAME)); - + assertDummyResourceGroupMembersReadCountIncrement(null, 0); assertSteadyResource(); } - + /** * Make the account point to a privilege that does not exist. * MidPoint should ignore such privilege. @@ -2889,7 +2889,7 @@ public void test226WillNonsensePrivilege() throws Exception { DummyAccount dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); dummyAccount.addAttributeValues(DummyAccount.ATTR_PRIVILEGES_NAME, PRIVILEGE_NONSENSE_NAME); - + syncServiceMock.reset(); // WHEN @@ -2898,32 +2898,32 @@ public void test226WillNonsensePrivilege() throws Exception { // THEN result.computeStatus(); display("Account", shadow); - + display(result); TestUtil.assertSuccess(result); assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 3); - + assertDummyResourceGroupMembersReadCountIncrement(null, 0); - + PrismObject foolsShadow = findShadowByName(new QName(RESOURCE_DUMMY_NS, OBJECTCLAS_GROUP_LOCAL_NAME), "fools", resource, result); assertNotNull("No shadow for group fools", foolsShadow); - + assertDummyResourceGroupMembersReadCountIncrement(null, 0); - + assertEntitlementGroup(shadow, GROUP_PIRATES_OID); assertEntitlementGroup(shadow, foolsShadow.getOid()); assertEntitlementPriv(shadow, PRIVILEGE_PILLAGE_OID); assertEntitlementPriv(shadow, PRIVILEGE_BARGAIN_OID); - + assertDummyResourceGroupMembersReadCountIncrement(null, 0); // Just make sure nothing has changed dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); assertNotNull("Account will is gone!", dummyAccount); Set accountProvileges = dummyAccount.getAttributeValues(DummyAccount.ATTR_PRIVILEGES_NAME, String.class); - PrismAsserts.assertSets("Wrong account privileges", accountProvileges, + PrismAsserts.assertSets("Wrong account privileges", accountProvileges, PRIVILEGE_PILLAGE_NAME, PRIVILEGE_BARGAIN_NAME, PRIVILEGE_NONSENSE_NAME); - + // Make sure that privilege object is still there DummyPrivilege priv = getDummyPrivilegeAssert(PRIVILEGE_PILLAGE_NAME, pillageIcfUid); assertNotNull("Privilege object is gone!", priv); @@ -2931,18 +2931,18 @@ public void test226WillNonsensePrivilege() throws Exception { assertNotNull("Privilege object (bargain) is gone!", priv2); assertDummyResourceGroupMembersReadCountIncrement(null, 0); - + DummyGroup group = getDummyGroupAssert(GROUP_PIRATES_NAME, piratesIcfUid); assertMember(group, transformNameToResource(ACCOUNT_WILL_USERNAME)); - + String foolsIcfUid = getIcfUid(foolsShadow); DummyGroup groupFools = getDummyGroupAssert("fools", foolsIcfUid); assertMember(groupFools, transformNameToResource(ACCOUNT_WILL_USERNAME)); - + assertDummyResourceGroupMembersReadCountIncrement(null, 0); assertSteadyResource(); } - + @Test public void test230DetitleAccountWillPirates() throws Exception { final String TEST_NAME = "test230DetitleAccountWillPirates"; @@ -2950,7 +2950,7 @@ public void test230DetitleAccountWillPirates() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + rememberDummyResourceGroupMembersReadCount(null); syncServiceMock.reset(); @@ -2968,26 +2968,26 @@ public void test230DetitleAccountWillPirates() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); if (isAvoidDuplicateValues()) { assertDummyResourceGroupMembersReadCountIncrement(null, 1); } else { assertDummyResourceGroupMembersReadCountIncrement(null, 0); } - + DummyGroup group = getDummyGroupAssert(GROUP_PIRATES_NAME, piratesIcfUid); assertNoMember(group, getWillRepoIcfName()); - + // Make sure that account is still there and it has the privilege DummyAccount dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); assertNotNull("Account will is gone!", dummyAccount); Set accountProvileges = dummyAccount.getAttributeValues(DummyAccount.ATTR_PRIVILEGES_NAME, String.class); - PrismAsserts.assertSets("Wrong account privileges", accountProvileges, + PrismAsserts.assertSets("Wrong account privileges", accountProvileges, PRIVILEGE_PILLAGE_NAME, PRIVILEGE_BARGAIN_NAME, PRIVILEGE_NONSENSE_NAME); - + assertDummyResourceGroupMembersReadCountIncrement(null, 0); - + // Make sure that privilege object is still there DummyPrivilege priv = getDummyPrivilegeAssert(PRIVILEGE_PILLAGE_NAME, pillageIcfUid); assertNotNull("Privilege object is gone!", priv); @@ -2996,15 +2996,15 @@ public void test230DetitleAccountWillPirates() throws Exception { assertDummyResourceGroupMembersReadCountIncrement(null, 0); syncServiceMock.assertNotifySuccessOnly(); - + PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); display("Shadow after", shadow); assertEntitlementPriv(shadow, PRIVILEGE_PILLAGE_OID); assertEntitlementPriv(shadow, PRIVILEGE_BARGAIN_OID); - + assertSteadyResource(); } - + @Test public void test232DetitleAccountWillPillage() throws Exception { final String TEST_NAME = "test232DetitleAccountWillPillage"; @@ -3012,10 +3012,10 @@ public void test232DetitleAccountWillPillage() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + syncServiceMock.reset(); - ObjectDelta delta = IntegrationTestTools.createDetitleDelta(ACCOUNT_WILL_OID, + ObjectDelta delta = IntegrationTestTools.createDetitleDelta(ACCOUNT_WILL_OID, ASSOCIATION_PRIV_NAME, PRIVILEGE_PILLAGE_OID, prismContext); display("ObjectDelta", delta); delta.checkConsistence(); @@ -3028,29 +3028,29 @@ public void test232DetitleAccountWillPillage() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); DummyGroup group = getDummyGroupAssert(GROUP_PIRATES_NAME, piratesIcfUid); assertNoMember(group, getWillRepoIcfName()); - + // Make sure that account is still there and it has the privilege DummyAccount dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); assertNotNull("Account will is gone!", dummyAccount); Set accountProvileges = dummyAccount.getAttributeValues(DummyAccount.ATTR_PRIVILEGES_NAME, String.class); - PrismAsserts.assertSets("Wrong account privileges", accountProvileges, + PrismAsserts.assertSets("Wrong account privileges", accountProvileges, PRIVILEGE_BARGAIN_NAME, PRIVILEGE_NONSENSE_NAME); - + // Make sure that privilege object is still there DummyPrivilege priv = getDummyPrivilegeAssert(PRIVILEGE_PILLAGE_NAME, pillageIcfUid); assertNotNull("Privilege object is gone!", priv); - + syncServiceMock.assertNotifySuccessOnly(); - + PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); display("Shadow after", shadow); assertEntitlementPriv(shadow, PRIVILEGE_BARGAIN_OID); - + assertSteadyResource(); } @@ -3125,10 +3125,10 @@ public void test260AddAccountLeChuck() throws Exception { assertEquals(ACCOUNT_LECHUCK_OID, addedObjectOid); accountBefore.checkConsistence(); - + PrismObject shadow = provisioningService.getObject(ShadowType.class, addedObjectOid, null, task, result); leChuckIcfUid = getIcfUid(shadow); - + // Check if the account was created in the dummy resource and that it has the entitlements DummyAccount dummyAccount = getDummyAccountAssert(ACCOUNT_LECHUCK_NAME, leChuckIcfUid); @@ -3139,11 +3139,11 @@ public void test260AddAccountLeChuck() throws Exception { Set accountProvileges = dummyAccount.getAttributeValues(DummyAccount.ATTR_PRIVILEGES_NAME, String.class); PrismAsserts.assertSets("account privileges", accountProvileges, PRIVILEGE_PILLAGE_NAME); - + // Make sure that privilege object is still there DummyPrivilege priv = getDummyPrivilegeAssert(PRIVILEGE_PILLAGE_NAME, pillageIcfUid); assertNotNull("Privilege object is gone!", priv); - + DummyGroup group = getDummyGroupAssert(GROUP_PIRATES_NAME, piratesIcfUid); assertMember(group, transformNameFromResource(ACCOUNT_LECHUCK_NAME)); @@ -3156,7 +3156,7 @@ public void test260AddAccountLeChuck() throws Exception { } else { assertAttribute(repoAccount, SchemaConstants.ICFS_UID, dummyAccount.getId()); } - + syncServiceMock.assertNotifySuccessOnly(); PrismObject provisioningAccount = provisioningService.getObject(ShadowType.class, @@ -3170,7 +3170,7 @@ public void test260AddAccountLeChuck() throws Exception { } else { assertAttribute(provisioningAccount, SchemaConstants.ICFS_UID, dummyAccount.getId()); } - + assertEntitlementGroup(provisioningAccount, GROUP_PIRATES_OID); assertEntitlementPriv(provisioningAccount, PRIVILEGE_PILLAGE_OID); @@ -3178,10 +3178,10 @@ public void test260AddAccountLeChuck() throws Exception { provisioningAccount, new QName(SchemaConstants.NS_ICF_SCHEMA, "password"))); checkConsistency(provisioningAccount); - + assertSteadyResource(); } - + /** * LeChuck has both group and priv entitlement. If deleted it should be correctly removed from all * the entitlements. @@ -3203,40 +3203,40 @@ public void test265DeleteAccountLeChuck() throws Exception { display("add object result", result); TestUtil.assertSuccess("addObject has failed (result)", result); syncServiceMock.assertNotifySuccessOnly(); - + // Check if the account is gone and that group membership is gone as well DummyAccount dummyAccount = getDummyAccount(ACCOUNT_LECHUCK_NAME, leChuckIcfUid); assertNull("Dummy account is NOT gone", dummyAccount); - + // Make sure that privilege object is still there DummyPrivilege priv = getDummyPrivilegeAssert(PRIVILEGE_PILLAGE_NAME, pillageIcfUid); assertNotNull("Privilege object is gone!", priv); - + DummyGroup group = getDummyGroupAssert(GROUP_PIRATES_NAME, piratesIcfUid); assertNoMember(group, ACCOUNT_LECHUCK_NAME); try { repositoryService.getObject(ShadowType.class, ACCOUNT_LECHUCK_OID, null, result); - + AssertJUnit.fail("Shadow (repo) is not gone"); } catch (ObjectNotFoundException e) { // This is expected } - + try { provisioningService.getObject(ShadowType.class, ACCOUNT_LECHUCK_OID, null, task, result); - + AssertJUnit.fail("Shadow (provisioning) is not gone"); } catch (ObjectNotFoundException e) { // This is expected } - + assertSteadyResource(); } - + // test28x in TestDummyCaseIgnore - + @Test public void test298DeletePrivPillage() throws Exception { final String TEST_NAME = "test298DeletePrivPillage"; @@ -3244,7 +3244,7 @@ public void test298DeletePrivPillage() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + syncServiceMock.reset(); // WHEN @@ -3254,16 +3254,16 @@ public void test298DeletePrivPillage() throws Exception { result.computeStatus(); display(result); TestUtil.assertSuccess(result); - + syncServiceMock.assertNotifySuccessOnly(); - + try { repositoryService.getObject(ShadowType.class, PRIVILEGE_PILLAGE_OID, null, result); AssertJUnit.fail("Priv shadow is not gone (repo)"); } catch (ObjectNotFoundException e) { // This is expected } - + try { provisioningService.getObject(ShadowType.class, PRIVILEGE_PILLAGE_OID, null, task, result); AssertJUnit.fail("Priv shadow is not gone (provisioning)"); @@ -3273,10 +3273,10 @@ public void test298DeletePrivPillage() throws Exception { DummyPrivilege priv = getDummyPrivilege(PRIVILEGE_PILLAGE_NAME, pillageIcfUid); assertNull("Privilege object NOT is gone", priv); - + assertSteadyResource(); } - + @Test public void test299DeleteGroupPirates() throws Exception { final String TEST_NAME = "test299DeleteGroupPirates"; @@ -3284,7 +3284,7 @@ public void test299DeleteGroupPirates() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + syncServiceMock.reset(); // WHEN @@ -3294,16 +3294,16 @@ public void test299DeleteGroupPirates() throws Exception { result.computeStatus(); display(result); TestUtil.assertSuccess(result); - + syncServiceMock.assertNotifySuccessOnly(); - + try { repositoryService.getObject(ShadowType.class, GROUP_PIRATES_OID, null, result); AssertJUnit.fail("Group shadow is not gone (repo)"); } catch (ObjectNotFoundException e) { // This is expected } - + try { provisioningService.getObject(ShadowType.class, GROUP_PIRATES_OID, null, task, result); AssertJUnit.fail("Group shadow is not gone (provisioning)"); @@ -3313,10 +3313,10 @@ public void test299DeleteGroupPirates() throws Exception { DummyGroup dummyAccount = getDummyGroup(GROUP_PIRATES_NAME, piratesIcfUid); assertNull("Dummy group '"+GROUP_PIRATES_NAME+"' is not gone from dummy resource", dummyAccount); - + assertSteadyResource(); } - + @Test public void test300AccountRename() throws Exception { final String TEST_NAME = "test300AccountRename"; @@ -3324,15 +3324,15 @@ public void test300AccountRename() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + syncServiceMock.reset(); - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, ACCOUNT_MORGAN_OID, SchemaTestConstants.ICFS_NAME_PATH, prismContext, "cptmorgan"); provisioningService.applyDefinition(delta, task, result); display("ObjectDelta", delta); delta.checkConsistence(); - + // WHEN provisioningService.modifyObject(ShadowType.class, delta.getOid(), delta.getModifications(), new OperationProvisioningScriptsType(), null, task, result); @@ -3341,33 +3341,33 @@ public void test300AccountRename() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); PrismObject account = provisioningService.getObject(ShadowType.class, ACCOUNT_MORGAN_OID, null, task, result); Collection> identifiers = ShadowUtil.getPrimaryIdentifiers(account); assertNotNull("Identifiers must not be null", identifiers); assertEquals("Expected one identifier", 1, identifiers.size()); - + ResourceAttribute identifier = identifiers.iterator().next(); - + String shadowUuid = "cptmorgan"; - + assertDummyAccountAttributeValues(shadowUuid, morganIcfUid, DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Captain Morgan"); - + PrismObject repoShadow = repositoryService.getObject(ShadowType.class, ACCOUNT_MORGAN_OID, null, result); assertAccountShadowRepo(repoShadow, ACCOUNT_MORGAN_OID, "cptmorgan", resourceType); - + if (!isIcfNameUidSame()) { shadowUuid = (String) identifier.getRealValue(); } PrismAsserts.assertPropertyValue(repoShadow, SchemaTestConstants.ICFS_UID_PATH, shadowUuid); - + syncServiceMock.assertNotifySuccessOnly(); - + assertSteadyResource(); } - + // test4xx reserved for subclasses @Test @@ -3390,11 +3390,11 @@ public void test501GetProtectedAccountShadow() throws Exception { assertEquals(""+account+" is not protected", Boolean.TRUE, account.asObjectable().isProtectedObject()); checkConsistency(account); - + result.computeStatus(); display("getObject result", result); TestUtil.assertSuccess(result); - + assertSteadyResource(); } @@ -3428,15 +3428,15 @@ public void test502ModifyProtectedAccountShadowAttributes() throws Exception { // This is expected display("Expected exception", e); } - + result.computeStatus(); display("modifyObject result (expected failure)", result); TestUtil.assertFailure(result); - + syncServiceMock.assertNotifyFailureOnly(); // checkConsistency(); - + assertSteadyResource(); } @@ -3463,12 +3463,12 @@ public void test503ModifyProtectedAccountShadowProperty() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + syncServiceMock.assertNotifySuccessOnly(); PrismObject shadowAfter = provisioningService.getObject(ShadowType.class, ACCOUNT_DAEMON_OID, null, task, result); assertEquals("Wrong situation", SynchronizationSituationType.DISPUTED, shadowAfter.asObjectable().getSynchronizationSituation()); - + assertSteadyResource(); } @@ -3489,18 +3489,18 @@ public void test509DeleteProtectedAccountShadow() throws Exception { // This is expected display("Expected exception", e); } - + result.computeStatus(); display("deleteObject result (expected failure)", result); TestUtil.assertFailure(result); - + syncServiceMock.assertNotifyFailureOnly(); // checkConsistency(); - + assertSteadyResource(); } - + @Test public void test510AddProtectedAccounts() throws Exception { final String TEST_NAME = "test510AddProtectedAccounts"; @@ -3513,7 +3513,7 @@ public void test510AddProtectedAccounts() throws Exception { testAddAccount(TEST_NAME, "piXel"); testAddAccount(TEST_NAME, "supernaturalius"); } - + @Test public void test511AddProtectedAccountCaseIgnore() throws Exception { final String TEST_NAME = "test511AddProtectedAccountCaseIgnore"; @@ -3522,7 +3522,7 @@ public void test511AddProtectedAccountCaseIgnore() throws Exception { testAddAccount(TEST_NAME, "xaxa"); testAddAccount(TEST_NAME, "somebody-ADM"); } - + private PrismObject createAccountShadow(String username) throws SchemaException { ResourceSchema resourceSchema = RefinedResourceSchemaImpl.getResourceSchema(resource, prismContext); ObjectClassComplexTypeDefinition defaultAccountDefinition = resourceSchema.findDefaultObjectClassDefinition(ShadowKindType.ACCOUNT); @@ -3539,12 +3539,12 @@ private PrismObject createAccountShadow(String username) throws Sche icfsNameProp.setRealValue(username); return shadow; } - + protected void testAddProtectedAccount(final String TEST_NAME, String username) throws SchemaException, ObjectAlreadyExistsException, CommunicationException, ObjectNotFoundException, ConfigurationException, ExpressionEvaluationException { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); syncServiceMock.reset(); - + PrismObject shadow = createAccountShadow(username); // WHEN @@ -3555,15 +3555,15 @@ protected void testAddProtectedAccount(final String TEST_NAME, String username) // This is expected display("Expected exception", e); } - + result.computeStatus(); display("addObject result (expected failure)", result); TestUtil.assertFailure(result); - + syncServiceMock.assertNotifyFailureOnly(); // checkConsistency(); - + assertSteadyResource(); } @@ -3571,20 +3571,20 @@ private void testAddAccount(final String TEST_NAME, String username) throws Sche Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); syncServiceMock.reset(); - + PrismObject shadow = createAccountShadow(username); // WHEN provisioningService.addObject(shadow, null, null, task, result); - + result.computeStatus(); display("addObject result (expected failure)", result); TestUtil.assertSuccess(result); - + syncServiceMock.assertNotifySuccessOnly(); // checkConsistency(); - + assertSteadyResource(); } @@ -3596,7 +3596,7 @@ public void test600AddAccountAlreadyExist() throws Exception { Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); syncServiceMock.reset(); - + dummyResourceCtl.addAccount(ACCOUNT_MURRAY_USERNAME, ACCOUNT_MURRAY_USERNAME); PrismObject account = createShadowNameOnly(resource, ACCOUNT_MURRAY_USERNAME); @@ -3607,7 +3607,7 @@ public void test600AddAccountAlreadyExist() throws Exception { // WHEN try { provisioningService.addObject(account, null, null, task, result); - + AssertJUnit.fail("Unexpected success"); } catch (ObjectAlreadyExistsException e) { // This is expected @@ -3620,19 +3620,19 @@ public void test600AddAccountAlreadyExist() throws Exception { TestUtil.assertFailure(result); // Even though the operation failed a shadow should be created for the conflicting object - - PrismObject accountRepo = findAccountShadowByUsername(getMurrayRepoIcfName(), resource, result); + + PrismObject accountRepo = findAccountShadowByUsername(getMurrayRepoIcfName(), resource, result); assertNotNull("Shadow was not created in the repository", accountRepo); display("Repository shadow", accountRepo); checkRepoAccountShadow(accountRepo); - + assertEquals("Wrong ICF NAME in murray (repo) shadow", getMurrayRepoIcfName(), getIcfName(accountRepo)); assertSteadyResource(); } - + static Task syncTokenTask = null; - + @Test public void test800LiveSyncInit() throws Exception { final String TEST_NAME = "test800LiveSyncInit"; @@ -3648,9 +3648,9 @@ public void test800LiveSyncInit() throws Exception { // Dry run to remember the current sync token in the task instance. // Otherwise a last sync token whould be used and // no change would be detected - ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, + ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); - + // WHEN displayWhen(TEST_NAME); provisioningService.synchronize(coords, syncTokenTask, result); @@ -3664,7 +3664,7 @@ public void test800LiveSyncInit() throws Exception { syncServiceMock.assertNoNotifyChange(); checkAllShadows(); - + assertSteadyResource(); } @@ -3672,7 +3672,7 @@ public void test800LiveSyncInit() throws Exception { public void test801LiveSyncAddBlackbeard() throws Exception { final String TEST_NAME = "test801LiveSyncAddBlackbeard"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); @@ -3689,9 +3689,9 @@ public void test801LiveSyncAddBlackbeard() throws Exception { display("Resource before sync", dummyResource.debugDump()); - ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, + ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); - + // WHEN displayWhen(TEST_NAME); provisioningService.synchronize(coords, syncTokenTask, result); @@ -3709,7 +3709,7 @@ public void test801LiveSyncAddBlackbeard() throws Exception { PrismObject oldShadow = lastChange.getOldShadow(); assertNotNull("Old shadow missing", oldShadow); assertNotNull("Old shadow does not have an OID", oldShadow.getOid()); - + assertNull("Delta present when not expecting it", lastChange.getObjectDelta()); PrismObject currentShadow = lastChange.getCurrentShadow(); assertNotNull("Current shadow missing", lastChange.getCurrentShadow()); @@ -3721,19 +3721,19 @@ public void test801LiveSyncAddBlackbeard() throws Exception { assertNotNull("No attributes container in current shadow", attributesContainer); Collection> attributes = attributesContainer.getAttributes(); assertFalse("Attributes container is empty", attributes.isEmpty()); - assertAttribute(currentShadow, + assertAttribute(currentShadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Edward Teach"); - assertAttribute(currentShadow, + assertAttribute(currentShadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOOT_NAME, 66666L); assertEquals("Unexpected number of attributes", 4, attributes.size()); - - PrismObject accountRepo = findAccountShadowByUsername(getBlackbeardRepoIcfName(), resource, result); + + PrismObject accountRepo = findAccountShadowByUsername(getBlackbeardRepoIcfName(), resource, result); assertNotNull("Shadow was not created in the repository", accountRepo); display("Repository shadow", accountRepo); checkRepoAccountShadow(accountRepo); checkAllShadows(); - + assertSteadyResource(); } @@ -3752,9 +3752,9 @@ public void test802LiveSyncModifyBlackbeard() throws Exception { display("Resource before sync", dummyResource.debugDump()); - ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, + ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); - + // WHEN displayWhen(TEST_NAME); provisioningService.synchronize(coords, syncTokenTask, result); @@ -3771,7 +3771,7 @@ public void test802LiveSyncModifyBlackbeard() throws Exception { PrismObject oldShadow = lastChange.getOldShadow(); assertSyncOldShadow(oldShadow, getBlackbeardRepoIcfName()); - + assertNull("Delta present when not expecting it", lastChange.getObjectDelta()); PrismObject currentShadow = lastChange.getCurrentShadow(); assertNotNull("Current shadow missing", lastChange.getCurrentShadow()); @@ -3783,27 +3783,27 @@ public void test802LiveSyncModifyBlackbeard() throws Exception { assertNotNull("No attributes container in current shadow", attributesContainer); Collection> attributes = attributesContainer.getAttributes(); assertFalse("Attributes container is empty", attributes.isEmpty()); - assertAttribute(currentShadow, + assertAttribute(currentShadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Captain Blackbeard"); - assertAttribute(currentShadow, + assertAttribute(currentShadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOOT_NAME, 66666L); assertEquals("Unexpected number of attributes", 4, attributes.size()); - PrismObject accountRepo = findAccountShadowByUsername(getBlackbeardRepoIcfName(), resource, result); + PrismObject accountRepo = findAccountShadowByUsername(getBlackbeardRepoIcfName(), resource, result); assertNotNull("Shadow was not created in the repository", accountRepo); display("Repository shadow", accountRepo); checkRepoAccountShadow(accountRepo); - + checkAllShadows(); - + assertSteadyResource(); } - + @Test public void test810LiveSyncAddDrakeDumbObjectClass() throws Exception { testLiveSyncAddDrake("test810LiveSyncAddDrakeDumbObjectClass", DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); } - + @Test public void test812LiveSyncModifyDrakeDumbObjectClass() throws Exception { testLiveSyncModifyDrake("test812LiveSyncModifyDrakeDumbObjectClass", DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); @@ -3813,47 +3813,47 @@ public void test812LiveSyncModifyDrakeDumbObjectClass() throws Exception { public void test815LiveSyncAddCorsairsDumbObjectClass() throws Exception { testLiveSyncAddCorsairs("test815LiveSyncAddCorsairsDumbObjectClass", DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), false); } - + @Test public void test817LiveSyncDeleteCorsairsDumbObjectClass() throws Exception { testLiveSyncDeleteCorsairs("test817LiveSyncDeleteCorsairsDumbObjectClass", DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), false); } - + @Test public void test819LiveSyncDeleteDrakeDumbObjectClass() throws Exception { testLiveSyncDeleteDrake("test819LiveSyncDeleteDrakeDumbObjectClass", DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); } - + @Test public void test820LiveSyncAddDrakeSmartObjectClass() throws Exception { testLiveSyncAddDrake("test820LiveSyncAddDrakeDumbObjectClass", DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); } - + @Test public void test822LiveSyncModifyDrakeSmartObjectClass() throws Exception { testLiveSyncModifyDrake("test822LiveSyncModifyDrakeDumbObjectClass", DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); } - + @Test public void test825LiveSyncAddCorsairsSmartObjectClass() throws Exception { testLiveSyncAddCorsairs("test825LiveSyncAddCorsairsDumbObjectClass", DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), false); } - + @Test public void test827LiveSyncDeleteCorsairsSmartObjectClass() throws Exception { testLiveSyncDeleteCorsairs("test827LiveSyncDeleteCorsairsDumbObjectClass", DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), false); } - + @Test public void test829LiveSyncDeleteDrakeSmartObjectClass() throws Exception { testLiveSyncDeleteDrake("test829LiveSyncDeleteDrakeDumbObjectClass", DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); } - + @Test public void test830LiveSyncAddDrakeDumbAny() throws Exception { testLiveSyncAddDrake("test830LiveSyncAddDrakeDumbAny", DummySyncStyle.DUMB, null); } - + @Test public void test832LiveSyncModifyDrakeDumbAny() throws Exception { testLiveSyncModifyDrake("test832LiveSyncModifyDrakeDumbAny", DummySyncStyle.DUMB, null); @@ -3863,42 +3863,42 @@ public void test832LiveSyncModifyDrakeDumbAny() throws Exception { public void test835LiveSyncAddCorsairsDumbAny() throws Exception { testLiveSyncAddCorsairs("test835LiveSyncAddCorsairsDumbAny", DummySyncStyle.DUMB, null, true); } - + @Test public void test837LiveSyncDeleteCorsairsDumbAny() throws Exception { testLiveSyncDeleteCorsairs("test837LiveSyncDeleteCorsairsDumbAny", DummySyncStyle.DUMB, null, true); } - + @Test public void test839LiveSyncDeleteDrakeDumbAny() throws Exception { testLiveSyncDeleteDrake("test839LiveSyncDeleteDrakeDumbAny", DummySyncStyle.DUMB, null); } - + @Test public void test840LiveSyncAddDrakeSmartAny() throws Exception { testLiveSyncAddDrake("test840LiveSyncAddDrakeSmartAny", DummySyncStyle.SMART, null); } - + @Test public void test842LiveSyncModifyDrakeSmartAny() throws Exception { testLiveSyncModifyDrake("test842LiveSyncModifyDrakeSmartAny", DummySyncStyle.SMART, null); } - + @Test public void test845LiveSyncAddCorsairsSmartAny() throws Exception { testLiveSyncAddCorsairs("test845LiveSyncAddCorsairsSmartAny", DummySyncStyle.SMART, null, true); } - + @Test public void test847LiveSyncDeleteCorsairsSmartAny() throws Exception { testLiveSyncDeleteCorsairs("test847LiveSyncDeleteCorsairsSmartAny", DummySyncStyle.SMART, null, true); } - + @Test public void test849LiveSyncDeleteDrakeSmartAny() throws Exception { testLiveSyncDeleteDrake("test849LiveSyncDeleteDrakeSmartAny", DummySyncStyle.SMART, null); } - + public void testLiveSyncAddDrake(final String TEST_NAME, DummySyncStyle syncStyle, QName objectClass) throws Exception { displayTestTitle(TEST_NAME); // GIVEN @@ -3916,9 +3916,9 @@ public void testLiveSyncAddDrake(final String TEST_NAME, DummySyncStyle syncStyl display("Resource before sync", dummyResource.debugDump()); - ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, + ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, objectClass); - + // WHEN displayWhen(TEST_NAME); provisioningService.synchronize(coords, syncTokenTask, result); @@ -3937,7 +3937,7 @@ public void testLiveSyncAddDrake(final String TEST_NAME, DummySyncStyle syncStyl PrismObject oldShadow = lastChange.getOldShadow(); assertNotNull("Old shadow missing", oldShadow); assertNotNull("Old shadow does not have an OID", oldShadow.getOid()); - + if (syncStyle == DummySyncStyle.DUMB) { assertNull("Delta present when not expecting it", lastChange.getObjectDelta()); } else { @@ -3945,7 +3945,7 @@ public void testLiveSyncAddDrake(final String TEST_NAME, DummySyncStyle syncStyl assertNotNull("Delta present when not expecting it", objectDelta); assertTrue("Delta is not add: "+objectDelta, objectDelta.isAdd()); } - + ShadowType currentShadowType = lastChange.getCurrentShadow().asObjectable(); assertNotNull("Current shadow missing", lastChange.getCurrentShadow()); PrismAsserts.assertClass("current shadow", ShadowType.class, currentShadowType); @@ -3961,21 +3961,21 @@ public void testLiveSyncAddDrake(final String TEST_NAME, DummySyncStyle syncStyl assertNotNull("No fullname attribute in current shadow", fullnameAttribute); assertEquals("Wrong value of fullname attribute in current shadow", "Sir Francis Drake", fullnameAttribute.getRealValue()); - + drakeAccountOid = currentShadowType.getOid(); PrismObject repoShadow = repositoryService.getObject(ShadowType.class, drakeAccountOid, null, result); display("Drake repo shadow", repoShadow); - - PrismObject accountRepo = findAccountShadowByUsername(getDrakeRepoIcfName(), resource, result); + + PrismObject accountRepo = findAccountShadowByUsername(getDrakeRepoIcfName(), resource, result); assertNotNull("Shadow was not created in the repository", accountRepo); display("Repository shadow", accountRepo); checkRepoAccountShadow(accountRepo); checkAllShadows(); - + assertSteadyResource(); } - + public void testLiveSyncModifyDrake(final String TEST_NAME, DummySyncStyle syncStyle, QName objectClass) throws Exception { displayTestTitle(TEST_NAME); // GIVEN @@ -3984,13 +3984,13 @@ public void testLiveSyncModifyDrake(final String TEST_NAME, DummySyncStyle syncS syncServiceMock.reset(); dummyResource.setSyncStyle(syncStyle); - + DummyAccount dummyAccount = getDummyAccountAssert(DRAKE_USERNAME, drakeIcfUid); dummyAccount.replaceAttributeValue("fullname", "Captain Drake"); - ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, + ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, objectClass); - + // WHEN displayWhen(TEST_NAME); provisioningService.synchronize(coords, syncTokenTask, result); @@ -4005,10 +4005,10 @@ public void testLiveSyncModifyDrake(final String TEST_NAME, DummySyncStyle syncS ResourceObjectShadowChangeDescription lastChange = syncServiceMock.getLastChange(); display("The change", lastChange); - + PrismObject oldShadow = lastChange.getOldShadow(); assertSyncOldShadow(oldShadow, getDrakeRepoIcfName()); - + assertNull("Delta present when not expecting it", lastChange.getObjectDelta()); PrismObject currentShadow = lastChange.getCurrentShadow(); assertNotNull("Current shadow missing", lastChange.getCurrentShadow()); @@ -4020,20 +4020,20 @@ public void testLiveSyncModifyDrake(final String TEST_NAME, DummySyncStyle syncS assertNotNull("No attributes container in current shadow", attributesContainer); Collection> attributes = attributesContainer.getAttributes(); assertFalse("Attributes container is empty", attributes.isEmpty()); - assertAttribute(currentShadow, + assertAttribute(currentShadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Captain Drake"); assertEquals("Unexpected number of attributes", 3, attributes.size()); - PrismObject accountRepo = findAccountShadowByUsername(getDrakeRepoIcfName(), resource, result); + PrismObject accountRepo = findAccountShadowByUsername(getDrakeRepoIcfName(), resource, result); assertNotNull("Shadow was not created in the repository", accountRepo); display("Repository shadow", accountRepo); checkRepoAccountShadow(accountRepo); - + checkAllShadows(); - + assertSteadyResource(); } - + public void testLiveSyncAddCorsairs(final String TEST_NAME, DummySyncStyle syncStyle, QName objectClass, boolean expectReaction) throws Exception { displayTestTitle(TEST_NAME); // GIVEN @@ -4049,9 +4049,9 @@ public void testLiveSyncAddCorsairs(final String TEST_NAME, DummySyncStyle syncS display("Resource before sync", dummyResource.debugDump()); - ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, + ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, objectClass); - + // WHEN displayWhen(TEST_NAME); provisioningService.synchronize(coords, syncTokenTask, result); @@ -4061,18 +4061,18 @@ public void testLiveSyncAddCorsairs(final String TEST_NAME, DummySyncStyle syncS result.computeStatus(); display("Synchronization result", result); TestUtil.assertSuccess("Synchronization result is not OK", result); - + if (expectReaction) { syncServiceMock.assertNotifyChange(); - + ResourceObjectShadowChangeDescription lastChange = syncServiceMock.getLastChange(); display("The change", lastChange); - + PrismObject oldShadow = lastChange.getOldShadow(); assertNotNull("Old shadow missing", oldShadow); assertNotNull("Old shadow does not have an OID", oldShadow.getOid()); - + if (syncStyle == DummySyncStyle.DUMB) { assertNull("Delta present when not expecting it", lastChange.getObjectDelta()); } else { @@ -4080,36 +4080,36 @@ public void testLiveSyncAddCorsairs(final String TEST_NAME, DummySyncStyle syncS assertNotNull("Delta present when not expecting it", objectDelta); assertTrue("Delta is not add: "+objectDelta, objectDelta.isAdd()); } - + ShadowType currentShadowType = lastChange.getCurrentShadow().asObjectable(); assertNotNull("Current shadow missing", lastChange.getCurrentShadow()); PrismAsserts.assertClass("current shadow", ShadowType.class, currentShadowType); - + ResourceAttributeContainer attributesContainer = ShadowUtil .getAttributesContainer(currentShadowType); assertNotNull("No attributes container in current shadow", attributesContainer); Collection> attributes = attributesContainer.getAttributes(); assertFalse("Attributes container is empty", attributes.isEmpty()); assertEquals("Unexpected number of attributes", 2, attributes.size()); - + corsairsShadowOid = currentShadowType.getOid(); PrismObject repoShadow = repositoryService.getObject(ShadowType.class, corsairsShadowOid, null, result); display("Corsairs repo shadow", repoShadow); - + PrismObject accountRepo = findShadowByName(new QName(RESOURCE_DUMMY_NS, SchemaConstants.GROUP_OBJECT_CLASS_LOCAL_NAME), GROUP_CORSAIRS_NAME, resource, result); assertNotNull("Shadow was not created in the repository", accountRepo); display("Repository shadow", accountRepo); ProvisioningTestUtil.checkRepoShadow(repoShadow, ShadowKindType.ENTITLEMENT); - + } else { syncServiceMock.assertNoNotifyChange(); } checkAllShadows(); - + assertSteadyResource(); } - + public void testLiveSyncDeleteCorsairs(final String TEST_NAME, DummySyncStyle syncStyle, QName objectClass, boolean expectReaction) throws Exception { displayTestTitle(TEST_NAME); // GIVEN @@ -4126,9 +4126,9 @@ public void testLiveSyncDeleteCorsairs(final String TEST_NAME, DummySyncStyle sy display("Resource before sync", dummyResource.debugDump()); - ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, + ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, objectClass); - + // WHEN displayWhen(TEST_NAME); provisioningService.synchronize(coords, syncTokenTask, result); @@ -4139,7 +4139,7 @@ public void testLiveSyncDeleteCorsairs(final String TEST_NAME, DummySyncStyle sy display("Synchronization result", result); TestUtil.assertSuccess("Synchronization result is not OK", result); - + if (expectReaction) { syncServiceMock.assertNotifyChange(); @@ -4162,33 +4162,33 @@ public void testLiveSyncDeleteCorsairs(final String TEST_NAME, DummySyncStyle sy assertNotNull("No ICF name attribute in old shadow", icfsNameAttribute); assertEquals("Wrong value of ICF name attribute in old shadow", GROUP_CORSAIRS_NAME, icfsNameAttribute.getRealValue()); - + ObjectDelta objectDelta = lastChange.getObjectDelta(); assertNotNull("Delta missing", objectDelta); assertEquals("Wrong delta changetype", ChangeType.DELETE, objectDelta.getChangeType()); PrismAsserts.assertClass("delta", ShadowType.class, objectDelta); assertNotNull("No OID in delta", objectDelta.getOid()); - + assertNull("Unexpected current shadow",lastChange.getCurrentShadow()); - + try { // The shadow should be gone PrismObject repoShadow = repositoryService.getObject(ShadowType.class, corsairsShadowOid, null, result); - + AssertJUnit.fail("The shadow "+repoShadow+" is not gone from repo"); } catch (ObjectNotFoundException e) { // This is expected } - + } else { syncServiceMock.assertNoNotifyChange(); } checkAllShadows(); - + assertSteadyResource(); } - + public void testLiveSyncDeleteDrake(final String TEST_NAME, DummySyncStyle syncStyle, QName objectClass) throws Exception { displayTestTitle(TEST_NAME); // GIVEN @@ -4205,9 +4205,9 @@ public void testLiveSyncDeleteDrake(final String TEST_NAME, DummySyncStyle syncS display("Resource before sync", dummyResource.debugDump()); - ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, + ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, objectClass); - + // WHEN displayWhen(TEST_NAME); provisioningService.synchronize(coords, syncTokenTask, result); @@ -4225,26 +4225,26 @@ public void testLiveSyncDeleteDrake(final String TEST_NAME, DummySyncStyle syncS PrismObject oldShadow = lastChange.getOldShadow(); assertSyncOldShadow(oldShadow, getDrakeRepoIcfName()); - + ObjectDelta objectDelta = lastChange.getObjectDelta(); assertNotNull("Delta missing", objectDelta); assertEquals("Wrong delta changetype", ChangeType.DELETE, objectDelta.getChangeType()); PrismAsserts.assertClass("delta", ShadowType.class, objectDelta); assertNotNull("No OID in delta", objectDelta.getOid()); - + assertNull("Unexpected current shadow",lastChange.getCurrentShadow()); - + try { // The shadow should be gone PrismObject repoShadow = repositoryService.getObject(ShadowType.class, drakeAccountOid, null, result); - + AssertJUnit.fail("The shadow "+repoShadow+" is not gone from repo"); } catch (ObjectNotFoundException e) { // This is expected } - + checkAllShadows(); - + assertSteadyResource(); } @@ -4261,9 +4261,9 @@ public void test890LiveSyncModifyProtectedAccount() throws Exception { DummyAccount dummyAccount = getDummyAccountAssert(ACCOUNT_DAEMON_USERNAME, daemonIcfUid); dummyAccount.replaceAttributeValue("fullname", "Maxwell deamon"); - ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, + ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_DUMMY_OID, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); - + // WHEN displayWhen(TEST_NAME); provisioningService.synchronize(coords, syncTokenTask, result); @@ -4279,7 +4279,7 @@ public void test890LiveSyncModifyProtectedAccount() throws Exception { syncServiceMock.assertNoNotifyChange(); checkAllShadows(); - + assertSteadyResource(); } @@ -4300,16 +4300,16 @@ public void test901FailResourceNotFound() throws Exception { } catch (ObjectNotFoundException e) { // This is expected } - + result.computeStatus(); display("getObject result (expected failure)", result); TestUtil.assertFailure(result); - + assertSteadyResource(); } - + // test999 shutdown in the superclass - + protected void checkCachedAccountShadow(PrismObject shadowType, OperationResult parentResult, boolean fullShadow, XMLGregorianCalendar startTs, XMLGregorianCalendar endTs) throws SchemaException { checkAccountShadow(shadowType, parentResult, fullShadow, startTs, endTs); @@ -4318,7 +4318,7 @@ protected void checkCachedAccountShadow(PrismObject shadowType, Oper private void checkGroupShadow(PrismObject shadow, OperationResult parentResult) throws SchemaException { checkEntitlementShadow(shadow, parentResult, SchemaTestConstants.ICF_GROUP_OBJECT_CLASS_LOCAL_NAME, true); } - + private void checkGroupShadow(PrismObject shadow, OperationResult parentResult, boolean fullShadow) throws SchemaException { checkEntitlementShadow(shadow, parentResult, SchemaTestConstants.ICF_GROUP_OBJECT_CLASS_LOCAL_NAME, fullShadow); } @@ -4335,16 +4335,16 @@ private void checkAllShadows() throws SchemaException, ObjectNotFoundException, IntegrationTestTools.checkAllShadows(resourceType, repositoryService, checker, prismContext); } - - + + protected void checkRepoEntitlementShadow(PrismObject repoShadow) { ProvisioningTestUtil.checkRepoEntitlementShadow(repoShadow); } - + protected void assertSyncOldShadow(PrismObject oldShadow, String repoName) { assertSyncOldShadow(oldShadow, repoName, 2); } - + protected void assertSyncOldShadow(PrismObject oldShadow, String repoName, Integer expectedNumberOfAttributes) { assertNotNull("Old shadow missing", oldShadow); assertNotNull("Old shadow does not have an OID", oldShadow.getOid()); @@ -4362,6 +4362,6 @@ protected void assertSyncOldShadow(PrismObject oldShadow, assertNotNull("No ICF name attribute in old shadow", icfsNameAttribute); assertEquals("Wrong value of ICF name attribute in old shadow", repoName, icfsNameAttribute.getRealValue()); - } + } } 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 de703916ad8..2a30844c42d 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 @@ -58,14 +58,14 @@ /** * Almost the same as TestDummy but this is using a caching configuration. - * + * * @author Radovan Semancik * */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext public class TestDummyCaching extends TestDummy { - + public static final File TEST_DIR = new File(TEST_DIR_DUMMY, "dummy-caching"); public static final File RESOURCE_DUMMY_FILE = new File(TEST_DIR, "resource-dummy.xml"); @@ -78,7 +78,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti protected File getResourceDummyFilename() { return RESOURCE_DUMMY_FILE; } - + /** * Make a native modification to an account and read it from the cache. Make sure that * cached data are returned and there is no read from the resource. @@ -92,20 +92,20 @@ public void test107AGetModifiedAccountFromCacheMax() throws Exception { // GIVEN OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + DummyAccount accountWill = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); accountWill.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Nice Pirate"); accountWill.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "Interceptor"); accountWill.setEnabled(true); - Collection> options = + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createMaxStaleness()); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); // WHEN TestUtil.displayWhen(TEST_NAME); - + PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, options, null, result); // THEN @@ -113,25 +113,25 @@ public void test107AGetModifiedAccountFromCacheMax() throws Exception { result.computeStatus(); display("getObject result", result); TestUtil.assertSuccess(result); - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); display("Retrieved account shadow", shadow); assertNotNull("No dummy account", shadow); - + assertAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Pirate"); assertAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "Black Pearl"); assertAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, "sword", "love"); assertAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOOT_NAME, 42); Collection> attributes = ShadowUtil.getAttributes(shadow); assertEquals("Unexpected number of attributes", 7, attributes.size()); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); checkRepoAccountShadowWillBasic(shadowRepo, null, startTs, null); - + assertRepoShadowCachedAttributeValue(shadowRepo, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Pirate"); assertRepoShadowCachedAttributeValue(shadowRepo, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "Black Pearl"); assertRepoShadowCachedAttributeValue(shadowRepo, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, "sword", "love"); @@ -139,14 +139,14 @@ public void test107AGetModifiedAccountFromCacheMax() throws Exception { assertRepoShadowCacheActivation(shadowRepo, ActivationStatusType.DISABLED); checkConsistency(shadow); - + assertCachingMetadata(shadow, true, null, startTs); - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + assertSteadyResource(); } - + /** * Make a native modification to an account and read it with high staleness option. * This should return cached data. @@ -160,45 +160,45 @@ public void test107BGetModifiedAccountFromCacheHighStaleness() throws Exception // GIVEN OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - + DummyAccount accountWill = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); accountWill.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Very Nice Pirate"); accountWill.setEnabled(true); - Collection> options = + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createStaleness(1000000L)); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); // WHEN TestUtil.displayWhen(TEST_NAME); - + PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, options, null, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); display("getObject result", result); TestUtil.assertSuccess(result); - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); display("Retrieved account shadow", shadow); assertNotNull("No dummy account", shadow); - + assertAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Pirate"); assertAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "Black Pearl"); assertAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, "sword", "love"); assertAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOOT_NAME, 42); Collection> attributes = ShadowUtil.getAttributes(shadow); assertEquals("Unexpected number of attributes", 7, attributes.size()); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); checkRepoAccountShadowWillBasic(shadowRepo, null, startTs, null); - + assertRepoShadowCachedAttributeValue(shadowRepo, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Pirate"); assertRepoShadowCachedAttributeValue(shadowRepo, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "Black Pearl"); assertRepoShadowCachedAttributeValue(shadowRepo, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, "sword", "love"); @@ -206,14 +206,14 @@ public void test107BGetModifiedAccountFromCacheHighStaleness() throws Exception assertRepoShadowCacheActivation(shadowRepo, ActivationStatusType.DISABLED); checkConsistency(shadow); - + assertCachingMetadata(shadow, true, null, startTs); - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - + assertSteadyResource(); } - + /** * Search for all accounts with maximum staleness option. * This is supposed to return only cached data. Therefore @@ -231,27 +231,27 @@ public void test119SearchAllAccountsMaxStaleness() throws Exception { ObjectQuery query = IntegrationTestTools.createAllShadowsQuery(resourceType, SchemaTestConstants.ICF_ACCOUNT_OBJECT_CLASS_LOCAL_NAME, prismContext); display("All shadows query", query); - + XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - + rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - Collection> options = + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createMaxStaleness()); - + // WHEN List> allShadows = provisioningService.searchObjects(ShadowType.class, query, options, null, result); - + // THEN display("searchObjects result", result); assertSuccess(result); - + display("Found " + allShadows.size() + " shadows"); assertFalse("No shadows found", allShadows.isEmpty()); assertEquals("Wrong number of results", 4, allShadows.size()); - + for (PrismObject shadow: allShadows) { display("Found shadow", shadow); ShadowType shadowType = shadow.asObjectable(); @@ -261,33 +261,33 @@ public void test119SearchAllAccountsMaxStaleness() throws Exception { assertEquals("Wrong fetch result status in "+shadow, OperationResultStatusType.SUCCESS, fetchResult.getStatus()); } assertCachingMetadata(shadow, true, null, startTs); - + if (shadow.asObjectable().getName().getOrig().equals("meathook")) { assertAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "Sea Monkey"); } } - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); assertProtected(allShadows, 1); - + assertSteadyResource(); } - + @Override protected void checkRepoAccountShadowWill(PrismObject shadowRepo, XMLGregorianCalendar start, XMLGregorianCalendar end) { // Sometimes there are 6 and sometimes 7 attributes. Treasure is not returned by default. It is not normally in the cache. // So do not check for number of attributes here. Check for individual values. checkRepoAccountShadowWillBasic(shadowRepo, start, end, null); - + assertRepoShadowCachedAttributeValue(shadowRepo, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "Flying Dutchman"); // this is shadow, values are normalized assertRepoShadowCachedAttributeValue(shadowRepo, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME, "sword", "love"); assertRepoShadowCachedAttributeValue(shadowRepo, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOOT_NAME, 42); - + assertRepoShadowCacheActivation(shadowRepo, ActivationStatusType.ENABLED); } - + @Override protected void assertRepoShadowCacheActivation(PrismObject shadowRepo, ActivationStatusType expectedAdministrativeStatus) { ActivationType activationType = shadowRepo.asObjectable().getActivation(); @@ -295,7 +295,7 @@ protected void assertRepoShadowCacheActivation(PrismObject shadowRep ActivationStatusType administrativeStatus = activationType.getAdministrativeStatus(); assertEquals("Wrong activation administrativeStatus in repo shadow "+shadowRepo, expectedAdministrativeStatus, administrativeStatus); } - + /** * We do not know what the timestamp should be. But some timestamp should be there. */ @@ -303,20 +303,20 @@ protected void assertRepoShadowCacheActivation(PrismObject shadowRep protected void assertRepoCachingMetadata(PrismObject shadowFromRepo) { CachingMetadataType cachingMetadata = shadowFromRepo.asObjectable().getCachingMetadata(); assertNotNull("No caching metadata in "+shadowFromRepo, cachingMetadata); - - assertNotNull("Missing retrieval timestamp in caching metadata in "+shadowFromRepo, + + assertNotNull("Missing retrieval timestamp in caching metadata in "+shadowFromRepo, cachingMetadata.getRetrievalTimestamp()); } - + @Override protected void assertRepoCachingMetadata(PrismObject shadowFromRepo, XMLGregorianCalendar start, XMLGregorianCalendar end) { CachingMetadataType cachingMetadata = shadowFromRepo.asObjectable().getCachingMetadata(); 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()); } - + @Override protected void assertCachingMetadata(PrismObject shadow, boolean expectedCached, XMLGregorianCalendar startTs, XMLGregorianCalendar endTs) { CachingMetadataType cachingMetadata = shadow.asObjectable().getCachingMetadata(); @@ -328,29 +328,29 @@ protected void assertCachingMetadata(PrismObject shadow, boolean exp } } - + @Override protected void checkRepoAccountShadow(PrismObject repoShadow) { ProvisioningTestUtil.checkRepoShadow(repoShadow, ShadowKindType.ACCOUNT, null); } - + @Override protected void checkRepoEntitlementShadow(PrismObject repoShadow) { ProvisioningTestUtil.checkRepoShadow(repoShadow, ShadowKindType.ENTITLEMENT, null); } - + @Override protected void assertRepoShadowAttributes(List> 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); } - + @Override protected void assertSyncOldShadow(PrismObject oldShadow, String repoName) { assertSyncOldShadow(oldShadow, repoName, null); } - + @Override protected void assertRepoShadowCachedAttributeValue(PrismObject shadowRepo, String attrName, T... attrValues) { assertAttribute(shadowRepo, attrName, attrValues); @@ -361,7 +361,7 @@ protected void checkCachedAccountShadow(PrismObject shadow, Operatio XMLGregorianCalendar endTs) throws SchemaException { super.checkAccountShadow(shadow, parentResult, fullShadow, startTs, endTs); if (fullShadow) { - assertCachingMetadata(shadow, true, startTs, endTs); + assertCachingMetadata(shadow, true, startTs, endTs); } } } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyCaseIgnore.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyCaseIgnore.java index 03d13b5b359..5b7de2706be 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyCaseIgnore.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyCaseIgnore.java @@ -44,14 +44,14 @@ /** * Almost the same as TestDummy but this is using a caseIgnore resource version. - * + * * @author Radovan Semancik * */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext public class TestDummyCaseIgnore extends TestDummy { - + public static final File TEST_DIR = new File(TEST_DIR_DUMMY, "dummy-case-ignore"); public static final File RESOURCE_DUMMY_FILE = new File(TEST_DIR, "resource-dummy.xml"); private MatchingRule uidMatchingRule; @@ -66,12 +66,12 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti protected File getResourceDummyFilename() { return RESOURCE_DUMMY_FILE; } - + @Override protected String getWillRepoIcfName() { return "will"; } - + @Override protected String getMurrayRepoIcfName() { return StringUtils.lowerCase(super.getMurrayRepoIcfName()); @@ -101,20 +101,20 @@ protected boolean isAvoidDuplicateValues() { public void test175SearchUidCase() throws Exception { final String TEST_NAME = "test175SearchUidCase"; TestUtil.displayTestTitle(TEST_NAME); - testSeachIterativeSingleAttrFilter(TEST_NAME, + testSeachIterativeSingleAttrFilter(TEST_NAME, SchemaConstants.ICFS_UID, "wIlL", null, true, transformNameFromResource("Will")); } - + @Test public void test176SearchUidCaseNoFetch() throws Exception { final String TEST_NAME = "test176SearchUidCaseNoFetch"; TestUtil.displayTestTitle(TEST_NAME); - testSeachIterativeSingleAttrFilter(TEST_NAME, + testSeachIterativeSingleAttrFilter(TEST_NAME, SchemaConstants.ICFS_UID, "wIlL", GetOperationOptions.createNoFetch(), false, transformNameFromResource("Will")); } - + /** * Add will to the group pirates. But he is already there. */ @@ -125,13 +125,13 @@ public void test280EntitleAccountWillPiratesAlreadyThere() throws Exception { Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + DummyGroup groupPirates = getDummyGroup(GROUP_PIRATES_NAME, piratesIcfUid); groupPirates.addMember(getWillRepoIcfName()); - + syncServiceMock.reset(); - ObjectDelta delta = IntegrationTestTools.createEntitleDelta(ACCOUNT_WILL_OID, + ObjectDelta delta = IntegrationTestTools.createEntitleDelta(ACCOUNT_WILL_OID, dummyResourceCtl.getAttributeQName(DummyResourceContoller.DUMMY_ENTITLEMENT_GROUP_NAME), GROUP_PIRATES_OID, prismContext); display("ObjectDelta", delta); @@ -145,17 +145,17 @@ public void test280EntitleAccountWillPiratesAlreadyThere() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); DummyGroup group = getDummyGroupAssert(GROUP_PIRATES_NAME, piratesIcfUid); assertMember(group, getWillRepoIcfName()); - + syncServiceMock.assertNotifySuccessOnly(); - + PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); display("Shadow after", shadow); assertEntitlementGroup(shadow, GROUP_PIRATES_OID); - + assertSteadyResource(); } @@ -167,7 +167,7 @@ public void test282DetitleAccountWillPirates() throws Exception { Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + syncServiceMock.reset(); ObjectDelta delta = IntegrationTestTools.createDetitleDelta(ACCOUNT_WILL_OID, @@ -184,15 +184,15 @@ public void test282DetitleAccountWillPirates() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); DummyGroup group = getDummyGroupAssert(GROUP_PIRATES_NAME, piratesIcfUid); assertNoMember(group, getWillRepoIcfName()); - + // Make sure that account is still there and it has the privilege DummyAccount dummyAccount = getDummyAccountAssert(ACCOUNT_WILL_USERNAME, willIcfUid); assertNotNull("Account will is gone!", dummyAccount); - + syncServiceMock.assertNotifySuccessOnly(); assertSteadyResource(); } @@ -207,13 +207,13 @@ public void test285EntitleAccountWillPiratesAlreadyThereCaseIgnore() throws Exce Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + DummyGroup groupPirates = getDummyGroup(GROUP_PIRATES_NAME, piratesIcfUid); groupPirates.addMember(getWillRepoIcfName().toUpperCase()); - + syncServiceMock.reset(); - ObjectDelta delta = IntegrationTestTools.createEntitleDelta(ACCOUNT_WILL_OID, + ObjectDelta delta = IntegrationTestTools.createEntitleDelta(ACCOUNT_WILL_OID, dummyResourceCtl.getAttributeQName(DummyResourceContoller.DUMMY_ENTITLEMENT_GROUP_NAME), GROUP_PIRATES_OID, prismContext); display("ObjectDelta", delta); @@ -227,17 +227,17 @@ public void test285EntitleAccountWillPiratesAlreadyThereCaseIgnore() throws Exce result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); DummyGroup group = getDummyGroupAssert(GROUP_PIRATES_NAME, piratesIcfUid); IntegrationTestTools.assertGroupMember(group, getWillRepoIcfName(),true); - + syncServiceMock.assertNotifySuccessOnly(); - + PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); display("Shadow after", shadow); assertEntitlementGroup(shadow, GROUP_PIRATES_OID); - + assertSteadyResource(); } @@ -249,7 +249,7 @@ public void test289DetitleAccountWillPirates() throws Exception { Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + syncServiceMock.reset(); ObjectDelta delta = IntegrationTestTools.createDetitleDelta(ACCOUNT_WILL_OID, @@ -266,21 +266,21 @@ public void test289DetitleAccountWillPirates() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); DummyGroup group = getDummyGroupAssert(GROUP_PIRATES_NAME, piratesIcfUid); assertNoMember(group, getWillRepoIcfName()); assertNoMember(group, getWillRepoIcfName().toUpperCase()); assertNoMember(group, getWillRepoIcfName().toLowerCase()); - + // Make sure that account is still there and it has the privilege DummyAccount dummyAccount = getDummyAccountAssert(ACCOUNT_WILL_USERNAME, willIcfUid); assertNotNull("Account will is gone!", dummyAccount); - + syncServiceMock.assertNotifySuccessOnly(); assertSteadyResource(); } - + @Test public void test511AddProtectedAccountCaseIgnore() throws Exception { final String TEST_NAME = "test511AddProtectedAccountCaseIgnore"; diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyCaseIgnoreUpcaseName.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyCaseIgnoreUpcaseName.java index 007ab6c8fbd..8d38d86e4e2 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyCaseIgnoreUpcaseName.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyCaseIgnoreUpcaseName.java @@ -27,14 +27,14 @@ /** * Almost the same as TestDummyCaseIgnore but the resource is changing all names to upper case. - * + * * @author Radovan Semancik * */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext public class TestDummyCaseIgnoreUpcaseName extends TestDummyCaseIgnore { - + public static final File TEST_DIR = new File(TEST_DIR_DUMMY, "dummy-case-ignore-upcase-name"); public static final File RESOURCE_DUMMY_FILE = new File(TEST_DIR, "resource-dummy.xml"); @@ -57,5 +57,5 @@ protected String transformNameToResource(String origName) { protected void assertShadowName(PrismObject shadow, String expectedName) { assertEquals("Shadow name is wrong in "+shadow, expectedName.toLowerCase(), shadow.asObjectable().getName().getOrig().toLowerCase()); } - + } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyExpression.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyExpression.java index c95f4271d53..97911d3d1e3 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyExpression.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyExpression.java @@ -32,14 +32,14 @@ /** * Testing expressions in dummy resource configuration. - * + * * @author Radovan Semancik * */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext public class TestDummyExpression extends AbstractBasicDummyTest { - + public static final File TEST_DIR = new File(TEST_DIR_DUMMY, "dummy-expression"); public static final File RESOURCE_DUMMY_FILE = new File(TEST_DIR, "resource-dummy.xml"); @@ -52,7 +52,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti protected File getResourceDummyFilename() { return RESOURCE_DUMMY_FILE; } - + @Override protected void assertConfigurationProperty(PrismProperty confProp) { T val = confProp.getRealValue(); @@ -60,7 +60,7 @@ protected void assertConfigurationProperty(PrismProperty confProp) { case "instanceId": assertEquals("Wrong value for "+confProp, "", val); break; - + case "uselessString": assertEquals("Wrong value for "+confProp, "Shiver me timbers!", val); assertExpression(confProp, "value"); @@ -70,5 +70,5 @@ protected void assertConfigurationProperty(PrismProperty confProp) { break; } } - + } 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 1e548757604..84d55c8f34c 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 @@ -58,7 +58,7 @@ * Almost the same as TestDummy but with some extra things, such as: * * readable password * * account-account assciations - * + * * @author Radovan Semancik * */ @@ -66,44 +66,44 @@ @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) @DirtiesContext public class TestDummyExtra extends TestDummy { - + public static final File TEST_DIR = new File(TEST_DIR_DUMMY, "dummy-extra"); public static final File RESOURCE_DUMMY_FILE = new File(TEST_DIR, "resource-dummy.xml"); - + private static final String DUMMY_ACCOUNT_ATTRIBUTE_MATE_NAME = "mate"; - + protected static final QName ASSOCIATION_CREW_NAME = new QName(RESOURCE_DUMMY_NS, "crew"); @Override protected File getResourceDummyFilename() { return RESOURCE_DUMMY_FILE; } - + @Override protected void extraDummyResourceInit() throws Exception { DummyObjectClass accountObjectClass = dummyResource.getAccountObjectClass(); dummyResourceCtl.addAttrDef(accountObjectClass, DUMMY_ACCOUNT_ATTRIBUTE_MATE_NAME, String.class, false, true); } - + @Override protected int getExpectedRefinedSchemaDefinitions() { return super.getExpectedRefinedSchemaDefinitions() + 1; } - + @Override protected void assertSchemaSanity(ResourceSchema resourceSchema, ResourceType resourceType) throws Exception { // schema is extended, displayOrders are changed dummyResourceCtl.assertDummyResourceSchemaSanityExtended(resourceSchema, resourceType, false, 18); - + RefinedResourceSchema refinedSchema = RefinedResourceSchemaImpl.getRefinedSchema(resource); RefinedObjectClassDefinition accountRDef = refinedSchema.getDefaultRefinedDefinition(ShadowKindType.ACCOUNT); - + 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); } - + @Override protected void assertNativeCredentialsCapability(CredentialsCapabilityType capCred) { PasswordCapabilityType passwordCapabilityType = capCred.getPassword(); @@ -112,7 +112,7 @@ protected void assertNativeCredentialsCapability(CredentialsCapabilityType capCr assertNotNull("No 'readable' inducation in password capability", readable); assertTrue("Password not 'readable' in password capability", readable); } - + @Test public void test400AddAccountElizabeth() throws Exception { final String TEST_NAME = "test400AddAccountElizabeth"; @@ -126,7 +126,7 @@ public void test400AddAccountElizabeth() throws Exception { account.checkConsistence(); display("Adding shadow", account); - + XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); // WHEN @@ -136,20 +136,20 @@ public void test400AddAccountElizabeth() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); - + assertEquals(ACCOUNT_ELIZABETH_OID, addedObjectOid); account.checkConsistence(); - + syncServiceMock.assertNotifySuccessOnly(); 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); @@ -159,7 +159,7 @@ public void test400AddAccountElizabeth() throws Exception { checkConsistency(accountProvisioning); assertSteadyResource(); } - + /** * MID-2668 */ @@ -170,10 +170,10 @@ public void test410AssociateCrewWillElizabeth() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + syncServiceMock.reset(); - ObjectDelta delta = IntegrationTestTools.createEntitleDelta(ACCOUNT_WILL_OID, + ObjectDelta delta = IntegrationTestTools.createEntitleDelta(ACCOUNT_WILL_OID, ASSOCIATION_CREW_NAME, ACCOUNT_ELIZABETH_OID, prismContext); display("ObjectDelta", delta); delta.checkConsistence(); @@ -189,23 +189,23 @@ public void test410AssociateCrewWillElizabeth() throws Exception { display("modifyObject result", result); TestUtil.assertSuccess(result); - syncServiceMock.assertNotifySuccessOnly(); + syncServiceMock.assertNotifySuccessOnly(); delta.checkConsistence(); - + DummyAccount dummyAccountWill = getDummyAccountAssert(ACCOUNT_WILL_USERNAME, ACCOUNT_WILL_USERNAME); display("Dummy account will", dummyAccountWill); assertNotNull("No dummy account will", dummyAccountWill); assertTrue("The account will is not enabled", dummyAccountWill.isEnabled()); assertDummyAttributeValues(dummyAccountWill, DUMMY_ACCOUNT_ATTRIBUTE_MATE_NAME, ACCOUNT_ELIZABETH_USERNAME); - + PrismObject accountWillProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - display("Account will from provisioning", accountWillProvisioning); + display("Account will from provisioning", accountWillProvisioning); assertAssociation(accountWillProvisioning, ASSOCIATION_CREW_NAME, ACCOUNT_ELIZABETH_OID); - + assertSteadyResource(); } - + /** * MID-2668 */ @@ -216,10 +216,10 @@ public void test419DisassociateCrewWillElizabeth() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + syncServiceMock.reset(); - ObjectDelta delta = IntegrationTestTools.createDetitleDelta(ACCOUNT_WILL_OID, + ObjectDelta delta = IntegrationTestTools.createDetitleDelta(ACCOUNT_WILL_OID, ASSOCIATION_CREW_NAME, ACCOUNT_ELIZABETH_OID, prismContext); display("ObjectDelta", delta); delta.checkConsistence(); @@ -235,25 +235,25 @@ public void test419DisassociateCrewWillElizabeth() throws Exception { display("modifyObject result", result); TestUtil.assertSuccess(result); - syncServiceMock.assertNotifySuccessOnly(); + syncServiceMock.assertNotifySuccessOnly(); delta.checkConsistence(); - + DummyAccount dummyAccountWill = getDummyAccountAssert(ACCOUNT_WILL_USERNAME, ACCOUNT_WILL_USERNAME); display("Dummy account will", dummyAccountWill); assertNotNull("No dummy account will", dummyAccountWill); assertTrue("The account will is not enabled", dummyAccountWill.isEnabled()); assertNoDummyAttribute(dummyAccountWill, DUMMY_ACCOUNT_ATTRIBUTE_MATE_NAME); - + PrismObject accountWillProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - display("Account will from provisioning", accountWillProvisioning); + display("Account will from provisioning", accountWillProvisioning); assertNoAssociation(accountWillProvisioning, ASSOCIATION_CREW_NAME, ACCOUNT_ELIZABETH_OID); - + assertSteadyResource(); } - + // TODO: disassociate - + @Test public void test499DeleteAccountElizabeth() throws Exception { final String TEST_NAME = "test499DeleteAccountElizabeth"; @@ -262,7 +262,7 @@ public void test499DeleteAccountElizabeth() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); syncServiceMock.reset(); - + // WHEN displayWhen(TEST_NAME); provisioningService.deleteObject(ShadowType.class, ACCOUNT_ELIZABETH_OID, null, null, task, result); @@ -270,7 +270,7 @@ public void test499DeleteAccountElizabeth() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + syncServiceMock.assertNotifySuccessOnly(); assertNoRepoObject(ShadowType.class, ACCOUNT_ELIZABETH_OID); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyHacks.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyHacks.java index 35541c3aedc..922d9c030cc 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyHacks.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyHacks.java @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.provisioning.impl.dummy; @@ -64,21 +64,21 @@ /** * The test of Provisioning service on the API level. The test is using dummy resource for speed and flexibility. - * + * * @author Radovan Semancik - * + * */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext public class TestDummyHacks extends AbstractIntegrationTest { - + private static final File TEST_DIR = new File(AbstractDummyTest.TEST_DIR_DUMMY, "dummy-hacks"); private static final File CONNECTOR_DUMMY_FILE = new File(TEST_DIR, "connector-dummy.xml"); private static final File RESOURCE_DUMMY_FILE = new File(TEST_DIR, "resource-dummy.xml"); - private static final String RESOURCE_DUMMY_OID = "ef2bc95b-76e0-59e2-86d6-9999dddddddd"; - + private static final String RESOURCE_DUMMY_OID = "ef2bc95b-76e0-59e2-86d6-9999dddddddd"; + private static final Trace LOGGER = TraceManager.getTrace(TestDummyHacks.class); private PrismObject connector; @@ -86,17 +86,17 @@ public class TestDummyHacks extends AbstractIntegrationTest { private ResourceType resourceType; private static DummyResource dummyResource; private static Task syncTask; - + @Autowired(required=true) private ProvisioningService provisioningService; - + // Used to make sure that the connector is cached @Autowired(required=true) private ConnectorManager connectorManager; - + @Autowired(required=true) - private SynchornizationServiceMock syncServiceMock; - + private SynchornizationServiceMock syncServiceMock; + public TestDummyHacks() { super(); @@ -104,7 +104,7 @@ public TestDummyHacks() { /* * (non-Javadoc) - * + * * @see com.evolveum.midpoint.test.AbstractIntegrationTest#initSystem() */ @@ -113,12 +113,12 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti // DO NOT DO provisioningService.postInit(..) // We want to avoid connector discovery and insert our own connector object // provisioningService.postInit(initResult); - + connector = repoAddObjectFromFile(CONNECTOR_DUMMY_FILE, initResult); - + resource = repoAddObjectFromFile(RESOURCE_DUMMY_FILE, initResult); resourceType = resource.asObjectable(); - + dummyResource = DummyResource.getInstance(); dummyResource.reset(); dummyResource.populateWithDefaultSchema(); @@ -129,7 +129,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti /** * 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. @@ -161,14 +161,14 @@ public void test003Connection() throws Exception { TestUtil.assertSuccess("Test resource failed (result)", testResult); PrismObject resourceRepoAfter = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, result); - ResourceType resourceTypeRepoAfter = resourceRepoAfter.asObjectable(); + ResourceType resourceTypeRepoAfter = resourceRepoAfter.asObjectable(); display("Resource after test", resourceTypeRepoAfter); XmlSchemaType xmlSchemaTypeAfter = resourceTypeRepoAfter.getSchema(); assertNotNull("No schema after test connection", xmlSchemaTypeAfter); Element resourceXsdSchemaElementAfter = ResourceTypeUtil.getResourceXsdSchema(resourceTypeRepoAfter); assertNotNull("No schema after test connection", resourceXsdSchemaElementAfter); - + String resourceXml = prismContext.serializeObjectToString(resourceRepoAfter, PrismContext.LANG_XML); display("Resource XML", resourceXml); @@ -181,19 +181,19 @@ public void test003Connection() throws Exception { ResourceSchema parsedSchema = ResourceSchemaImpl.parse(xsdElement, resourceBefore.toString(), prismContext); assertNotNull("No schema after parsing", parsedSchema); display("Parsed schema", parsedSchema); - + ComplexTypeDefinition accountDef = parsedSchema.findComplexTypeDefinition( new QName(parsedSchema.getNamespace(),SchemaConstants.ACCOUNT_OBJECT_CLASS_LOCAL_NAME)); assertNotNull("No account definition in schema after parsing", accountDef); PrismAsserts.assertPropertyDefinition(accountDef, SchemaConstants.ICFS_NAME, DOMUtil.XSD_STRING, 1, 1); PrismAsserts.assertPropertyDefinition(accountDef, - new QName(SchemaConstants.NS_ICF_SCHEMA, "description"), + new QName(SchemaConstants.NS_ICF_SCHEMA, "description"), DOMUtil.XSD_STRING, 0, 1); // The useless configuration variables should be reflected to the resource now assertEquals("Wrong useless string", "Shiver me timbers!", dummyResource.getUselessString()); assertEquals("Wrong guarded useless string", "Dead men tell no tales", dummyResource.getUselessGuardedString()); } - + } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyIncomplete.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyIncomplete.java index efb371069f8..6469d0b9891 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyIncomplete.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyIncomplete.java @@ -41,15 +41,15 @@ /** * Almost the same as TestDummy but using incomplete attribute flags - * + * * MID-3573 - * + * * @author Radovan Semancik */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext public class TestDummyIncomplete extends TestDummy { - + public static final File TEST_DIR = new File(TEST_DIR_DUMMY, "dummy-incomplete"); public static final File RESOURCE_DUMMY_FILE = new File(TEST_DIR, "resource-dummy.xml"); @@ -57,12 +57,12 @@ public class TestDummyIncomplete extends TestDummy { protected File getResourceDummyFilename() { return RESOURCE_DUMMY_FILE; } - + @Override protected int getExpectedRefinedSchemaDefinitions() { return super.getExpectedRefinedSchemaDefinitions() + 1; } - + @Override protected void assertNativeCredentialsCapability(CredentialsCapabilityType capCred) { PasswordCapabilityType passwordCapabilityType = capCred.getPassword(); @@ -84,10 +84,10 @@ protected void checkAccountWill(PrismObject shadow, OperationResult assertTrue("Unexpected password value in "+shadow+": "+valueProperty, valueProperty.getValues().isEmpty()); assertTrue("No incompleteness in password value in "+shadow+": "+valueProperty, valueProperty.isIncomplete()); } - + @Test public void testFakeToEnableDebug() { - + } - + } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyLegacy.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyLegacy.java index 95a0f72d342..19d4fd8f1e2 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyLegacy.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyLegacy.java @@ -69,7 +69,7 @@ public class TestDummyLegacy extends AbstractIntegrationTest { private static final String OBJECTCLASS_NATIVE_ACCOUNT = "account"; private static final String OBJECTCLASS_NATIVE_GROUP = "group"; private static final String OBJECTCLASS_NATIVE_PRIVILEGE = "privilege"; - + private static final String OBJECTCLASS_LEGACY_ACCOUNT = "CustomaccountObjectClass"; private static final String OBJECTCLASS_LEGACY_GROUP = "CustomgroupObjectClass"; private static final String OBJECTCLASS_LEGACY_PRIVILEGE = "CustomprivilegeObjectClass"; @@ -90,7 +90,7 @@ public class TestDummyLegacy extends AbstractIntegrationTest { @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { provisioningService.postInit(initResult); - + InternalsConfig.encryptionChecks = false; resourceNative = addResourceFromFile(RESOURCE_DUMMY_NATIVE_FILE, IntegrationTestTools.DUMMY_CONNECTOR_TYPE, initResult); @@ -105,7 +105,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti dummyResourceLegacyCtl.setResource(resourceLegacy); dummyResourceLegacy = dummyResourceLegacyCtl.getDummyResource(); } - + @Test public void test100NativeIntegrity() throws Exception { final String TEST_NAME = "test100NativeIntegrity"; @@ -117,20 +117,20 @@ public void test100NativeIntegrity() throws Exception { assertNotNull("ResourceType is null", resourceTypeNative); Task task = createTask(TEST_NAME); - OperationResult result = task.getResult(); + OperationResult result = task.getResult(); ResourceType resource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_NATIVE_OID, null, result) - .asObjectable(); + .asObjectable(); } - + @Test public void test103NativeTestResource() throws Exception { final String TEST_NAME = "test103NativeTestResource"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); - OperationResult result = task.getResult(); + OperationResult result = task.getResult(); // Check that there is no schema before test (pre-condition) ResourceType resourceBefore = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_NATIVE_OID, null, result) .asObjectable(); @@ -167,7 +167,7 @@ public void test103NativeTestResource() throws Exception { public void test105NativeParsedSchema() throws Exception { final String TEST_NAME = "test105NativeParsedSchema"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(TestDummyLegacy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); @@ -183,7 +183,7 @@ public void test105NativeParsedSchema() throws Exception { ResourceSchema returnedSchema = RefinedResourceSchemaImpl.getResourceSchema(resourceTypeNative, prismContext); display("Parsed resource schema", returnedSchema); assertNotNull("No parsed schema", returnedSchema); - + assertObjectClass(returnedSchema, OBJECTCLASS_NATIVE_ACCOUNT); assertObjectClass(returnedSchema, OBJECTCLASS_NATIVE_GROUP); assertObjectClass(returnedSchema, OBJECTCLASS_NATIVE_PRIVILEGE); @@ -191,7 +191,7 @@ public void test105NativeParsedSchema() throws Exception { assertNoObjectClass(returnedSchema, OBJECTCLASS_LEGACY_GROUP); assertNoObjectClass(returnedSchema, OBJECTCLASS_LEGACY_PRIVILEGE); } - + @Test public void test200LegacyIntegrity() throws Exception { final String TEST_NAME = "test200LegacyIntegrity"; @@ -203,20 +203,20 @@ public void test200LegacyIntegrity() throws Exception { assertNotNull("ResourceType is null", resourceTypeLegacy); Task task = taskManager.createTaskInstance(TestDummyLegacy.class.getName() + "." + TEST_NAME); - OperationResult result = task.getResult(); + OperationResult result = task.getResult(); ResourceType resource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_LEGACY_OID, null, result) .asObjectable(); } - + @Test public void test203LegacyTestResource() throws Exception { final String TEST_NAME = "test203LegacyTestResource"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); - OperationResult result = task.getResult(); + OperationResult result = task.getResult(); // Check that there is no schema before test (pre-condition) ResourceType resourceBefore = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_LEGACY_OID, null, result) .asObjectable(); @@ -253,7 +253,7 @@ public void test203LegacyTestResource() throws Exception { public void test205LegacyParsedSchema() throws Exception { final String TEST_NAME = "test205LegacyParsedSchema"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(TestDummyLegacy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); @@ -269,7 +269,7 @@ public void test205LegacyParsedSchema() throws Exception { ResourceSchema returnedSchema = RefinedResourceSchemaImpl.getResourceSchema(resourceTypeLegacy, prismContext); display("Parsed resource schema", returnedSchema); assertNotNull("No parsed schema", returnedSchema); - + assertObjectClass(returnedSchema, OBJECTCLASS_LEGACY_ACCOUNT); assertObjectClass(returnedSchema, OBJECTCLASS_LEGACY_GROUP); assertObjectClass(returnedSchema, OBJECTCLASS_LEGACY_PRIVILEGE); @@ -280,7 +280,7 @@ public void test205LegacyParsedSchema() throws Exception { private void assertObjectClass(ResourceSchema schema, String objectClassLocalName) { ObjectClassComplexTypeDefinition ocDef = schema.findObjectClassDefinition(objectClassLocalName); - assertNotNull("No objectclass "+objectClassLocalName+" found in schema", ocDef); + assertNotNull("No objectclass "+objectClassLocalName+" found in schema", ocDef); } private void assertNoObjectClass(ResourceSchema schema, String objectClassLocalName) { 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 53e7f1102b3..58fd2af61e6 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 @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.provisioning.impl.dummy; @@ -53,42 +53,42 @@ /** * @author Radovan Semancik - * + * */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext public class TestDummyNegative extends AbstractDummyTest { private static final Trace LOGGER = TraceManager.getTrace(TestDummyNegative.class); - + private static final File ACCOUNT_ELAINE_RESOURCE_NOT_FOUND_FILE = new File(TEST_DIR, "account-elaine-resource-not-found.xml"); - + @Test public void test110GetResourceBrokenSchemaNetwork() throws Exception { testGetResourceBrokenSchema(BreakMode.NETWORK, "test110GetResourceBrokenSchemaNetwork"); } - + @Test public void test111GetResourceBrokenSchemaGeneric() throws Exception { testGetResourceBrokenSchema(BreakMode.GENERIC, "test111GetResourceBrokenSchemaGeneric"); } - + @Test public void test112GetResourceBrokenSchemaIo() throws Exception { testGetResourceBrokenSchema(BreakMode.IO, "test112GetResourceBrokenSchemaIO"); } - + @Test public void test113GetResourceBrokenSchemaRuntime() throws Exception { testGetResourceBrokenSchema(BreakMode.RUNTIME, "test113GetResourceBrokenSchemaRuntime"); } - + public void testGetResourceBrokenSchema(BreakMode breakMode, String testName) throws Exception { TestUtil.displayTestTitle(testName); // GIVEN OperationResult result = new OperationResult(TestDummyNegative.class.getName() + "."+testName); - + // precondition PrismObject repoResource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, result); display("Repo resource (before)", repoResource); @@ -97,22 +97,22 @@ public void testGetResourceBrokenSchema(BreakMode breakMode, String testName) th dummyResource.setSchemaBreakMode(breakMode); try { - + // WHEN PrismObject resource = provisioningService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, null, result); - + // THEN display("Resource with broken schema", resource); OperationResultType fetchResult = resource.asObjectable().getFetchResult(); - + result.computeStatus(); display("getObject result", result); assertEquals("Unexpected result of getObject operation", OperationResultStatus.PARTIAL_ERROR, result.getStatus()); - + assertNotNull("No fetch result", fetchResult); display("fetchResult", fetchResult); assertEquals("Unexpected result of fetchResult", OperationResultStatusType.PARTIAL_ERROR, fetchResult.getStatus()); - + } finally { dummyResource.setSchemaBreakMode(BreakMode.NONE); } @@ -131,15 +131,15 @@ public void test190GetResource() throws Exception { // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject resource = provisioningService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, task, result); - + TestUtil.displayThen(TEST_NAME); assertSuccess(result); - + display("Resource after", resource); IntegrationTestTools.displayXml("Resource after (XML)", resource); assertHasSchema(resource, "dummy"); } - + @Test public void test200AddAccountNullAttributes() throws Exception { final String TEST_NAME = "test200AddAccountNullAttributes"; @@ -152,7 +152,7 @@ public void test200AddAccountNullAttributes() throws Exception { ShadowType accountType = parseObjectType(ACCOUNT_WILL_FILE, ShadowType.class); PrismObject account = accountType.asPrismObject(); account.checkConsistence(); - + account.removeContainer(ShadowType.F_ATTRIBUTES); display("Adding shadow", account); @@ -161,17 +161,17 @@ public void test200AddAccountNullAttributes() throws Exception { // WHEN TestUtil.displayWhen(TEST_NAME); provisioningService.addObject(account, null, null, task, result); - + AssertJUnit.fail("The addObject operation was successful. But expecting an exception."); } catch (SchemaException e) { // This is expected display("Expected exception", e); } - + TestUtil.displayThen(TEST_NAME); syncServiceMock.assertNotifyFailureOnly(); } - + @Test public void test201AddAccountEmptyAttributes() throws Exception { TestUtil.displayTestTitle("test201AddAccountEmptyAttributes"); @@ -185,7 +185,7 @@ public void test201AddAccountEmptyAttributes() throws Exception { ShadowType accountType = parseObjectType(ACCOUNT_WILL_FILE, ShadowType.class); PrismObject account = accountType.asPrismObject(); account.checkConsistence(); - + account.findContainer(ShadowType.F_ATTRIBUTES).getValue().clear(); display("Adding shadow", account); @@ -193,16 +193,16 @@ public void test201AddAccountEmptyAttributes() throws Exception { try { // WHEN provisioningService.addObject(account, null, null, task, result); - + AssertJUnit.fail("The addObject operation was successful. But expecting an exception."); } catch (SchemaException e) { // This is expected display("Expected exception", e); } - + syncServiceMock.assertNotifyFailureOnly(); } - + @Test public void test210AddAccountNoObjectclass() throws Exception { TestUtil.displayTestTitle("test210AddAccountNoObjectclass"); @@ -216,7 +216,7 @@ public void test210AddAccountNoObjectclass() throws Exception { ShadowType accountType = parseObjectType(ACCOUNT_WILL_FILE, ShadowType.class); PrismObject account = accountType.asPrismObject(); account.checkConsistence(); - + // IMPORTANT: deliberately violating the schema accountType.setObjectClass(null); accountType.setKind(null); @@ -226,7 +226,7 @@ public void test210AddAccountNoObjectclass() throws Exception { try { // WHEN provisioningService.addObject(account, null, null, task, result); - + AssertJUnit.fail("The addObject operation was successful. But expecting an exception."); } catch (SchemaException e) { // This is expected @@ -235,7 +235,7 @@ public void test210AddAccountNoObjectclass() throws Exception { syncServiceMock.assertNotifyFailureOnly(); } - + @Test public void test220AddAccountNoResourceRef() throws Exception { final String TEST_NAME = "test220AddAccountNoResourceRef"; @@ -249,7 +249,7 @@ public void test220AddAccountNoResourceRef() throws Exception { ShadowType accountType = parseObjectType(ACCOUNT_WILL_FILE, ShadowType.class); PrismObject account = accountType.asPrismObject(); account.checkConsistence(); - + accountType.setResourceRef(null); display("Adding shadow", account); @@ -257,17 +257,17 @@ public void test220AddAccountNoResourceRef() throws Exception { try { // WHEN provisioningService.addObject(account, null, null, task, result); - + AssertJUnit.fail("The addObject operation was successful. But expecting an exception."); } catch (SchemaException e) { // This is expected 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 reosurce is not specified, provisioning probably will be not called. // syncServiceMock.assertNotifyFailureOnly(); } - + @Test public void test221DeleteAccountResourceNotFound() throws Exception { final String TEST_NAME = "test221DeleteAccountResourceNotFound"; @@ -281,7 +281,7 @@ public void test221DeleteAccountResourceNotFound() throws Exception { ShadowType accountType = parseObjectType(ACCOUNT_ELAINE_RESOURCE_NOT_FOUND_FILE); PrismObject account = accountType.asPrismObject(); account.checkConsistence(); - + // accountType.setResourceRef(null); display("Adding shadow", account); @@ -302,8 +302,8 @@ public void test221DeleteAccountResourceNotFound() throws Exception { } /** - * Try to get an account when a shadow has been deleted (but the account exists). - * Proper ObjectNotFoundException is expected, compensation should not run. + * Try to get an account when a shadow has been deleted (but the account exists). + * Proper ObjectNotFoundException is expected, compensation should not run. */ @Test public void test230GetAccountDeletedShadow() throws Exception { @@ -313,12 +313,12 @@ public void test230GetAccountDeletedShadow() throws Exception { Task task = taskManager.createTaskInstance(TestDummyNegative.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject account = PrismTestUtil.parseObject(ACCOUNT_MORGAN_FILE); String shadowOid = provisioningService.addObject(account, null, null, task, result); - + repositoryService.deleteObject(ShadowType.class, shadowOid, result); - + // reset task = taskManager.createTaskInstance(TestDummyNegative.class.getName() + "." + TEST_NAME); result = task.getResult(); @@ -327,7 +327,7 @@ public void test230GetAccountDeletedShadow() throws Exception { try { // WHEN provisioningService.getObject(ShadowType.class, shadowOid, null, task, result); - + AssertJUnit.fail("Unexpected success"); } catch (ObjectNotFoundException e) { // this is expected @@ -335,7 +335,7 @@ public void test230GetAccountDeletedShadow() throws Exception { result.computeStatus(); display("Result", result); TestUtil.assertFailure(result); - + } syncServiceMock.assertNoNotifyChange(); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyNoActivation.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyNoActivation.java index fc833571513..ce87a9684eb 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyNoActivation.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyNoActivation.java @@ -44,37 +44,37 @@ /** * Almost the same as TestDummy but this is using a resource without activation support. * Let's test that we are able to do all the operations without NPEs and other side effects. - * + * * @author Radovan Semancik * */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext public class TestDummyNoActivation extends TestDummy { - + public static final File TEST_DIR = new File(TEST_DIR_DUMMY, "dummy-no-activation"); public static final File RESOURCE_DUMMY_FILE = new File(TEST_DIR, "resource-dummy.xml"); - + protected static final File ACCOUNT_WILL_FILE = new File(TEST_DIR, "account-will.xml"); @Override protected boolean supportsActivation() { return false; } - + @Override protected File getResourceDummyFilename() { return RESOURCE_DUMMY_FILE; } - + protected File getAccountWillFile() { return ACCOUNT_WILL_FILE; } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + syncServiceMock.setSupportActivation(false); } @@ -99,28 +99,28 @@ public void test150DisableAccount() throws Exception { // WHEN provisioningService.modifyObject(ShadowType.class, delta.getOid(), delta.getModifications(), new OperationProvisioningScriptsType(), null, task, result); - + AssertJUnit.fail("Unexpected success"); } catch (SchemaException e) { // This is expected - + } // THEN result.computeStatus(); display("modifyObject result", result); TestUtil.assertFailure(result); - + delta.checkConsistence(); // check if activation was unchanged DummyAccount dummyAccount = dummyResource.getAccountByUsername(ACCOUNT_WILL_USERNAME); assertTrue("Dummy account "+ACCOUNT_WILL_USERNAME+" is disabled, expected enabled", dummyAccount.isEnabled()); - + syncServiceMock.assertNotifyFailureOnly(); - + assertSteadyResource(); } - + @Override public void test151SearchDisabledAccounts() throws Exception { // N/A @@ -142,33 +142,33 @@ public void test152ActivationStatusUndefinedAccount() throws Exception { display("ObjectDelta", delta); delta.checkConsistence(); - + try { // WHEN provisioningService.modifyObject(ShadowType.class, delta.getOid(), delta.getModifications(), new OperationProvisioningScriptsType(), null, task, result); - + AssertJUnit.fail("Unexpected success"); } catch (SchemaException e) { // This is expected - + } - + // THEN result.computeStatus(); display("modifyObject result", result); TestUtil.assertFailure(result); - + delta.checkConsistence(); // check if activation was unchanged DummyAccount dummyAccount = dummyResource.getAccountByUsername(ACCOUNT_WILL_USERNAME); assertTrue("Dummy account "+ACCOUNT_WILL_USERNAME+" is disabled, expected enabled", dummyAccount.isEnabled()); - + syncServiceMock.assertNotifyFailureOnly(); - + assertSteadyResource(); } - + @Test @Override public void test154EnableAccount() throws Exception { @@ -186,33 +186,33 @@ public void test154EnableAccount() throws Exception { display("ObjectDelta", delta); delta.checkConsistence(); - + try { // WHEN provisioningService.modifyObject(ShadowType.class, delta.getOid(), delta.getModifications(), new OperationProvisioningScriptsType(), null, task, result); - + AssertJUnit.fail("Unexpected success"); } catch (SchemaException e) { // This is expected - + } - + // THEN result.computeStatus(); display("modifyObject result", result); TestUtil.assertFailure(result); - + delta.checkConsistence(); // check if activation was unchanged DummyAccount dummyAccount = dummyResource.getAccountByUsername(ACCOUNT_WILL_USERNAME); assertTrue("Dummy account "+ACCOUNT_WILL_USERNAME+" is disabled, expected enabled", dummyAccount.isEnabled()); - + syncServiceMock.assertNotifyFailureOnly(); - + assertSteadyResource(); } - + @Override public void test155SearchDisabledAccounts() throws Exception { // N/A @@ -230,7 +230,7 @@ public void test156SetValidFrom() throws Exception { syncServiceMock.reset(); long millis = VALID_FROM_MILLIS; - + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, ACCOUNT_WILL_OID, SchemaConstants.PATH_ACTIVATION_VALID_FROM, prismContext, XmlTypeConverter.createXMLGregorianCalendar(VALID_FROM_MILLIS)); @@ -240,30 +240,30 @@ public void test156SetValidFrom() throws Exception { // WHEN provisioningService.modifyObject(ShadowType.class, delta.getOid(), delta.getModifications(), new OperationProvisioningScriptsType(), null, task, result); - + AssertJUnit.fail("Unexpected success"); } catch (SchemaException e) { // This is expected - + } - + // THEN result.computeStatus(); display("modifyObject result", result); TestUtil.assertFailure(result); - + delta.checkConsistence(); // check if activation was not changed DummyAccount dummyAccount = dummyResource.getAccountByUsername(ACCOUNT_WILL_USERNAME); assertTrue("Dummy account "+ACCOUNT_WILL_USERNAME+" is disabled, expected enabled", dummyAccount.isEnabled()); assertNull("Unexpected account validFrom in account "+ACCOUNT_WILL_USERNAME+": "+dummyAccount.getValidFrom(), dummyAccount.getValidFrom()); assertNull("Unexpected account validTo in account "+ACCOUNT_WILL_USERNAME+": "+dummyAccount.getValidTo(), dummyAccount.getValidTo()); - + syncServiceMock.assertNotifyFailureOnly(); - + assertSteadyResource(); } - + @Test @Override public void test157SetValidTo() throws Exception { @@ -276,7 +276,7 @@ public void test157SetValidTo() throws Exception { syncServiceMock.reset(); long millis = VALID_TO_MILLIS; - + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, ACCOUNT_WILL_OID, SchemaConstants.PATH_ACTIVATION_VALID_TO, prismContext, XmlTypeConverter.createXMLGregorianCalendar(VALID_TO_MILLIS)); @@ -286,30 +286,30 @@ public void test157SetValidTo() throws Exception { // WHEN provisioningService.modifyObject(ShadowType.class, delta.getOid(), delta.getModifications(), new OperationProvisioningScriptsType(), null, task, result); - + AssertJUnit.fail("Unexpected success"); } catch (SchemaException e) { // This is expected - + } - + // THEN result.computeStatus(); display("modifyObject result", result); TestUtil.assertFailure(result); - + delta.checkConsistence(); // check if activation was changed DummyAccount dummyAccount = dummyResource.getAccountByUsername(ACCOUNT_WILL_USERNAME); assertTrue("Dummy account "+ACCOUNT_WILL_USERNAME+" is disabled, expected enabled", dummyAccount.isEnabled()); assertNull("Unexpected account validFrom in account "+ACCOUNT_WILL_USERNAME+": "+dummyAccount.getValidFrom(), dummyAccount.getValidFrom()); assertNull("Unexpected account validTo in account "+ACCOUNT_WILL_USERNAME+": "+dummyAccount.getValidTo(), dummyAccount.getValidTo()); - + syncServiceMock.assertNotifyFailureOnly(); - + assertSteadyResource(); } - + @Override public void test158DeleteValidToValidFrom() throws Exception { final String TEST_NAME = "test158DeleteValidToValidFrom"; @@ -320,7 +320,7 @@ public void test158DeleteValidToValidFrom() throws Exception { OperationResult result = task.getResult(); syncServiceMock.reset(); - + ObjectDelta delta = ObjectDelta.createModificationDeleteProperty(ShadowType.class, ACCOUNT_WILL_OID, SchemaConstants.PATH_ACTIVATION_VALID_TO, prismContext, XmlTypeConverter.createXMLGregorianCalendar(VALID_TO_MILLIS)); @@ -330,43 +330,43 @@ public void test158DeleteValidToValidFrom() throws Exception { XmlTypeConverter.createXMLGregorianCalendar(VALID_FROM_MILLIS)); delta.addModification(validFromDelta); delta.checkConsistence(); - - + + try { // WHEN provisioningService.modifyObject(ShadowType.class, delta.getOid(), delta.getModifications(), new OperationProvisioningScriptsType(), null, task, result); - + AssertJUnit.fail("Unexpected success"); } catch (SchemaException e) { // This is expected - + } - + // THEN result.computeStatus(); display("modifyObject result", result); TestUtil.assertFailure(result); - + delta.checkConsistence(); // check if activation was changed DummyAccount dummyAccount = dummyResource.getAccountByUsername(ACCOUNT_WILL_USERNAME); assertTrue("Dummy account "+ACCOUNT_WILL_USERNAME+" is disabled, expected enabled", dummyAccount.isEnabled()); assertNull("Unexpected account validFrom in account "+ACCOUNT_WILL_USERNAME+": "+dummyAccount.getValidFrom(), dummyAccount.getValidFrom()); assertNull("Unexpected account validTo in account "+ACCOUNT_WILL_USERNAME+": "+dummyAccount.getValidTo(), dummyAccount.getValidTo()); - + syncServiceMock.assertNotifyFailureOnly(); - + assertSteadyResource(); - + } - + @Test @Override public void test159GetLockedoutAccount() throws Exception { // Not relevant } - + @Override public void test160SearchLockedAccounts() throws Exception { // N/A @@ -381,7 +381,7 @@ public void test162UnlockAccount() throws Exception { Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + syncServiceMock.reset(); ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, @@ -389,29 +389,29 @@ public void test162UnlockAccount() throws Exception { LockoutStatusType.NORMAL); display("ObjectDelta", delta); delta.checkConsistence(); - + try { // WHEN provisioningService.modifyObject(ShadowType.class, delta.getOid(), delta.getModifications(), new OperationProvisioningScriptsType(), null, task, result); - + AssertJUnit.fail("Unexpected success"); } catch (SchemaException e) { // This is expected } - - + + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); display("modifyObject result", result); TestUtil.assertFailure(result); - + delta.checkConsistence(); - + syncServiceMock.assertNotifyFailureOnly(); - + assertSteadyResource(); } - + } 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 edd210fbd14..43baa0b9f69 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 @@ -15,11 +15,13 @@ */ /** - * + * */ package com.evolveum.midpoint.provisioning.impl.dummy; import java.io.File; +import java.util.ArrayList; +import java.util.Collection; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; @@ -27,25 +29,31 @@ import org.testng.annotations.Test; import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.delta.ItemDelta; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +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.Counter; import com.evolveum.midpoint.test.util.ParallelTestThread; +import com.evolveum.midpoint.util.FailableProducer; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; 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.ShadowType; /** - * The test of Provisioning service on the API level. - * + * The test of Provisioning service on the API level. + * * This test is focused on parallelism and race conditions. - * + * * The test is using dummy resource for speed and flexibility. - * + * * @author Radovan Semancik - * + * */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext @@ -53,38 +61,38 @@ public class TestDummyParallelism extends AbstractBasicDummyTest { private static final Trace LOGGER = TraceManager.getTrace(TestDummyParallelism.class); - + public static final File TEST_DIR = new File(TEST_DIR_DUMMY, "dummy-parallelism"); public static final File RESOURCE_DUMMY_FILE = new File(TEST_DIR, "resource-dummy.xml"); private static final long WAIT_TIMEOUT = 60000L; private static final int DUMMY_OPERATION_DELAY_RANGE = 1000; - + private String accountMorganOid; - + protected int getConcurrentTestNumberOfThreads() { return 5; } - + protected int getConcurrentTestRandomStartDelayRange() { return 10; } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); dummyResource.setOperationDelayRange(DUMMY_OPERATION_DELAY_RANGE); // InternalMonitor.setTraceConnectorOperation(true); } - + @Override protected File getResourceDummyFilename() { return RESOURCE_DUMMY_FILE; } // test000-test100 in the superclasses - + @Test public void test200ParallelCreate() throws Exception { final String TEST_NAME = "test200ParallelCreate"; @@ -92,20 +100,20 @@ public void test200ParallelCreate() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + final Counter successCounter = new Counter(); rememberDummyResourceWriteOperationCount(null); // WHEN displayWhen(TEST_NAME); - - ParallelTestThread[] threads = multithread(TEST_NAME, - () -> { + + ParallelTestThread[] threads = multithread(TEST_NAME, + (i) -> { Task localTask = createTask(TEST_NAME + ".local"); OperationResult localResult = localTask.getResult(); - + ShadowType account = parseObjectType(ACCOUNT_MORGAN_FILE, ShadowType.class); - + try { accountMorganOid = provisioningService.addObject(account.asPrismObject(), null, null, localTask, localResult); successCounter.click(); @@ -113,40 +121,131 @@ public void test200ParallelCreate() throws Exception { // this is expected ... sometimes LOGGER.info("Exception (maybe expected): {}: {}", e.getClass().getSimpleName(), e.getMessage()); } - + }, getConcurrentTestNumberOfThreads(), getConcurrentTestRandomStartDelayRange()); - + // THEN displayThen(TEST_NAME); waitForThreads(threads, WAIT_TIMEOUT); - + successCounter.assertCount("Wrong number of successful operations", 1); - + PrismObject shadowAfter = provisioningService.getObject(ShadowType.class, accountMorganOid, null, task, result); display("Shadow after", shadowAfter); - + assertDummyResourceWriteOperationCountIncrement(null, 1); + + assertSteadyResource(); + } + + /** + * Create a lot parallel modifications for the same property and the same value. + * These should all be eliminated - except for one of them. + * + * There is a slight chance that one of the thread starts after the first operation + * is finished. But the threads are fast and the operations are slow. So this is + * a very slim chance. + */ + @Test + public void test202ParallelModifyCaptainMorgan() throws Exception { + final String TEST_NAME = "test202ParallelModifyCaptainMorgan"; + + PrismObject shadowAfter = parallelModifyTest(TEST_NAME, + () -> ObjectDelta.createModificationReplaceProperty(ShadowType.class, + accountMorganOid, dummyResourceCtl.getAttributeFullnamePath(), prismContext, "Captain Morgan")); + + assertAttribute(shadowAfter, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Captain Morgan"); + } + + /** + * Create a lot parallel modifications for the same property and the same value. + * These should all be eliminated - except for one of them. + * + * There is a slight chance that one of the thread starts after the first operation + * is finished. But the threads are fast and the operations are slow. So this is + * a very slim chance. + */ + @Test + public void test204ParallelModifyDisable() throws Exception { + final String TEST_NAME = "test204ParallelModifyDisable"; + + PrismObject shadowAfter = parallelModifyTest(TEST_NAME, + () -> ObjectDelta.createModificationReplaceProperty(ShadowType.class, + accountMorganOid, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, prismContext, ActivationStatusType.DISABLED)); + + assertActivationAdministrativeStatus(shadowAfter, ActivationStatusType.DISABLED); + } + private PrismObject parallelModifyTest(final String TEST_NAME, FailableProducer> deltaProducer) throws Exception { + displayTestTitle(TEST_NAME); + + // GIVEN + Task task = createTask(TEST_NAME); + OperationResult result = task.getResult(); + + final Counter successCounter = new Counter(); + rememberDummyResourceWriteOperationCount(null); + + // WHEN + displayWhen(TEST_NAME); + + ParallelTestThread[] threads = multithread(TEST_NAME, + (i) -> { + Task localTask = createTask(TEST_NAME + ".local"); + OperationResult localResult = localTask.getResult(); + + display("Thread "+Thread.currentThread().getName()+" START"); + + ObjectDelta delta = deltaProducer.run(); + display("ObjectDelta", delta); + + provisioningService.modifyObject(ShadowType.class, accountMorganOid, delta.getModifications(), null, null, localTask, localResult); + + localResult.computeStatus(); + display("Thread "+Thread.currentThread().getName()+" DONE, result", localResult); + if (localResult.isSuccess()) { + successCounter.click(); + } else if (localResult.isInProgress()) { + // expected + } else { + fail("Unexpected thread result status " + localResult.getStatus()); + } + + }, getConcurrentTestNumberOfThreads(), getConcurrentTestRandomStartDelayRange()); + + // THEN + displayThen(TEST_NAME); + waitForThreads(threads, WAIT_TIMEOUT); + + PrismObject shadowAfter = provisioningService.getObject(ShadowType.class, accountMorganOid, null, task, result); + display("Shadow after", shadowAfter); + + successCounter.assertCount("Wrong number of successful operations", 1); + + assertDummyResourceWriteOperationCountIncrement(null, 1); + assertSteadyResource(); + + return shadowAfter; } @Test public void test229ParallelDelete() throws Exception { final String TEST_NAME = "test229ParallelDelete"; displayTestTitle(TEST_NAME); - + // GIVEN final Counter successCounter = new Counter(); rememberDummyResourceWriteOperationCount(null); // WHEN displayWhen(TEST_NAME); - - ParallelTestThread[] threads = multithread(TEST_NAME, - () -> { + + ParallelTestThread[] threads = multithread(TEST_NAME, + (i) -> { Task localTask = createTask(TEST_NAME + ".local"); OperationResult localResult = localTask.getResult(); - + try { display("Thread "+Thread.currentThread().getName()+" START"); provisioningService.deleteObject(ShadowType.class, accountMorganOid, null, null, localTask, localResult); @@ -163,19 +262,19 @@ public void test229ParallelDelete() throws Exception { // this is expected ... sometimes LOGGER.info("Exception (maybe expected): {}: {}", e.getClass().getSimpleName(), e.getMessage()); } - + }, getConcurrentTestNumberOfThreads(), getConcurrentTestRandomStartDelayRange()); - + // THEN displayThen(TEST_NAME); waitForThreads(threads, WAIT_TIMEOUT); - + successCounter.assertCount("Wrong number of successful operations", 1); assertNoRepoObject(ShadowType.class, accountMorganOid); - + assertDummyResourceWriteOperationCountIncrement(null, 1); - + assertSteadyResource(); } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyPrioritiesAndReadReplace.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyPrioritiesAndReadReplace.java index c929010a972..cd28ae0eb1d 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyPrioritiesAndReadReplace.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyPrioritiesAndReadReplace.java @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.provisioning.impl.dummy; @@ -70,10 +70,10 @@ /** * The test of Provisioning service on the API level. The test is using dummy * resource for speed and flexibility. - * + * * @author Radovan Semancik * @author Pavol Mederly - * + * */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyReadReplaceForAll.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyReadReplaceForAll.java index 7d727a7c202..31a4d1a78e0 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyReadReplaceForAll.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyReadReplaceForAll.java @@ -25,7 +25,7 @@ /** * Almost the same as TestDummy but uses READ+REPLACE mode for all account+group attributes. - * + * * @author Radovan Semancik * @author Pavol Mederly * @@ -33,7 +33,7 @@ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext public class TestDummyReadReplaceForAll extends TestDummy { - + public static final File TEST_DIR = new File(TEST_DIR_DUMMY, "dummy-priorities-read-replace"); public static final File RESOURCE_DUMMY_FILENAME = new File(TEST_DIR, "resource-dummy-all-read-replace.xml"); @@ -46,5 +46,5 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti protected File getResourceDummyFilename() { return RESOURCE_DUMMY_FILE; } - + } 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 67d54522318..7946b5f1997 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 @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.provisioning.impl.dummy; @@ -63,19 +63,19 @@ 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 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 - * + * */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext public class TestDummyResourceAndSchemaCaching extends AbstractDummyTest { private static final Trace LOGGER = TraceManager.getTrace(TestDummyResourceAndSchemaCaching.class); - + @Test public void test010GetResource() throws Exception { final String TEST_NAME = "test010GetResource"; @@ -83,7 +83,7 @@ public void test010GetResource() throws Exception { // GIVEN OperationResult result = new OperationResult(TestDummyResourceAndSchemaCaching.class.getName() + "." + TEST_NAME); - + // Some connector initialization and other things might happen in previous tests. // The monitor is static, not part of spring context, it will not be cleared rememberCounter(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT); @@ -92,13 +92,13 @@ public void test010GetResource() throws Exception { rememberCounter(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT); rememberCounter(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT); rememberResourceCacheStats(); - + // Check that there is no schema before test (pre-condition) PrismObject resourceBefore = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, result); ResourceType resourceTypeBefore = resourceBefore.asObjectable(); Element resourceXsdSchemaElementBefore = ResourceTypeUtil.getResourceXsdSchema(resourceTypeBefore); AssertJUnit.assertNull("Found schema before test connection. Bad test setup?", resourceXsdSchemaElementBefore); - + assertVersion(resourceBefore, "0"); // WHEN @@ -111,34 +111,34 @@ public void test010GetResource() throws Exception { assertHasSchema(resourceProvisioning, "provisioning resource"); rememberSchemaMetadata(resourceProvisioning); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 1); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 1); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 1); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 1); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 1); - + rememberConnectorInstance(resourceProvisioning); - + PrismObject resourceRepoAfter = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, result); assertHasSchema(resourceRepoAfter, "repo resource after"); assertSchemaMetadataUnchanged(resourceRepoAfter); - + display("Resource cache", InternalMonitor.getResourceCacheStats()); assertResourceCacheHitsIncrement(0); assertResourceCacheMissesIncrement(1); - + rememberResourceSchema(RefinedResourceSchemaImpl.getResourceSchema(resourceProvisioning, prismContext)); rememberRefinedResourceSchema(RefinedResourceSchemaImpl.getRefinedSchema(resourceProvisioning)); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); - + // Just refresh the resource used by other tests. This one has a complete schema. resourceType = resourceProvisioning.asObjectable(); rememberResourceVersion(resourceType.getVersion()); } - + @Test public void test011GetResourceAgain() throws Exception { final String TEST_NAME = "test011GetResourceAgain"; @@ -146,7 +146,7 @@ public void test011GetResourceAgain() throws Exception { // GIVEN OperationResult result = new OperationResult(TestDummyResourceAndSchemaCaching.class.getName() + "." + TEST_NAME); - + // WHEN PrismObject resourceProvisioning = provisioningService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, null, result); @@ -157,25 +157,25 @@ public void test011GetResourceAgain() throws Exception { assertHasSchema(resourceProvisioning, "provisioning resource(1)"); assertSchemaMetadataUnchanged(resourceProvisioning); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); - + assertResourceVersionIncrement(resourceProvisioning, 0); - + display("Resource cache (1)", InternalMonitor.getResourceCacheStats()); assertResourceCacheHitsIncrement(1); assertResourceCacheMissesIncrement(0); - + assertResourceSchemaUnchanged(RefinedResourceSchemaImpl.getResourceSchema(resourceProvisioning, prismContext)); assertRefinedResourceSchemaUnchanged(RefinedResourceSchemaImpl.getRefinedSchema(resourceProvisioning)); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); - + assertConnectorInstanceUnchanged(resourceProvisioning); - + // WHEN resourceProvisioning = provisioningService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, null, result); @@ -186,25 +186,25 @@ public void test011GetResourceAgain() throws Exception { assertHasSchema(resourceProvisioning, "provisioning resource(2)"); assertSchemaMetadataUnchanged(resourceProvisioning); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); - + assertResourceVersionIncrement(resourceProvisioning, 0); - + display("Resource cache (1)", InternalMonitor.getResourceCacheStats()); assertResourceCacheHitsIncrement(1); assertResourceCacheMissesIncrement(0); - + assertResourceSchemaUnchanged(RefinedResourceSchemaImpl.getResourceSchema(resourceProvisioning, prismContext)); assertRefinedResourceSchemaUnchanged(RefinedResourceSchemaImpl.getRefinedSchema(resourceProvisioning)); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); - + assertConnectorInstanceUnchanged(resourceProvisioning); } - + /** * Add new account. This is connector operation. Check that the initialized connector is * reused and that it is not initialized again. Check that resource is still cached. @@ -216,15 +216,15 @@ public void test012AddAccountGetResource() throws Exception { // GIVEN OperationResult result = new OperationResult(TestDummyResourceAndSchemaCaching.class.getName() + "." + TEST_NAME); - + // WHEN addAccount(ACCOUNT_WILL_FILE); - + // THEN display("Resource cache (1)", InternalMonitor.getResourceCacheStats()); assertResourceCacheHitsIncrement(1); assertResourceCacheMissesIncrement(0); - + PrismObject resourceProvisioning = provisioningService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, null, result); display("Resource(2)", resource); result.computeStatus(); @@ -232,27 +232,27 @@ public void test012AddAccountGetResource() throws Exception { assertHasSchema(resourceProvisioning, "provisioning resource(2)"); assertSchemaMetadataUnchanged(resourceProvisioning); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); - + assertResourceVersionIncrement(resourceProvisioning, 0); - + display("Resource cache (2)", InternalMonitor.getResourceCacheStats()); assertResourceCacheHitsIncrement(1); assertResourceCacheMissesIncrement(0); - + assertResourceSchemaUnchanged(RefinedResourceSchemaImpl.getResourceSchema(resourceProvisioning, prismContext)); assertRefinedResourceSchemaUnchanged(RefinedResourceSchemaImpl.getRefinedSchema(resourceProvisioning)); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); - + 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. @@ -265,17 +265,17 @@ public void test020ModifyAndGetResource() throws Exception { Task task = taskManager.createTaskInstance(TestDummyResourceAndSchemaCaching.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // Change something that's not that important ProjectionPolicyType accountSynchronizationSettingsType = new ProjectionPolicyType(); accountSynchronizationSettingsType.setLegalize(true); - - ObjectDelta objectDelta = ObjectDelta.createModificationReplaceProperty(ResourceType.class, RESOURCE_DUMMY_OID, + + ObjectDelta objectDelta = ObjectDelta.createModificationReplaceProperty(ResourceType.class, RESOURCE_DUMMY_OID, ResourceType.F_PROJECTION, prismContext, accountSynchronizationSettingsType); - + // WHEN provisioningService.modifyObject(ResourceType.class, RESOURCE_DUMMY_OID, objectDelta.getModifications(), null, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); @@ -293,27 +293,27 @@ public void test020ModifyAndGetResource() throws Exception { assertHasSchema(resourceProvisioning, "provisioning resource"); assertSchemaMetadataUnchanged(resourceProvisioning); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 1); - + assertResourceVersionIncrement(resourceProvisioning, 0); - + display("Resource cache", InternalMonitor.getResourceCacheStats()); assertResourceCacheHitsIncrement(0); assertResourceCacheMissesIncrement(1); - + // There are expected to be re-parsed rememberResourceSchema(RefinedResourceSchemaImpl.getResourceSchema(resourceProvisioning, prismContext)); rememberRefinedResourceSchema(RefinedResourceSchemaImpl.getRefinedSchema(resourceProvisioning)); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); - + assertConnectorInstanceUnchanged(resourceProvisioning); } - + /** * Get the account. This is connector operation. Check that the initialized connector is * reused and that it is not initialized again. Check that resource is still cached. @@ -325,15 +325,15 @@ public void test022GetAccountGetResource() throws Exception { // GIVEN OperationResult result = new OperationResult(TestDummyResourceAndSchemaCaching.class.getName() + "." + TEST_NAME); - + // WHEN getAccount(ACCOUNT_WILL_OID); - + // THEN display("Resource cache (1)", InternalMonitor.getResourceCacheStats()); assertResourceCacheHitsIncrement(1); assertResourceCacheMissesIncrement(0); - + PrismObject resourceProvisioning = provisioningService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, null, result); display("Resource(2)", resource); result.computeStatus(); @@ -341,30 +341,30 @@ public void test022GetAccountGetResource() throws Exception { assertHasSchema(resourceProvisioning, "provisioning resource(2)"); assertSchemaMetadataUnchanged(resourceProvisioning); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); - + assertResourceVersionIncrement(resourceProvisioning, 0); - + display("Resource cache (2)", InternalMonitor.getResourceCacheStats()); assertResourceCacheHitsIncrement(1); assertResourceCacheMissesIncrement(0); - + assertResourceSchemaUnchanged(RefinedResourceSchemaImpl.getResourceSchema(resourceProvisioning, prismContext)); assertRefinedResourceSchemaUnchanged(RefinedResourceSchemaImpl.getRefinedSchema(resourceProvisioning)); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); - + assertConnectorInstanceUnchanged(resourceProvisioning); } - + /** * 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. */ @@ -376,17 +376,17 @@ public void test023ModifyRepoAndGetResource() throws Exception { Task task = taskManager.createTaskInstance(TestDummyResourceAndSchemaCaching.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // Change something that's not that important ProjectionPolicyType accountSynchronizationSettingsType = new ProjectionPolicyType(); accountSynchronizationSettingsType.setLegalize(true); - - ObjectDelta objectDelta = ObjectDelta.createModificationReplaceProperty(ResourceType.class, RESOURCE_DUMMY_OID, + + ObjectDelta objectDelta = ObjectDelta.createModificationReplaceProperty(ResourceType.class, RESOURCE_DUMMY_OID, ResourceType.F_PROJECTION, prismContext, accountSynchronizationSettingsType); - + // WHEN repositoryService.modifyObject(ResourceType.class, RESOURCE_DUMMY_OID, objectDelta.getModifications(), result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); @@ -404,27 +404,27 @@ public void test023ModifyRepoAndGetResource() throws Exception { assertHasSchema(resourceProvisioning, "provisioning resource"); assertSchemaMetadataUnchanged(resourceProvisioning); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 1); - + assertResourceVersionIncrement(resourceProvisioning, 0); - + display("Resource cache", InternalMonitor.getResourceCacheStats()); assertResourceCacheHitsIncrement(0); assertResourceCacheMissesIncrement(1); - + // There are expected to be re-parsed rememberResourceSchema(RefinedResourceSchemaImpl.getResourceSchema(resourceProvisioning, prismContext)); rememberRefinedResourceSchema(RefinedResourceSchemaImpl.getRefinedSchema(resourceProvisioning)); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); - + assertConnectorInstanceUnchanged(resourceProvisioning); } - + /** * Change part of connector configuration. The cached resource should be refreshed, the schema re-parsed. * The connector also needs to re-initialized. @@ -437,27 +437,27 @@ public void test030ModifyConnectorConfigAndGetResource() throws Exception { Task task = taskManager.createTaskInstance(TestDummyResourceAndSchemaCaching.class.getName() + "." + TEST_NAME); 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); - + // WHEN provisioningService.modifyObject(ResourceType.class, RESOURCE_DUMMY_OID, modifications, null, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + assertConnectorConfigChanged(); } - + /** * Change part of connector configuration. Change it directly in repo to simulate change - * from another midPoint node. - * + * from another midPoint node. + * * The cached resource should be refreshed, the schema re-parsed. * The connector also needs to re-initialized. */ @@ -469,23 +469,23 @@ public void test031ModifyConnectorConfigRepoAndGetResource() throws Exception { Task task = taskManager.createTaskInstance(TestDummyResourceAndSchemaCaching.class.getName() + "." + TEST_NAME); 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); - + // WHEN repositoryService.modifyObject(ResourceType.class, RESOURCE_DUMMY_OID, modifications, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + assertConnectorConfigChanged(); } - + @Test public void test900DeleteResource() throws Exception { final String TEST_NAME = "test900DeleteResource"; @@ -494,40 +494,40 @@ public void test900DeleteResource() throws Exception { Task task = taskManager.createTaskInstance(TestDummyResourceAndSchemaCaching.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN provisioningService.deleteObject(ResourceType.class, RESOURCE_DUMMY_OID, null, null, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + try { repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, result); AssertJUnit.fail("Resource not gone from repo"); } catch (ObjectNotFoundException e) { // This is expected } - + try { provisioningService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, task, result); AssertJUnit.fail("Resource not gone from provisioning"); } catch (ObjectNotFoundException e) { // This is expected } - + } - + private PropertyDelta createUselessStringDelta(String newVal) { PropertyDelta uselessStringDelta = PropertyDelta.createModificationReplaceProperty( - new ItemPath(ResourceType.F_CONNECTOR_CONFIGURATION, + new ItemPath(ResourceType.F_CONNECTOR_CONFIGURATION, SchemaConstants.CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_QNAME, DummyResourceContoller.CONNECTOR_DUMMY_USELESS_STRING_QNAME), new PrismPropertyDefinitionImpl(DummyResourceContoller.CONNECTOR_DUMMY_USELESS_STRING_QNAME, DOMUtil.XSD_STRING, prismContext), newVal); return uselessStringDelta; } - + private void assertConnectorConfigChanged() throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { Task task = taskManager.createTaskInstance(TestDummyResourceAndSchemaCaching.class.getName() + ".assertConnectorConfigChanged"); @@ -546,41 +546,41 @@ private void assertConnectorConfigChanged() throws ObjectNotFoundException, Sche assertHasSchema(resourceProvisioning, "provisioning resource"); assertSchemaMetadataUnchanged(resourceProvisioning); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 1); - + assertResourceVersionIncrement(resourceProvisioning, 0); - + display("Resource cache", InternalMonitor.getResourceCacheStats()); assertResourceCacheHitsIncrement(0); assertResourceCacheMissesIncrement(1); - + // There are expected to be re-parsed rememberResourceSchema(RefinedResourceSchemaImpl.getResourceSchema(resourceProvisioning, prismContext)); rememberRefinedResourceSchema(RefinedResourceSchemaImpl.getRefinedSchema(resourceProvisioning)); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); - + // WHEN getAccount(ACCOUNT_WILL_OID); - + // THEN display("Resource cache (2)", InternalMonitor.getResourceCacheStats()); assertResourceCacheHitsIncrement(1); assertResourceCacheMissesIncrement(0); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 1); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); - + assertConnectorInstanceChanged(resourceProvisioning); } - + private String addAccount(File file) throws SchemaException, ObjectAlreadyExistsException, CommunicationException, ObjectNotFoundException, ConfigurationException, SecurityViolationException, IOException, ExpressionEvaluationException { Task task = taskManager.createTaskInstance(TestDummyResourceAndSchemaCaching.class.getName() + ".addAccount"); @@ -591,7 +591,7 @@ private String addAccount(File file) throws SchemaException, ObjectAlreadyExists TestUtil.assertSuccess(result); return oid; } - + private PrismObject getAccount(String oid) throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { OperationResult result = new OperationResult(TestDummyResourceAndSchemaCaching.class.getName() + ".getAccount"); 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 bf860537335..97d9db81292 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 @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.provisioning.impl.dummy; @@ -75,9 +75,9 @@ * The test of Provisioning service on the API level. The test is using dummy * resource WITHOUT A SCHEMA. It checks if the system is still able to basically operate. * Even though the resource will not be usable until the schema is specified manually. - * + * * @author Radovan Semancik - * + * */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext @@ -88,11 +88,11 @@ public class TestDummySchemaless extends AbstractIntegrationTest { private static final File RESOURCE_DUMMY_NO_SCHEMA_FILE = new File(TEST_DIR, "resource-dummy-schemaless-no-schema.xml"); private static final String RESOURCE_DUMMY_NO_SCHEMA_OID = "ef2bc95b-76e0-59e2-86d6-9999dddd0000"; private static final String RESOURCE_DUMMY_NO_SCHEMA_INSTANCE_ID = "schemaless"; - + private static final File RESOURCE_DUMMY_STATIC_SCHEMA_FILE = new File(TEST_DIR, "resource-dummy-schemaless-static-schema.xml"); private static final String RESOURCE_DUMMY_STATIC_SCHEMA_OID = "ef2bc95b-76e0-59e2-86d6-9999dddd0505"; private static final String RESOURCE_DUMMY_STATIC_SCHEMA_INSTANCE_ID = "staticSchema"; - + private static final File ACCOUNT_WILL_FILE = new File(TEST_DIR, "account-will.xml"); private static final String ACCOUNT_WILL_OID = "c0c010c0-d34d-b44f-f11d-33322212dddd"; private static final String ACCOUNT_WILL_ICF_UID = "will"; @@ -102,7 +102,7 @@ public class TestDummySchemaless extends AbstractIntegrationTest { private PrismObject resourceSchemaless; private ResourceType resourceTypeSchemaless; private static DummyResource dummyResourceSchemaless; - + private PrismObject resourceStaticSchema; private ResourceType resourceTypeStaticSchema; private static DummyResource dummyResourceStaticSchema; @@ -117,14 +117,14 @@ public TestDummySchemaless() { /* * (non-Javadoc) - * + * * @see com.evolveum.midpoint.test.AbstractIntegrationTest#initSystem() */ @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { provisioningService.postInit(initResult); - + InternalsConfig.encryptionChecks = false; resourceSchemaless = addResourceFromFile(RESOURCE_DUMMY_NO_SCHEMA_FILE, IntegrationTestTools.DUMMY_CONNECTOR_TYPE, initResult); @@ -133,7 +133,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti dummyResourceSchemalessCtl = DummyResourceContoller.create(RESOURCE_DUMMY_NO_SCHEMA_INSTANCE_ID); dummyResourceSchemalessCtl.setResource(resourceSchemaless); dummyResourceSchemaless = dummyResourceSchemalessCtl.getDummyResource(); - + resourceStaticSchema = addResourceFromFile(RESOURCE_DUMMY_STATIC_SCHEMA_FILE, IntegrationTestTools.DUMMY_CONNECTOR_TYPE, initResult); resourceTypeStaticSchema = resourceStaticSchema.asObjectable(); @@ -159,7 +159,7 @@ public void test000Integrity() throws Exception { ResourceType resource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_NO_SCHEMA_OID, null, result) .asObjectable(); String connectorOid = resource.getConnectorRef().getOid(); - + ConnectorType connector = repositoryService.getObject(ConnectorType.class, connectorOid, null, result).asObjectable(); assertNotNull(connector); display("Dummy Connector", connector); @@ -167,11 +167,11 @@ public void test000Integrity() throws Exception { // Check connector schema 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. @@ -233,7 +233,7 @@ public void test005ParsedSchemaSchemaless() throws Exception { ResourceSchema returnedSchema = RefinedResourceSchemaImpl.getResourceSchema(resourceTypeSchemaless, prismContext); display("Parsed resource schema", returnedSchema); - + assertNull("Unexpected schema after parsing", returnedSchema); } @@ -248,12 +248,12 @@ public void test006GetObjectSchemaless() throws Exception { assertNotNull("Resource is null", resource); ResourceType resourceType = resource.asObjectable(); assertNotNull("No connector ref", resourceType.getConnectorRef()); - assertNotNull("No connector ref OID", resourceType.getConnectorRef().getOid()); + assertNotNull("No connector ref OID", resourceType.getConnectorRef().getOid()); } /** * 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. @@ -267,7 +267,7 @@ public void test103ConnectionStaticSchema() throws Exception { OperationResult result = task.getResult(); // Check that there a schema before test (pre-condition) - ResourceType resourceBefore = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_STATIC_SCHEMA_OID, null, + ResourceType resourceBefore = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_STATIC_SCHEMA_OID, null, result) .asObjectable(); XmlSchemaType xmlSchemaTypeBefore = resourceBefore.getSchema(); @@ -292,7 +292,7 @@ public void test103ConnectionStaticSchema() throws Exception { RESOURCE_DUMMY_NO_SCHEMA_OID, null, result); ResourceType resourceTypeRepoAfter = resourceRepoAfter.asObjectable(); display("Resource after test", resourceTypeRepoAfter); - + // TODO } @@ -315,7 +315,7 @@ public void test105ParsedSchemaStaticSchema() throws Exception { display("Parsed resource schema", returnedSchema); assertNotNull("Null resource schema", returnedSchema); - + dummyResourceSchemalessCtl.assertDummyResourceSchemaSanity(returnedSchema, resourceTypeStaticSchema, true); } @@ -331,15 +331,15 @@ public void test106GetObjectStaticSchema() throws Exception { ResourceType resourceType = resource.asObjectable(); assertNotNull("No connector ref", resourceType.getConnectorRef()); assertNotNull("No connector ref OID", resourceType.getConnectorRef().getOid()); - + ResourceSchema returnedSchema = RefinedResourceSchemaImpl.getResourceSchema(resource, prismContext); display("Parsed resource schema", returnedSchema); assertNotNull("Null resource schema", returnedSchema); - + dummyResourceSchemalessCtl.assertDummyResourceSchemaSanity(returnedSchema, resource.asObjectable(), true); } - + @Test public void test107Capabilities() throws Exception { final String TEST_NAME = "test107Capabilities"; @@ -371,7 +371,7 @@ public void test107Capabilities() throws Exception { assertNotNull("native script capability not present", capScript); assertNotNull("No host in native script capability", capScript.getHost()); assertFalse("No host in native script capability", capScript.getHost().isEmpty()); - + CredentialsCapabilityType capCred = CapabilityUtil.getCapability(nativeCapabilitiesList, CredentialsCapabilityType.class); assertNull("Unexpected native credentials capability", capCred); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummySecurity.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummySecurity.java index adfc7b30859..57df85bda86 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummySecurity.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummySecurity.java @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.provisioning.impl.dummy; @@ -56,9 +56,9 @@ /** * The test of Provisioning service on the API level. The test is using dummy * resource for speed and flexibility. - * + * * @author Radovan Semancik - * + * */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext @@ -80,7 +80,7 @@ public void test100AddAccountDrink() throws Exception { PrismObject account = prismContext.parseObject(ACCOUNT_WILL_FILE); account.checkConsistence(); - + setAttribute(account, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, "water"); display("Adding shadow", account); @@ -88,22 +88,22 @@ public void test100AddAccountDrink() throws Exception { try { // WHEN provisioningService.addObject(account, null, null, syncTask, result); - + AssertJUnit.fail("Unexpected success"); - + } catch (SecurityViolationException e) { // This is expected display("Expected exception", e); } } - + private void setAttribute(PrismObject account, String attrName, T val) throws SchemaException { PrismContainer attrsCont = account.findContainer(ShadowType.F_ATTRIBUTES); ResourceAttribute attr = new ResourceAttribute( dummyResourceCtl.getAttributeQName(attrName), null, prismContext); attr.setRealValue(val); - attrsCont.add(attr); + attrsCont.add(attr); } @Test @@ -119,7 +119,7 @@ public void test199AddAccount() throws Exception { PrismObject account = prismContext.parseObject(ACCOUNT_WILL_FILE); account.checkConsistence(); - + setAttribute(account, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "At the moment?"); setAttribute(account, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "Eunuch"); @@ -127,7 +127,7 @@ public void test199AddAccount() throws Exception { // WHEN provisioningService.addObject(account, null, null, syncTask, result); - + // THEN PrismObject accountProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, syncTask, result); @@ -135,7 +135,7 @@ public void test199AddAccount() throws Exception { willIcfUid = getIcfUid(accountProvisioning); } - + @Test public void test200ModifyAccountDrink() throws Exception { final String TEST_NAME = "test200ModifyAccountDrink"; @@ -144,12 +144,12 @@ public void test200ModifyAccountDrink() throws Exception { Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + syncServiceMock.reset(); - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, - ACCOUNT_WILL_OID, - dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME), + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, + ACCOUNT_WILL_OID, + dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME), prismContext, "RUM"); display("ObjectDelta", delta); delta.checkConsistence(); @@ -162,14 +162,14 @@ public void test200ModifyAccountDrink() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); assertDummyAccountAttributeValues(ACCOUNT_WILL_USERNAME, willIcfUid, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, "RUM"); - + syncServiceMock.assertNotifySuccessOnly(); } - + @Test public void test201ModifyAccountGossip() throws Exception { final String TEST_NAME = "test201ModifyAccountGossip"; @@ -178,12 +178,12 @@ public void test201ModifyAccountGossip() throws Exception { Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + syncServiceMock.reset(); - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, - ACCOUNT_WILL_OID, - dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME), + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, + ACCOUNT_WILL_OID, + dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME), prismContext, "pirate"); display("ObjectDelta", delta); delta.checkConsistence(); @@ -196,14 +196,14 @@ public void test201ModifyAccountGossip() throws Exception { result.computeStatus(); display("modifyObject result", result); TestUtil.assertSuccess(result); - + delta.checkConsistence(); - assertDummyAccountAttributeValues(ACCOUNT_WILL_USERNAME, willIcfUid, + assertDummyAccountAttributeValues(ACCOUNT_WILL_USERNAME, willIcfUid, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "pirate"); - + syncServiceMock.assertNotifySuccessOnly(); } - + @Test public void test210ModifyAccountQuote() throws Exception { final String TEST_NAME = "test210ModifyAccountQuote"; @@ -212,12 +212,12 @@ public void test210ModifyAccountQuote() throws Exception { Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + syncServiceMock.reset(); - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, - ACCOUNT_WILL_OID, - dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME), + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, + ACCOUNT_WILL_OID, + dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME), prismContext, "eh?"); display("ObjectDelta", delta); delta.checkConsistence(); @@ -226,15 +226,15 @@ public void test210ModifyAccountQuote() throws Exception { // WHEN provisioningService.modifyObject(ShadowType.class, delta.getOid(), delta.getModifications(), new OperationProvisioningScriptsType(), null, task, result); - + AssertJUnit.fail("Unexpected success"); - + } catch (SecurityViolationException e) { // This is expected display("Expected exception", e); } } - + @Test public void test300GetAccount() throws Exception { final String TEST_NAME = "test300GetAccount"; @@ -259,7 +259,7 @@ public void test300GetAccount() throws Exception { checkConsistency(shadow); } - + @Test public void test310SearchAllShadows() throws Exception { final String TEST_NAME = "test310SearchAllShadows"; @@ -274,28 +274,28 @@ public void test310SearchAllShadows() throws Exception { // WHEN List> allShadows = provisioningService.searchObjects(ShadowType.class, query, null, null, result); - + // THEN result.computeStatus(); display("searchObjects result", result); TestUtil.assertSuccess(result); - + display("Found " + allShadows.size() + " shadows"); assertFalse("No shadows found", allShadows.isEmpty()); - + checkConsistency(allShadows); - + for (PrismObject shadow: allShadows) { assertNoAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME); assertNoAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WATER_NAME); } - + assertEquals("Wrong number of results", 2, allShadows.size()); } - + // TODO: search - + private void checkAccountWill(PrismObject shadow, OperationResult result) { Collection> attributes = ShadowUtil.getAttributes(shadow); assertAttribute(shadow, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "Flying Dutchman"); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyUuid.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyUuid.java index b0499f9957b..f9270c96149 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyUuid.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyUuid.java @@ -22,14 +22,14 @@ /** * Almost the same as TestDummy but this is using a UUID as ICF UID. - * + * * @author Radovan Semancik * */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext public class TestDummyUuid extends TestDummy { - + public static final File TEST_DIR = new File(TEST_DIR_DUMMY, "dummy-uuid"); public static final File RESOURCE_DUMMY_FILE = new File(TEST_DIR, "resource-dummy.xml"); @@ -42,10 +42,10 @@ protected File getResourceDummyFilename() { protected boolean isIcfNameUidSame() { return false; } - + @Override protected boolean isNameUnique(){ return false; } - + } 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 318036e67ea..24fb75a00f8 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 @@ -63,17 +63,17 @@ /** * Almost the same as TestDummy but this is using a UUID as ICF UID. - * + * * @author Radovan Semancik * */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext public class TestDummyUuidNonUniqueName extends TestDummyUuid { - + public static final File TEST_DIR = new File(TEST_DIR_DUMMY, "dummy-uuid-nonunique-name"); public static final File RESOURCE_DUMMY_FILE = new File(TEST_DIR, "resource-dummy.xml"); - + public static final String ACCOUNT_FETTUCINI_NAME = "fettucini"; public static final File ACCOUNT_FETTUCINI_ALFREDO_FILE = new File(TEST_DIR, "account-alfredo-fettucini.xml"); public static final String ACCOUNT_FETTUCINI_ALFREDO_OID = "c0c010c0-d34d-b44f-f11d-444400009ffa"; @@ -87,12 +87,12 @@ public class TestDummyUuidNonUniqueName extends TestDummyUuid { protected File getResourceDummyFilename() { return RESOURCE_DUMMY_FILE; } - + @Override protected boolean isNameUnique() { return false; } - + @Test public void test770AddAccountFettuciniAlfredo() throws Exception { final String TEST_NAME = "test770AddAccountFettuciniAlfredo"; @@ -100,7 +100,7 @@ public void test770AddAccountFettuciniAlfredo() throws Exception { addFettucini(TEST_NAME, ACCOUNT_FETTUCINI_ALFREDO_FILE, ACCOUNT_FETTUCINI_ALFREDO_OID, ACCOUNT_FETTUCINI_ALFREDO_FULLNAME); searchFettucini(1); } - + @Test public void test772AddAccountFettuciniBill() throws Exception { final String TEST_NAME = "test772AddAccountFettuciniBill"; @@ -108,7 +108,7 @@ public void test772AddAccountFettuciniBill() throws Exception { addFettucini(TEST_NAME, ACCOUNT_FETTUCINI_BILL_FILE, ACCOUNT_FETTUCINI_BILL_OID, ACCOUNT_FETTUCINI_BILL_FULLNAME); searchFettucini(2); } - + /** * Add directly on resource. Therefore provisioning must create the shadow during search. */ @@ -119,7 +119,7 @@ public void test774AddAccountFettuciniCarlo() throws Exception { dummyResourceCtl.addAccount(ACCOUNT_FETTUCINI_NAME, ACCOUNT_FETTUCINI_CARLO_FULLNAME); searchFettucini(3); } - + @Override @Test public void test600AddAccountAlreadyExist() throws Exception { @@ -155,7 +155,7 @@ private String addFettucini(final String TEST_NAME, File file, String oid, Strin assertEquals("Wrong kind (repo)", ShadowKindType.ACCOUNT, accountTypeRepo.getKind()); assertAttribute(accountRepo, SchemaConstants.ICFS_NAME, ACCOUNT_FETTUCINI_NAME); String icfUid = getIcfUid(accountRepo); - + syncServiceMock.assertNotifySuccessOnly(); PrismObject accountProvisioning = provisioningService.getObject(ShadowType.class, @@ -183,10 +183,10 @@ private String addFettucini(final String TEST_NAME, File file, String oid, Strin checkConsistency(accountProvisioning); assertSteadyResource(); - + return icfUid; } - + private void searchFettucini(int expectedNumberOfFettucinis) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { Task task = createTask(TestDummy.class.getName() + ".searchFettucini"); OperationResult result = task.getResult(); @@ -205,5 +205,5 @@ private PrismPropertyDefinition getIcfNameDefinition() { return new PrismPropertyDefinitionImpl<>(SchemaConstants.ICFS_NAME, DOMUtil.XSD_STRING, prismContext); } - + } 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 aa8ded7cc0a..3aac919147f 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 @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.provisioning.impl.manual; @@ -114,17 +114,17 @@ public abstract class AbstractManualResourceTest extends AbstractProvisioningIntegrationTest { protected static final File TEST_DIR = new File("src/test/resources/manual/"); - + protected static final File RESOURCE_MANUAL_FILE = new File(TEST_DIR, "resource-manual.xml"); protected static final String RESOURCE_MANUAL_OID = "8a8e19de-1a14-11e7-965f-6f995b457a8b"; - + protected static final File RESOURCE_SEMI_MANUAL_FILE = new File(TEST_DIR, "resource-semi-manual.xml"); protected static final String RESOURCE_SEMI_MANUAL_OID = "8a8e19de-1a14-11e7-965f-6f995b457a8b"; public static final QName RESOURCE_ACCOUNT_OBJECTCLASS = new QName(MidPointConstants.NS_RI, "AccountObjectClass"); - + protected static final String MANUAL_CONNECTOR_TYPE = "ManualConnector"; - + private static final Trace LOGGER = TraceManager.getTrace(AbstractManualResourceTest.class); protected static final String NS_MANUAL_CONF = "http://midpoint.evolveum.com/xml/ns/public/connector/builtin-1/bundle/com.evolveum.midpoint.provisioning.ucf.impl.builtin/ManualConnector"; @@ -141,23 +141,23 @@ public abstract class AbstractManualResourceTest extends AbstractProvisioningInt protected static final String ATTR_USERNAME = "username"; protected static final QName ATTR_USERNAME_QNAME = new QName(MidPointConstants.NS_RI, ATTR_USERNAME); - + protected static final String ATTR_FULLNAME = "fullname"; protected static final QName ATTR_FULLNAME_QNAME = new QName(MidPointConstants.NS_RI, ATTR_FULLNAME); - + protected static final String ATTR_DESCRIPTION = "description"; protected static final QName ATTR_DESCRIPTION_QNAME = new QName(MidPointConstants.NS_RI, ATTR_DESCRIPTION); protected PrismObject resource; protected ResourceType resourceType; - + protected XMLGregorianCalendar accountWillReqestTimestampStart; protected XMLGregorianCalendar accountWillReqestTimestampEnd; - + protected XMLGregorianCalendar accountWillCompletionTimestampStart; protected XMLGregorianCalendar accountWillCompletionTimestampEnd; - + protected XMLGregorianCalendar accountWillSecondReqestTimestampStart; protected XMLGregorianCalendar accountWillSecondReqestTimestampEnd; @@ -166,24 +166,24 @@ public abstract class AbstractManualResourceTest extends AbstractProvisioningInt protected String willLastCaseOid; protected String willSecondLastCaseOid; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { // We need to switch off the encryption checks. Some values cannot be encrypted as we do // not have a definition here InternalsConfig.encryptionChecks = false; - + super.initSystem(initTask, initResult); - + InternalsConfig.setSanityChecks(true); } - + protected abstract File getResourceFile(); - + protected String getResourceOid() { return RESOURCE_MANUAL_OID; } - + protected boolean supportsBackingStore() { return false; } @@ -192,7 +192,7 @@ protected boolean supportsBackingStore() { public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; TestUtil.displayTestTitle(TEST_NAME); - + assertNotNull("Resource is null", resource); assertNotNull("ResourceType is null", resourceType); @@ -208,7 +208,7 @@ public void test000Sanity() throws Exception { .getObject(ConnectorType.class, connectorOid, null, result).asObjectable(); assertNotNull(repoConnector); display("Manual Connector", repoConnector); - + // Check connector schema IntegrationTestTools.assertConnectorSchemaSanity(repoConnector, prismContext); } @@ -220,14 +220,14 @@ public void test003Connection() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // Check that there is a schema, but no capabilities before test (pre-condition) ResourceType resourceBefore = repositoryService.getObject(ResourceType.class, getResourceOid(), null, result).asObjectable(); - + Element resourceXsdSchemaElementBefore = ResourceTypeUtil.getResourceXsdSchema(resourceBefore); assertResourceSchemaBeforeTest(resourceXsdSchemaElementBefore); - + CapabilitiesType capabilities = resourceBefore.getCapabilities(); if (capabilities != null) { AssertJUnit.assertNull("Native capabilities present before test connection. Bad test setup?", capabilities.getNative()); @@ -241,14 +241,14 @@ public void test003Connection() throws Exception { TestUtil.assertSuccess("Test resource failed (result)", testResult); PrismObject resourceRepoAfter = repositoryService.getObject(ResourceType.class, getResourceOid(), null, result); - ResourceType resourceTypeRepoAfter = resourceRepoAfter.asObjectable(); + ResourceType resourceTypeRepoAfter = resourceRepoAfter.asObjectable(); display("Resource after test", resourceTypeRepoAfter); XmlSchemaType xmlSchemaTypeAfter = resourceTypeRepoAfter.getSchema(); assertNotNull("No schema after test connection", xmlSchemaTypeAfter); Element resourceXsdSchemaElementAfter = ResourceTypeUtil.getResourceXsdSchema(resourceTypeRepoAfter); assertNotNull("No schema after test connection", resourceXsdSchemaElementAfter); - + String resourceXml = prismContext.serializeObjectToString(resourceRepoAfter, PrismContext.LANG_XML); display("Resource XML", resourceXml); @@ -263,7 +263,7 @@ public void test003Connection() throws Exception { // schema will be checked in next test } - + protected abstract void assertResourceSchemaBeforeTest(Element resourceXsdSchemaElementBefore); @Test @@ -284,11 +284,11 @@ public void test004Configuration() throws Exception { assertNotNull("No configuration container definition", confContDef); PrismProperty propDefaultAssignee = configurationContainer.findProperty(CONF_PROPERTY_DEFAULT_ASSIGNEE_QNAME); assertNotNull("No defaultAssignee conf prop", propDefaultAssignee); - + // assertNotNull("No configuration properties container", confingurationPropertiesContainer); // PrismContainerDefinition confPropDef = confingurationPropertiesContainer.getDefinition(); // assertNotNull("No configuration properties container definition", confPropDef); - + } @Test @@ -304,22 +304,22 @@ public void test005ParsedSchema() throws Exception { // Also test if the utility method returns the same thing ResourceSchema resourceSchema = RefinedResourceSchemaImpl.getResourceSchema(resourceType, prismContext); - + display("Parsed resource schema", resourceSchema); // 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)); - + ObjectClassComplexTypeDefinition accountDef = resourceSchema.findObjectClassDefinition(RESOURCE_ACCOUNT_OBJECTCLASS); assertNotNull("Account definition is missing", accountDef); assertNotNull("Null identifiers in account", accountDef.getPrimaryIdentifiers()); assertFalse("Empty identifiers in account", accountDef.getPrimaryIdentifiers().isEmpty()); assertNotNull("No naming attribute in account", accountDef.getNamingAttribute()); - + assertEquals("Unexpected number of definitions", getNumberOfAccountAttributeDefinitions(), accountDef.getDefinitions().size()); - + ResourceAttributeDefinition usernameDef = accountDef.findAttributeDefinition(ATTR_USERNAME); assertNotNull("No definition for username", usernameDef); assertEquals(1, usernameDef.getMaxOccurs()); @@ -327,7 +327,7 @@ public void test005ParsedSchema() throws Exception { assertTrue("No username create", usernameDef.canAdd()); assertTrue("No username update", usernameDef.canModify()); assertTrue("No username read", usernameDef.canRead()); - + ResourceAttributeDefinition fullnameDef = accountDef.findAttributeDefinition(ATTR_FULLNAME); assertNotNull("No definition for fullname", fullnameDef); assertEquals(1, fullnameDef.getMaxOccurs()); @@ -336,7 +336,7 @@ public void test005ParsedSchema() throws Exception { assertTrue("No fullname update", fullnameDef.canModify()); assertTrue("No fullname read", fullnameDef.canRead()); } - + protected int getNumberOfAccountAttributeDefinitions() { return 4; } @@ -351,11 +351,11 @@ public void test006Capabilities() throws Exception { // WHEN ResourceType resource = provisioningService.getObject(ResourceType.class, getResourceOid(), null, null, result).asObjectable(); - + // THEN display("Resource from provisioninig", resource); display("Resource from provisioninig (XML)", PrismTestUtil.serializeObjectToString(resource.asPrismObject(), PrismContext.LANG_XML)); - + CapabilityCollectionType nativeCapabilities = resource.getCapabilities().getNative(); List nativeCapabilitiesList = nativeCapabilities.getAny(); assertFalse("Empty capabilities returned",nativeCapabilitiesList.isEmpty()); @@ -363,19 +363,19 @@ public void test006Capabilities() throws Exception { CreateCapabilityType capCreate = CapabilityUtil.getCapability(nativeCapabilitiesList, CreateCapabilityType.class); assertNotNull("Missing create capability", capCreate); assertManual(capCreate); - + ActivationCapabilityType capAct = CapabilityUtil.getCapability(nativeCapabilitiesList, ActivationCapabilityType.class); assertNotNull("Missing activation capability", capAct); - + ReadCapabilityType capRead = CapabilityUtil.getCapability(nativeCapabilitiesList, ReadCapabilityType.class); assertNotNull("Missing read capability" ,capRead); assertEquals("Wrong caching-only setting in read capability", Boolean.TRUE, capRead.isCachingOnly()); - + List effectiveCapabilities = ResourceTypeUtil.getEffectiveCapabilities(resource); for (Object capability : effectiveCapabilities) { System.out.println("Capability: "+CapabilityUtil.getCapabilityDisplayName(capability)+" : "+capability); } - + } @Test @@ -391,7 +391,7 @@ public void test100AddAccountWill() throws Exception { account.checkConsistence(); display("Adding shadow", account); - + accountWillReqestTimestampStart = clock.currentTimeXMLGregorianCalendar(); // WHEN @@ -402,7 +402,7 @@ public void test100AddAccountWill() throws Exception { displayThen(TEST_NAME); display("result", result); willLastCaseOid = assertInProgress(result); - + accountWillReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); assertEquals(ACCOUNT_WILL_OID, addedObjectOid); account.checkConsistence(); @@ -416,13 +416,13 @@ public void test100AddAccountWill() throws Exception { assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertShadowExists(shadowRepo, false); assertNoShadowPassword(shadowRepo); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNotifyInProgressOnly(); PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + display("Provisioning shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, ACCOUNT_WILL_USERNAME); @@ -434,13 +434,13 @@ public void test100AddAccountWill() throws Exception { assertNoShadowPassword(shadowProvisioning); assertSinglePendingOperation(shadowProvisioning, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); - + assertNotNull("No async reference in result", willLastCaseOid); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } - + @Test public void test102GetAccountWillFuture() throws Exception { @@ -450,7 +450,7 @@ public void test102GetAccountWillFuture() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); syncServiceMock.reset(); - + Collection> options = SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)); // WHEN @@ -459,8 +459,8 @@ public void test102GetAccountWillFuture() throws Exception { // THEN displayThen(TEST_NAME); - assertSuccess(result); - + assertSuccess(result); + display("Provisioning shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, ACCOUNT_WILL_USERNAME); @@ -470,7 +470,7 @@ public void test102GetAccountWillFuture() throws Exception { assertNoAttribute(shadowProvisioning, ATTR_DESCRIPTION_QNAME); assertShadowActivationAdministrativeStatus(shadowProvisioning, ActivationStatusType.ENABLED); assertShadowExists(shadowProvisioning, true); - // TODO + // TODO // assertShadowPassword(shadowProvisioning); } @@ -488,7 +488,7 @@ public void test104RefreshAccountWill() throws Exception { PrismObject shadowBefore = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); display("Shadow before", shadowBefore); - + // WHEN displayWhen(TEST_NAME); provisioningService.refreshShadow(shadowBefore, null, task, result); @@ -496,7 +496,7 @@ public void test104RefreshAccountWill() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); @@ -506,13 +506,13 @@ public void test104RefreshAccountWill() throws Exception { assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertNoShadowPassword(shadowRepo); assertShadowExists(shadowRepo, false); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNoNotifcations(); PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + display("Provisioning shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, ACCOUNT_WILL_USERNAME); @@ -524,14 +524,14 @@ public void test104RefreshAccountWill() throws Exception { assertNoShadowPassword(shadowProvisioning); PendingOperationType pendingOperation = assertSinglePendingOperation(shadowProvisioning, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); - + assertCase(pendingOperation.getAsynchronousOperationReference(), SchemaConstants.CASE_STATE_OPEN); } protected void backingStoreAddWill() throws IOException { // nothing to do here } - + @Test public void test106AddToBackingStoreAndGetAccountWill() throws Exception { final String TEST_NAME = "test106AddToBackingStoreAndGetAccountWill"; @@ -539,30 +539,30 @@ public void test106AddToBackingStoreAndGetAccountWill() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + backingStoreAddWill(); - + syncServiceMock.reset(); - + // WHEN displayWhen(TEST_NAME); PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); // THEN displayThen(TEST_NAME); - assertSuccess(result); - + assertSuccess(result); + display("Provisioning shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, ACCOUNT_WILL_USERNAME); assertEquals("Wrong kind (provisioning)", ShadowKindType.ACCOUNT, shadowTypeProvisioning.getKind()); assertAttribute(shadowProvisioning, ATTR_USERNAME_QNAME, ACCOUNT_WILL_USERNAME); assertAttribute(shadowProvisioning, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME); - assertAttributeFromBackingStore(shadowProvisioning, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); + assertAttributeFromBackingStore(shadowProvisioning, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowActivationAdministrativeStatus(shadowProvisioning, ActivationStatusType.ENABLED); assertShadowExists(shadowProvisioning, supportsBackingStore()); assertShadowPassword(shadowProvisioning); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); @@ -573,7 +573,7 @@ public void test106AddToBackingStoreAndGetAccountWill() throws Exception { assertNoShadowPassword(shadowRepo); assertShadowExists(shadowRepo, supportsBackingStore()); } - + @Test public void test108GetAccountWillFuture() throws Exception { final String TEST_NAME = "test108GetAccountWillFuture"; @@ -581,19 +581,19 @@ public void test108GetAccountWillFuture() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + syncServiceMock.reset(); Collection> options = SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)); - + // WHEN displayWhen(TEST_NAME); PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, options, task, result); // THEN displayThen(TEST_NAME); - assertSuccess(result); - + assertSuccess(result); + display("Provisioning shadow", shadowProvisioning); assertNotNull("no OID", shadowProvisioning.getOid()); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); @@ -601,12 +601,12 @@ public void test108GetAccountWillFuture() throws Exception { assertEquals("Wrong kind (provisioning)", ShadowKindType.ACCOUNT, shadowTypeProvisioning.getKind()); assertAttribute(shadowProvisioning, ATTR_USERNAME_QNAME, ACCOUNT_WILL_USERNAME); assertAttribute(shadowProvisioning, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME); - assertAttributeFromBackingStore(shadowProvisioning, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); + assertAttributeFromBackingStore(shadowProvisioning, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowActivationAdministrativeStatus(shadowProvisioning, ActivationStatusType.ENABLED); assertShadowExists(shadowProvisioning, true); // TODO // assertShadowPassword(shadowProvisioning); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); @@ -617,7 +617,7 @@ public void test108GetAccountWillFuture() throws Exception { assertNoShadowPassword(shadowRepo); assertShadowExists(shadowRepo, supportsBackingStore()); } - + @Test public void test109GetAccountWillFutureNoFetch() throws Exception { final String TEST_NAME = "test109GetAccountWillFutureNoFetch"; @@ -625,22 +625,22 @@ public void test109GetAccountWillFutureNoFetch() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + GetOperationOptions options = GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE); options.setNoFetch(true); - + // WHEN displayWhen(TEST_NAME); PrismObject shadowProvisioningFuture = provisioningService.getObject(ShadowType.class, - ACCOUNT_WILL_OID, + ACCOUNT_WILL_OID, SelectorOptions.createCollection(options), task, result); - - + + // THEN displayThen(TEST_NAME); assertSuccess(result); - + display("Provisioning shadow (future,noFetch)", shadowProvisioningFuture); assertNotNull("no OID", shadowProvisioningFuture.getOid()); ShadowType shadowTypeProvisioning = shadowProvisioningFuture.asObjectable(); @@ -648,13 +648,13 @@ public void test109GetAccountWillFutureNoFetch() throws Exception { assertEquals("Wrong kind (provisioning)", ShadowKindType.ACCOUNT, shadowTypeProvisioning.getKind()); assertAttribute(shadowProvisioningFuture, ATTR_USERNAME_QNAME, ACCOUNT_WILL_USERNAME); assertAttributeFromCache(shadowProvisioningFuture, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME); - assertNoAttribute(shadowProvisioningFuture, ATTR_DESCRIPTION_QNAME); + assertNoAttribute(shadowProvisioningFuture, ATTR_DESCRIPTION_QNAME); assertShadowActivationAdministrativeStatusFromCache(shadowProvisioningFuture, ActivationStatusType.ENABLED); assertShadowExists(shadowProvisioningFuture, true); // TODO // assertShadowPassword(shadowProvisioningFuture); } - + /** * Case is closed. The operation is complete. */ @@ -666,14 +666,14 @@ public void test110CloseCaseAndRefreshAccountWill() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); syncServiceMock.reset(); - + PrismObject shadowBefore = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); display("Shadow before", shadowBefore); closeCase(willLastCaseOid); - + accountWillCompletionTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); provisioningService.refreshShadow(shadowBefore, null, task, result); @@ -681,25 +681,25 @@ public void test110CloseCaseAndRefreshAccountWill() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + accountWillCompletionTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); - assertSinglePendingOperation(shadowRepo, + assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, ACCOUNT_WILL_USERNAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME); assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNotifySuccessOnly(); PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + display("Provisioning shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, ACCOUNT_WILL_USERNAME); @@ -709,15 +709,15 @@ public void test110CloseCaseAndRefreshAccountWill() throws Exception { assertAttributeFromBackingStore(shadowProvisioning, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowActivationAdministrativeStatus(shadowProvisioning, ActivationStatusType.ENABLED); assertShadowPassword(shadowProvisioning); - - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowProvisioning, + + PendingOperationType pendingOperation = assertSinglePendingOperation(shadowProvisioning, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + /** * ff 5min, everything should be the same (grace not expired yet) */ @@ -731,10 +731,10 @@ public void test120RefreshAccountWillAfter5min() throws Exception { syncServiceMock.reset(); clock.overrideDuration("PT5M"); - + PrismObject shadowBefore = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); display("Shadow before", shadowBefore); - + // WHEN displayWhen(TEST_NAME); provisioningService.refreshShadow(shadowBefore, null, task, result); @@ -742,10 +742,10 @@ public void test120RefreshAccountWillAfter5min() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); - assertSinglePendingOperation(shadowRepo, + assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); @@ -754,17 +754,17 @@ public void test120RefreshAccountWillAfter5min() throws Exception { PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowProvisioning, + PendingOperationType pendingOperation = assertSinglePendingOperation(shadowProvisioning, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNoNotifcations(); } - + /** * ff 20min, grace should expire */ @@ -778,10 +778,10 @@ public void test130RefreshAccountWillAfter25min() throws Exception { syncServiceMock.reset(); clock.overrideDuration("PT20M"); - + PrismObject shadowBefore = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); display("Shadow before", shadowBefore); - + // WHEN displayWhen(TEST_NAME); provisioningService.refreshShadow(shadowBefore, null, task, result); @@ -789,7 +789,7 @@ public void test130RefreshAccountWillAfter25min() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); assertNoPendingOperation(shadowRepo); @@ -798,9 +798,9 @@ public void test130RefreshAccountWillAfter25min() throws Exception { PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); assertNoPendingOperation(shadowProvisioning); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNoNotifcations(); } @@ -813,26 +813,26 @@ public void test200ModifyAccountWillFullname() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); syncServiceMock.reset(); - - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, - ACCOUNT_WILL_OID, new ItemPath(ShadowType.F_ATTRIBUTES, ATTR_FULLNAME_QNAME), prismContext, + + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, + ACCOUNT_WILL_OID, new ItemPath(ShadowType.F_ATTRIBUTES, ATTR_FULLNAME_QNAME), prismContext, ACCOUNT_WILL_FULLNAME_PIRATE); display("ObjectDelta", delta); accountWillReqestTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); provisioningService.modifyObject(ShadowType.class, delta.getOid(), delta.getModifications(), null, null, task, result); - + // THEN displayThen(TEST_NAME); display("result", result); willLastCaseOid = assertInProgress(result); - + accountWillReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); PendingOperationType pendingOperation = assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); @@ -841,13 +841,13 @@ ACCOUNT_WILL_OID, new ItemPath(ShadowType.F_ATTRIBUTES, ATTR_FULLNAME_QNAME), pr assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, ACCOUNT_WILL_USERNAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNotifyInProgressOnly(); PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + display("Provisioning shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, ACCOUNT_WILL_USERNAME); @@ -859,9 +859,9 @@ ACCOUNT_WILL_OID, new ItemPath(ShadowType.F_ATTRIBUTES, ATTR_FULLNAME_QNAME), pr assertShadowPassword(shadowProvisioning); assertSinglePendingOperation(shadowProvisioning, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); - + PrismObject shadowProvisioningFuture = provisioningService.getObject(ShadowType.class, - ACCOUNT_WILL_OID, + ACCOUNT_WILL_OID, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Provisioning shadow (future)", shadowProvisioningFuture); @@ -872,12 +872,12 @@ ACCOUNT_WILL_OID, new ItemPath(ShadowType.F_ATTRIBUTES, ATTR_FULLNAME_QNAME), pr assertAttribute(shadowProvisioningFuture, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioningFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioningFuture); - + assertNotNull("No async reference in result", willLastCaseOid); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } - + @Test public void test202RefreshAccountWill() throws Exception { final String TEST_NAME = "test202RefreshAccountWill"; @@ -886,18 +886,18 @@ public void test202RefreshAccountWill() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); syncServiceMock.reset(); - + PrismObject shadowBefore = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); display("Shadow before", shadowBefore); - + // WHEN displayWhen(TEST_NAME); provisioningService.refreshShadow(shadowBefore, null, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); PendingOperationType pendingOperation = assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); @@ -906,13 +906,13 @@ public void test202RefreshAccountWill() throws Exception { assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, ACCOUNT_WILL_USERNAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNoNotifcations(); PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + display("Provisioning shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, ACCOUNT_WILL_USERNAME); @@ -923,9 +923,9 @@ public void test202RefreshAccountWill() throws Exception { assertShadowPassword(shadowProvisioning); assertSinglePendingOperation(shadowProvisioning, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); - + PrismObject shadowProvisioningFuture = provisioningService.getObject(ShadowType.class, - ACCOUNT_WILL_OID, + ACCOUNT_WILL_OID, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Provisioning shadow (future)", shadowProvisioningFuture); @@ -935,11 +935,11 @@ public void test202RefreshAccountWill() throws Exception { assertAttribute(shadowProvisioningFuture, ATTR_USERNAME_QNAME, ACCOUNT_WILL_USERNAME); assertAttribute(shadowProvisioningFuture, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); assertShadowPassword(shadowProvisioningFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_OPEN); - + } - + /** * Case is closed. The operation is complete. */ @@ -956,9 +956,9 @@ public void test204CloseCaseAndRefreshAccountWill() throws Exception { display("Shadow before", shadowBefore); closeCase(willLastCaseOid); - + accountWillCompletionTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); provisioningService.refreshShadow(shadowBefore, null, task, result); @@ -966,12 +966,12 @@ public void test204CloseCaseAndRefreshAccountWill() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + accountWillCompletionTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); - assertSinglePendingOperation(shadowRepo, + assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); @@ -981,7 +981,7 @@ public void test204CloseCaseAndRefreshAccountWill() throws Exception { PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + display("Provisioning shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, ACCOUNT_WILL_USERNAME); @@ -994,15 +994,15 @@ public void test204CloseCaseAndRefreshAccountWill() throws Exception { assertAttribute(shadowProvisioning, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); } assertAttributeFromBackingStore(shadowProvisioning, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); - assertShadowPassword(shadowProvisioning); + assertShadowPassword(shadowProvisioning); - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowProvisioning, + PendingOperationType pendingOperation = assertSinglePendingOperation(shadowProvisioning, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + PrismObject shadowProvisioningFuture = provisioningService.getObject(ShadowType.class, - ACCOUNT_WILL_OID, + ACCOUNT_WILL_OID, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Provisioning shadow (future)", shadowProvisioningFuture); @@ -1013,7 +1013,7 @@ public void test204CloseCaseAndRefreshAccountWill() throws Exception { assertAttribute(shadowProvisioningFuture, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioningFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioningFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); // In this case check notifications at the end. There were some reads that @@ -1021,7 +1021,7 @@ public void test204CloseCaseAndRefreshAccountWill() throws Exception { syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNotifySuccessOnly(); } - + /** * ff 5min, everything should be the same (grace not expired yet) */ @@ -1035,10 +1035,10 @@ public void test210RefreshAccountWillAfter5min() throws Exception { syncServiceMock.reset(); clock.overrideDuration("PT5M"); - + PrismObject shadowBefore = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); display("Shadow before", shadowBefore); - + // WHEN displayWhen(TEST_NAME); provisioningService.refreshShadow(shadowBefore, null, task, result); @@ -1046,14 +1046,14 @@ public void test210RefreshAccountWillAfter5min() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); - assertSinglePendingOperation(shadowRepo, + assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNoNotifcations(); @@ -1069,13 +1069,13 @@ public void test210RefreshAccountWillAfter5min() throws Exception { assertAttributeFromBackingStore(shadowProvisioning, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioning); - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowProvisioning, + PendingOperationType pendingOperation = assertSinglePendingOperation(shadowProvisioning, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + PrismObject shadowProvisioningFuture = provisioningService.getObject(ShadowType.class, - ACCOUNT_WILL_OID, + ACCOUNT_WILL_OID, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Provisioning shadow (future)", shadowProvisioningFuture); @@ -1086,14 +1086,14 @@ public void test210RefreshAccountWillAfter5min() throws Exception { assertAttribute(shadowProvisioningFuture, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioningFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioningFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + protected void backingStoreUpdateWill(String newFullName, ActivationStatusType newAdministrativeStatus, String password) throws IOException { // nothing to do here } - + @Test public void test212UpdateBackingStoreAndGetAccountWill() throws Exception { final String TEST_NAME = "test212UpdateBackingStoreAndGetAccountWill"; @@ -1102,12 +1102,12 @@ public void test212UpdateBackingStoreAndGetAccountWill() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); syncServiceMock.reset(); - + PrismObject shadowBefore = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); display("Shadow before", shadowBefore); - + backingStoreUpdateWill(ACCOUNT_WILL_FULLNAME_PIRATE, ActivationStatusType.ENABLED, ACCOUNT_WILL_PASSWORD_OLD); - + // WHEN displayWhen(TEST_NAME); provisioningService.refreshShadow(shadowBefore, null, task, result); @@ -1115,14 +1115,14 @@ public void test212UpdateBackingStoreAndGetAccountWill() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); - assertSinglePendingOperation(shadowRepo, + assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNoNotifcations(); @@ -1134,13 +1134,13 @@ public void test212UpdateBackingStoreAndGetAccountWill() throws Exception { assertAttributeFromBackingStore(shadowProvisioning, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioning); - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowProvisioning, + PendingOperationType pendingOperation = assertSinglePendingOperation(shadowProvisioning, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + PrismObject shadowProvisioningFuture = provisioningService.getObject(ShadowType.class, - ACCOUNT_WILL_OID, + ACCOUNT_WILL_OID, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Provisioning shadow (future)", shadowProvisioningFuture); @@ -1151,11 +1151,11 @@ public void test212UpdateBackingStoreAndGetAccountWill() throws Exception { assertAttribute(shadowProvisioningFuture, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioningFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioningFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + /** * disable - do not complete yet (do not wait for delta to expire, we want several deltas at once). */ @@ -1167,45 +1167,45 @@ public void test220ModifyAccountWillDisable() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); syncServiceMock.reset(); - - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, - ACCOUNT_WILL_OID, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, prismContext, + + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, + ACCOUNT_WILL_OID, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, prismContext, ActivationStatusType.DISABLED); display("ObjectDelta", delta); accountWillReqestTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); provisioningService.modifyObject(ShadowType.class, delta.getOid(), delta.getModifications(), null, null, task, result); - + // THEN displayThen(TEST_NAME); display("result", result); willLastCaseOid = assertInProgress(result); - + accountWillReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); assertPendingOperationDeltas(shadowRepo, 2); - PendingOperationType pendingOperation = findPendingOperation(shadowRepo, + PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.IN_PROGRESS, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS); assertPendingOperation(shadowRepo, pendingOperation, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); - + assertNotNull("No ID in pending operation", pendingOperation.getId()); // Still old data in the repo. The operation is not completed yet. assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, ACCOUNT_WILL_USERNAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNotifyInProgressOnly(); PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + display("Provisioning shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, ACCOUNT_WILL_USERNAME); @@ -1217,12 +1217,12 @@ public void test220ModifyAccountWillDisable() throws Exception { assertShadowPassword(shadowProvisioning); assertPendingOperationDeltas(shadowProvisioning, 2); - pendingOperation = findPendingOperation(shadowProvisioning, + pendingOperation = findPendingOperation(shadowProvisioning, OperationResultStatusType.IN_PROGRESS, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS); assertPendingOperation(shadowProvisioning, pendingOperation, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); - + PrismObject shadowProvisioningFuture = provisioningService.getObject(ShadowType.class, - ACCOUNT_WILL_OID, + ACCOUNT_WILL_OID, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Provisioning shadow (future)", shadowProvisioningFuture); @@ -1233,12 +1233,12 @@ public void test220ModifyAccountWillDisable() throws Exception { assertAttribute(shadowProvisioningFuture, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioningFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioningFuture); - + assertNotNull("No async reference in result", willLastCaseOid); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } - + /** * Change password, enable. There is still pending disable delta. Make sure all the deltas are * stored correctly. @@ -1251,9 +1251,9 @@ public void test230ModifyAccountWillChangePasswordAndEnable() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); syncServiceMock.reset(); - - ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, - ACCOUNT_WILL_OID, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, prismContext, + + ObjectDelta delta = ObjectDelta.createModificationReplaceProperty(ShadowType.class, + ACCOUNT_WILL_OID, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, prismContext, ActivationStatusType.ENABLED); ProtectedStringType ps = new ProtectedStringType(); ps.setClearValue(ACCOUNT_WILL_PASSWORD_NEW); @@ -1261,38 +1261,38 @@ public void test230ModifyAccountWillChangePasswordAndEnable() throws Exception { display("ObjectDelta", delta); accountWillSecondReqestTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); provisioningService.modifyObject(ShadowType.class, delta.getOid(), delta.getModifications(), null, null, task, result); - + // THEN displayThen(TEST_NAME); display("result", result); willSecondLastCaseOid = assertInProgress(result); - + accountWillSecondReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); assertPendingOperationDeltas(shadowRepo, 3); - PendingOperationType pendingOperation = findPendingOperation(shadowRepo, + PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.IN_PROGRESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd); - + assertNotNull("No ID in pending operation", pendingOperation.getId()); // Still old data in the repo. The operation is not completed yet. assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, ACCOUNT_WILL_USERNAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNotifyInProgressOnly(); PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + display("Provisioning shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, ACCOUNT_WILL_USERNAME); @@ -1302,15 +1302,15 @@ public void test230ModifyAccountWillChangePasswordAndEnable() throws Exception { assertAttribute(shadowProvisioning, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioning, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioning); - + assertPendingOperationDeltas(shadowProvisioning, 3); - pendingOperation = findPendingOperation(shadowProvisioning, + pendingOperation = findPendingOperation(shadowProvisioning, OperationResultStatusType.IN_PROGRESS, SchemaConstants.PATH_PASSWORD_VALUE); - assertPendingOperation(shadowProvisioning, pendingOperation, + assertPendingOperation(shadowProvisioning, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd); - + PrismObject shadowProvisioningFuture = provisioningService.getObject(ShadowType.class, - ACCOUNT_WILL_OID, + ACCOUNT_WILL_OID, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Provisioning shadow (future)", shadowProvisioningFuture); @@ -1321,13 +1321,13 @@ public void test230ModifyAccountWillChangePasswordAndEnable() throws Exception { assertAttribute(shadowProvisioningFuture, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioningFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadow(shadowProvisioningFuture); - + assertNotNull("No async reference in result", willSecondLastCaseOid); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_OPEN); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } - + /** * Disable case is closed. The account should be disabled. But there is still the other * delta pending. @@ -1343,12 +1343,12 @@ public void test240CloseDisableCaseAndReadAccountWill() throws Exception { syncServiceMock.reset(); closeCase(willLastCaseOid); - + PrismObject shadowBefore = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); display("Shadow before", shadowBefore); - + accountWillCompletionTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, @@ -1357,32 +1357,32 @@ public void test240CloseDisableCaseAndReadAccountWill() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + accountWillCompletionTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); - + assertPendingOperationDeltas(shadowRepo, 3); - - PendingOperationType pendingOperation = findPendingOperation(shadowRepo, + + PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS); assertPendingOperation(shadowRepo, pendingOperation, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - - pendingOperation = findPendingOperation(shadowRepo, + + pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.IN_PROGRESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd); - + assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.DISABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, ACCOUNT_WILL_USERNAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNotifySuccessOnly(); - + display("Provisioning shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, ACCOUNT_WILL_USERNAME); @@ -1392,22 +1392,22 @@ public void test240CloseDisableCaseAndReadAccountWill() throws Exception { } else { assertShadowActivationAdministrativeStatus(shadowProvisioning, ActivationStatusType.DISABLED); } - + assertAttribute(shadowProvisioning, ATTR_USERNAME_QNAME, ACCOUNT_WILL_USERNAME); assertAttribute(shadowProvisioning, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioning, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioning); - + assertPendingOperationDeltas(shadowProvisioning, 3); - pendingOperation = findPendingOperation(shadowProvisioning, + pendingOperation = findPendingOperation(shadowProvisioning, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS); assertPendingOperation(shadowProvisioning, pendingOperation, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + PrismObject shadowProvisioningFuture = provisioningService.getObject(ShadowType.class, - ACCOUNT_WILL_OID, + ACCOUNT_WILL_OID, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Provisioning shadow (future)", shadowProvisioningFuture); @@ -1419,11 +1419,11 @@ public void test240CloseDisableCaseAndReadAccountWill() throws Exception { assertAttributeFromBackingStore(shadowProvisioningFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); // TODO // assertShadowPassword(shadowProvisioningFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } - + /** * lets ff 5min just for fun. Refresh, make sure everything should be the same (grace not expired yet) */ @@ -1437,10 +1437,10 @@ public void test250RefreshAccountWillAfter5min() throws Exception { syncServiceMock.reset(); clock.overrideDuration("PT5M"); - + PrismObject shadowBefore = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); display("Shadow before", shadowBefore); - + // WHEN displayWhen(TEST_NAME); provisioningService.refreshShadow(shadowBefore, null, task, result); @@ -1448,33 +1448,33 @@ public void test250RefreshAccountWillAfter5min() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); - + assertPendingOperationDeltas(shadowRepo, 3); - - PendingOperationType pendingOperation = findPendingOperation(shadowRepo, + + PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS); assertPendingOperation(shadowRepo, pendingOperation, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - - pendingOperation = findPendingOperation(shadowRepo, + + pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.IN_PROGRESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd); - + assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.DISABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, ACCOUNT_WILL_USERNAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNoNotifcations(); PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + display("Provisioning shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, ACCOUNT_WILL_USERNAME); @@ -1488,17 +1488,17 @@ public void test250RefreshAccountWillAfter5min() throws Exception { assertAttribute(shadowProvisioning, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioning, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioning); - + assertPendingOperationDeltas(shadowProvisioning, 3); - pendingOperation = findPendingOperation(shadowProvisioning, + pendingOperation = findPendingOperation(shadowProvisioning, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS); assertPendingOperation(shadowProvisioning, pendingOperation, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + PrismObject shadowProvisioningFuture = provisioningService.getObject(ShadowType.class, - ACCOUNT_WILL_OID, + ACCOUNT_WILL_OID, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Provisioning shadow (future)", shadowProvisioningFuture); @@ -1510,11 +1510,11 @@ public void test250RefreshAccountWillAfter5min() throws Exception { assertAttributeFromBackingStore(shadowProvisioningFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); // TODO // assertShadowPassword(shadowProvisioningFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } - + @Test public void test252UpdateBackingStoreAndGetAccountWill() throws Exception { final String TEST_NAME = "test252UpdateBackingStoreAndGetAccountWill"; @@ -1523,12 +1523,12 @@ public void test252UpdateBackingStoreAndGetAccountWill() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); syncServiceMock.reset(); - + PrismObject shadowBefore = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); display("Shadow before", shadowBefore); - + backingStoreUpdateWill(ACCOUNT_WILL_FULLNAME_PIRATE, ActivationStatusType.DISABLED, ACCOUNT_WILL_PASSWORD_OLD); - + // WHEN displayWhen(TEST_NAME); provisioningService.refreshShadow(shadowBefore, null, task, result); @@ -1536,17 +1536,17 @@ public void test252UpdateBackingStoreAndGetAccountWill() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); assertPendingOperationDeltas(shadowRepo, 3); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNoNotifcations(); PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + display("Provisioning shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, ACCOUNT_WILL_USERNAME); @@ -1556,11 +1556,11 @@ public void test252UpdateBackingStoreAndGetAccountWill() throws Exception { assertAttribute(shadowProvisioning, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioning, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioning); - + assertPendingOperationDeltas(shadowProvisioning, 3); - + PrismObject shadowProvisioningFuture = provisioningService.getObject(ShadowType.class, - ACCOUNT_WILL_OID, + ACCOUNT_WILL_OID, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Provisioning shadow (future)", shadowProvisioningFuture); @@ -1572,7 +1572,7 @@ public void test252UpdateBackingStoreAndGetAccountWill() throws Exception { assertAttributeFromBackingStore(shadowProvisioningFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); // TODO // assertShadowPassword(shadowProvisioningFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } @@ -1591,14 +1591,14 @@ public void test260ClosePasswordChangeCaseAndRefreshAccountWill() throws Excepti syncServiceMock.reset(); closeCase(willSecondLastCaseOid); - + // Get repo shadow here. Make sure refresh works with this as well. PrismObject shadowBefore = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); provisioningService.applyDefinition(shadowBefore, task, result); display("Shadow before", shadowBefore); - + accountWillSecondCompletionTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); provisioningService.refreshShadow(shadowBefore, null, task, result); @@ -1606,38 +1606,38 @@ public void test260ClosePasswordChangeCaseAndRefreshAccountWill() throws Excepti // THEN displayThen(TEST_NAME); assertSuccess(result); - + accountWillSecondCompletionTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); - + assertPendingOperationDeltas(shadowRepo, 3); - - PendingOperationType pendingOperation = findPendingOperation(shadowRepo, + + PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillSecondCompletionTimestampStart, accountWillSecondCompletionTimestampEnd); - - pendingOperation = findPendingOperation(shadowRepo, + + pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillSecondCompletionTimestampStart, accountWillSecondCompletionTimestampEnd); - + assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, ACCOUNT_WILL_USERNAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNotifySuccessOnly(); PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + display("Provisioning shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, ACCOUNT_WILL_USERNAME); @@ -1651,17 +1651,17 @@ public void test260ClosePasswordChangeCaseAndRefreshAccountWill() throws Excepti assertAttribute(shadowProvisioning, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioning, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioning); - + assertPendingOperationDeltas(shadowProvisioning, 3); - pendingOperation = findPendingOperation(shadowProvisioning, + pendingOperation = findPendingOperation(shadowProvisioning, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillSecondCompletionTimestampStart, accountWillSecondCompletionTimestampEnd); - + PrismObject shadowProvisioningFuture = provisioningService.getObject(ShadowType.class, - ACCOUNT_WILL_OID, + ACCOUNT_WILL_OID, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Provisioning shadow (future)", shadowProvisioningFuture); @@ -1672,11 +1672,11 @@ public void test260ClosePasswordChangeCaseAndRefreshAccountWill() throws Excepti assertAttribute(shadowProvisioningFuture, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioningFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioningFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + /** * ff 10min. Refresh. Oldest delta should expire. */ @@ -1690,10 +1690,10 @@ public void test270RefreshAccountWillAfter10min() throws Exception { syncServiceMock.reset(); clock.overrideDuration("PT10M"); - + PrismObject shadowBefore = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); display("Shadow before", shadowBefore); - + // WHEN displayWhen(TEST_NAME); provisioningService.refreshShadow(shadowBefore, null, task, result); @@ -1701,36 +1701,36 @@ public void test270RefreshAccountWillAfter10min() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); - + assertPendingOperationDeltas(shadowRepo, 2); - - PendingOperationType pendingOperation = findPendingOperation(shadowRepo, + + PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillSecondCompletionTimestampStart, accountWillSecondCompletionTimestampEnd); - - pendingOperation = findPendingOperation(shadowRepo, + + pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillSecondCompletionTimestampStart, accountWillSecondCompletionTimestampEnd); - + assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, ACCOUNT_WILL_USERNAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNoNotifcations(); PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + display("Provisioning shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, ACCOUNT_WILL_USERNAME); @@ -1744,17 +1744,17 @@ public void test270RefreshAccountWillAfter10min() throws Exception { assertAttribute(shadowProvisioning, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioning, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioning); - + assertPendingOperationDeltas(shadowProvisioning, 2); - pendingOperation = findPendingOperation(shadowProvisioning, + pendingOperation = findPendingOperation(shadowProvisioning, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillSecondCompletionTimestampStart, accountWillSecondCompletionTimestampEnd); - + PrismObject shadowProvisioningFuture = provisioningService.getObject(ShadowType.class, - ACCOUNT_WILL_OID, + ACCOUNT_WILL_OID, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Provisioning shadow (future)", shadowProvisioningFuture); @@ -1765,11 +1765,11 @@ public void test270RefreshAccountWillAfter10min() throws Exception { assertAttribute(shadowProvisioningFuture, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioningFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioningFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + @Test public void test272UpdateBackingStoreAndGetAccountWill() throws Exception { final String TEST_NAME = "test272UpdateBackingStoreAndGetAccountWill"; @@ -1778,12 +1778,12 @@ public void test272UpdateBackingStoreAndGetAccountWill() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); syncServiceMock.reset(); - + PrismObject shadowBefore = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); display("Shadow before", shadowBefore); - + backingStoreUpdateWill(ACCOUNT_WILL_FULLNAME_PIRATE, ActivationStatusType.ENABLED, ACCOUNT_WILL_PASSWORD_NEW); - + // WHEN displayWhen(TEST_NAME); provisioningService.refreshShadow(shadowBefore, null, task, result); @@ -1791,17 +1791,17 @@ public void test272UpdateBackingStoreAndGetAccountWill() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); assertPendingOperationDeltas(shadowRepo, 2); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNoNotifcations(); PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + display("Provisioning shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, ACCOUNT_WILL_USERNAME); @@ -1811,11 +1811,11 @@ public void test272UpdateBackingStoreAndGetAccountWill() throws Exception { assertAttribute(shadowProvisioning, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioning, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioning); - + assertPendingOperationDeltas(shadowProvisioning, 2); - + PrismObject shadowProvisioningFuture = provisioningService.getObject(ShadowType.class, - ACCOUNT_WILL_OID, + ACCOUNT_WILL_OID, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Provisioning shadow (future)", shadowProvisioningFuture); @@ -1827,11 +1827,11 @@ public void test272UpdateBackingStoreAndGetAccountWill() throws Exception { assertAttributeFromBackingStore(shadowProvisioningFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); // TODO // assertShadowPassword(shadowProvisioningFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + /** * ff 5min. Refresh. Another delta should expire. */ @@ -1845,10 +1845,10 @@ public void test280RefreshAccountWillAfter5min() throws Exception { syncServiceMock.reset(); clock.overrideDuration("PT5M"); - + PrismObject shadowBefore = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); display("Shadow before", shadowBefore); - + // WHEN displayWhen(TEST_NAME); provisioningService.refreshShadow(shadowBefore, null, task, result); @@ -1856,36 +1856,36 @@ public void test280RefreshAccountWillAfter5min() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); - + assertPendingOperationDeltas(shadowRepo, 1); - - PendingOperationType pendingOperation = findPendingOperation(shadowRepo, + + PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillSecondCompletionTimestampStart, accountWillSecondCompletionTimestampEnd); - - pendingOperation = findPendingOperation(shadowRepo, + + pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillSecondCompletionTimestampStart, accountWillSecondCompletionTimestampEnd); - + assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, ACCOUNT_WILL_USERNAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNoNotifcations(); PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + display("Provisioning shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, ACCOUNT_WILL_USERNAME); @@ -1895,17 +1895,17 @@ public void test280RefreshAccountWillAfter5min() throws Exception { assertAttribute(shadowProvisioning, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioning, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioning); - + assertPendingOperationDeltas(shadowProvisioning, 1); - pendingOperation = findPendingOperation(shadowProvisioning, + pendingOperation = findPendingOperation(shadowProvisioning, OperationResultStatusType.SUCCESS, SchemaConstants.PATH_PASSWORD_VALUE); assertPendingOperation(shadowRepo, pendingOperation, accountWillSecondReqestTimestampStart, accountWillSecondReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillSecondCompletionTimestampStart, accountWillSecondCompletionTimestampEnd); - + PrismObject shadowProvisioningFuture = provisioningService.getObject(ShadowType.class, - ACCOUNT_WILL_OID, + ACCOUNT_WILL_OID, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Provisioning shadow (future)", shadowProvisioningFuture); @@ -1916,11 +1916,11 @@ public void test280RefreshAccountWillAfter5min() throws Exception { assertAttribute(shadowProvisioningFuture, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioningFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioningFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + /** * ff 5min. Refresh. All delta should expire. */ @@ -1934,10 +1934,10 @@ public void test290RefreshAccountWillAfter5min() throws Exception { syncServiceMock.reset(); clock.overrideDuration("PT5M"); - + PrismObject shadowBefore = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Shadow before", shadowBefore); - + // WHEN displayWhen(TEST_NAME); provisioningService.refreshShadow(shadowBefore, null, task, result); @@ -1945,22 +1945,22 @@ public void test290RefreshAccountWillAfter5min() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); - + assertPendingOperationDeltas(shadowRepo, 0); - + assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, ACCOUNT_WILL_USERNAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNoNotifcations(); PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + display("Provisioning shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, ACCOUNT_WILL_USERNAME); @@ -1970,11 +1970,11 @@ public void test290RefreshAccountWillAfter5min() throws Exception { assertAttribute(shadowProvisioning, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioning, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioning); - + assertPendingOperationDeltas(shadowProvisioning, 0); - + PrismObject shadowProvisioningFuture = provisioningService.getObject(ShadowType.class, - ACCOUNT_WILL_OID, + ACCOUNT_WILL_OID, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Provisioning shadow (future)", shadowProvisioningFuture); @@ -1985,11 +1985,11 @@ public void test290RefreshAccountWillAfter5min() throws Exception { assertAttribute(shadowProvisioningFuture, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); assertAttributeFromBackingStore(shadowProvisioningFuture, ATTR_DESCRIPTION_QNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL); assertShadowPassword(shadowProvisioningFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); assertCase(willSecondLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + @Test public void test300DeleteAccountWill() throws Exception { final String TEST_NAME = "test300DeleteAccountWill"; @@ -1998,39 +1998,39 @@ public void test300DeleteAccountWill() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); syncServiceMock.reset(); - + accountWillReqestTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); provisioningService.deleteObject(ShadowType.class, ACCOUNT_WILL_OID, null, null, task, result); - + // THEN displayThen(TEST_NAME); display("result", result); willLastCaseOid = assertInProgress(result); - + accountWillReqestTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); assertPendingOperationDeltas(shadowRepo, 1); - PendingOperationType pendingOperation = findPendingOperation(shadowRepo, + PendingOperationType pendingOperation = findPendingOperation(shadowRepo, OperationResultStatusType.IN_PROGRESS, null); assertPendingOperation(shadowRepo, pendingOperation, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); - + assertNotNull("No ID in pending operation", pendingOperation.getId()); // Still old data in the repo. The operation is not completed yet. assertShadowActivationAdministrativeStatusFromCache(shadowRepo, ActivationStatusType.ENABLED); assertAttribute(shadowRepo, ATTR_USERNAME_QNAME, ACCOUNT_WILL_USERNAME); assertAttributeFromCache(shadowRepo, ATTR_FULLNAME_QNAME, ACCOUNT_WILL_FULLNAME_PIRATE); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNotifyInProgressOnly(); PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + display("Provisioning shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, ACCOUNT_WILL_USERNAME); @@ -2042,24 +2042,24 @@ public void test300DeleteAccountWill() throws Exception { assertShadowPassword(shadowProvisioning); assertPendingOperationDeltas(shadowProvisioning, 1); - pendingOperation = findPendingOperation(shadowProvisioning, + pendingOperation = findPendingOperation(shadowProvisioning, OperationResultStatusType.IN_PROGRESS, null); assertPendingOperation(shadowProvisioning, pendingOperation, accountWillReqestTimestampStart, accountWillReqestTimestampEnd); - + PrismObject shadowProvisioningFuture = provisioningService.getObject(ShadowType.class, - ACCOUNT_WILL_OID, + ACCOUNT_WILL_OID, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Provisioning shadow (future)", shadowProvisioningFuture); assertShadowName(shadowProvisioningFuture, ACCOUNT_WILL_USERNAME); assertShadowDead(shadowProvisioningFuture); assertShadowPassword(shadowProvisioningFuture); - + assertNotNull("No async reference in result", willLastCaseOid); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_OPEN); } - + @Test public void test302GetAccountWillFuture() throws Exception { final String TEST_NAME = "test302GetAccountWillFuture"; @@ -2067,25 +2067,25 @@ public void test302GetAccountWillFuture() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); PrismObject shadowProvisioningFuture = provisioningService.getObject(ShadowType.class, - ACCOUNT_WILL_OID, + ACCOUNT_WILL_OID, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); - - + + // THEN displayThen(TEST_NAME); assertSuccess(result); - + display("Provisioning shadow (future)", shadowProvisioningFuture); assertShadowName(shadowProvisioningFuture, ACCOUNT_WILL_USERNAME); assertShadowDead(shadowProvisioningFuture); - assertShadowPassword(shadowProvisioningFuture); + assertShadowPassword(shadowProvisioningFuture); } - + @Test public void test303GetAccountWillFutureNoFetch() throws Exception { final String TEST_NAME = "test303GetAccountWillFutureNoFetch"; @@ -2093,29 +2093,29 @@ public void test303GetAccountWillFutureNoFetch() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + GetOperationOptions options = GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE); options.setNoFetch(true); - + // WHEN displayWhen(TEST_NAME); PrismObject shadowProvisioningFuture = provisioningService.getObject(ShadowType.class, - ACCOUNT_WILL_OID, + ACCOUNT_WILL_OID, SelectorOptions.createCollection(options), task, result); - - + + // THEN displayThen(TEST_NAME); assertSuccess(result); - + display("Provisioning shadow (future,noFetch)", shadowProvisioningFuture); assertNotNull("no OID", shadowProvisioningFuture.getOid()); assertShadowName(shadowProvisioningFuture, ACCOUNT_WILL_USERNAME); assertShadowDead(shadowProvisioningFuture); - assertNoShadowPassword(shadowProvisioningFuture); + assertNoShadowPassword(shadowProvisioningFuture); } - + /** * Case is closed. The operation is complete. */ @@ -2129,12 +2129,12 @@ public void test310CloseCaseAndRefreshAccountWill() throws Exception { syncServiceMock.reset(); closeCase(willLastCaseOid); - + PrismObject shadowBefore = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); display("Shadow before", shadowBefore); - + accountWillCompletionTimestampStart = clock.currentTimeXMLGregorianCalendar(); - + // WHEN displayWhen(TEST_NAME); provisioningService.refreshShadow(shadowBefore, null, task, result); @@ -2142,23 +2142,23 @@ public void test310CloseCaseAndRefreshAccountWill() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + accountWillCompletionTimestampEnd = clock.currentTimeXMLGregorianCalendar(); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); - assertSinglePendingOperation(shadowRepo, + assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); assertShadowDead(shadowRepo); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNotifySuccessOnly(); PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + display("Provisioning shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, ACCOUNT_WILL_USERNAME); @@ -2166,23 +2166,23 @@ public void test310CloseCaseAndRefreshAccountWill() throws Exception { assertShadowDead(shadowProvisioning); assertShadowPassword(shadowProvisioning); - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowProvisioning, + PendingOperationType pendingOperation = assertSinglePendingOperation(shadowProvisioning, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + PrismObject shadowProvisioningFuture = provisioningService.getObject(ShadowType.class, - ACCOUNT_WILL_OID, + ACCOUNT_WILL_OID, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Provisioning shadow (future)", shadowProvisioningFuture); assertShadowName(shadowProvisioningFuture, ACCOUNT_WILL_USERNAME); assertShadowDead(shadowProvisioningFuture); assertShadowPassword(shadowProvisioningFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + /** * ff 5min, everything should be the same (grace not expired yet) */ @@ -2196,10 +2196,10 @@ public void test320RefreshAccountWillAfter5min() throws Exception { syncServiceMock.reset(); clock.overrideDuration("PT5M"); - + PrismObject shadowBefore = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); display("Shadow before", shadowBefore); - + // WHEN displayWhen(TEST_NAME); provisioningService.refreshShadow(shadowBefore, null, task, result); @@ -2207,47 +2207,47 @@ public void test320RefreshAccountWillAfter5min() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result); display("Repo shadow", shadowRepo); - assertSinglePendingOperation(shadowRepo, + assertSinglePendingOperation(shadowRepo, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); assertShadowDead(shadowRepo); - + syncServiceMock.assertNoNotifyChange(); syncServiceMock.assertNoNotifcations(); PrismObject shadowProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + display("Provisioning shadow", shadowProvisioning); ShadowType shadowTypeProvisioning = shadowProvisioning.asObjectable(); assertShadowName(shadowProvisioning, ACCOUNT_WILL_USERNAME); assertEquals("Wrong kind (provisioning)", ShadowKindType.ACCOUNT, shadowTypeProvisioning.getKind()); assertShadowDead(shadowProvisioning); assertShadowPassword(shadowProvisioning); - - PendingOperationType pendingOperation = assertSinglePendingOperation(shadowProvisioning, + + PendingOperationType pendingOperation = assertSinglePendingOperation(shadowProvisioning, accountWillReqestTimestampStart, accountWillReqestTimestampEnd, OperationResultStatusType.SUCCESS, accountWillCompletionTimestampStart, accountWillCompletionTimestampEnd); - + PrismObject shadowProvisioningFuture = provisioningService.getObject(ShadowType.class, - ACCOUNT_WILL_OID, + ACCOUNT_WILL_OID, SelectorOptions.createCollection(GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE)), task, result); display("Provisioning shadow (future)", shadowProvisioningFuture); assertShadowName(shadowProvisioningFuture, ACCOUNT_WILL_USERNAME); assertShadowDead(shadowProvisioningFuture); assertShadowPassword(shadowProvisioningFuture); - + assertCase(willLastCaseOid, SchemaConstants.CASE_STATE_CLOSED); } - + // TODO: create, close case, then update backing store. - + // TODO: let grace period expire without updating the backing store (semi-manual-only) private void assertPendingOperationDeltas(PrismObject shadow, int expectedNumber) { @@ -2255,13 +2255,13 @@ private void assertPendingOperationDeltas(PrismObject shadow, int ex assertEquals("Wroung number of pending operations in "+shadow, expectedNumber, pendingOperations.size()); } - private PendingOperationType assertSinglePendingOperation(PrismObject shadow, + private PendingOperationType assertSinglePendingOperation(PrismObject shadow, XMLGregorianCalendar requestStart, XMLGregorianCalendar requestEnd) { - return assertSinglePendingOperation(shadow, requestStart, requestEnd, + return assertSinglePendingOperation(shadow, requestStart, requestEnd, OperationResultStatusType.IN_PROGRESS, null, null); } - - private PendingOperationType assertSinglePendingOperation(PrismObject shadow, + + private PendingOperationType assertSinglePendingOperation(PrismObject shadow, XMLGregorianCalendar requestStart, XMLGregorianCalendar requestEnd, OperationResultStatusType expectedStatus, XMLGregorianCalendar completionStart, XMLGregorianCalendar completionEnd) { @@ -2269,38 +2269,38 @@ private PendingOperationType assertSinglePendingOperation(PrismObject shadow, PendingOperationType pendingOperation, + PrismObject shadow, PendingOperationType pendingOperation, XMLGregorianCalendar requestStart, XMLGregorianCalendar requestEnd) { - return assertPendingOperation(shadow, pendingOperation, requestStart, requestEnd, + return assertPendingOperation(shadow, pendingOperation, requestStart, requestEnd, OperationResultStatusType.IN_PROGRESS, null, null); } - + private PendingOperationType assertPendingOperation( PrismObject shadow, PendingOperationType pendingOperation, XMLGregorianCalendar requestStart, XMLGregorianCalendar requestEnd, OperationResultStatusType expectedStatus, XMLGregorianCalendar completionStart, XMLGregorianCalendar completionEnd) { assertNotNull("No operation ", pendingOperation); - + ObjectDeltaType deltaType = pendingOperation.getDelta(); assertNotNull("No delta in pending operation in "+shadow, deltaType); // TODO: check content of pending operations in the shadow - + TestUtil.assertBetween("No request timestamp in pending operation in "+shadow, requestStart, requestEnd, pendingOperation.getRequestTimestamp()); - + OperationResultStatusType status = pendingOperation.getResultStatus(); assertEquals("Wrong status in pending operation in "+shadow, expectedStatus, status); - + if (expectedStatus != OperationResultStatusType.IN_PROGRESS) { TestUtil.assertBetween("No completion timestamp in pending operation in "+shadow, completionStart, completionEnd, pendingOperation.getCompletionTimestamp()); } - + return pendingOperation; } - - private PendingOperationType findPendingOperation(PrismObject shadow, + + private PendingOperationType findPendingOperation(PrismObject shadow, OperationResultStatusType expectedResult, ItemPath itemPath) { List pendingOperations = shadow.asObjectable().getPendingOperation(); for (PendingOperationType pendingOperation: pendingOperations) { @@ -2321,19 +2321,19 @@ private PendingOperationType findPendingOperation(PrismObject shadow if (itemPath.equivalent(deltaPath)) { return pendingOperation; } - } + } } return null; } - + protected void assertAttribute(PrismObject shadow, QName attrName, T... expectedValues) { assertAttribute(resource, shadow.asObjectable(), attrName, expectedValues); } - + protected void assertNoAttribute(PrismObject shadow, QName attrName) { assertNoAttribute(resource, shadow.asObjectable(), attrName); } - + protected void assertAttributeFromCache(PrismObject shadow, QName attrQName, String... attrVals) { if (supportsBackingStore()) { @@ -2342,7 +2342,7 @@ protected void assertAttributeFromCache(PrismObject shadow, QName at assertAttribute(shadow, attrQName, attrVals); } } - + protected void assertAttributeFromBackingStore(PrismObject shadow, QName attrQName, String... attrVals) { if (supportsBackingStore()) { @@ -2351,7 +2351,7 @@ protected void assertAttributeFromBackingStore(PrismObject shadow, Q assertNoAttribute(shadow, attrQName); } } - + protected void assertShadowActivationAdministrativeStatusFromCache(PrismObject shadow, ActivationStatusType expectedStatus) { if (supportsBackingStore()) { assertShadowActivationAdministrativeStatus(shadow, null); @@ -2359,18 +2359,18 @@ protected void assertShadowActivationAdministrativeStatusFromCache(PrismObject shadow, ActivationStatusType expectedStatus) { assertActivationAdministrativeStatus(shadow, expectedStatus); } - + protected void assertShadowPassword(PrismObject shadow) { // pure manual resource should never "read" password assertNoShadowPassword(shadow); } - + private void assertManual(AbstractWriteCapabilityType cap) { assertEquals("Manual flag not set in capability "+cap, Boolean.TRUE, cap.isManual()); } - + } \ No newline at end of file diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/TestManual.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/TestManual.java index 39e7fbb0b7a..0bb771ac00a 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/TestManual.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/TestManual.java @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.provisioning.impl.manual; @@ -108,11 +108,11 @@ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext public class TestManual extends AbstractManualResourceTest { - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + resource = addResourceFromFile(getResourceFile(), MANUAL_CONNECTOR_TYPE, initResult); resourceType = resource.asObjectable(); } @@ -121,7 +121,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti protected File getResourceFile() { return RESOURCE_MANUAL_FILE; } - + @Override protected void assertResourceSchemaBeforeTest(Element resourceXsdSchemaElementBefore) { AssertJUnit.assertNotNull("No schema before test connection. Bad test setup?", resourceXsdSchemaElementBefore); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/TestSemiManual.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/TestSemiManual.java index eb6c606fbfe..b77e365a955 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/TestSemiManual.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/TestSemiManual.java @@ -15,7 +15,7 @@ */ /** - * + * */ package com.evolveum.midpoint.provisioning.impl.manual; @@ -64,22 +64,22 @@ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext public class TestSemiManual extends AbstractManualResourceTest { - + private static final File CSV_SOURCE_FILE = new File(TEST_DIR, "semi-manual.csv"); private static final File CSV_TARGET_FILE = new File("target/semi-manual.csv"); - + private static final Trace LOGGER = TraceManager.getTrace(TestSemiManual.class); - + protected static final String ATTR_DISABLED = "disabled"; protected static final QName ATTR_DISABLED_QNAME = new QName(MidPointConstants.NS_RI, ATTR_DISABLED); - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + resource = addResource(initResult); resourceType = resource.asObjectable(); - + FileUtils.copyFile(CSV_SOURCE_FILE, CSV_TARGET_FILE); } @@ -87,12 +87,12 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti protected File getResourceFile() { return RESOURCE_SEMI_MANUAL_FILE; } - + @Override protected boolean supportsBackingStore() { return true; } - + protected PrismObject addResource(OperationResult result) throws JAXBException, SchemaException, ObjectAlreadyExistsException, EncryptionException, IOException { PrismObject resource = prismContext.parseObject(getResourceFile()); @@ -104,12 +104,12 @@ protected PrismObject addResource(OperationResult result) resource.setOid(oid); return resource; } - + @Override protected void assertResourceSchemaBeforeTest(Element resourceXsdSchemaElementBefore) { AssertJUnit.assertNull("Resource schema sneaked in before test connection", resourceXsdSchemaElementBefore); } - + @Override protected int getNumberOfAccountAttributeDefinitions() { return 5; @@ -119,7 +119,7 @@ protected int getNumberOfAccountAttributeDefinitions() { protected void backingStoreAddWill() throws IOException { appendToCsv(new String[]{ACCOUNT_WILL_USERNAME, ACCOUNT_WILL_FULLNAME, ACCOUNT_WILL_DESCRIPTION_MANUAL, "", "false", ACCOUNT_WILL_PASSWORD_OLD}); } - + @Override protected void backingStoreUpdateWill(String newFullName, ActivationStatusType newAdministrativeStatus, String password) throws IOException { String disabled; @@ -135,7 +135,7 @@ private void appendToCsv(String[] data) throws IOException { String line = formatCsvLine(data) + "\n"; Files.write(Paths.get(CSV_TARGET_FILE.getPath()), line.getBytes(), StandardOpenOption.APPEND); } - + private void replaceInCsv(String[] data) throws IOException { List lines = Files.readAllLines(Paths.get(CSV_TARGET_FILE.getPath())); for (int i = 0; i < lines.size(); i++) { diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/AbstractOpenDjTest.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/AbstractOpenDjTest.java index 89c995334d6..ca18db2b84a 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/AbstractOpenDjTest.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/AbstractOpenDjTest.java @@ -48,55 +48,55 @@ * */ public abstract class AbstractOpenDjTest extends AbstractIntegrationTest { - + protected static final File TEST_DIR = new File("src/test/resources/opendj"); - + protected static final File RESOURCE_OPENDJ_FILE = ProvisioningTestUtil.RESOURCE_OPENDJ_FILE; protected static final File RESOURCE_OPENDJ_INITIALIZED_FILE = new File(TEST_DIR, "resource-opendj-initialized.xml"); protected static final String RESOURCE_OPENDJ_OID = "ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff"; protected static final String RESOURCE_OPENDJ_NS = "http://midpoint.evolveum.com/xml/ns/public/resource/instance/ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff"; - + protected static final File RESOURCE_OPENDJ_BAD_CREDENTIALS_FILE = new File(TEST_DIR, "resource-opendj-bad-credentials.xml"); protected static final String RESOURCE_OPENDJ_BAD_CREDENTIALS_OID = "8bc3ff5a-ef5d-11e4-8bba-001e8c717e5b"; - + protected static final File RESOURCE_OPENDJ_BAD_BIND_DN_FILE = new File(TEST_DIR, "resource-opendj-bad-bind-dn.xml"); protected static final String RESOURCE_OPENDJ_BAD_BIND_DN_OID = "d180258a-ef5f-11e4-8737-001e8c717e5b"; - + protected static final File ACCOUNT_JBOND_FILE = new File (TEST_DIR, "account-jbond.xml"); protected static final File ACCOUNT_JBOND_REPO_FILE = new File(TEST_DIR, "account-jbond-repo.xml"); protected static final String ACCOUNT_JBOND_OID = "dbb0c37d-9ee6-44a4-8d39-016dbce1cccc"; - + protected static final File ACCOUNT_WILL_FILE = new File(TEST_DIR, "account-will.xml"); protected static final String ACCOUNT_WILL_OID = "c0c010c0-d34d-b44f-f11d-333222123456"; protected static final String ACCOUNT_WILL_DN = "uid=will,ou=People,dc=example,dc=com"; - + protected static final File ACCOUNT_BAD_FILE = new File(TEST_DIR, "account-bad.xml"); protected static final String ACCOUNT_BAD_OID = "dbb0c37d-9ee6-44a4-8d39-016dbce1ffff"; - + protected static final File ACCOUNT_JACK_FILE = new File(TEST_DIR, "account-jack.xml"); protected static final File ACCOUNT_JACK_REPO_FILE = new File(TEST_DIR, "account-jack-repo.xml"); protected static final String ACCOUNT_JACK_OID = "c0c010c0-d34d-b44f-f11d-333222444555"; protected static final String ACCOUNT_JACK_NAME = "jack"; protected static final File ACCOUNT_JACK_CHANGE_FILE = new File(TEST_DIR, "account-jack-change.xml"); - + protected static final String ACCOUNT_BARBOSSA_DN = "uid=hbarbossa,ou=People,dc=example,dc=com"; - + protected static final File ACCOUNT_MODIFY_PASSWORD_FILE = new File(TEST_DIR, "account-modify-password.xml"); protected static final String ACCOUNT_MODIFY_PASSWORD_OID = "c0c010c0-d34d-b44f-f11d-333222444566"; - + protected static final File ACCOUNT_SPARROW_FILE = new File(TEST_DIR, "account-sparrow.xml"); protected static final File ACCOUNT_SPARROW_REPO_FILE = new File(TEST_DIR, "account-sparrow-repo.xml"); protected static final String ACCOUNT_SPARROW_OID = "c0c010c0-d34d-b44f-f11d-333222654321"; - + protected static final File ACCOUNT_SEARCH_ITERATIVE_FILE = new File(TEST_DIR, "account-search-iterative.xml"); protected static final String ACCOUNT_SEARCH_ITERATIVE_OID = "c0c010c0-d34d-b44f-f11d-333222666666"; - + protected static final File ACCOUNT_SEARCH_FILE = new File(TEST_DIR, "account-search.xml"); protected static final String ACCOUNT_SEARCH_OID = "c0c010c0-d34d-b44f-f11d-333222777777"; - + protected static final File ACCOUNT_NEW_WITH_PASSWORD_FILE = new File(TEST_DIR, "account-new-with-password.xml"); protected static final String ACCOUNT_NEW_WITH_PASSWORD_OID = "c0c010c0-d34d-b44f-f11d-333222124422"; - + protected static final File ACCOUNT_NEW_DISABLED_FILE = new File (TEST_DIR, "account-new-disabled.xml"); protected static final String ACCOUNT_NEW_DISABLED_OID = "c0c010c0-d34d-b44f-f11d-d3d2d2d2d4d2"; @@ -105,23 +105,23 @@ public abstract class AbstractOpenDjTest extends AbstractIntegrationTest { protected static final File ACCOUNT_DISABLE_SIMULATED_FILE = new File(TEST_DIR, "account-disable-simulated-opendj.xml"); protected static final String ACCOUNT_DISABLE_SIMULATED_OID = "dbb0c37d-9ee6-44a4-8d39-016dbce1aaaa"; - + protected static final File ACCOUNT_POSIX_MCMUTTON_FILE = new File (TEST_DIR, "account-posix-mcmutton.xml"); protected static final String ACCOUNT_POSIX_MCMUTTON_OID = "3a1902a4-14d8-11e5-b0b5-001e8c717e5b"; protected static final String ACCOUNT_POSIX_MCMUTTON_DN = "uid=mcmutton,ou=People,dc=example,dc=com"; protected static final File ACCOUNT_POSIX_MCMUTTON_CHANGE_FILE = new File (TEST_DIR, "account-posix-mcmutton-change.xml"); protected static final File ACCOUNT_POSIX_VANHELGEN_LDIF_FILE = new File(TEST_DIR, "vanhelgen.ldif"); - + protected static final File REQUEST_DISABLE_ACCOUNT_SIMULATED_FILE = new File(TEST_DIR, "disable-account-simulated.xml"); - + protected static final File ACCOUNT_NO_SN_FILE = new File(TEST_DIR, "account-opendj-no-sn.xml"); protected static final String ACCOUNT_NO_SN_OID = "c0c010c0-d34d-beef-f33d-113222123444"; - + protected static final File ACCOUNT_MORGAN_FILE = new File(TEST_DIR, "account-morgan.xml"); protected static final String ACCOUNT_MORGAN_OID = "8dfcf05e-c571-11e3-abbd-001e8c717e5b"; protected static final String ACCOUNT_MORGAN_DN = "uid=morgan,ou=People,dc=example,dc=com"; - + protected static final File GROUP_SWASHBUCKLERS_FILE = new File(TEST_DIR, "group-swashbucklers.xml"); protected static final String GROUP_SWASHBUCKLERS_OID = "3d96846e-c570-11e3-a80f-001e8c717e5b"; protected static final String GROUP_SWASHBUCKLERS_DN = "cn=swashbucklers,ou=groups,dc=example,dc=com"; @@ -133,31 +133,31 @@ public abstract class AbstractOpenDjTest extends AbstractIntegrationTest { protected static final File GROUP_CORSAIRS_FILE = new File(TEST_DIR, "group-corsairs.xml"); protected static final String GROUP_CORSAIRS_OID = "70a1f3ee-4b5b-11e5-95d0-001e8c717e5b"; protected static final String GROUP_CORSAIRS_DN = "cn=corsairs,ou=groups,dc=example,dc=com"; - + protected static final String NON_EXISTENT_OID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"; - + public static final String RESOURCE_NS = "http://midpoint.evolveum.com/xml/ns/public/resource/instance/ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff"; public static final QName RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS = new QName(RESOURCE_NS, "inetOrgPerson"); public static final QName RESOURCE_OPENDJ_GROUP_OBJECTCLASS = new QName(RESOURCE_NS, "groupOfUniqueNames"); public static final QName RESOURCE_OPENDJ_POSIX_ACCOUNT_OBJECTCLASS = new QName(RESOURCE_NS, "posixAccount"); - + protected static final File QUERY_COMPLEX_FILTER_FILE = new File(TEST_DIR, "query-complex-filter.xml"); protected static final File QUERY_ALL_ACCOUNTS_FILE = new File(TEST_DIR, "query-filter-all-accounts.xml"); protected static final File QUERY_VANHELGEN_FILE = new File(TEST_DIR, "query-vanhelgen.xml"); - + protected static final String OBJECT_CLASS_INETORGPERSON_NAME = "inetOrgPerson"; protected static final String GROUP_MEMBER_ATTR_NAME = "uniqueMember"; - + protected static final QName ASSOCIATION_GROUP_NAME = new QName(RESOURCE_OPENDJ_NS, "group"); - + private static final Trace LOGGER = TraceManager.getTrace(AbstractOpenDjTest.class); - + protected MatchingRule dnMatchingRule; - + protected PrismObject resource; protected ResourceType resourceType; protected PrismObject connector; - + @Autowired(required = true) protected ProvisioningService provisioningService; @@ -167,14 +167,14 @@ public abstract class AbstractOpenDjTest extends AbstractIntegrationTest { @Autowired(required = true) protected SynchornizationServiceMock syncServiceMock; - + @Autowired(required = true) protected MatchingRuleRegistry matchingRuleRegistry; protected File getResourceOpenDjFile() { return RESOURCE_OPENDJ_FILE; } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { // We need to switch off the encryption checks. Some values cannot be encrypted as we do @@ -183,14 +183,14 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti provisioningService.postInit(initResult); resource = addResourceFromFile(getResourceOpenDjFile(), IntegrationTestTools.CONNECTOR_LDAP_TYPE, initResult); repoAddShadowFromFile(ACCOUNT_BAD_FILE, initResult); - + dnMatchingRule = matchingRuleRegistry.getMatchingRule(DistinguishedNameMatchingRule.NAME, DOMUtil.XSD_STRING); } - + protected void assertAttribute(ShadowType shadow, String attrName, T... expectedValues) { assertAttribute(resource, shadow, attrName, expectedValues); } - + protected void assertAttribute(PrismObject shadow, String attrName, T... expectedValues) { assertAttribute(resource, shadow.asObjectable(), attrName, expectedValues); } @@ -198,7 +198,7 @@ protected void assertAttribute(PrismObject shadow, String attrNa protected void assertAttribute(ShadowType shadow, QName attrName, T... expectedValues) { assertAttribute(resource, shadow, attrName, expectedValues); } - + protected QName getPrimaryIdentifierQName() { return new QName(ResourceTypeUtil.getResourceNamespace(resourceType), OpenDJController.RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME); } 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 16d23f28de8..66607ff9ecf 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 @@ -141,16 +141,16 @@ /** * Test for provisioning service implementation. - * + * * This test will initialize mock repository and fill-in some test data. The * "default" repository objects cannot be used, as the new provisioning service * implementation assumes a slightly different connector configuration that was * used in the OpenIDM. - * + * * This test will initialize embedded OpenDJ as a target resource. - * + * * The test calls the new Provisioning Service Interface (java). No WSDL mess. - * + * * @author Radovan Semancik * @author Katka Valalikova */ @@ -159,25 +159,25 @@ public class TestOpenDj extends AbstractOpenDjTest { private static Trace LOGGER = TraceManager.getTrace(TestOpenDj.class); - + private String groupSailorOid; @Autowired TaskManager taskManager; - + protected int getNumberOfBaseContextShadows() { return 0; } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + openDJController.addEntry("dn: ou=specialgroups,dc=example,dc=com\n"+ "objectclass: organizationalUnit\n"+ "ou: specialgroups\n"); } - + @BeforeClass public static void startLdap() throws Exception { LOGGER.info("------------------------------------------------------------------------------"); @@ -198,10 +198,10 @@ public static void stopLdap() throws Exception { LOGGER.info("STOP: ProvisioningServiceImplOpenDJTest"); LOGGER.info("------------------------------------------------------------------------------"); } - + /** * 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. @@ -221,42 +221,42 @@ public void test003Connection() throws Exception { assertNotNull(connectorType); Element resourceXsdSchemaElementBefore = ResourceTypeUtil.getResourceXsdSchema(resourceTypeBefore); AssertJUnit.assertNull("Found schema before test connection. Bad test setup?", resourceXsdSchemaElementBefore); - + OperationResult operationResult = provisioningService.testResource(RESOURCE_OPENDJ_OID, task); - + display("Test connection result",operationResult); TestUtil.assertSuccess("Test connection failed",operationResult); PrismObject resourceRepoAfter = repositoryService.getObject(ResourceType.class,RESOURCE_OPENDJ_OID, null, result); ResourceType resourceTypeRepoAfter = resourceRepoAfter.asObjectable(); - + display("Resource after testResource (repository)",resourceTypeRepoAfter); - + display("Resource after testResource (repository, XML)", PrismTestUtil.serializeObjectToString(resourceTypeRepoAfter.asPrismObject(), PrismContext.LANG_XML)); - + XmlSchemaType xmlSchemaTypeAfter = resourceTypeRepoAfter.getSchema(); assertNotNull("No schema after test connection",xmlSchemaTypeAfter); Element resourceXsdSchemaElementAfter = ResourceTypeUtil.getResourceXsdSchema(resourceTypeRepoAfter); assertNotNull("No schema after test connection", resourceXsdSchemaElementAfter); - + CachingMetadataType cachingMetadata = xmlSchemaTypeAfter.getCachingMetadata(); assertNotNull("No caching metadata",cachingMetadata); assertNotNull("No retrievalTimestamp",cachingMetadata.getRetrievalTimestamp()); assertNotNull("No serialNumber",cachingMetadata.getSerialNumber()); - + Element xsdElement = ResourceTypeUtil.getResourceXsdSchema(resourceTypeRepoAfter); ResourceSchema parsedSchema = ResourceSchemaImpl.parse(xsdElement, resourceTypeRepoAfter.toString(), prismContext); assertNotNull("No schema after parsing",parsedSchema); - + ObjectClassComplexTypeDefinition inetOrgPersonDefinition = parsedSchema.findObjectClassDefinition(RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS); assertNull("The _PASSSWORD_ attribute sneaked into schema", inetOrgPersonDefinition.findAttributeDefinition( new QName(SchemaConstants.NS_ICF_SCHEMA,"password"))); assertNull("The userPassword attribute sneaked into schema", inetOrgPersonDefinition.findAttributeDefinition( new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeRepoAfter),"userPassword"))); - + assertShadows(1); } - + @Test public void test004ResourceAndConnectorCaching() throws Exception { final String TEST_NAME = "test004ResourceAndConnectorCaching"; @@ -264,7 +264,7 @@ public void test004ResourceAndConnectorCaching() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + resource = provisioningService.getObject(ResourceType.class,RESOURCE_OPENDJ_OID, null, null, result); resourceType = resource.asObjectable(); ConnectorInstance configuredConnectorInstance = resourceManager.getConfiguredConnectorInstance( @@ -272,17 +272,17 @@ public void test004ResourceAndConnectorCaching() throws Exception { assertNotNull("No configuredConnectorInstance", configuredConnectorInstance); ResourceSchema resourceSchema = RefinedResourceSchemaImpl.getResourceSchema(resource, prismContext); assertNotNull("No resource schema", resourceSchema); - + // WHEN PrismObject resourceAgain = provisioningService.getObject(ResourceType.class,RESOURCE_OPENDJ_OID, null, task, result); - + // THEN ResourceType resourceTypeAgain = resourceAgain.asObjectable(); assertNotNull("No connector ref",resourceTypeAgain.getConnectorRef()); assertNotNull("No connector ref OID",resourceTypeAgain.getConnectorRef().getOid()); - + PrismContainer configurationContainer = resource.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); - PrismContainer configurationContainerAgain = resourceAgain.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); + PrismContainer configurationContainerAgain = resourceAgain.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); assertTrue("Configurations not equivalent", configurationContainer.equivalent(configurationContainerAgain)); assertTrue("Configurations not equals", configurationContainer.equals(configurationContainerAgain)); @@ -291,16 +291,16 @@ public void test004ResourceAndConnectorCaching() throws Exception { assertEquals("Schema serial number mismatch", resourceType.getSchema().getCachingMetadata().getSerialNumber(), resourceTypeAgain.getSchema().getCachingMetadata().getSerialNumber()); assertTrue("Resource schema was not cached", resourceSchema == resourceSchemaAgain); - + // Now we stick our nose deep inside the provisioning impl. But we need to make sure that the // configured connector is properly cached ConnectorInstance configuredConnectorInstanceAgain = resourceManager.getConfiguredConnectorInstance( resourceAgain, ReadCapabilityType.class, false, result); assertTrue("Connector instance was not cached", configuredConnectorInstance == configuredConnectorInstanceAgain); - + assertShadows(1); } - + @Test public void test005Capabilities() throws Exception { final String TEST_NAME = "test005Capabilities"; @@ -308,15 +308,15 @@ public void test005Capabilities() throws Exception { // GIVEN Task task = createTask(TEST_NAME); - OperationResult result = task.getResult(); + OperationResult result = task.getResult(); // WHEN ResourceType resource = provisioningService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, task, result).asObjectable(); - + // THEN display("Resource from provisioninig", resource); display("Resource from provisioninig (XML)", PrismTestUtil.serializeObjectToString(resource.asPrismObject(), PrismContext.LANG_XML)); - + CapabilityCollectionType nativeCapabilities = resource.getCapabilities().getNative(); List nativeCapabilitiesList = nativeCapabilities.getAny(); assertFalse("Empty capabilities returned",nativeCapabilitiesList.isEmpty()); @@ -325,11 +325,11 @@ public void test005Capabilities() throws Exception { PasswordCapabilityType capPassword = capCred.getPassword(); assertNotNull("password capability not present", capPassword); assertPasswordCapability(capPassword); - + // Connector cannot do activation, this should be null ActivationCapabilityType capAct = CapabilityUtil.getCapability(nativeCapabilitiesList, ActivationCapabilityType.class); assertNull("Found activation capability while not expecting it" ,capAct); - + ScriptCapabilityType capScript = CapabilityUtil.getCapability(nativeCapabilitiesList, ScriptCapabilityType.class); assertNotNull("No script capability", capScript); List scriptHosts = capScript.getHost(); @@ -337,25 +337,25 @@ public void test005Capabilities() throws Exception { Host scriptHost = scriptHosts.get(0); assertEquals("Wrong script host type", ProvisioningScriptHostType.CONNECTOR, scriptHost.getType()); // assertEquals("Wrong script host language", ....., scriptHost.getLanguage()); - + CreateCapabilityType capCreate = CapabilityUtil.getCapability(nativeCapabilitiesList, CreateCapabilityType.class); assertNotNull("No create capability", capCreate); - + ReadCapabilityType capRead = CapabilityUtil.getCapability(nativeCapabilitiesList, ReadCapabilityType.class); assertNotNull("No read capability", capRead); - + UpdateCapabilityType capUpdate = CapabilityUtil.getCapability(nativeCapabilitiesList, UpdateCapabilityType.class); assertNotNull("No update capability", capUpdate); - + DeleteCapabilityType capDelete = CapabilityUtil.getCapability(nativeCapabilitiesList, DeleteCapabilityType.class); assertNotNull("No delete capability", capDelete); - - + + List effectiveCapabilities = ResourceTypeUtil.getEffectiveCapabilities(resource); for (Object capability : effectiveCapabilities) { System.out.println("Capability: "+CapabilityUtil.getCapabilityDisplayName(capability)+" : "+capability); } - + capCred = ResourceTypeUtil.getEffectiveCapability(resource, CredentialsCapabilityType.class); assertNotNull("credentials effective capability not found",capCred); assertNotNull("password effective capability not found",capCred.getPassword()); @@ -363,15 +363,15 @@ public void test005Capabilities() throws Exception { // Therefore the following should succeed capAct = ResourceTypeUtil.getEffectiveCapability(resource, ActivationCapabilityType.class); assertNotNull("activation capability not found",capAct); - + PagedSearchCapabilityType capPage = ResourceTypeUtil.getEffectiveCapability(resource, PagedSearchCapabilityType.class); assertNotNull("paged search capability not present", capPage); - + assertShadows(1); } - + protected void assertPasswordCapability(PasswordCapabilityType capPassword) { - assertTrue("Wrong password capability readable flag: "+capPassword.isReadable(), + assertTrue("Wrong password capability readable flag: "+capPassword.isReadable(), capPassword.isReadable() != Boolean.TRUE); } @@ -423,7 +423,7 @@ public void test006Schema() throws Exception { assertTrue("No cn update", cnDef.canModify()); assertTrue("No cn read", cnDef.canRead()); assertEquals("Wrong cn matching rule", StringIgnoreCaseMatchingRule.NAME, cnDef.getMatchingRuleQName()); - + ResourceAttributeDefinition jpegPhoto = accountDef.findAttributeDefinition("jpegPhoto"); assertNotNull("No definition for jpegPhoto", jpegPhoto); assertEquals(-1, jpegPhoto.getMaxOccurs()); @@ -432,7 +432,7 @@ public void test006Schema() throws Exception { assertTrue("No jpegPhoto update", jpegPhoto.canModify()); assertTrue("No jpegPhoto read", jpegPhoto.canRead()); assertEquals("Wrong jpegPhoto matching rule", null, jpegPhoto.getMatchingRuleQName()); - + ResourceAttributeDefinition dsDef = accountDef.findAttributeDefinition("ds-pwp-account-disabled"); assertNotNull("No definition for ds-pwp-account-disabled", dsDef); assertEquals(1, dsDef.getMaxOccurs()); @@ -442,7 +442,7 @@ public void test006Schema() throws Exception { assertTrue("No ds-pwp-account-disabled update", dsDef.canModify()); // TODO: MID-2358 // assertTrue("ds-pwp-account-disabled is NOT operational", dsDef.isOperational()); - + ResourceAttributeDefinition memberOfDef = accountDef.findAttributeDefinition("isMemberOf"); assertNotNull("No definition for isMemberOf", memberOfDef); assertEquals(-1, memberOfDef.getMaxOccurs()); @@ -469,7 +469,7 @@ public void test006Schema() throws Exception { assertTrue("No secretary update", secretaryDef.canModify()); assertTrue("No secretary read", secretaryDef.canRead()); assertEquals("Wrong secretary matching rule", DistinguishedNameMatchingRule.NAME, secretaryDef.getMatchingRuleQName()); - + ResourceAttributeDefinition createTimestampDef = accountDef.findAttributeDefinition("createTimestamp"); assertNotNull("No definition for createTimestamp", createTimestampDef); assertEquals(1, createTimestampDef.getMaxOccurs()); @@ -481,10 +481,10 @@ public void test006Schema() throws Exception { assertNull("The _PASSSWORD_ attribute sneaked into schema", accountDef.findAttributeDefinition(new QName(SchemaConstants.NS_ICF_SCHEMA, "password"))); - + assertNull("The userPassword attribute sneaked into schema", accountDef.findAttributeDefinition(new QName(accountDef.getTypeName().getNamespaceURI(), "userPassword"))); - + assertNull("The objectClass attribute sneaked into schema", accountDef.findAttributeDefinition(new QName(accountDef.getTypeName().getNamespaceURI(), "objectClass"))); @@ -524,7 +524,7 @@ public void test006Schema() throws Exception { assertNotNull("No definition for normalTestingObjectClass", normalDef); assertNotNull("The cn attribute missing in normalTestingObjectClass", normalDef.findAttributeDefinition(new QName(normalDef.getTypeName().getNamespaceURI(), "cn"))); - + ObjectClassComplexTypeDefinition hybridDef = resourceSchema.findObjectClassDefinition(new QName(RESOURCE_NS, "hybridTestingObjectClass")); display("Hybrid object class def", hybridDef); assertNotNull("No definition for hybridTestingObjectClass", hybridDef); @@ -532,16 +532,16 @@ public void test006Schema() throws Exception { hybridDef.findAttributeDefinition(new QName(hybridDef.getTypeName().getNamespaceURI(), "cn"))); assertNotNull("The uuidIdentifiedAttribute attribute missing in hybridTestingObjectClass", hybridDef.findAttributeDefinition(new QName(hybridDef.getTypeName().getNamespaceURI(), "uuidIdentifiedAttribute"))); - + ObjectClassComplexTypeDefinition uuidDef = resourceSchema.findObjectClassDefinition(new QName(RESOURCE_NS, "uuidIdentifiedObjectClass")); display("uuidIdentifiedObjectClass object class def", uuidDef); assertNotNull("No definition for uuidIdentifiedObjectClass", uuidDef); assertNotNull("The uuidIdentifiedAttribute attribute missing in uuidIdentifiedObjectClass", uuidDef.findAttributeDefinition(new QName(uuidDef.getTypeName().getNamespaceURI(), "uuidIdentifiedAttribute"))); - + assertShadows(1); } - + @Test public void test007RefinedSchema() throws Exception { final String TEST_NAME = "test007RefinedSchema"; @@ -594,7 +594,7 @@ public void test007RefinedSchema() throws Exception { assertTrue("No cn create", cnDef.canAdd()); assertTrue("No cn update", cnDef.canModify()); assertTrue("No cn read", cnDef.canRead()); - + ResourceAttributeDefinition memberOfDef = accountDef.findAttributeDefinition("isMemberOf"); assertNotNull("No definition for isMemberOf", memberOfDef); assertEquals(-1, memberOfDef.getMaxOccurs()); @@ -603,7 +603,7 @@ public void test007RefinedSchema() throws Exception { assertFalse("isMemberOf update", memberOfDef.canModify()); assertTrue("No isMemberOf read", memberOfDef.canRead()); assertEquals("Wrong isMemberOf matching rule", DistinguishedNameMatchingRule.NAME, memberOfDef.getMatchingRuleQName()); - + ResourceAttributeDefinition secretaryDef = accountDef.findAttributeDefinition("secretary"); assertNotNull("No definition for secretary", secretaryDef); assertEquals(-1, secretaryDef.getMaxOccurs()); @@ -612,7 +612,7 @@ public void test007RefinedSchema() throws Exception { assertTrue("No secretary update", secretaryDef.canModify()); assertTrue("No secretary read", secretaryDef.canRead()); assertEquals("Wrong secretary matching rule", XmlMatchingRule.NAME, secretaryDef.getMatchingRuleQName()); - + RefinedAttributeDefinition dsDef = accountDef.findAttributeDefinition("ds-pwp-account-disabled"); assertNotNull("No definition for cn", dsDef); assertEquals(1, dsDef.getMaxOccurs()); @@ -626,7 +626,7 @@ public void test007RefinedSchema() throws Exception { assertNull("The _PASSSWORD_ attribute sneaked into schema", accountDef.findAttributeDefinition(new QName(SchemaConstants.NS_ICF_SCHEMA, "password"))); - + RefinedObjectClassDefinition posixAccountDef = refinedSchema.getRefinedDefinition(RESOURCE_OPENDJ_POSIX_ACCOUNT_OBJECTCLASS); assertNotNull("posixAccount definition is missing", posixAccountDef); assertNotNull("Null identifiers in posixAccount", posixAccountDef.getPrimaryIdentifiers()); @@ -666,16 +666,16 @@ public void test020ListResourceObjects() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN List> objectList = provisioningService.listResourceObjects( RESOURCE_OPENDJ_OID, RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS, null, task, result); - + // THEN assertNotNull(objectList); assertFalse("Empty list returned",objectList.isEmpty()); display("Resource object list "+RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS,objectList); - + assertShadows(1 + getNumberOfBaseContextShadows()); } @@ -684,7 +684,7 @@ public void test020ListResourceObjects() throws Exception { public void test110GetObject() throws Exception { final String TEST_NAME = "test110GetObject"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); @@ -692,7 +692,7 @@ public void test110GetObject() throws Exception { display(SchemaDebugUtil.prettyPrint(objectToAdd)); display(objectToAdd.asPrismObject().debugDump()); - + String addedObjectOid = provisioningService.addObject(objectToAdd.asPrismObject(), null, null, task, result); assertEquals(ACCOUNT_JBOND_OID, addedObjectOid); PropertyReferenceListType resolve = new PropertyReferenceListType(); @@ -704,14 +704,14 @@ public void test110GetObject() throws Exception { // THEN TestUtil.displayThen(TEST_NAME); assertSuccess(result); - + assertNotNull(provisioningShadow); display("Account provisioning", provisioningShadow); - + PrismAsserts.assertEqualsPolyString("Name not equals.", "uid=jbond,ou=People,dc=example,dc=com", provisioningShadow.getName()); - + final String resourceNamespace = ResourceTypeUtil.getResourceNamespace(resource); - + assertNotNull(provisioningShadow.getOid()); assertNotNull(provisioningShadow.getName()); assertEquals(new QName(resourceNamespace, OBJECT_CLASS_INETORGPERSON_NAME), provisioningShadow.getObjectClass()); @@ -724,12 +724,12 @@ public void test110GetObject() throws Exception { assertEquals("Wrong secondary identifier", "uid=jbond,ou=People,dc=example,dc=com", idSecondaryVal); assertEquals("Wrong LDAP uid", "jbond", getAttributeValue(provisioningShadow, new QName(resourceNamespace, "uid"))); assertEquals("Wrong LDAP cn", "James Bond", getAttributeValue(provisioningShadow, new QName(resourceNamespace, "cn"))); - assertEquals("Wrong LDAP sn", "Bond", getAttributeValue(provisioningShadow, new QName(resourceNamespace, "sn"))); + assertEquals("Wrong LDAP sn", "Bond", getAttributeValue(provisioningShadow, new QName(resourceNamespace, "sn"))); assertNotNull("Missing activation", provisioningShadow.getActivation()); assertNotNull("Missing activation status", provisioningShadow.getActivation().getAdministrativeStatus()); assertEquals("Not enabled", ActivationStatusType.ENABLED, provisioningShadow.getActivation().getAdministrativeStatus()); assertShadowPassword(provisioningShadow); - + ShadowType repoShadow = repositoryService.getObject(ShadowType.class, provisioningShadow.getOid(), null, result).asObjectable(); display("Account repo", repoShadow); assertEquals(new QName(resourceNamespace, OBJECT_CLASS_INETORGPERSON_NAME), repoShadow.getObjectClass()); @@ -741,7 +741,7 @@ public void test110GetObject() throws Exception { // must be all lowercase assertEquals("Wrong secondary identifier (repo)", "uid=jbond,ou=people,dc=example,dc=com", idSecondaryVal); - assertShadows(2 + getNumberOfBaseContextShadows()); + assertShadows(2 + getNumberOfBaseContextShadows()); } protected void assertShadowPassword(ShadowType provisioningShadow) throws Exception { @@ -764,7 +764,7 @@ protected void assertShadowPassword(ShadowType provisioningShadow) throws Except public void test111GetObjectNotFoundRepo() throws Exception { final String TEST_NAME = "test111GetObjectNotFoundRepo"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); @@ -799,7 +799,7 @@ public void test111GetObjectNotFoundRepo() throws Exception { public void test112GetObjectNotFoundResource() throws Exception { final String TEST_NAME = "test112GetObjectNotFoundResource"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); @@ -839,7 +839,7 @@ public void test112GetObjectNotFoundResource() throws Exception { public void test120AddAccountWill() throws Exception { final String TEST_NAME = "test120AddAccountWill"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); @@ -859,7 +859,7 @@ public void test120AddAccountWill() throws Exception { ShadowType provisioningAccountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result).asObjectable(); PrismAsserts.assertEqualsPolyString("Name not equal.", "uid=will,ou=People,dc=example,dc=com", provisioningAccountType.getName()); - + assertShadows(1 + getNumberOfBaseContextShadows()); } @@ -867,15 +867,15 @@ public void test120AddAccountWill() throws Exception { public void test121RenameAccountWillOnResource() throws Exception{ String TEST_NAME = "test121RenameAccountWillOnResource"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + openDJController.executeRenameChange(new File(TEST_DIR, "rename.ldif").getPath()); - + Entry entry = openDJController.fetchEntry("uid=will123,ou=People,dc=example,dc=com"); assertNotNull("Entry with dn uid=will123,ou=People,dc=example,dc=com does not exist", entry); - + ShadowType repoShadowType = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result).asObjectable(); PrismAsserts.assertEqualsPolyString("Name not equal (repo)", "uid=will,ou=People,dc=example,dc=com", repoShadowType.getName()); @@ -885,46 +885,46 @@ public void test121RenameAccountWillOnResource() throws Exception{ null, task, result).asObjectable(); PrismAsserts.assertEqualsPolyString("Name not equal.", "uid=will123,ou=People,dc=example,dc=com", provisioningAccountType.getName()); assertAttribute(provisioningAccountType, getSecondaryIdentifierQName(), "uid=will123,ou=People,dc=example,dc=com"); - + repoShadowType = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result).asObjectable(); PrismAsserts.assertEqualsPolyString("Name not equal (repo after provisioning)", "uid=will123,ou=People,dc=example,dc=com", repoShadowType.getName()); assertAttribute(repoShadowType, getSecondaryIdentifierQName(), "uid=will123,ou=people,dc=example,dc=com"); - + assertShadows(1 + getNumberOfBaseContextShadows()); } - + @Test public void test125AddObjectNull() throws Exception { final String TEST_NAME = "test125AddObjectNull"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); String addedObjectOid = null; - + try { - + // WHEN addedObjectOid = provisioningService.addObject(null, null, null, task, result); - + Assert.fail("Expected IllegalArgumentException but haven't got one."); } catch(IllegalArgumentException ex){ assertEquals("Object to add must not be null.", ex.getMessage()); } - + assertShadows(1 + getNumberOfBaseContextShadows()); } - + @Test public void test130AddDeleteAccountSparrow() throws Exception { final String TEST_NAME = "test130AddDeleteAccountSparrow"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ShadowType object = parseObjectType(ACCOUNT_SPARROW_FILE, ShadowType.class); System.out.println(SchemaDebugUtil.prettyPrint(object)); @@ -958,7 +958,7 @@ public void test130AddDeleteAccountSparrow() throws Exception { display("Expected exception", ex); assertTrue(ex.getMessage().contains(ACCOUNT_SPARROW_OID)); } - + // Account shadow + shadow for base context assertShadows(2); } @@ -967,7 +967,7 @@ public void test130AddDeleteAccountSparrow() throws Exception { public void test140AddAndModifyAccountJack() throws Exception { final String TEST_NAME = "test140AddAndModifyAccountJack"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); @@ -981,113 +981,113 @@ public void test140AddAndModifyAccountJack() throws Exception { ObjectModificationType objectChange = PrismTestUtil.parseAtomicValue(ACCOUNT_JACK_CHANGE_FILE, ObjectModificationType.COMPLEX_TYPE); ObjectDelta delta = DeltaConvertor.createObjectDelta(objectChange, object.asPrismObject().getDefinition()); - + ItemPath icfNamePath = new ItemPath( ShadowType.F_ATTRIBUTES, getSecondaryIdentifierQName()); PrismPropertyDefinition icfNameDef = object .asPrismObject().getDefinition().findPropertyDefinition(icfNamePath); ItemDelta renameDelta = PropertyDelta.createModificationReplaceProperty(icfNamePath, icfNameDef, "uid=rename,ou=People,dc=example,dc=com"); ((Collection)delta.getModifications()).add(renameDelta); - + display("Object change",delta); - + // WHEN TestUtil.displayWhen(TEST_NAME); provisioningService.modifyObject(ShadowType.class, objectChange.getOid(), delta.getModifications(), null, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_JACK_OID, null, taskManager.createTaskInstance(), result).asObjectable(); - + display("Object after change",accountType); - + String uid = ShadowUtil.getSingleStringAttributeValue(accountType, getPrimaryIdentifierQName()); List snValues = ShadowUtil.getAttributeValues(accountType, new QName(RESOURCE_NS, "sn")); assertNotNull("No 'sn' attribute", snValues); assertFalse("Surname attributes must not be empty", snValues.isEmpty()); assertEquals(1, snValues.size()); - + //check icf_name in the shadow object fetched only from the repository ShadowType repoShadow = repositoryService.getObject(ShadowType.class, objectChange.getOid(), null, result).asObjectable(); String name = ShadowUtil.getSingleStringAttributeValue(repoShadow, getSecondaryIdentifierQName()); assertEquals("After rename, dn is not equal.", "uid=rename,ou=people,dc=example,dc=com", name); assertEquals("shadow name not changed after rename", "uid=rename,ou=People,dc=example,dc=com", repoShadow.getName().getOrig()); - + String changedSn = (String) snValues.get(0); - + assertNotNull(uid); - + // Check if object was modified in LDAP - - Entry response = openDJController.searchAndAssertByEntryUuid(uid); + + Entry response = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP account", response); - + OpenDJController.assertAttribute(response, "sn", "First"); - + assertEquals("First", changedSn); - + assertShadows(3); } - + @Test public void test145ModifyAccountJackJpegPhoto() throws Exception { final String TEST_NAME = "test145ModifyAccountJackJpegPhoto"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + byte[] bytesIn = Files.readAllBytes(Paths.get(ProvisioningTestUtil.DOT_JPG_FILENAME)); display("Bytes in", MiscUtil.binaryToHex(bytesIn)); - + QName jpegPhotoQName = new QName(RESOURCE_OPENDJ_NS, "jpegPhoto"); - PropertyDelta jpegPhotoDelta = new PropertyDelta<>(new ItemPath(ShadowType.F_ATTRIBUTES, jpegPhotoQName), + PropertyDelta jpegPhotoDelta = new PropertyDelta<>(new ItemPath(ShadowType.F_ATTRIBUTES, jpegPhotoQName), null , prismContext); jpegPhotoDelta.setValueToReplace(new PrismPropertyValue(bytesIn)); - + Collection modifications = MiscSchemaUtil.createCollection(jpegPhotoDelta); - + display("Modifications",modifications); - + // WHEN TestUtil.displayWhen(TEST_NAME); provisioningService.modifyObject(ShadowType.class, ACCOUNT_JACK_OID, modifications, null, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + Entry entry = openDJController.searchByUid("rename"); display("LDAP Entry", entry); byte[] jpegPhotoLdap = OpenDJController.getAttributeValueBinary(entry, "jpegPhoto"); assertNotNull("No jpegPhoto in LDAP entry", jpegPhotoLdap); assertEquals("Byte length changed (LDAP)", bytesIn.length, jpegPhotoLdap.length); assertTrue("Bytes do not match (LDAP)", Arrays.equals(bytesIn, jpegPhotoLdap)); - + PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_JACK_OID, null, taskManager.createTaskInstance(), result); - + display("Object after change",shadow); - + PrismContainer attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES); PrismProperty jpegPhotoAttr = attributesContainer.findProperty(jpegPhotoQName); byte[] bytesOut = jpegPhotoAttr.getValues().get(0).getValue(); - + display("Bytes out", MiscUtil.binaryToHex(bytesOut)); - + assertEquals("Byte length changed (shadow)", bytesIn.length, bytesOut.length); assertTrue("Bytes do not match (shadow)", Arrays.equals(bytesIn, bytesOut)); - + assertShadows(3); } - + /** * Make a duplicate modification. Add a givenName value that is already there. * Normal LDAP should fail. So check that connector and midPoitn handles that. @@ -1096,50 +1096,50 @@ public void test145ModifyAccountJackJpegPhoto() throws Exception { public void test147ModifyAccountJackGivenNameDuplicit() throws Exception { final String TEST_NAME = "test147ModifyAccountJackGivenNameDuplicit"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PropertyDelta givenNameDelta = new PropertyDelta<>( - new ItemPath(ShadowType.F_ATTRIBUTES, new QName(RESOURCE_OPENDJ_NS, "givenName")), + new ItemPath(ShadowType.F_ATTRIBUTES, new QName(RESOURCE_OPENDJ_NS, "givenName")), null , prismContext); givenNameDelta.addValueToAdd(new PrismPropertyValue("Jack")); - + // Also make an ordinary non-conflicting modification. We need to make sure that // the operation was not ignored as a whole PropertyDelta titleDelta = new PropertyDelta<>( - new ItemPath(ShadowType.F_ATTRIBUTES, new QName(RESOURCE_OPENDJ_NS, "title")), + new ItemPath(ShadowType.F_ATTRIBUTES, new QName(RESOURCE_OPENDJ_NS, "title")), null , prismContext); titleDelta.addValueToAdd(new PrismPropertyValue("Great Captain")); - + Collection modifications = MiscSchemaUtil.createCollection(givenNameDelta, titleDelta); - + display("Modifications",modifications); - + // WHEN TestUtil.displayWhen(TEST_NAME); provisioningService.modifyObject(ShadowType.class, ACCOUNT_JACK_OID, modifications, null, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + Entry entry = openDJController.searchByUid("rename"); display("LDAP Entry", entry); OpenDJController.assertAttribute(entry, "givenName", "Jack"); OpenDJController.assertAttribute(entry, "title", "Great Captain"); - + PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_JACK_OID, null, taskManager.createTaskInstance(), result); - + display("Object after change",shadow); - + PrismContainer attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES); PrismAsserts.assertPropertyValue(attributesContainer, new QName(RESOURCE_OPENDJ_NS, "givenName"), "Jack"); PrismAsserts.assertPropertyValue(attributesContainer, new QName(RESOURCE_OPENDJ_NS, "title"), "Great Captain"); - + assertShadows(3); } @@ -1148,7 +1148,7 @@ public void test147ModifyAccountJackGivenNameDuplicit() throws Exception { public void test150ChangePassword() throws Exception { final String TEST_NAME = "test150ChangePassword"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); @@ -1157,22 +1157,22 @@ public void test150ChangePassword() throws Exception { String addedObjectOid = provisioningService.addObject(object.asPrismObject(), null, null, taskManager.createTaskInstance(), result); assertEquals(ACCOUNT_MODIFY_PASSWORD_OID, addedObjectOid); - + ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_MODIFY_PASSWORD_OID, null, taskManager.createTaskInstance(), result).asObjectable(); - + display("Object before password change",accountType); - + String uid = null; uid = ShadowUtil.getSingleStringAttributeValue(accountType, getPrimaryIdentifierQName()); assertNotNull(uid); - - Entry entryBefore = openDJController.searchAndAssertByEntryUuid(uid); + + Entry entryBefore = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP account before", entryBefore); String passwordBefore = OpenDJController.getAttributeValue(entryBefore, "userPassword"); assertNull("Unexpected password before change",passwordBefore); - + ObjectModificationType objectChange = PrismTestUtil.parseAtomicValue( new File(TEST_DIR, "account-change-password.xml"), ObjectModificationType.COMPLEX_TYPE); ObjectDelta delta = DeltaConvertor.createObjectDelta(objectChange, accountType.asPrismObject().getDefinition()); @@ -1184,16 +1184,16 @@ public void test150ChangePassword() throws Exception { // THEN TestUtil.displayThen(TEST_NAME); - + // Check if object was modified in LDAP - Entry entryAfter = openDJController.searchAndAssertByEntryUuid(uid); + Entry entryAfter = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP account after", entryAfter); String passwordAfter = OpenDJController.getAttributeValue(entryAfter, "userPassword"); assertNotNull("The password was not changed",passwordAfter); - + System.out.println("Changed password: "+passwordAfter); - + openDJController.assertPassword(entryAfter.getDN().toString(), "mehAbigH4X0R"); assertShadows(4); @@ -1203,7 +1203,7 @@ public void test150ChangePassword() throws Exception { public void test151AddObjectWithPassword() throws Exception { final String TEST_NAME = "test151AddObjectWithPassword"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); @@ -1224,7 +1224,7 @@ public void test151AddObjectWithPassword() throws Exception { null,taskManager.createTaskInstance(), result).asObjectable(); PrismAsserts.assertEqualsPolyString("Name not equal.", "uid=lechuck,ou=People,dc=example,dc=com", provisioningAccountType.getName()); // assertEquals("lechuck", provisioningAccountType.getName()); - + String uid = null; for (Object e : accountType.getAttributes().getAny()) { if (getPrimaryIdentifierQName().equals(JAXBUtil.getElementQName(e))) { @@ -1232,36 +1232,36 @@ public void test151AddObjectWithPassword() throws Exception { } } assertNotNull(uid); - + // Check if object was created in LDAP and that there is a password - - Entry entryAfter = openDJController.searchAndAssertByEntryUuid(uid); + + Entry entryAfter = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP account after", entryAfter); String passwordAfter = OpenDJController.getAttributeValue(entryAfter, "userPassword"); assertNotNull("The password was not changed",passwordAfter); - + System.out.println("Account password: "+passwordAfter); - + openDJController.assertPassword(entryAfter.getDN().toString(), "t4k30v3rTh3W0rld"); - + assertShadows(5); } - + @Test public void test160SearchAccountsIterative() throws Exception { final String TEST_NAME = "test160SearchAccountsIterative"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + final String resourceNamespace = ResourceTypeUtil.getResourceNamespace(resource); QName objectClass = new QName(resourceNamespace, OBJECT_CLASS_INETORGPERSON_NAME); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(resource.getOid(), objectClass, prismContext); - + final Collection objects = new HashSet(); ResultHandler handler = new ResultHandler() { @@ -1301,9 +1301,9 @@ public boolean handle(PrismObject prismObject, OperationResult paren display("Count", objects.size()); assertEquals("Unexpected number of shadows", 9, objects.size()); - // The extra shadow is a group shadow + // The extra shadow is a group shadow assertShadows(11); - + // Bad things may happen, so let's check if the shadow is still there and that is has the same OID PrismObject accountNew = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, taskManager.createTaskInstance(), result); } @@ -1328,7 +1328,7 @@ public boolean handle(PrismObject object, OperationResult parentResu public void test170DisableAccount() throws Exception{ final String TEST_NAME = "test170DisableAccount"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); @@ -1349,37 +1349,37 @@ public void test170DisableAccount() throws Exception{ TestUtil.displayWhen(TEST_NAME); provisioningService.modifyObject(ShadowType.class, objectChange.getOid(), delta.getModifications(), null, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_DISABLE_SIMULATED_OID, null, taskManager.createTaskInstance(), result).asObjectable(); - + display("Object after change",accountType); - + assertEquals("The account was not disabled in the shadow", ActivationStatusType.DISABLED, accountType.getActivation().getAdministrativeStatus()); - - String uid = ShadowUtil.getSingleStringAttributeValue(accountType, getPrimaryIdentifierQName()); + + String uid = ShadowUtil.getSingleStringAttributeValue(accountType, getPrimaryIdentifierQName()); assertNotNull(uid); - + // Check if object was modified in LDAP - + Entry response = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP account", response); - + String disabled = openDJController.getAttributeValue(response, "ds-pwp-account-disabled"); assertNotNull("no ds-pwp-account-disabled attribute in account "+uid, disabled); display("ds-pwp-account-disabled after change: " + disabled); assertEquals("ds-pwp-account-disabled not set to \"TRUE\"", "TRUE", disabled); - + PrismObject repoShadow = repositoryService.getObject(ShadowType.class, ACCOUNT_DISABLE_SIMULATED_OID, null, result); ActivationType repoActivation = repoShadow.asObjectable().getActivation(); assertNotNull("No activation in repo", repoActivation); XMLGregorianCalendar repoDisableTimestamp = repoActivation.getDisableTimestamp(); assertNotNull("No activation disableTimestamp in repo", repoDisableTimestamp); - assertEquals("Wrong activation disableTimestamp in repo", + assertEquals("Wrong activation disableTimestamp in repo", XmlTypeConverter.createXMLGregorianCalendar(2001, 2, 3, 4, 5, 6), repoDisableTimestamp); } @@ -1387,7 +1387,7 @@ public void test170DisableAccount() throws Exception{ public void test175AddDisabledAccount() throws Exception { final String TEST_NAME = "test175AddDisabledAccount"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); @@ -1397,7 +1397,7 @@ public void test175AddDisabledAccount() throws Exception { // WHEN String addedObjectOid = provisioningService.addObject(object.asPrismObject(), null, null, taskManager.createTaskInstance(), result); - + // THEN assertEquals(ACCOUNT_NEW_DISABLED_OID, addedObjectOid); @@ -1408,30 +1408,30 @@ public void test175AddDisabledAccount() throws Exception { ShadowType provisioningAccountType = provisioningService.getObject(ShadowType.class, ACCOUNT_NEW_DISABLED_OID, null, taskManager.createTaskInstance(), result).asObjectable(); PrismAsserts.assertEqualsPolyString("Wrong ICF name (provisioning)", "uid=rapp,ou=People,dc=example,dc=com", provisioningAccountType.getName()); - - String uid = ShadowUtil.getSingleStringAttributeValue(accountType, getPrimaryIdentifierQName()); + + String uid = ShadowUtil.getSingleStringAttributeValue(accountType, getPrimaryIdentifierQName()); assertNotNull(uid); - + // Check if object was modified in LDAP - + Entry response = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP account", response); - + String disabled = openDJController.getAttributeValue(response, "ds-pwp-account-disabled"); assertNotNull("no ds-pwp-account-disabled attribute in account "+uid, disabled); System.out.println("ds-pwp-account-disabled after change: " + disabled); assertEquals("ds-pwp-account-disabled not set to \"TRUE\"", "TRUE", disabled); - + ActivationType repoActivation = accountType.getActivation(); assertNotNull("No activation in repo", repoActivation); XMLGregorianCalendar repoDisableTimestamp = repoActivation.getDisableTimestamp(); assertNotNull("No activation disableTimestamp in repo", repoDisableTimestamp); - assertEquals("Wrong activation disableTimestamp in repo", + assertEquals("Wrong activation disableTimestamp in repo", XmlTypeConverter.createXMLGregorianCalendar(1999, 8, 7, 6, 5, 4), repoDisableTimestamp); } - + /** * Adding account with EXPLICIT enable. This triggers simulated activation in a different way. */ @@ -1439,7 +1439,7 @@ public void test175AddDisabledAccount() throws Exception { public void test176AddEnabledAccount() throws Exception { final String TEST_NAME = "test176AddEnabledAccount"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); @@ -1449,7 +1449,7 @@ public void test176AddEnabledAccount() throws Exception { // WHEN String addedObjectOid = provisioningService.addObject(object.asPrismObject(), null, null, taskManager.createTaskInstance(), result); - + // THEN assertEquals(ACCOUNT_NEW_ENABLED_OID, addedObjectOid); @@ -1460,47 +1460,47 @@ public void test176AddEnabledAccount() throws Exception { ShadowType provisioningAccountType = provisioningService.getObject(ShadowType.class, ACCOUNT_NEW_ENABLED_OID, null, taskManager.createTaskInstance(), result).asObjectable(); PrismAsserts.assertEqualsPolyString("Wrong ICF name (provisioning)", "uid=cook,ou=People,dc=example,dc=com", provisioningAccountType.getName()); - - String uid = ShadowUtil.getSingleStringAttributeValue(accountType, getPrimaryIdentifierQName()); + + String uid = ShadowUtil.getSingleStringAttributeValue(accountType, getPrimaryIdentifierQName()); assertNotNull(uid); - + // Check if object was modified in LDAP - + Entry response = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP account", response); - + String disabled = openDJController.getAttributeValue(response, "ds-pwp-account-disabled"); assertEquals("ds-pwp-account-disabled not set to \"FALSE\"", "FALSE", disabled); } - + @Test public void test180GetUnlockedAccount() throws Exception { final String TEST_NAME = "test180GetUnlockedAccount"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); // WHEN PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + // THEN result.computeStatus(); assertSuccess(result); - - PrismAsserts.assertPropertyValue(shadow, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, + + PrismAsserts.assertPropertyValue(shadow, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, LockoutStatusType.NORMAL); } - + @Test public void test182GetLockedAccount() throws Exception { final String TEST_NAME = "test182GetLockedAccount"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + openDJController.executeLdifChange( "dn: uid=will123,ou=People,dc=example,dc=com\n" + "changetype: modify\n" + @@ -1511,20 +1511,20 @@ public void test182GetLockedAccount() throws Exception { // WHEN PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); - + // THEN result.computeStatus(); assertSuccess(result); - - PrismAsserts.assertPropertyValue(shadow, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, + + PrismAsserts.assertPropertyValue(shadow, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, LockoutStatusType.LOCKED); } - + @Test public void test184UnlockAccount() throws Exception{ final String TEST_NAME = "test184UnlockAccount"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); @@ -1534,32 +1534,32 @@ public void test184UnlockAccount() throws Exception{ // WHEN provisioningService.modifyObject(ShadowType.class, delta.getOid(), delta.getModifications(), null, null, task, result); - + // THEN result.computeStatus(); assertSuccess(result); - + PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, taskManager.createTaskInstance(), result); - + display("Object after change",shadow); - - String uid = ShadowUtil.getSingleStringAttributeValue(shadow.asObjectable(), getPrimaryIdentifierQName()); + + String uid = ShadowUtil.getSingleStringAttributeValue(shadow.asObjectable(), getPrimaryIdentifierQName()); assertNotNull(uid); - + // Check if object was modified in LDAP - + Entry response = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP account", response); - + String pager = openDJController.getAttributeValue(response, "pager"); assertNull("Pager attribute found in account "+uid+": "+pager, pager); - - PrismAsserts.assertPropertyValue(shadow, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, + + PrismAsserts.assertPropertyValue(shadow, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, LockoutStatusType.NORMAL); } - - + + @Test public void test200SearchObjectsIterative() throws Exception { final String TEST_NAME = "test200SearchObjectsIterative"; @@ -1567,7 +1567,7 @@ public void test200SearchObjectsIterative() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ShadowType object = parseObjectType(ACCOUNT_SEARCH_ITERATIVE_FILE, ShadowType.class); System.out.println(SchemaDebugUtil.prettyPrint(object)); @@ -1580,7 +1580,7 @@ public void test200SearchObjectsIterative() throws Exception { QueryType queryType = PrismTestUtil.parseAtomicValue(QUERY_ALL_ACCOUNTS_FILE, QueryType.COMPLEX_TYPE); ObjectQuery query = QueryJaxbConvertor.createObjectQuery(ShadowType.class, queryType, prismContext); - + provisioningService.searchObjectsIterative(ShadowType.class, query, null, new ResultHandler() { @Override @@ -1611,7 +1611,7 @@ public void test201SearchObjects() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - ShadowType object = parseObjectType(ACCOUNT_SEARCH_FILE, ShadowType.class); + ShadowType object = parseObjectType(ACCOUNT_SEARCH_FILE, ShadowType.class); display("New object", object); String addedObjectOid = provisioningService.addObject(object.asPrismObject(), null, null, taskManager.createTaskInstance(), result); @@ -1619,20 +1619,20 @@ public void test201SearchObjects() throws Exception { QueryType queryType = PrismTestUtil.parseAtomicValue(QUERY_ALL_ACCOUNTS_FILE, QueryType.COMPLEX_TYPE); ObjectQuery query = QueryJaxbConvertor.createObjectQuery(ShadowType.class, queryType, prismContext); - + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); // WHEN SearchResultList> searchResults = provisioningService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN result.computeStatus(); assertSuccess(result); display("Search resutls", searchResults); - + assertEquals("Unexpected number of search results", 14, searchResults.size()); - + assertConnectorOperationIncrement(1, 29); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); } @@ -1652,28 +1652,28 @@ public void test202SearchObjectsCompexFilter() throws Exception { rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); - List> objListType = + List> objListType = provisioningService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + for (PrismObject objType : objListType) { assertNotNull("Null search result", objType); display("found object", objType); } - + assertEquals("Unexpected number of objects found", 1, objListType.size()); - + assertConnectorOperationIncrement(1, 3); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); } - + @Test public void test203SearchObjectsByDnExists() throws Exception { final String TEST_NAME = "test203SearchObjectsByDnExists"; @@ -1686,31 +1686,31 @@ public void test203SearchObjectsByDnExists() throws Exception { rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); - List> objListType = + List> objListType = provisioningService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + for (PrismObject objType : objListType) { assertNotNull("Null search result", objType); display("found object", objType); } - + assertEquals("Unexpected number of objects found", 1, objListType.size()); - + PrismObject shadow = objListType.get(0); assertAttribute(shadow, "dn", ACCOUNT_BARBOSSA_DN); - + assertConnectorOperationIncrement(1, 3); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); } - + /** * Search for non-existent DN should return no results. It should NOT * throw an error. @@ -1729,24 +1729,24 @@ public void test205SearchObjectsByDnNotExists() throws Exception { rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); - List> objListType = + List> objListType = provisioningService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + for (PrismObject objType : objListType) { assertNotNull("Null search result", objType); display("found object", objType); } - + assertEquals("Unexpected number of objects found", 0, objListType.size()); - + assertConnectorOperationIncrement(1, 1); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); } @@ -1761,30 +1761,30 @@ public void test230SearchObjectsPagedNoOffset() throws Exception { QueryType queryType = PrismTestUtil.parseAtomicValue(QUERY_ALL_ACCOUNTS_FILE, QueryType.COMPLEX_TYPE); ObjectQuery query = QueryJaxbConvertor.createObjectQuery(ShadowType.class, queryType, prismContext); - + ObjectPaging paging = ObjectPaging.createPaging(null, 3); query.setPaging(paging); - + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); // WHEN TestUtil.displayWhen(TEST_NAME); - List> searchResults = + List> searchResults = provisioningService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); assertSuccess(result); display("Search resutls", searchResults); - + assertSearchResults(searchResults, "cook", "drake", "hbarbossa" ); - + assertConnectorOperationIncrement(1, 7); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); } - + @Test public void test231SearchObjectsPagedOffsetZero() throws Exception { final String TEST_NAME = "test231SearchObjectsPagedOffsetZero"; @@ -1795,30 +1795,30 @@ public void test231SearchObjectsPagedOffsetZero() throws Exception { QueryType queryType = PrismTestUtil.parseAtomicValue(QUERY_ALL_ACCOUNTS_FILE, QueryType.COMPLEX_TYPE); ObjectQuery query = QueryJaxbConvertor.createObjectQuery(ShadowType.class, queryType, prismContext); - + ObjectPaging paging = ObjectPaging.createPaging(0, 4); query.setPaging(paging); - + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); // WHEN TestUtil.displayWhen(TEST_NAME); - List> searchResults = + List> searchResults = provisioningService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); assertSuccess(result); display("Search resutls", searchResults); - + assertSearchResults(searchResults, "cook", "drake", "hbarbossa", "idm"); - + assertConnectorOperationIncrement(1, 9); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); } - + @Test public void test232SearchObjectsPagedOffset() throws Exception { final String TEST_NAME = "test232SearchObjectsPagedOffset"; @@ -1829,30 +1829,30 @@ public void test232SearchObjectsPagedOffset() throws Exception { QueryType queryType = PrismTestUtil.parseAtomicValue(QUERY_ALL_ACCOUNTS_FILE, QueryType.COMPLEX_TYPE); ObjectQuery query = QueryJaxbConvertor.createObjectQuery(ShadowType.class, queryType, prismContext); - + ObjectPaging paging = ObjectPaging.createPaging(2, 5); query.setPaging(paging); - + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); // WHEN TestUtil.displayWhen(TEST_NAME); SearchResultList> searchResults = provisioningService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); assertSuccess(result); display("Search resutls", searchResults); - + // The results should be this: assertSearchResults(searchResults, "hbarbossa", "idm", "jbeckett", "jbond", "jgibbs" ); - + assertConnectorOperationIncrement(1, 11); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); } - + @Test public void test233SearchObjectsPagedNoOffsetSortSn() throws Exception { final String TEST_NAME = "test233SearchObjectsPagedNoOffsetSortSn"; @@ -1863,32 +1863,32 @@ public void test233SearchObjectsPagedNoOffsetSortSn() throws Exception { QueryType queryType = PrismTestUtil.parseAtomicValue(QUERY_ALL_ACCOUNTS_FILE, QueryType.COMPLEX_TYPE); ObjectQuery query = QueryJaxbConvertor.createObjectQuery(ShadowType.class, queryType, prismContext); - + ObjectPaging paging = ObjectPaging.createPaging(null, 4); paging.setOrdering(ObjectOrdering.createOrdering( new ItemPath(ShadowType.F_ATTRIBUTES, new QName(RESOURCE_NS, "sn")), OrderDirection.ASCENDING)); query.setPaging(paging); - + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); // WHEN TestUtil.displayWhen(TEST_NAME); - List> searchResults = + List> searchResults = provisioningService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); assertSuccess(result); display("Search resutls", searchResults); - + assertSearchResults(searchResults, "monk", "hbarbossa", "jbeckett", "jbond" ); - + assertConnectorOperationIncrement(1, 9); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); } - + @Test public void test234SearchObjectsPagedOffsetSortSn() throws Exception { final String TEST_NAME = "test234SearchObjectsPagedOffsetSortSn"; @@ -1899,32 +1899,32 @@ public void test234SearchObjectsPagedOffsetSortSn() throws Exception { QueryType queryType = PrismTestUtil.parseAtomicValue(QUERY_ALL_ACCOUNTS_FILE, QueryType.COMPLEX_TYPE); ObjectQuery query = QueryJaxbConvertor.createObjectQuery(ShadowType.class, queryType, prismContext); - + ObjectPaging paging = ObjectPaging.createPaging(2, 4); paging.setOrdering(ObjectOrdering.createOrdering( new ItemPath(ShadowType.F_ATTRIBUTES, new QName(RESOURCE_NS, "sn")), OrderDirection.ASCENDING)); query.setPaging(paging); - + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); // WHEN TestUtil.displayWhen(TEST_NAME); - List> searchResults = + List> searchResults = provisioningService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); assertSuccess(result); display("Search resutls", searchResults); - + assertSearchResults(searchResults, "jbeckett", "jbond", "cook", "drake" ); - + assertConnectorOperationIncrement(1, 9); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); } - + private void assertSearchResults(List> searchResults, String... expectedUids) { assertEquals("Unexpected number of search results", expectedUids.length, searchResults.size()); int i = 0; @@ -1937,7 +1937,7 @@ private void assertSearchResults(List> searchResults, St i++; } } - + @Test public void test250CountObjects() throws Exception { final String TEST_NAME = "test250CountObjects"; @@ -1951,14 +1951,14 @@ public void test250CountObjects() throws Exception { // WHEN Integer count = provisioningService.countObjects(ShadowType.class, query, null, task, result); - + // THEN result.computeStatus(); assertSuccess(result); - + assertEquals("Unexpected number of search results", (Integer)14, count); } - + /** * The exception comes from the resource. There is no shadow for this object. */ @@ -1966,68 +1966,68 @@ public void test250CountObjects() throws Exception { public void test300AddObjectObjectAlreadyExistResource() throws Exception { final String TEST_NAME = "test300AddObjectObjectAlreadyExistResource"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject account = PrismTestUtil.parseObject(ACCOUNT_SEARCH_FILE); display("Account to add", account); - + try { // WHEN provisioningService.addObject(account, null, null, task, result); - + AssertJUnit.fail("Expected addObject operation to fail but it was successful"); - + } catch (ObjectAlreadyExistsException e) { // This is expected display("Expected exception", e); - + // The exception should originate from the LDAP layers IntegrationTestTools.assertInMessageRecursive(e, "LDAP"); } - + // TODO: search to check that the shadow with the same NAME exists (search for OID will not do) } - + @Test public void test310AddObjectNoSn() throws Exception { final String TEST_NAME = "test310AddObjectNoSn"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); PrismObject account = PrismTestUtil.parseObject(ACCOUNT_NO_SN_FILE); display("Account to add", account); - + try { // WHEN provisioningService.addObject(account, null, null, task, result); - + AssertJUnit.fail("Expected addObject operation to fail but it was successful"); - + } catch (SchemaException e) { // This is expected display("Expected exception", e); - + // This error should be detectable before it reaches a resource. Therefore we check that the // cause was not a LDAP exception - + // MID-1007 // IntegrationTestTools.assertNotInMessageRecursive(e, "LDAP"); } - + // TODO: search to check that the shadow with the same NAME exists (search for OID will not do) } - + @Test public void test320AddAccountPosix() throws Exception { final String TEST_NAME = "test320AddAccountPosix"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); @@ -2037,7 +2037,7 @@ public void test320AddAccountPosix() throws Exception { // WHEN TestUtil.displayWhen(TEST_NAME); String addedObjectOid = provisioningService.addObject(object.asPrismObject(), null, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertEquals(ACCOUNT_POSIX_MCMUTTON_OID, addedObjectOid); @@ -2058,46 +2058,46 @@ public void test320AddAccountPosix() throws Exception { assertAttribute(provisioningShadowType, "sn", "McMutton"); assertAttribute(provisioningShadowType, "homeDirectory", "/home/scotland"); assertAttribute(provisioningShadowType, "uidNumber", 1001); - + String uid = ShadowUtil.getSingleStringAttributeValue(repoShadowType, getPrimaryIdentifierQName()); assertNotNull(uid); - + // Check if object was modified in LDAP - - Entry entry = openDJController.searchAndAssertByEntryUuid(uid); + + Entry entry = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "cn", "Haggis McMutton"); OpenDJController.assertAttribute(entry, "sn", "McMutton"); OpenDJController.assertAttribute(entry, "uidNumber", "1001"); OpenDJController.assertAttribute(entry, "loginShell", "/bin/whisky"); OpenDJController.assertAttribute(entry, "homeDirectory", "/home/scotland"); - + assertShadows(17); } - + @Test public void test322ModifyAccountPosix() throws Exception { final String TEST_NAME = "test322ModifyAccountPosix"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); ObjectModificationType objectChange = PrismTestUtil.parseAtomicValue(ACCOUNT_POSIX_MCMUTTON_CHANGE_FILE, ObjectModificationType.COMPLEX_TYPE); ObjectDelta delta = DeltaConvertor.createObjectDelta(objectChange, getShadowDefinition()); - + display("Object change",delta); - + // WHEN TestUtil.displayWhen(TEST_NAME); provisioningService.modifyObject(ShadowType.class, objectChange.getOid(), delta.getModifications(), null, null, taskManager.createTaskInstance(), result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_POSIX_MCMUTTON_OID, null, task, result).asObjectable(); display("Object after change",accountType); @@ -2108,24 +2108,24 @@ public void test322ModifyAccountPosix() throws Exception { assertAttribute(accountType, "homeDirectory", "/home/caribbean"); assertAttribute(accountType, "roomNumber", "Barber Shop"); assertAttribute(accountType, "uidNumber", 1001); - + // Check if object was modified in LDAP - - Entry entry = openDJController.searchAndAssertByEntryUuid(uid); + + Entry entry = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "cn", "Haggis McMutton"); OpenDJController.assertAttribute(entry, "homeDirectory", "/home/caribbean"); OpenDJController.assertAttribute(entry, "roomNumber", "Barber Shop"); OpenDJController.assertAttribute(entry, "uidNumber", "1001"); - + assertShadows(17); } - + @Test public void test329DeleteAccountPosix() throws Exception { final String TEST_NAME = "test329DeleteAccountPosix"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); @@ -2151,10 +2151,10 @@ public void test329DeleteAccountPosix() throws Exception { display("Expected exception", ex); assertTrue(ex.getMessage().contains(ACCOUNT_POSIX_MCMUTTON_OID)); } - + assertShadows(16); } - + /** * Search for account created directly on resource (no shadow in repo). The account has * posixAccount auxiliary object class. Provisioning should figure that out. @@ -2171,54 +2171,54 @@ public void test330SearchForPosixAccount() throws Exception { QueryType.COMPLEX_TYPE); ObjectQuery query = QueryJaxbConvertor.createObjectQuery(ShadowType.class, queryType, prismContext); provisioningService.applyDefinition(ShadowType.class, query, task, result); - + Entry entry = openDJController.addEntryFromLdifFile(ACCOUNT_POSIX_VANHELGEN_LDIF_FILE); rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - + // WHEN - List> objListType = + List> objListType = provisioningService.searchObjects(ShadowType.class, query, null, null, result); - + // THEN for (PrismObject objType : objListType) { assertNotNull("Null search result", objType); display("found object", objType); } - + assertEquals("Unexpected number of objects found", 1, objListType.size()); - + PrismObject provisioningShadow = objListType.get(0); assertAttribute(provisioningShadow, "cn", "Edward Van Helgen"); assertAttribute(provisioningShadow, "homeDirectory", "/home/vanhelgen"); assertAttribute(provisioningShadow, "uidNumber", 1002); - + assertConnectorOperationIncrement(1, 3); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + assertShadows(17); } - + // TODO: synchronization of auxiliary object classes - - - + + + @Test public void test400AddGroupSwashbucklers() throws Exception { final String TEST_NAME = "test400AddGroupSwashbucklers"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ShadowType object = parseObjectType(GROUP_SWASHBUCKLERS_FILE, ShadowType.class); IntegrationTestTools.display("Adding object", object); // WHEN TestUtil.displayWhen(TEST_NAME); String addedObjectOid = provisioningService.addObject(object.asPrismObject(), null, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertEquals(GROUP_SWASHBUCKLERS_OID, addedObjectOid); @@ -2230,28 +2230,28 @@ public void test400AddGroupSwashbucklers() throws Exception { PrismObject provisioningShadow = provisioningService.getObject(ShadowType.class, GROUP_SWASHBUCKLERS_OID, null, taskManager.createTaskInstance(), result); ShadowType provisioningShadowType = provisioningShadow.asObjectable(); - assertEquals("Wrong ICF name (provisioning)", dnMatchingRule.normalize(GROUP_SWASHBUCKLERS_DN), + assertEquals("Wrong ICF name (provisioning)", dnMatchingRule.normalize(GROUP_SWASHBUCKLERS_DN), dnMatchingRule.normalize(provisioningShadowType.getName().getOrig())); - - String uid = ShadowUtil.getSingleStringAttributeValue(shadowType, getPrimaryIdentifierQName()); + + String uid = ShadowUtil.getSingleStringAttributeValue(shadowType, getPrimaryIdentifierQName()); assertNotNull(uid); ResourceAttribute memberAttr = ShadowUtil.getAttribute(provisioningShadow, new QName(RESOURCE_OPENDJ_NS, GROUP_MEMBER_ATTR_NAME)); assertNull("Member attribute sneaked in", memberAttr); - + Entry ldapEntry = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP group", ldapEntry); assertNotNull("No LDAP group entry"); String groupDn = ldapEntry.getDN().toString(); assertEquals("Wrong group DN", dnMatchingRule.normalize(GROUP_SWASHBUCKLERS_DN), dnMatchingRule.normalize(groupDn)); - + assertShadows(18); } - + @Test public void test402AddAccountMorganWithAssociation() throws Exception { final String TEST_NAME = "test402AddAccountMorganWithAssociation"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); @@ -2260,7 +2260,7 @@ public void test402AddAccountMorganWithAssociation() throws Exception { // WHEN String addedObjectOid = provisioningService.addObject(object.asPrismObject(), null, null, task, result); - + // THEN assertEquals(ACCOUNT_MORGAN_OID, addedObjectOid); @@ -2272,59 +2272,59 @@ public void test402AddAccountMorganWithAssociation() throws Exception { null, taskManager.createTaskInstance(), result).asObjectable(); PrismAsserts.assertEqualsPolyString("Wrong ICF name (provisioning)", ACCOUNT_MORGAN_DN, provisioningShadowType.getName()); - - String uid = ShadowUtil.getSingleStringAttributeValue(shadowType, getPrimaryIdentifierQName()); + + String uid = ShadowUtil.getSingleStringAttributeValue(shadowType, getPrimaryIdentifierQName()); assertNotNull(uid); - + List associations = provisioningShadowType.getAssociation(); assertEquals("Unexpected number of associations", 1, associations.size()); ShadowAssociationType association = associations.get(0); assertEquals("Wrong group OID in association", GROUP_SWASHBUCKLERS_OID, association.getShadowRef().getOid()); - + Entry accountEntry = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP account", accountEntry); assertNotNull("No LDAP account entry"); String accountDn = accountEntry.getDN().toString(); assertEquals("Wrong account DN", ACCOUNT_MORGAN_DN, accountDn); - + Entry groupEntry = openDJController.fetchEntry(GROUP_SWASHBUCKLERS_DN); display("LDAP group", groupEntry); assertNotNull("No LDAP group entry"); openDJController.assertUniqueMember(groupEntry, accountDn); - + assertShadows(19); } - + @Test public void test405GetGroupSwashbucklers() throws Exception { final String TEST_NAME = "test405GetGroupSwashbucklers"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject provisioningShadow = provisioningService.getObject(ShadowType.class, GROUP_SWASHBUCKLERS_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); ShadowType provisioningShadowType = provisioningShadow.asObjectable(); assertEquals("Wrong ICF name (provisioning)", dnMatchingRule.normalize(GROUP_SWASHBUCKLERS_DN), dnMatchingRule.normalize(provisioningShadowType.getName().getOrig())); - - String uid = ShadowUtil.getSingleStringAttributeValue(provisioningShadowType, getPrimaryIdentifierQName()); + + String uid = ShadowUtil.getSingleStringAttributeValue(provisioningShadowType, getPrimaryIdentifierQName()); assertNotNull(uid); ResourceAttribute memberAttr = ShadowUtil.getAttribute(provisioningShadow, new QName(RESOURCE_OPENDJ_NS, GROUP_MEMBER_ATTR_NAME)); assertNull("Member attribute sneaked in", memberAttr); - + Entry ldapEntry = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP group", ldapEntry); assertNotNull("No LDAP group entry"); String groupDn = ldapEntry.getDN().toString(); assertEquals("Wrong group DN", dnMatchingRule.normalize(GROUP_SWASHBUCKLERS_DN), dnMatchingRule.normalize(groupDn)); - + assertShadows(19); } @@ -2332,90 +2332,90 @@ public void test405GetGroupSwashbucklers() throws Exception { public void test410CreateLdapGroupAndSearchGroups() throws Exception { final String TEST_NAME = "test410CreateLdapGroupAndSearchGroups"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + openDJController.addEntry("dn: cn=seadogs,ou=groups,dc=EXAMPLE,dc=com\n" + "objectClass: groupOfUniqueNames\n" + "objectClass: top\n" + "cn: seadogs"); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_OPENDJ_OID, + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_OPENDJ_OID, RESOURCE_OPENDJ_GROUP_OBJECTCLASS, prismContext); - + // WHEN TestUtil.displayWhen(TEST_NAME); SearchResultList> resultList = provisioningService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); assertSuccess(result); display("Search result", resultList); - + IntegrationTestTools.assertSearchResultNames(resultList, dnMatchingRule, - "cn=Pirates,ou=groups,dc=example,dc=com", + "cn=Pirates,ou=groups,dc=example,dc=com", "cn=swashbucklers,ou=Groups,dc=example,dc=com", "cn=seadogs,ou=Groups,dc=example,dc=com"); - + assertShadows(20); } - + @Test public void test412CreateLdapGroupWithMemberAndGet() throws Exception { final String TEST_NAME = "test412CreateLdapGroupWithMemberAndGet"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + openDJController.addEntry("dn: cn=sailor,ou=Groups,dc=example,dc=com\n" + "objectClass: groupOfUniqueNames\n" + "objectClass: top\n" + "cn: sailor\n" + "uniqueMember: uid=MOrgan,ou=PEOPLE,dc=example,dc=com"); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_OPENDJ_OID, + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_OPENDJ_OID, RESOURCE_OPENDJ_GROUP_OBJECTCLASS, prismContext); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_MORGAN_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); assertSuccess(result); display("Account shadow after", shadow); - + assertShadows(21); - + PrismObject groupSailorShadow = findShadowByName(RESOURCE_OPENDJ_GROUP_OBJECTCLASS, "cn=sailor,ou=groups,dc=example,dc=com", resource, result); display("Group shadow", groupSailorShadow); groupSailorOid = groupSailorShadow.getOid(); - + assertEntitlementGroup(shadow, groupSailorOid); - + assertShadows(21); } - + @Test public void test414AddGroupCorsairsAssociateUser() throws Exception { final String TEST_NAME = "test414AddGroupCorsairsAssociateUser"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ShadowType object = parseObjectType(GROUP_CORSAIRS_FILE, ShadowType.class); IntegrationTestTools.display("Adding object", object); // WHEN TestUtil.displayWhen(TEST_NAME); String addedObjectOid = provisioningService.addObject(object.asPrismObject(), null, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertEquals(GROUP_CORSAIRS_OID, addedObjectOid); @@ -2425,7 +2425,7 @@ public void test414AddGroupCorsairsAssociateUser() throws Exception { PrismAsserts.assertEqualsPolyString("Wrong ICF name (repo)", GROUP_CORSAIRS_DN, shadowType.getName()); // Do NOT read provisioning shadow here. We want everything to be "fresh" - + assertShadows(22); } @@ -2436,28 +2436,28 @@ public void test416AssociateUserToCorsairs() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - - ObjectDelta delta = IntegrationTestTools.createEntitleDelta(ACCOUNT_MORGAN_OID, + + ObjectDelta delta = IntegrationTestTools.createEntitleDelta(ACCOUNT_MORGAN_OID, ASSOCIATION_GROUP_NAME, GROUP_CORSAIRS_OID, prismContext); display("ObjectDelta", delta); delta.checkConsistence(); - + // WHEN TestUtil.displayWhen(TEST_NAME); provisioningService.modifyObject(ShadowType.class, delta.getOid(), delta.getModifications(), new OperationProvisioningScriptsType(), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); - + Entry groupEntry = openDJController.fetchEntry(GROUP_CORSAIRS_DN); display("LDAP group", groupEntry); assertNotNull("No LDAP group entry"); openDJController.assertUniqueMember(groupEntry, ACCOUNT_MORGAN_DN); - + assertShadows(22); } - + @Test public void test418GetMorgan() throws Exception { final String TEST_NAME = "test418GetMorgan"; @@ -2465,24 +2465,24 @@ public void test418GetMorgan() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject shadow = provisioningService.getObject(ShadowType.class, ACCOUNT_MORGAN_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); assertSuccess(result); display("Shadow", shadow); - + assertEntitlementGroup(shadow, GROUP_SWASHBUCKLERS_OID); assertEntitlementGroup(shadow, groupSailorOid); assertEntitlementGroup(shadow, GROUP_CORSAIRS_OID); - + assertShadows(22); } - + /** * Morgan has a group associations. If the account is gone the group memberships should also be gone. */ @@ -2490,10 +2490,10 @@ public void test418GetMorgan() throws Exception { public void test429DeleteAccountMorgan() throws Exception { final String TEST_NAME = "test429DeleteAccountMorgan"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN provisioningService.deleteObject(ShadowType.class, ACCOUNT_MORGAN_OID, null, null, task, result); @@ -2518,31 +2518,31 @@ public void test429DeleteAccountMorgan() throws Exception { assertEquals(ex.getClass(), ObjectNotFoundException.class); assertTrue(ex.getMessage().contains(ACCOUNT_MORGAN_OID)); } - + Entry groupEntry = openDJController.fetchEntry(GROUP_SWASHBUCKLERS_DN); display("LDAP group", groupEntry); assertNotNull("No LDAP group entry"); openDJController.assertNoUniqueMember(groupEntry, ACCOUNT_MORGAN_DN); - + assertShadows(21); } - + @Test public void test450ListGroupsObjectclass() throws Exception { final String TEST_NAME = "test450ListGroupsObjectclass"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_OPENDJ_OID, + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_OPENDJ_OID, RESOURCE_OPENDJ_GROUP_OBJECTCLASS, prismContext); display("query", query); - + // WHEN TestUtil.displayWhen(TEST_NAME); SearchResultList> objects = provisioningService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); display("found objects", objects); @@ -2550,26 +2550,26 @@ public void test450ListGroupsObjectclass() throws Exception { TestUtil.assertSuccess(result); assertEquals("Wrong number of objects found", 5, objects.size()); - + assertShadows(21); } - + @Test public void test452ListLdapGroupsKindIntent() throws Exception { final String TEST_NAME = "test452ListLdapGroupsKindIntent"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndKindIntent(RESOURCE_OPENDJ_OID, ShadowKindType.ENTITLEMENT, "ldapGroup", prismContext); display("query", query); - + // WHEN TestUtil.displayWhen(TEST_NAME); SearchResultList> objects = provisioningService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); display("found objects", objects); @@ -2577,7 +2577,7 @@ public void test452ListLdapGroupsKindIntent() throws Exception { TestUtil.assertSuccess(result); assertEquals("Wrong number of objects found", 5, objects.size()); - + assertShadows(21); } @@ -2585,18 +2585,18 @@ public void test452ListLdapGroupsKindIntent() throws Exception { public void test454ListSpecialGroupsKindIntent() throws Exception { final String TEST_NAME = "test454ListSpecialGroupsKindIntent"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndKindIntent(RESOURCE_OPENDJ_OID, ShadowKindType.ENTITLEMENT, "specialGroup", prismContext); display("query", query); - + // WHEN TestUtil.displayWhen(TEST_NAME); SearchResultList> objects = provisioningService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); display("found objects", objects); @@ -2605,26 +2605,26 @@ public void test454ListSpecialGroupsKindIntent() throws Exception { // Check that none of the normal LDAP groups appear here ... even if they have the same objectclass assertEquals("Wrong number of objects found", 0, objects.size()); - + // Discovered base context for specialgroups assertShadows(22); } - + @Test public void test456AddGroupSpecialists() throws Exception { final String TEST_NAME = "test456AddGroupSpecialists"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ShadowType object = parseObjectType(GROUP_SPECIALISTS_FILE, ShadowType.class); IntegrationTestTools.display("Adding object", object); // WHEN TestUtil.displayWhen(TEST_NAME); String addedObjectOid = provisioningService.addObject(object.asPrismObject(), null, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); assertEquals(GROUP_SPECIALISTS_OID, addedObjectOid); @@ -2636,39 +2636,39 @@ public void test456AddGroupSpecialists() throws Exception { PrismObject provisioningShadow = provisioningService.getObject(ShadowType.class, GROUP_SPECIALISTS_OID, null, taskManager.createTaskInstance(), result); ShadowType provisioningShadowType = provisioningShadow.asObjectable(); - assertEquals("Wrong ICF name (provisioning)", dnMatchingRule.normalize(GROUP_SPECIALISTS_DN), + assertEquals("Wrong ICF name (provisioning)", dnMatchingRule.normalize(GROUP_SPECIALISTS_DN), dnMatchingRule.normalize(provisioningShadowType.getName().getOrig())); - - String uid = ShadowUtil.getSingleStringAttributeValue(shadowType, getPrimaryIdentifierQName()); + + String uid = ShadowUtil.getSingleStringAttributeValue(shadowType, getPrimaryIdentifierQName()); assertNotNull(uid); ResourceAttribute memberAttr = ShadowUtil.getAttribute(provisioningShadow, new QName(RESOURCE_OPENDJ_NS, GROUP_MEMBER_ATTR_NAME)); assertNull("Member attribute sneaked in", memberAttr); - + Entry ldapEntry = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP group", ldapEntry); assertNotNull("No LDAP group entry"); String groupDn = ldapEntry.getDN().toString(); assertEquals("Wrong group DN", dnMatchingRule.normalize(GROUP_SPECIALISTS_DN), dnMatchingRule.normalize(groupDn)); - + assertShadows(23); } - + @Test public void test457ListLdapGroupsKindIntent() throws Exception { final String TEST_NAME = "test457ListLdapGroupsKindIntent"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndKindIntent(RESOURCE_OPENDJ_OID, ShadowKindType.ENTITLEMENT, "ldapGroup", prismContext); display("query", query); - + // WHEN TestUtil.displayWhen(TEST_NAME); SearchResultList> objects = provisioningService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); display("found objects", objects); @@ -2676,7 +2676,7 @@ public void test457ListLdapGroupsKindIntent() throws Exception { TestUtil.assertSuccess(result); assertEquals("Wrong number of objects found", 5, objects.size()); - + assertShadows(23); } @@ -2684,18 +2684,18 @@ public void test457ListLdapGroupsKindIntent() throws Exception { public void test458ListSpecialGroupsKindIntent() throws Exception { final String TEST_NAME = "test458ListSpecialGroupsKindIntent"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndKindIntent(RESOURCE_OPENDJ_OID, ShadowKindType.ENTITLEMENT, "specialGroup", prismContext); display("query", query); - + // WHEN TestUtil.displayWhen(TEST_NAME); SearchResultList> objects = provisioningService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); display("found objects", objects); @@ -2704,11 +2704,11 @@ public void test458ListSpecialGroupsKindIntent() throws Exception { // Check that none of the normal LDAP groups appear here ... even if they have the same objectclass assertEquals("Wrong number of objects found", 1, objects.size()); - + // Discovered base context for specialgroups assertShadows(23); } - + /** * List organizationUnits with intent ou-people. There are no sub-ous in People. * But the definition has objectclass organizationalUnit and it has baseContext that @@ -2719,18 +2719,18 @@ public void test458ListSpecialGroupsKindIntent() throws Exception { public void test460ListOrganizationalUnitPeopleKindIntent() throws Exception { final String TEST_NAME = "test460ListOrganizationalUnitPeopleKindIntent"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndKindIntent(RESOURCE_OPENDJ_OID, ShadowKindType.GENERIC, "ou-people", prismContext); display("query", query); - + // WHEN TestUtil.displayWhen(TEST_NAME); SearchResultList> objects = provisioningService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); display("found objects", objects); @@ -2739,38 +2739,38 @@ public void test460ListOrganizationalUnitPeopleKindIntent() throws Exception { // Just the ou=People itself assertEquals("Wrong number of objects found", 1, objects.size()); - + assertShadows(24); } - + @Test public void test701ConfiguredCapabilityNoRead() throws Exception{ final String TEST_NAME = "test701ConfiguredCapabilityNoRead"; - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + addResourceFromFile(new File(TEST_DIR, "resource-opendj-no-read.xml"), IntegrationTestTools.CONNECTOR_LDAP_TYPE, true, result); - + try { provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, result); AssertJUnit .fail("Expected unsupported operation exception, but haven't got one."); } catch (SystemException ex) { - // this is expected.. + // this is expected.. } } @Test public void test702ConfiguredCapabilityNoCreate() throws Exception{ final String TEST_NAME = "test702ConfiguredCapabilityNoCreate"; - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + addResourceFromFile(new File(TEST_DIR, "/resource-opendj-no-create.xml"), IntegrationTestTools.CONNECTOR_LDAP_TYPE, true, result); - + try { PrismObject shadow = parseObjectType(ACCOUNT_WILL_FILE, ShadowType.class).asPrismObject(); provisioningService.addObject(shadow, null, null, task, result); @@ -2778,37 +2778,37 @@ public void test702ConfiguredCapabilityNoCreate() throws Exception{ .fail("Expected unsupported operation exception, but haven't got one."); } catch (SystemException ex) { LOGGER.info("exception: {}", ex.getMessage(), ex); - // this is expected.. + // this is expected.. } } - + @Test public void test703ConfiguredCapabilityNoDelete() throws Exception{ final String TEST_NAME = "test703ConfiguredCapabilityNoDelete"; - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + addResourceFromFile(new File(TEST_DIR, "/resource-opendj-no-delete.xml"), IntegrationTestTools.CONNECTOR_LDAP_TYPE, true, result); - + try { provisioningService.deleteObject(ShadowType.class, ACCOUNT_WILL_OID, null, null, task, result); AssertJUnit .fail("Expected unsupported operation exception, but haven't got one."); } catch (SystemException ex) { - // this is expected.. + // this is expected.. } } - + @Test public void test704ConfiguredCapabilityNoUpdate() throws Exception{ final String TEST_NAME = "test704ConfiguredCapabilityNoUpdate"; - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - - addResourceFromFile(new File(TEST_DIR, "/resource-opendj-no-update.xml"), IntegrationTestTools.CONNECTOR_LDAP_TYPE, true, result); - + + addResourceFromFile(new File(TEST_DIR, "/resource-opendj-no-update.xml"), IntegrationTestTools.CONNECTOR_LDAP_TYPE, true, result); + try { PropertyDelta delta = PropertyDelta.createModificationReplaceProperty(new ItemPath(ShadowType.F_ATTRIBUTES, new QName(resourceType.getNamespace(), "sn")), prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(ShadowType.class), "doesnotmatter"); Collection modifications = MiscUtil.createCollection(delta); @@ -2816,10 +2816,10 @@ public void test704ConfiguredCapabilityNoUpdate() throws Exception{ AssertJUnit .fail("Expected unsupported operation exception, but haven't got one."); } catch (SystemException ex) { - // this is expected.. + // this is expected.. } } - + @Test public void test710AddResourceOpenDjBadCredentials() throws Exception { final String TEST_NAME = "test710AddResourceOpenDjBadCredentials"; @@ -2833,29 +2833,29 @@ public void test710AddResourceOpenDjBadCredentials() throws Exception { // WHEN String addedObjectOid = provisioningService.addObject(resource, null, null, task, result); - + // THEN result.computeStatus(); display(result); assertSuccess(result); - + assertEquals("Wrong oid", RESOURCE_OPENDJ_BAD_CREDENTIALS_OID, addedObjectOid); } - + @Test public void test713ConnectionBadCredentials() throws Exception { final String TEST_NAME = "test713ConnectionBadCredentials"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); // WHEN OperationResult testResult = provisioningService.testResource(RESOURCE_OPENDJ_BAD_CREDENTIALS_OID, task); - + display("Test connection result (expected failure)",testResult); TestUtil.assertFailure(testResult); - + OperationResult connectorResult = assertSingleConnectorTestResult(testResult); OperationResult connectResult = connectorResult.findSubresult(ConnectorTestOperation.CONNECTOR_CONFIGURATION.getOperation()); assertNotNull("No connector connect result", connectResult); @@ -2863,7 +2863,7 @@ public void test713ConnectionBadCredentials() throws Exception { // assertTrue("Unexpected connector initialization message: "+connectResult.getMessage(), connectResult.getMessage().contains("invalidCredentials")); // assertTrue("Unexpected connector initialization message: "+connectResult.getMessage(), connectResult.getMessage().contains("49")); } - + @Test public void test720AddResourceOpenDjBadBindDn() throws Exception { final String TEST_NAME = "test720AddResourceOpenDjBadBindDn"; @@ -2877,44 +2877,44 @@ public void test720AddResourceOpenDjBadBindDn() throws Exception { // WHEN String addedObjectOid = provisioningService.addObject(resource, null, null, task, result); - + // THEN result.computeStatus(); display(result); assertSuccess(result); - + assertEquals("Wrong oid", RESOURCE_OPENDJ_BAD_BIND_DN_OID, addedObjectOid); } - + @Test public void test723ConnectionBadBindDn() throws Exception { final String TEST_NAME = "test723ConnectionBadBindDn"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); // WHEN OperationResult testResult = provisioningService.testResource(RESOURCE_OPENDJ_BAD_BIND_DN_OID, task); - + display("Test connection result (expected failure)",testResult); TestUtil.assertFailure(testResult); - + OperationResult connectorResult = assertSingleConnectorTestResult(testResult); OperationResult initResult = connectorResult.findSubresult(ConnectorTestOperation.CONNECTOR_CONFIGURATION.getOperation()); // MID-4103 // assertTrue("Unexpected connector initialization message: "+initResult.getMessage(), initResult.getMessage().contains("invalidCredentials")); // assertTrue("Unexpected connector initialization message: "+initResult.getMessage(), initResult.getMessage().contains("49")); } - + protected void assertEntitlementGroup(PrismObject account, String entitlementOid) { ShadowAssociationType associationType = IntegrationTestTools.assertAssociation(account, ASSOCIATION_GROUP_NAME, entitlementOid); PrismContainerValue identifiersCVal = associationType.getIdentifiers().asPrismContainerValue(); PrismProperty dnProp = identifiersCVal.findProperty(getSecondaryIdentifierQName()); assertNotNull("No DN identifier in group association in "+account+", got "+identifiersCVal, dnProp); - + } - + protected void assertConnectorOperationIncrement(int expectedIncrementSmart, int expectedIncrementDumb) { assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, expectedIncrementSmart); } 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 9a1701cb4b8..a7f2ca98100 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 @@ -29,7 +29,7 @@ * Test for provisioning service implementation using embedded OpenDj instance. * This is the same test as TestOpenDj, but the OpenDJ resource configuration is * somehow dumber: no shortcut in associations, expclicit duplicity checks, etc. - * + * * @author Radovan Semancik */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @@ -37,19 +37,19 @@ public class TestOpenDjDumber extends TestOpenDj { protected static final File RESOURCE_OPENDJ_DUMBER_FILE = new File(TEST_DIR, "resource-opendj-dumber.xml"); - + private static Trace LOGGER = TraceManager.getTrace(TestOpenDjDumber.class); - + @Override protected File getResourceOpenDjFile() { return RESOURCE_OPENDJ_DUMBER_FILE; } - + @Override protected int getNumberOfBaseContextShadows() { return 1; } - + @Override protected void assertConnectorOperationIncrement(int expectedIncrementSmart, int expectedIncrementDumb) { assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, expectedIncrementDumb); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjIncompletePassword.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjIncompletePassword.java index 5874b2ba1d1..cfbd84eb3d6 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjIncompletePassword.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjIncompletePassword.java @@ -37,10 +37,10 @@ /** * Test for provisioning service implementation using embedded OpenDj instance. - * This is the same test as TestOpenDj, but the configuration allows incomplete + * This is the same test as TestOpenDj, but the configuration allows incomplete * password reading. This means that the actual password value is not revealed, * but it is indicated that there is a password set. - * + * * @author Radovan Semancik */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @@ -48,20 +48,20 @@ public class TestOpenDjIncompletePassword extends TestOpenDj { protected static final File RESOURCE_OPENDJ_INCOMPLETE_PASSWORD_FILE = new File(TEST_DIR, "resource-opendj-incomplete-password.xml"); - + private static Trace LOGGER = TraceManager.getTrace(TestOpenDjIncompletePassword.class); - + @Override protected File getResourceOpenDjFile() { return RESOURCE_OPENDJ_INCOMPLETE_PASSWORD_FILE; } - + @Override protected void assertPasswordCapability(PasswordCapabilityType capPassword) { - assertTrue("Wrong password capability readable flag: "+capPassword.isReadable(), + assertTrue("Wrong password capability readable flag: "+capPassword.isReadable(), capPassword.isReadable() == Boolean.TRUE); } - + @Override protected void assertShadowPassword(ShadowType provisioningShadow) { CredentialsType credentials = provisioningShadow.getCredentials(); @@ -74,7 +74,7 @@ protected void assertShadowPassword(ShadowType provisioningShadow) { } ProtectedStringType passwordValue = passwordType.getValue(); assertNull("Unexpected password value in "+provisioningShadow+": "+passwordValue, passwordValue); - + PrismContainerValue passwordContainer = passwordType.asPrismContainerValue(); PrismProperty valueProp = passwordContainer.findProperty(PasswordType.F_VALUE); assertTrue("Incomplete flag is NOT set for password value in "+provisioningShadow, valueProp.isIncomplete()); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjNegative.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjNegative.java index 7b3307ab6c9..ce9864b5dc1 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjNegative.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjNegative.java @@ -83,25 +83,25 @@ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext public class TestOpenDjNegative extends AbstractOpenDjTest { - + private static Trace LOGGER = TraceManager.getTrace(TestOpenDjNegative.class); @Autowired TaskManager taskManager; - + // @Autowired // private ResourceObjectChangeListener syncServiceMock; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + repoAddShadowFromFile(ACCOUNT_JBOND_REPO_FILE, initResult); repoAddShadowFromFile(ACCOUNT_SPARROW_REPO_FILE, initResult); repoAddShadowFromFile(ACCOUNT_JACK_REPO_FILE, initResult); } - + @BeforeClass public static void stoptLdap() throws Exception { // Make sure that OpenDJ is stopped. We want to see the blood .. err ... errors @@ -111,7 +111,7 @@ public static void stoptLdap() throws Exception { LOGGER.trace("Exeception during stopping already stopped LDAP (probably harmless)", ex); } } - + @Test public void test003Connection() throws Exception { final String TEST_NAME = "test003Connection"; @@ -130,24 +130,24 @@ public void test003Connection() throws Exception { AssertJUnit.assertNull("Found schema before test connection. Bad test setup?", xmlSchemaTypeBefore); Element resourceXsdSchemaElementBefore = ResourceTypeUtil.getResourceXsdSchema(resourceTypeBefore); AssertJUnit.assertNull("Found schema element before test connection. Bad test setup?", resourceXsdSchemaElementBefore); - + // WHEN OperationResult operationResult = provisioningService.testResource(RESOURCE_OPENDJ_OID, task); - + display("Test connection result (expected failure)",operationResult); TestUtil.assertFailure(operationResult); - + PrismObject resourceRepoAfter = repositoryService.getObject(ResourceType.class,RESOURCE_OPENDJ_OID, null, result); display("Resource after testResource (repository)", resourceRepoAfter); ResourceType resourceTypeRepoAfter = resourceRepoAfter.asObjectable(); display("Resource after testResource (repository, XML)", PrismTestUtil.serializeObjectToString(resourceTypeRepoAfter.asPrismObject(), PrismContext.LANG_XML)); - + XmlSchemaType xmlSchemaTypeAfter = resourceTypeRepoAfter.getSchema(); assertNull("The schema was generated after test connection but it should not be",xmlSchemaTypeAfter); Element resourceXsdSchemaElementAfter = ResourceTypeUtil.getResourceXsdSchema(resourceTypeRepoAfter); - assertNull("Schema after test connection (and should not be)", resourceXsdSchemaElementAfter); + assertNull("Schema after test connection (and should not be)", resourceXsdSchemaElementAfter); } - + @Test public void test004ResourceAndConnectorCaching() throws Exception { TestUtil.displayTestTitle("test004ResourceAndConnectorCaching"); @@ -165,53 +165,53 @@ public void test004ResourceAndConnectorCaching() throws Exception { display("getObject(resource) result", result); TestUtil.assertFailure(result); TestUtil.assertFailure(resource.asObjectable().getFetchResult()); - + ResourceSchema resourceSchema = RefinedResourceSchemaImpl.getResourceSchema(resource, prismContext); assertNull("Resource schema found", resourceSchema); - + // WHEN PrismObject resourceAgain = provisioningService.getObject(ResourceType.class,RESOURCE_OPENDJ_OID, null, task, result); - + // THEN result.computeStatus(); display("getObject(resourceAgain) result", result); TestUtil.assertFailure(result); TestUtil.assertFailure(resourceAgain.asObjectable().getFetchResult()); - + ResourceType resourceTypeAgain = resourceAgain.asObjectable(); assertNotNull("No connector ref",resourceTypeAgain.getConnectorRef()); assertNotNull("No connector ref OID",resourceTypeAgain.getConnectorRef().getOid()); - + PrismContainer configurationContainer = resource.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); - PrismContainer configurationContainerAgain = resourceAgain.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); + PrismContainer configurationContainerAgain = resourceAgain.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); assertTrue("Configurations not equivalent", configurationContainer.equivalent(configurationContainerAgain)); assertTrue("Configurations not equals", configurationContainer.equals(configurationContainerAgain)); ResourceSchema resourceSchemaAgain = RefinedResourceSchemaImpl.getResourceSchema(resourceAgain, prismContext); assertNull("Resource schema (again)", resourceSchemaAgain); } - + /** * This goes to local repo, therefore the expected result is ObjectNotFound. - * We know that the shadow does not exist. + * We know that the shadow does not exist. */ @Test public void test110GetObjectNoShadow() throws Exception { final String TEST_NAME = "test110GetObjectNoShadow"; TestUtil.displayTestTitle(TEST_NAME); - + OperationResult result = new OperationResult(TestOpenDjNegative.class.getName() + "." + TEST_NAME); try { ShadowType acct = provisioningService.getObject(ShadowType.class, NON_EXISTENT_OID, null, taskManager.createTaskInstance(), result).asObjectable(); - + AssertJUnit.fail("getObject succeeded unexpectedly"); } catch (ObjectNotFoundException e) { // This is expected display("Expected exception", e); } - + result.computeStatus(); TestUtil.assertFailure(result); } @@ -220,16 +220,16 @@ public void test110GetObjectNoShadow() throws Exception { * This is using the shadow to go to the resource. But it cannot as OpenDJ is down. * It even cannot fetch schema. If there is no schema it does not even know how to process * identifiers in the shadow. Therefore the expected result is ConfigurationException (CommunicationException). - * It must not be ObjectNotFound as we do NOT know that the shadow does not exist. + * It must not be ObjectNotFound as we do NOT know that the shadow does not exist. */ @Test public void test111GetObjectShadow() throws Exception { final String TEST_NAME = "test111GetObjectShadow"; TestUtil.displayTestTitle(TEST_NAME); - + OperationResult result = new OperationResult(TestOpenDjNegative.class.getName() + "." + TEST_NAME); - + try { ShadowType acct = provisioningService.getObject(ShadowType.class, ACCOUNT_JBOND_OID, null, taskManager.createTaskInstance(), result).asObjectable(); @@ -240,11 +240,11 @@ public void test111GetObjectShadow() throws Exception { // This is expected display("Expected exception", e); } - + result.computeStatus(); TestUtil.assertFailure(result); } - + @Test public void test120ListResourceObjects() throws Exception { final String TEST_NAME = "test120ListResourceObjects"; @@ -252,22 +252,22 @@ public void test120ListResourceObjects() throws Exception { // GIVEN OperationResult result = new OperationResult(TestOpenDjNegative.class.getName() + "." + TEST_NAME); - + try { // WHEN List> objectList = provisioningService.listResourceObjects( RESOURCE_OPENDJ_OID, RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS, null, null, result); - + AssertJUnit.fail("listResourceObjects succeeded unexpectedly"); } catch (ConfigurationException e) { // This is expected display("Expected exception", e); } - + result.computeStatus(); TestUtil.assertFailure(result); } - + @Test public void test121SearchAccounts() throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, Exception { @@ -281,23 +281,23 @@ public void test121SearchAccounts() throws SchemaException, ObjectNotFoundExcept QName objectClass = new QName(resourceNamespace, OBJECT_CLASS_INETORGPERSON_NAME); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(resource.getOid(), objectClass, prismContext); - + try { - + // WHEN provisioningService.searchObjects(ShadowType.class, query, null, null, result); - + AssertJUnit.fail("searchObjectsIterative succeeded unexpectedly"); } catch (ConfigurationException e) { // This is expected display("Expected exception", e); } - + result.computeStatus(); display(result); TestUtil.assertFailure(result); } - + @Test public void test122SearchAccountsIterative() throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, Exception { @@ -311,7 +311,7 @@ public void test122SearchAccountsIterative() throws SchemaException, ObjectNotFo QName objectClass = new QName(resourceNamespace, OBJECT_CLASS_INETORGPERSON_NAME); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(resource.getOid(), objectClass, prismContext); - + ResultHandler handler = new ResultHandler() { @Override public boolean handle(PrismObject prismObject, OperationResult parentResult) { @@ -321,20 +321,20 @@ public boolean handle(PrismObject prismObject, OperationResult paren }; try { - + // WHEN provisioningService.searchObjectsIterative(ShadowType.class, query, null, handler, null, result); - + AssertJUnit.fail("searchObjectsIterative succeeded unexpectedly"); } catch (ConfigurationException e) { // This is expected display("Expected exception", e); } - + result.computeStatus(); TestUtil.assertFailure(result); } - + @Test public void test130AddAccountWill() throws Exception { final String TEST_NAME = "test130AddAccountWill"; @@ -350,18 +350,18 @@ public void test130AddAccountWill() throws Exception { try { // WHEN String addedObjectOid = provisioningService.addObject(object.asPrismObject(), null, null, taskManager.createTaskInstance(), result); - + AssertJUnit.fail("addObject succeeded unexpectedly"); } catch (ConfigurationException e) { // This is expected display("Expected exception", e); } - + result.computeStatus(); TestUtil.assertFailure(result); } - + @Test public void test140AddDeleteAccountSparrow() throws Exception { final String TEST_NAME = "test140AddDeleteAccountSparrow"; @@ -379,12 +379,12 @@ public void test140AddDeleteAccountSparrow() throws Exception { // This is expected display("Expected exception", e); } - + result.computeStatus(); TestUtil.assertFailure(result); } - + @Test public void test150ModifyObject() throws Exception { final String TEST_NAME = "test150ModifyObject"; @@ -396,22 +396,22 @@ public void test150ModifyObject() throws Exception { ObjectModificationType objectChange = PrismTestUtil.parseAtomicValue(ACCOUNT_JACK_CHANGE_FILE, ObjectModificationType.COMPLEX_TYPE); ObjectDelta delta = DeltaConvertor.createObjectDelta(objectChange, ShadowType.class, PrismTestUtil.getPrismContext()); display("Object change",delta); - + try { provisioningService.modifyObject(ShadowType.class, objectChange.getOid(), delta.getModifications(), null, null, taskManager.createTaskInstance(), result); - + AssertJUnit.fail("addObject succeeded unexpectedly"); } catch (ConfigurationException e) { // This is expected display("Expected exception", e); } - + result.computeStatus(); TestUtil.assertFailure(result); } - + @Test public void test190Synchronize() throws Exception { final String TEST_NAME = "test190Synhronize"; @@ -420,80 +420,80 @@ public void test190Synchronize() throws Exception { Task task = taskManager.createTaskInstance(TestOpenDjNegative.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - - ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_OPENDJ_OID, + + ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_OPENDJ_OID, new QName(RESOURCE_NS, SchemaConstants.ACCOUNT_OBJECT_CLASS_LOCAL_NAME)); - + try { provisioningService.synchronize(coords, task, result); - + AssertJUnit.fail("addObject succeeded unexpectedly"); } catch (CommunicationException e) { // This is expected display("Expected exception", e); } - + result.computeStatus(); TestUtil.assertFailure(result); } - + // ========================================================================================================= // Now lets replace the resource with one that has schema and capabilities. And re-run some of the tests. // OpenDJ is still down so the results should be the same. But the code may take a different path if // schema is present. // ========================================================================================================= - + @Test public void test500ReplaceResource() throws Exception { final String TEST_NAME = "test500ReplaceResource"; TestUtil.displayTestTitle(TEST_NAME); - + OperationResult result = new OperationResult(TestOpenDjNegative.class.getName() + "." + TEST_NAME); // Delete should work fine even though OpenDJ is down provisioningService.deleteObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, null, taskManager.createTaskInstance(), result); - + result.computeStatus(); TestUtil.assertSuccess(result); - + resource = addResourceFromFile(RESOURCE_OPENDJ_INITIALIZED_FILE, IntegrationTestTools.CONNECTOR_LDAP_TYPE, result); result.computeStatus(); TestUtil.assertSuccess(result); } - + /** * This goes to local repo, therefore the expected result is ObjectNotFound. - * We know that the shadow does not exist. + * We know that the shadow does not exist. */ @Test public void test510GetObjectNoShadow() throws Exception { final String TEST_NAME = "test510GetObjectNoShadow"; TestUtil.displayTestTitle(TEST_NAME); - + OperationResult result = new OperationResult(TestOpenDjNegative.class.getName() + "." + TEST_NAME); try { ShadowType acct = provisioningService.getObject(ShadowType.class, NON_EXISTENT_OID, null, taskManager.createTaskInstance(), result).asObjectable(); - + AssertJUnit.fail("getObject succeeded unexpectedly"); } catch (ObjectNotFoundException e) { // This is expected display("Expected exception", e); } - + result.computeStatus(); TestUtil.assertFailure(result); } /** - * This is using the shadow to go to the resource. But it cannot as OpenDJ is down. - * Therefore the expected result is CommunicationException. It must not be ObjectNotFound as + * This is using the shadow to go to the resource. But it cannot as OpenDJ is down. + * Therefore the expected result is CommunicationException. It must not be ObjectNotFound as * we do NOT know that the shadow does not exist. * Provisioning should return a repo shadow and indicate the result both in operation result and * in fetchResult in the returned shadow. @@ -502,29 +502,29 @@ public void test510GetObjectNoShadow() throws Exception { public void test511GetObjectShadow() throws Exception { final String TEST_NAME = "test511GetObjectShadow"; TestUtil.displayTestTitle(TEST_NAME); - + OperationResult result = new OperationResult(TestOpenDjNegative.class.getName() + "." + TEST_NAME); - + PrismObject acct = provisioningService.getObject(ShadowType.class, ACCOUNT_JBOND_OID, null, taskManager.createTaskInstance(), result); display("Account", acct); - + result.computeStatus(); display("getObject result", result); - assertEquals("Expected result partial error but was "+result.getStatus(), + assertEquals("Expected result partial error but was "+result.getStatus(), OperationResultStatus.PARTIAL_ERROR, result.getStatus()); - + OperationResultType fetchResult = acct.asObjectable().getFetchResult(); display("getObject fetchResult", fetchResult); - assertEquals("Expected fetchResult partial error but was "+result.getStatus(), + assertEquals("Expected fetchResult partial error but was "+result.getStatus(), OperationResultStatusType.PARTIAL_ERROR, fetchResult.getStatus()); } /** - * This is using the shadow to go to the resource. But it cannot as OpenDJ is down. - * Therefore the expected result is CommunicationException. It must not be ObjectNotFound as - * we do NOT know that the shadow does not exist. + * This is using the shadow to go to the resource. But it cannot as OpenDJ is down. + * Therefore the expected result is CommunicationException. It must not be ObjectNotFound as + * we do NOT know that the shadow does not exist. */ @Test public void test520ListResourceObjects() throws Exception { @@ -533,22 +533,22 @@ public void test520ListResourceObjects() throws Exception { // GIVEN OperationResult result = new OperationResult(TestOpenDjNegative.class.getName() + "." + TEST_NAME); - + try { // WHEN List> objectList = provisioningService.listResourceObjects( RESOURCE_OPENDJ_OID, RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS, null, null, result); - + AssertJUnit.fail("listResourceObjects succeeded unexpectedly"); } catch (CommunicationException e) { // This is expected display("Expected exception", e); } - + result.computeStatus(); TestUtil.assertFailure(result); } - + @Test public void test521SearchAccounts() throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, Exception { @@ -562,22 +562,22 @@ public void test521SearchAccounts() throws SchemaException, ObjectNotFoundExcept QName objectClass = new QName(resourceNamespace, OBJECT_CLASS_INETORGPERSON_NAME); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(resource.getOid(), objectClass, prismContext); - + try { - + // WHEN provisioningService.searchObjects(ShadowType.class, query, null, null, result); - + AssertJUnit.fail("searchObjectsIterative succeeded unexpectedly"); } catch (CommunicationException e) { // This is expected display("Expected exception", e); } - + result.computeStatus(); TestUtil.assertFailure(result); } - + @Test public void test522SearchAccountsIterative() throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, Exception { @@ -591,7 +591,7 @@ public void test522SearchAccountsIterative() throws SchemaException, ObjectNotFo QName objectClass = new QName(resourceNamespace, OBJECT_CLASS_INETORGPERSON_NAME); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(resource.getOid(), objectClass, prismContext); - + ResultHandler handler = new ResultHandler() { @Override public boolean handle(PrismObject prismObject, OperationResult parentResult) { @@ -601,27 +601,27 @@ public boolean handle(PrismObject prismObject, OperationResult paren }; try { - + // WHEN provisioningService.searchObjectsIterative(ShadowType.class, query, null, handler, null, result); - + AssertJUnit.fail("searchObjectsIterative succeeded unexpectedly"); } catch (CommunicationException e) { // This is expected display("Expected exception", e); } - + result.computeStatus(); display(result); TestUtil.assertFailure(result); } - + @Test public void test530AddAccountWill() throws Exception { final String TEST_NAME = "test530AddAccountWill"; TestUtil.displayTestTitle(TEST_NAME); // GIVEN - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); @@ -630,12 +630,12 @@ public void test530AddAccountWill() throws Exception { // WHEN String addedObjectOid = provisioningService.addObject(object.asPrismObject(), null, null, task, result); - + // THEN result.computeStatus(); display("addObject result", result); assertEquals("Wrong result", OperationResultStatus.HANDLED_ERROR, result.getStatus()); - + assertEquals(ACCOUNT_WILL_OID, addedObjectOid); ShadowType repoAccountType = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, @@ -657,7 +657,7 @@ public void test530AddAccountWill() throws Exception { TestUtil.assertFailure("Result in shadow (repo)", provisioningResult); } - + @Test public void test540DeleteObject() throws Exception { final String TEST_NAME = "test540DeleteObject"; @@ -674,7 +674,7 @@ public void test540DeleteObject() throws Exception { result.computeStatus(); display("deleteObject result", result); assertEquals("Wrong result", OperationResultStatus.HANDLED_ERROR, result.getStatus()); - + ShadowType repoAccountType = repositoryService.getObject(ShadowType.class, ACCOUNT_SPARROW_OID, null, result).asObjectable(); display("repo shadow", repoAccountType); @@ -690,7 +690,7 @@ public void test540DeleteObject() throws Exception { assertEquals("Wrong failedOperationType in repo", FailedOperationTypeType.DELETE, provisioningAccountType.getFailedOperationType()); OperationResultType provisioningResult = provisioningAccountType.getResult(); assertNotNull("No result in shadow (repo)", provisioningResult); - TestUtil.assertFailure("Result in shadow (repo)", provisioningResult); + TestUtil.assertFailure("Result in shadow (repo)", provisioningResult); } @Test @@ -704,17 +704,17 @@ public void test550ModifyObject() throws Exception { ObjectModificationType objectChange = PrismTestUtil.parseAtomicValue(ACCOUNT_JACK_CHANGE_FILE, ObjectModificationType.COMPLEX_TYPE); ObjectDelta delta = DeltaConvertor.createObjectDelta(objectChange, ShadowType.class, PrismTestUtil.getPrismContext()); display("Object change",delta); - + Task task = taskManager.createTaskInstance(); provisioningService.modifyObject(ShadowType.class, objectChange.getOid(), delta.getModifications(), null, null, task, result); - - + + // THEN result.computeStatus(); display("deleteObject result", result); assertEquals("Wrong result", OperationResultStatus.HANDLED_ERROR, result.getStatus()); - + ShadowType repoAccountType = repositoryService.getObject(ShadowType.class, ACCOUNT_JACK_OID, null, result).asObjectable(); display("repo shadow", repoAccountType); @@ -730,9 +730,9 @@ public void test550ModifyObject() throws Exception { OperationResultType provisioningResult = provisioningAccountType.getResult(); assertNotNull("No result in shadow (repo)", provisioningResult); TestUtil.assertFailure("Result in shadow (repo)", provisioningResult); - + } - + @Test public void test590Synchronize() throws Exception { final String TEST_NAME = "test590Synhronize"; @@ -741,21 +741,21 @@ public void test590Synchronize() throws Exception { Task task = taskManager.createTaskInstance(TestOpenDjNegative.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - - ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_OPENDJ_OID, + + ResourceShadowDiscriminator coords = new ResourceShadowDiscriminator(RESOURCE_OPENDJ_OID, new QName(RESOURCE_NS, SchemaConstants.ACCOUNT_OBJECT_CLASS_LOCAL_NAME)); - + try { provisioningService.synchronize(coords, task, result); - + AssertJUnit.fail("addObject succeeded unexpectedly"); } catch (CommunicationException e) { // This is expected display("Expected exception", e); } - + result.computeStatus(); TestUtil.assertFailure(result); } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjReadablePassword.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjReadablePassword.java index fd320b4875a..5d909ab7723 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjReadablePassword.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjReadablePassword.java @@ -38,7 +38,7 @@ /** * Test for provisioning service implementation using embedded OpenDj instance. * This is the same test as TestOpenDj, but the configuration allows password reading. - * + * * @author Radovan Semancik */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @@ -46,20 +46,20 @@ public class TestOpenDjReadablePassword extends TestOpenDj { protected static final File RESOURCE_OPENDJ_READABLE_PASSWORD_FILE = new File(TEST_DIR, "resource-opendj-readable-password.xml"); - + private static Trace LOGGER = TraceManager.getTrace(TestOpenDjReadablePassword.class); - + @Override protected File getResourceOpenDjFile() { return RESOURCE_OPENDJ_READABLE_PASSWORD_FILE; } - + @Override protected void assertPasswordCapability(PasswordCapabilityType capPassword) { - assertTrue("Wrong password capability readable flag: "+capPassword.isReadable(), + assertTrue("Wrong password capability readable flag: "+capPassword.isReadable(), capPassword.isReadable() == Boolean.TRUE); } - + @Override protected void assertShadowPassword(ShadowType provisioningShadow) throws Exception { CredentialsType credentials = provisioningShadow.getCredentials(); @@ -75,7 +75,7 @@ protected void assertShadowPassword(ShadowType provisioningShadow) throws Except assertFalse("Empty password value in "+provisioningShadow, passwordValue.isEmpty()); String clearPassword = protector.decryptString(passwordValue); display("Clear password of "+provisioningShadow+": "+clearPassword); - + PrismContainerValue passwordContainer = passwordType.asPrismContainerValue(); PrismProperty valueProp = passwordContainer.findProperty(PasswordType.F_VALUE); assertFalse("Incomplete password value in "+provisioningShadow, valueProp.isIncomplete()); diff --git a/provisioning/provisioning-impl/src/test/resources/logback-test.xml b/provisioning/provisioning-impl/src/test/resources/logback-test.xml index b07c6c94cc6..4688718ab45 100644 --- a/provisioning/provisioning-impl/src/test/resources/logback-test.xml +++ b/provisioning/provisioning-impl/src/test/resources/logback-test.xml @@ -26,6 +26,7 @@ + + xmlns:icfccsvfile="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.polygon.connector-csv/com.evolveum.polygon.connector.csv.CsvConnector"> /var/opt/midpoint-book/resources/hr.csv utf-8 - " , ; - false - id - + empno password diff --git a/samples/book/2/resource-csv-hr.xml b/samples/book/2/resource-csv-hr.xml index 477862df731..43c834b9501 100644 --- a/samples/book/2/resource-csv-hr.xml +++ b/samples/book/2/resource-csv-hr.xml @@ -38,7 +38,7 @@ This file is an example of Resource definition. It defines CSV resource. c:connectorType - com.evolveum.polygon.csvfile.CSVFileConnector + com.evolveum.polygon.connector.csv.CsvConnector @@ -47,19 +47,15 @@ This file is an example of Resource definition. It defines CSV resource. + xmlns:icfccsvfile="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.polygon.connector-csv/com.evolveum.polygon.connector.csv.CsvConnector"> /var/opt/midpoint-book/resources/hr.csv utf-8 - " , ; - false - id - + empno password - @@ -69,16 +65,7 @@ This file is an example of Resource definition. It defines CSV resource. true ri:AccountObjectClass - icfs:uid - ID - - - true - - - - - icfs:name + ri:empno Name 0 @@ -145,7 +132,7 @@ This file is an example of Resource definition. It defines CSV resource. c:name - $account/attributes/icfs:name + $account/attributes/empno diff --git a/samples/book/5/hr.csv b/samples/book/5/hr.csv index 51903a1b563..660e96b5fde 100644 --- a/samples/book/5/hr.csv +++ b/samples/book/5/hr.csv @@ -1,4 +1,4 @@ -"id","firstname","lastname","password" +"empno","firstname","lastname","password" "001","Alice","Anderson","qwe123" "002","Bob","Brown","qwe123" "003","Carol","Cooper","qwe123" diff --git a/samples/book/5/resource-csv-hr.xml b/samples/book/5/resource-csv-hr.xml index 24fec03b04f..f8100eda51a 100644 --- a/samples/book/5/resource-csv-hr.xml +++ b/samples/book/5/resource-csv-hr.xml @@ -30,38 +30,34 @@ HR System - HR resource using CSVFile connector. This is the HR feed (source) resource. + HR resource using CSV connector. This is the HR feed (source) resource. This is a sample used in the "Practical Identity Management with MidPoint" book, chapter 5. - - - - c:connectorType - com.evolveum.polygon.csvfile.CSVFileConnector - - - - - - - - - /var/opt/midpoint-book/resources/hr.csv - utf-8 - " - , - ; - false - id - - password - - - - + + + + c:connectorType + com.evolveum.polygon.connector.csv.CsvConnector + + + + + + + + + /var/opt/midpoint-book/resources/hr.csv + utf-8 + , + ; + empno + password + + + @@ -70,16 +66,7 @@ true ri:AccountObjectClass - icfs:uid - ID - - - true - - - - - icfs:name + ri:empno Name 0 @@ -108,7 +95,6 @@ $focus/givenName - ri:lastname @@ -149,9 +135,9 @@ true - c:name + employeeNumber - $shadow/attributes/icfs:name + $shadow/attributes/empno diff --git a/samples/model-client-sample/src/main/java/com/evolveum/midpoint/testing/model/client/sample/Main.java b/samples/model-client-sample/src/main/java/com/evolveum/midpoint/testing/model/client/sample/Main.java index 619d754751b..03eeaada272 100644 --- a/samples/model-client-sample/src/main/java/com/evolveum/midpoint/testing/model/client/sample/Main.java +++ b/samples/model-client-sample/src/main/java/com/evolveum/midpoint/testing/model/client/sample/Main.java @@ -82,12 +82,12 @@ * */ public class Main { - + // Configuration public static final String ADM_USERNAME = "administrator"; public static final String ADM_PASSWORD = "5ecr3t"; private static final String DEFAULT_ENDPOINT_URL = "http://localhost:8080/midpoint/model/model-3"; - + // Object OIDs private static final String ROLE_PIRATE_OID = "2de6a600-636f-11e4-9cc7-3c970e467874"; private static final String ROLE_CAPTAIN_OID = "12345678-d34d-b33f-f00d-987987cccccc"; @@ -97,7 +97,7 @@ public class Main { */ public static void main(String[] args) { try { - + ModelPortType modelPort = createModelPort(args); SystemConfigurationType configurationType = getConfiguration(modelPort); @@ -176,7 +176,7 @@ public static void main(String[] args) { deleteUser(modelPort, userLeChuckOid); deleteRole(modelPort, seaSuperuserRole); System.out.println("Deleted user(s)"); - + } catch (Exception e) { e.printStackTrace(); System.exit(-1); @@ -195,10 +195,10 @@ private static SystemConfigurationType getConfiguration(ModelPortType modelPort) Holder objectHolder = new Holder(); Holder resultHolder = new Holder(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); - + modelPort.getObject(ModelClientUtil.getTypeQName(SystemConfigurationType.class), SystemObjectsType.SYSTEM_CONFIGURATION.value(), options, objectHolder, resultHolder); - + return (SystemConfigurationType) objectHolder.value; } @@ -207,10 +207,10 @@ private static UserType getUser(ModelPortType modelPort, String oid) throws Faul Holder objectHolder = new Holder(); Holder resultHolder = new Holder(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); - + modelPort.getObject(ModelClientUtil.getTypeQName(UserType.class), oid, options, objectHolder, resultHolder); - + return (UserType) objectHolder.value; } @@ -220,7 +220,7 @@ private static Collection listResources(ModelPortType modelPort) t Holder resultHolder = new Holder(); modelPort.searchObjects(ModelClientUtil.getTypeQName(ResourceType.class), null, options, objectListHolder, resultHolder); - + ObjectListType objectList = objectListHolder.value; return (Collection) objectList.getObject(); } @@ -273,7 +273,7 @@ private static Collection listTasks(ModelPortType modelPort) throws SA private static String createUserGuybrush(ModelPortType modelPort, RoleType role) throws FaultMessage { Document doc = ModelClientUtil.getDocumnent(); - + UserType user = new UserType(); user.setName(ModelClientUtil.createPolyStringType("guybrush", doc)); user.setFullName(ModelClientUtil.createPolyStringType("Guybrush Threepwood", doc)); @@ -283,19 +283,19 @@ private static String createUserGuybrush(ModelPortType modelPort, RoleType role) user.getOrganization().add(ModelClientUtil.createPolyStringType("Pirate Brethren International", doc)); user.getOrganizationalUnit().add(ModelClientUtil.createPolyStringType("Pirate Wannabes", doc)); user.setCredentials(ModelClientUtil.createPasswordCredentials("IwannaBEaPIRATE")); - + if (role != null) { // create user with a role assignment AssignmentType roleAssignment = ModelClientUtil.createRoleAssignment(role.getOid()); user.getAssignment().add(roleAssignment); } - + return createUser(modelPort, user); } private static String createUserFromSystemResource(ModelPortType modelPort, String resourcePath) throws FileNotFoundException, JAXBException, FaultMessage { UserType user = ModelClientUtil.unmarshallResource(resourcePath); - + return createUser(modelPort, user); } @@ -304,7 +304,7 @@ private static String createRoleFromSystemResource(ModelPortType modelPort, Stri return createRole(modelPort, role); } - + private static String createUser(ModelPortType modelPort, UserType userType) throws FaultMessage { ObjectDeltaType deltaType = new ObjectDeltaType(); deltaType.setObjectType(ModelClientUtil.getTypeQName(UserType.class)); @@ -328,7 +328,7 @@ private static String createRole(ModelPortType modelPort, RoleType roleType) thr ObjectDeltaOperationListType operationListType = modelPort.executeChanges(deltaListType, null); return ModelClientUtil.getOidFromDeltaOperationList(operationListType, deltaType); } - + private static void changeUserPassword(ModelPortType modelPort, String oid, String newPassword) throws FaultMessage { ItemDeltaType passwordDelta = new ItemDeltaType(); passwordDelta.setModificationType(ModificationTypeType.REPLACE); @@ -383,11 +383,11 @@ private static void reconcileUser(ModelPortType modelPort, String oid) throws Fa private static void assignRoles(ModelPortType modelPort, String userOid, String... roleOids) throws FaultMessage { modifyRoleAssignment(modelPort, userOid, true, roleOids); } - + private static void unAssignRoles(ModelPortType modelPort, String userOid, String... roleOids) throws FaultMessage { modifyRoleAssignment(modelPort, userOid, false, roleOids); } - + private static void modifyRoleAssignment(ModelPortType modelPort, String userOid, boolean isAdd, String... roleOids) throws FaultMessage { ItemDeltaType assignmentDelta = new ItemDeltaType(); if (isAdd) { @@ -521,9 +521,9 @@ private static UserType searchUserByName(ModelPortType modelPort, String usernam SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); Holder objectListHolder = new Holder(); Holder resultHolder = new Holder(); - + modelPort.searchObjects(ModelClientUtil.getTypeQName(UserType.class), createUserQuery1(username), options, objectListHolder, resultHolder); - + ObjectListType objectList = objectListHolder.value; List objects = objectList.getObject(); if (objects.isEmpty()) { @@ -534,7 +534,7 @@ private static UserType searchUserByName(ModelPortType modelPort, String usernam } throw new IllegalStateException("Expected to find a single user with username '"+username+"' but found "+objects.size()+" users instead"); } - + private static RoleType searchRoleByName(ModelPortType modelPort, String roleName) throws SAXException, IOException, FaultMessage, JAXBException { // WARNING: in a real case make sure that the role name is properly escaped before putting it in XML SearchFilterType filter = ModelClientUtil.parseSearchFilterType( @@ -548,9 +548,9 @@ private static RoleType searchRoleByName(ModelPortType modelPort, String roleNam SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); Holder objectListHolder = new Holder(); Holder resultHolder = new Holder(); - + modelPort.searchObjects(ModelClientUtil.getTypeQName(RoleType.class), query, options, objectListHolder, resultHolder); - + ObjectListType objectList = objectListHolder.value; List objects = objectList.getObject(); if (objects.isEmpty()) { @@ -574,9 +574,9 @@ private static Collection listRequestableRoles(ModelPortType modelPort SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); Holder objectListHolder = new Holder(); Holder resultHolder = new Holder(); - + modelPort.searchObjects(ModelClientUtil.getTypeQName(RoleType.class), query, options, objectListHolder, resultHolder); - + ObjectListType objectList = objectListHolder.value; return (Collection) objectList.getObject(); } @@ -622,10 +622,10 @@ private static void deleteTask(ModelPortType modelPort, String oid) throws Fault executeOptionsType.setRaw(true); modelPort.executeChanges(deltaListType, executeOptionsType); } - + public static ModelPortType createModelPort(String[] args) { String endpointUrl = DEFAULT_ENDPOINT_URL; - + if (args.length > 0) { endpointUrl = args[0]; } @@ -634,23 +634,23 @@ public static ModelPortType createModelPort(String[] args) { // uncomment this if you want to use Fiddler or any other proxy //ProxySelector.setDefault(new MyProxySelector("127.0.0.1", 8888)); - + ModelService modelService = new ModelService(); ModelPortType modelPort = modelService.getModelPort(); BindingProvider bp = (BindingProvider)modelPort; Map requestContext = bp.getRequestContext(); requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointUrl); - + org.apache.cxf.endpoint.Client client = ClientProxy.getClient(modelPort); org.apache.cxf.endpoint.Endpoint cxfEndpoint = client.getEndpoint(); - + Map outProps = new HashMap(); - + outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN); outProps.put(WSHandlerConstants.USER, ADM_USERNAME); outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_DIGEST); outProps.put(WSHandlerConstants.PW_CALLBACK_CLASS, ClientPasswordHandler.class.getName()); - + WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps); cxfEndpoint.getOutInterceptors().add(wssOut); // enable the following to get client-side logging of outgoing requests and incoming responses diff --git a/samples/model-client-sample/src/main/java/com/evolveum/midpoint/testing/model/client/sample/RunScript.java b/samples/model-client-sample/src/main/java/com/evolveum/midpoint/testing/model/client/sample/RunScript.java index 71e821107be..5f62e7a6b18 100644 --- a/samples/model-client-sample/src/main/java/com/evolveum/midpoint/testing/model/client/sample/RunScript.java +++ b/samples/model-client-sample/src/main/java/com/evolveum/midpoint/testing/model/client/sample/RunScript.java @@ -65,7 +65,7 @@ * */ public class RunScript { - + // Configuration public static final String ADM_USERNAME = "administrator"; public static final String ADM_PASSWORD = "5ecr3t"; @@ -261,8 +261,8 @@ private static String determineEncoding(String filename) throws IOException { private static T unmarshalFile(File file) throws JAXBException, FileNotFoundException { JAXBContext jc = getJaxbContext(); - Unmarshaller unmarshaller = jc.createUnmarshaller(); - + Unmarshaller unmarshaller = jc.createUnmarshaller(); + InputStream is = null; JAXBElement element = null; try { @@ -301,8 +301,8 @@ private static String marshalObject(Object object) throws JAXBException, FileNot private static T unmarshallResouce(String path) throws JAXBException, FileNotFoundException { JAXBContext jc = getJaxbContext(); - Unmarshaller unmarshaller = jc.createUnmarshaller(); - + Unmarshaller unmarshaller = jc.createUnmarshaller(); + InputStream is = null; JAXBElement element = null; try { @@ -327,23 +327,23 @@ public static ModelPortType createModelPort(CommandLine cmdLine) { String user = cmdLine.getOptionValue(OPT_USER, ADM_USERNAME); ClientPasswordHandler.setPassword(cmdLine.getOptionValue(OPT_PASSWORD, ADM_PASSWORD)); System.out.println("Endpoint URL: " + endpointUrl); - + ModelService modelService = new ModelService(); ModelPortType modelPort = modelService.getModelPort(); BindingProvider bp = (BindingProvider)modelPort; Map requestContext = bp.getRequestContext(); requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointUrl); - + org.apache.cxf.endpoint.Client client = ClientProxy.getClient(modelPort); org.apache.cxf.endpoint.Endpoint cxfEndpoint = client.getEndpoint(); - + Map outProps = new HashMap<>(); - + outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN); outProps.put(WSHandlerConstants.USER, user); outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_DIGEST); outProps.put(WSHandlerConstants.PW_CALLBACK_CLASS, ClientPasswordHandler.class.getName()); - + WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps); cxfEndpoint.getOutInterceptors().add(wssOut); diff --git a/samples/model-client-sample/src/main/java/com/evolveum/midpoint/testing/model/client/sample/Upload.java b/samples/model-client-sample/src/main/java/com/evolveum/midpoint/testing/model/client/sample/Upload.java index 2f1416f1c87..acd4050842c 100644 --- a/samples/model-client-sample/src/main/java/com/evolveum/midpoint/testing/model/client/sample/Upload.java +++ b/samples/model-client-sample/src/main/java/com/evolveum/midpoint/testing/model/client/sample/Upload.java @@ -61,7 +61,7 @@ * */ public class Upload { - + // Configuration public static final String ADM_USERNAME = "administrator"; public static final String ADM_PASSWORD = "5ecr3t"; @@ -283,23 +283,23 @@ public static ModelPortType createModelPort(CommandLine cmdLine) { String user = cmdLine.getOptionValue(OPT_USER, ADM_USERNAME); ClientPasswordHandler.setPassword(cmdLine.getOptionValue(OPT_PASSWORD, ADM_PASSWORD)); System.out.println("Endpoint URL: " + endpointUrl); - + ModelService modelService = new ModelService(); ModelPortType modelPort = modelService.getModelPort(); BindingProvider bp = (BindingProvider)modelPort; Map requestContext = bp.getRequestContext(); requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointUrl); - + org.apache.cxf.endpoint.Client client = ClientProxy.getClient(modelPort); org.apache.cxf.endpoint.Endpoint cxfEndpoint = client.getEndpoint(); - + Map outProps = new HashMap<>(); - + outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN); outProps.put(WSHandlerConstants.USER, user); outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_DIGEST); outProps.put(WSHandlerConstants.PW_CALLBACK_CLASS, ClientPasswordHandler.class.getName()); - + WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps); cxfEndpoint.getOutInterceptors().add(wssOut); diff --git a/samples/model-client-sample/src/test/java/com/evolveum/midpoint/testing/model/client/sample/AbstractTestForExchangeConnector.java b/samples/model-client-sample/src/test/java/com/evolveum/midpoint/testing/model/client/sample/AbstractTestForExchangeConnector.java index 8f6c4d5a0f6..2afd28fd208 100644 --- a/samples/model-client-sample/src/test/java/com/evolveum/midpoint/testing/model/client/sample/AbstractTestForExchangeConnector.java +++ b/samples/model-client-sample/src/test/java/com/evolveum/midpoint/testing/model/client/sample/AbstractTestForExchangeConnector.java @@ -95,12 +95,12 @@ * @author mederly */ public class AbstractTestForExchangeConnector { - + // Configuration public static final String ADM_USERNAME = "administrator"; public static final String ADM_PASSWORD = "5ecr3t"; public static final String DEFAULT_ENDPOINT_URL = "http://localhost.:8080/midpoint/model/model-3"; - + // Object OIDs // Other @@ -768,10 +768,10 @@ protected SystemConfigurationType getConfiguration() throws FaultMessage { Holder objectHolder = new Holder(); Holder resultHolder = new Holder(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); - + modelPort.getObject(ModelClientUtil.getTypeQName(SystemConfigurationType.class), SystemObjectsType.SYSTEM_CONFIGURATION.value(), options, objectHolder, resultHolder); - + return (SystemConfigurationType) objectHolder.value; } @@ -781,7 +781,7 @@ protected Collection listResources() throws SAXException, IOExcept Holder resultHolder = new Holder(); modelPort.searchObjects(ModelClientUtil.getTypeQName(ResourceType.class), null, options, objectListHolder, resultHolder); - + ObjectListType objectList = objectListHolder.value; return (Collection) objectList.getObject(); } @@ -865,7 +865,7 @@ protected Collection listTasks() throws SAXException, IOException, Fau protected String createUserGuybrush(RoleType role) throws FaultMessage { Document doc = ModelClientUtil.getDocumnent(); - + UserType user = new UserType(); user.setName(ModelClientUtil.createPolyStringType("guybrush", doc)); user.setFullName(ModelClientUtil.createPolyStringType("Guybrush Threepwood", doc)); @@ -875,13 +875,13 @@ protected String createUserGuybrush(RoleType role) throws FaultMessage { user.getOrganization().add(ModelClientUtil.createPolyStringType("Pirate Brethren International", doc)); user.getOrganizationalUnit().add(ModelClientUtil.createPolyStringType("Pirate Wannabes", doc)); user.setCredentials(ModelClientUtil.createPasswordCredentials("IwannaBEaPIRATE")); - + if (role != null) { // create user with a role assignment AssignmentType roleAssignment = createRoleAssignment(role.getOid()); user.getAssignment().add(roleAssignment); } - + return createUser(user); } @@ -1025,14 +1025,14 @@ public static ObjectReferenceType createObjectReferenceType(Class T unmarshallFile(File file) throws JAXBException, FileNotFoundException { JAXBContext jc = ModelClientUtil.instantiateJaxbContext(); - Unmarshaller unmarshaller = jc.createUnmarshaller(); - + Unmarshaller unmarshaller = jc.createUnmarshaller(); + InputStream is = null; JAXBElement element = null; try { @@ -1051,8 +1051,8 @@ protected static T unmarshallFile(File file) throws JAXBException, FileNotFo protected static T unmarshallResource(String path) throws JAXBException, FileNotFoundException { JAXBContext jc = ModelClientUtil.instantiateJaxbContext(); - Unmarshaller unmarshaller = jc.createUnmarshaller(); - + Unmarshaller unmarshaller = jc.createUnmarshaller(); + InputStream is = null; JAXBElement element = null; try { @@ -1256,9 +1256,9 @@ protected UserType searchUserByName(String username) throws SAXException, IOExce SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); Holder objectListHolder = new Holder(); Holder resultHolder = new Holder(); - + modelPort.searchObjects(ModelClientUtil.getTypeQName(UserType.class), query, options, objectListHolder, resultHolder); - + ObjectListType objectList = objectListHolder.value; List objects = objectList.getObject(); if (objects.isEmpty()) { @@ -1283,9 +1283,9 @@ protected RoleType searchRoleByName(String roleName) throws SAXException, IOExce SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); Holder objectListHolder = new Holder(); Holder resultHolder = new Holder(); - + modelPort.searchObjects(ModelClientUtil.getTypeQName(RoleType.class), query, options, objectListHolder, resultHolder); - + ObjectListType objectList = objectListHolder.value; List objects = objectList.getObject(); if (objects.isEmpty()) { @@ -1309,9 +1309,9 @@ protected Collection listRequestableRoles() throws SAXException, IOExc SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); Holder objectListHolder = new Holder(); Holder resultHolder = new Holder(); - + modelPort.searchObjects(ModelClientUtil.getTypeQName(RoleType.class), query, options, objectListHolder, resultHolder); - + ObjectListType objectList = objectListHolder.value; return (Collection) objectList.getObject(); } @@ -1343,10 +1343,10 @@ protected void deleteTask(String oid) throws FaultMessage { executeOptionsType.setRaw(true); modelPort.executeChanges(deltaListType, executeOptionsType); } - + public ModelPortType createModelPort(String[] args) { String endpointUrl = DEFAULT_ENDPOINT_URL; - + if (args.length > 0) { endpointUrl = args[0]; } @@ -1355,7 +1355,7 @@ public ModelPortType createModelPort(String[] args) { // uncomment this if you want to use Fiddler or any other proxy // ProxySelector.setDefault(new MyProxySelector("127.0.0.1", 8888)); - + ModelService modelService = new ModelService(); ModelPortType modelPort = modelService.getModelPort(); BindingProvider bp = (BindingProvider)modelPort; @@ -1370,14 +1370,14 @@ public ModelPortType createModelPort(String[] args) { http.setClient(httpClientPolicy); org.apache.cxf.endpoint.Endpoint cxfEndpoint = client.getEndpoint(); - + Map outProps = new HashMap(); - + outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN); outProps.put(WSHandlerConstants.USER, ADM_USERNAME); outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_DIGEST); outProps.put(WSHandlerConstants.PW_CALLBACK_CLASS, ClientPasswordHandler.class.getName()); - + WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps); cxfEndpoint.getOutInterceptors().add(wssOut); // enable the following to get client-side logging of outgoing requests and incoming responses diff --git a/samples/model-client-sample/src/test/java/com/evolveum/midpoint/testing/model/client/sample/TestExchangeAlreadyExistsHandling.java b/samples/model-client-sample/src/test/java/com/evolveum/midpoint/testing/model/client/sample/TestExchangeAlreadyExistsHandling.java index 7c49ebe3752..e665620952b 100644 --- a/samples/model-client-sample/src/test/java/com/evolveum/midpoint/testing/model/client/sample/TestExchangeAlreadyExistsHandling.java +++ b/samples/model-client-sample/src/test/java/com/evolveum/midpoint/testing/model/client/sample/TestExchangeAlreadyExistsHandling.java @@ -35,7 +35,7 @@ * */ public class TestExchangeAlreadyExistsHandling extends AbstractTestForExchangeConnector { - + private String orvilleOid; private String wilburOid; @@ -50,7 +50,7 @@ private String mail(String givenName, String sn) { private String getContainer() { return System.getProperty("container"); } - + public String getMailDomain() { return System.getProperty("mailDomain"); } diff --git a/samples/model-client-sample/src/test/java/com/evolveum/midpoint/testing/model/client/sample/TestExchangeConnectorLow.java b/samples/model-client-sample/src/test/java/com/evolveum/midpoint/testing/model/client/sample/TestExchangeConnectorLow.java index 5a62c2f3476..1b8bafac904 100644 --- a/samples/model-client-sample/src/test/java/com/evolveum/midpoint/testing/model/client/sample/TestExchangeConnectorLow.java +++ b/samples/model-client-sample/src/test/java/com/evolveum/midpoint/testing/model/client/sample/TestExchangeConnectorLow.java @@ -72,7 +72,7 @@ * */ public class TestExchangeConnectorLow extends AbstractTestForExchangeConnector { - + private static final String NEWTON_GIVEN_NAME = "Isaac"; private static final String NEWTON_SN = "Newton"; private String newtonOid; @@ -100,7 +100,7 @@ private String mail(String givenName, String sn) { private String getContainer() { return System.getProperty("container"); } - + public String getMailDomain() { return System.getProperty("mailDomain"); } diff --git a/samples/samples-test/src/test/java/com/evolveum/midpoint/samples/test/TestSampleImport.java b/samples/samples-test/src/test/java/com/evolveum/midpoint/samples/test/TestSampleImport.java index c8216d11474..b0bdac6cc5c 100644 --- a/samples/samples-test/src/test/java/com/evolveum/midpoint/samples/test/TestSampleImport.java +++ b/samples/samples-test/src/test/java/com/evolveum/midpoint/samples/test/TestSampleImport.java @@ -50,25 +50,25 @@ /** * Try to import selected samples to a real repository in an initialized system. - * + * * We cannot import all the samples as some of them are mutually exclusive. - * + * * @author Radovan Semancik * */ @ContextConfiguration(locations = {"classpath:ctx-samples-test-main.xml"}) @DirtiesContext(classMode=ClassMode.AFTER_CLASS) public class TestSampleImport extends AbstractModelIntegrationTest { - + private static final String SAMPLE_DIRECTORY_NAME = "../"; private static final String SCHEMA_DIRECTORY_NAME = SAMPLE_DIRECTORY_NAME + "schema/"; private static final String USER_ADMINISTRATOR_FILENAME = "src/test/resources/user-administrator.xml"; - + private static final Trace LOGGER = TraceManager.getTrace(TestSampleImport.class); - + @Autowired(required = true) private ModelService modelService; - + @Autowired(required = true) private PrismContext prismContext; @@ -79,21 +79,21 @@ public TestSampleImport() throws JAXBException { @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + // This should discover the connectors LOGGER.trace("initSystem: trying modelService.postInit()"); modelService.postInit(initResult); LOGGER.trace("initSystem: modelService.postInit() done"); - + PrismObject userAdministrator = repoAddObjectFromFile(USER_ADMINISTRATOR_FILENAME, initResult); - loginSuperUser(userAdministrator); + loginSuperUser(userAdministrator); } - + @Test public void importOpenDJBasic() throws FileNotFoundException, SchemaException { importSample(new File(SAMPLE_DIRECTORY_NAME + "resources/opendj/opendj-localhost-basic.xml"), ResourceType.class, "Basic Localhost OpenDJ"); } - + @Test public void importOpenDJAdvanced() throws FileNotFoundException, SchemaException { importSample(new File(SAMPLE_DIRECTORY_NAME + "resources/opendj/opendj-localhost-resource-sync-advanced.xml"), ResourceType.class, "Localhost OpenDJ"); @@ -104,7 +104,7 @@ public void importOpenDJAdvanced() throws FileNotFoundException, SchemaException // public void importDBTableSimple() throws FileNotFoundException, SchemaException { // importSample(new File(SAMPLE_DIRECTORY_NAME + "databasetable/localhost-dbtable-simple.xml"), ResourceType.class, "Localhost DBTable"); // } - + public void importSample(File sampleFile, Class type, String objectName) throws FileNotFoundException, SchemaException { TestUtil.displayTestTitle(this, "Import sample "+sampleFile.getPath()); // GIVEN @@ -121,18 +121,18 @@ public void importSample(File sampleFile, Class type, display("Result after good import", result); TestUtil.assertSuccessOrWarning("Import has failed (result)", result,1); -// ObjectQuery query = ObjectQuery.createObjectQuery(EqualsFilter.createEqual(type, prismContext, +// ObjectQuery query = ObjectQuery.createObjectQuery(EqualsFilter.createEqual(type, prismContext, // ObjectType.F_NAME, PrismTestUtil.createPolyString(objectName))); // QueryType query = QueryUtil.createNameQuery(objectName); ObjectQuery query = ObjectQueryUtil.createNameQuery(objectName, prismContext); - + List> objects = repositoryService.searchObjects(type, query, null, result); for (PrismObject o : objects) { T object = o.asObjectable(); display("Found object",object); } assertEquals("Unexpected search result: "+objects,1,objects.size()); - + } - + } diff --git a/samples/samples-test/src/test/java/com/evolveum/midpoint/samples/test/TestSamples.java b/samples/samples-test/src/test/java/com/evolveum/midpoint/samples/test/TestSamples.java index 005372caef4..b1c82275582 100644 --- a/samples/samples-test/src/test/java/com/evolveum/midpoint/samples/test/TestSamples.java +++ b/samples/samples-test/src/test/java/com/evolveum/midpoint/samples/test/TestSamples.java @@ -44,7 +44,7 @@ /** * Test validity of the samples in the trunk/samples directory. - * + * * @author Radovan Semancik * */ @@ -57,13 +57,13 @@ public class TestSamples { public static final String[] CHECK_PATTERNS = new String[]{ ".*.xml" }; public static final String OBJECT_RESULT_OPERATION_NAME = TestSamples.class.getName()+".validateObject"; private static final String RESULT_OPERATION_NAME = TestSamples.class.getName()+".validateFile"; - + @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } - + @Test(enabled = false) public void testSamples() throws FileNotFoundException { testSamplesDirectory(new File(SAMPLES_DIRECTORY_NAME)); @@ -97,7 +97,7 @@ private boolean matches(String s, String[] patterns) { } return false; } - + private void validate(File file) throws FileNotFoundException { System.out.println("===> Validating file "+file.getPath()); @@ -112,14 +112,14 @@ public EventResult preMarshall(Element objectElement, Node postValidationTree, @Override public EventResult postMarshall(PrismObject object, Element objectElement, OperationResult objectResult) { - + // Try to marshall it back. This may detect some JAXB miscofiguration problems. try { String serializedString = PrismTestUtil.serializeObjectToString(object, PrismContext.LANG_XML); } catch (SchemaException e) { objectResult.recordFatalError("Object serialization failed", e); } - + return EventResult.cont(); } @@ -127,9 +127,9 @@ public EventResult postMarshall(PrismObject object, El public void handleGlobalError(OperationResult currentResult) { // no reaction } - + }; - + Validator validator = new Validator(PrismTestUtil.getPrismContext()); validator.setVerbose(false); validator.setAllowAnyType(true); @@ -154,9 +154,9 @@ public void handleGlobalError(OperationResult currentResult) { System.out.println("OK"); //System.out.println(result.dump()); } - + System.out.println(); - + } - + } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Abstract389DsDnTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Abstract389DsDnTest.java index b6b7b27fe57..f0a15bf9950 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Abstract389DsDnTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Abstract389DsDnTest.java @@ -43,17 +43,17 @@ * */ public abstract class Abstract389DsDnTest extends Abstract389DsTest { - + @Override public String getPrimaryIdentifierAttributeName() { return "dn"; } - + @Override protected boolean syncCanDetectDelete() { return true; } - + @Override protected boolean isUsingGroupShortcutAttribute() { return false; @@ -63,17 +63,17 @@ protected boolean isUsingGroupShortcutAttribute() { public void test025SchemaDn() throws Exception { final String TEST_NAME = "test025SchemaDn"; TestUtil.displayTestTitle(this, TEST_NAME); - + ResourceAttributeDefinition dnDef = accountObjectClassDefinition.findAttributeDefinition("dn"); display("DN defintion", dnDef); PrismAsserts.assertDefinition(dnDef, new QName(MidPointConstants.NS_RI, "dn"), DOMUtil.XSD_STRING, 1, 1); assertTrue("dn read", dnDef.canRead()); assertTrue("dn modify", dnDef.canModify()); assertTrue("dn add", dnDef.canAdd()); - + assertTrue("Dn is not an identifier", accountObjectClassDefinition.getPrimaryIdentifiers().contains(dnDef)); - assertTrue("Secodary identifiers are not empty: "+accountObjectClassDefinition.getSecondaryIdentifiers(), + assertTrue("Secodary identifiers are not empty: "+accountObjectClassDefinition.getSecondaryIdentifiers(), accountObjectClassDefinition.getSecondaryIdentifiers().isEmpty()); } - + } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Abstract389DsNsUniqueIdTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Abstract389DsNsUniqueIdTest.java index 44194772057..ae9f9a06fd4 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Abstract389DsNsUniqueIdTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Abstract389DsNsUniqueIdTest.java @@ -28,17 +28,17 @@ * */ public abstract class Abstract389DsNsUniqueIdTest extends Abstract389DsTest { - + @Override public String getPrimaryIdentifierAttributeName() { return "nsUniqueId"; } - + @Override protected boolean syncCanDetectDelete() { return false; } - + @Override protected boolean isUsingGroupShortcutAttribute() { return false; diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Abstract389DsTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Abstract389DsTest.java index ee0e5ddc31b..f0eb9105941 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Abstract389DsTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Abstract389DsTest.java @@ -33,12 +33,12 @@ public abstract class Abstract389DsTest extends AbstractLdapConnTest { protected File getBaseDir() { return new File(MidPointTestConstants.TEST_RESOURCES_DIR, "389ds"); } - + @Override protected String getResourceOid() { return "eaee8a88-ce54-11e4-a311-001e8c717e5b"; } - + @Override protected int getLdapServerPort() { return 2389; @@ -53,23 +53,23 @@ protected String getLdapBindDn() { protected String getLdapBindPassword() { return "qwe12345"; } - + @Override protected String getPeopleLdapSuffix() { // The capitalization that 389ds is using return "ou=People,"+getLdapSuffix(); } - + @Override protected String getAccount0Cn() { return "Warlaz Kunjegjul (00000000)"; } - + @Override protected int getSearchSizeLimit() { return 2000; } - + @Override protected String getLdapGroupObjectClass() { return "groupOfUniqueNames"; @@ -89,22 +89,22 @@ protected String getSyncTaskOid() { protected boolean isIdmAdminInteOrgPerson() { return false; } - + @Override public String getPrimaryIdentifierAttributeName() { return "nsUniqueId"; } - + @Override protected boolean syncCanDetectDelete() { return false; } - + @Override protected boolean isVlvSearchBeyondEndResurnsLastEntry() { return true; } - + @Override protected boolean hasAssociationShortcut() { return false; @@ -114,7 +114,7 @@ protected boolean hasAssociationShortcut() { protected void assertStepSyncToken(String syncTaskOid, int step, long tsStart, long tsEnd) throws ObjectNotFoundException, SchemaException { // TODO Auto-generated method stub - + } } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractAdLdapCookedTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractAdLdapCookedTest.java index fc47c565639..cf72aade169 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractAdLdapCookedTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractAdLdapCookedTest.java @@ -30,29 +30,29 @@ /** * Test for Active Directory LDAP-based access. This test is NOT using any raw settings. - * + * * @author semancik */ public abstract class AbstractAdLdapCookedTest extends AbstractAdLdapTest { - + @Test public void test050Capabilities() throws Exception { final String TEST_NAME = "test050Capabilities"; TestUtil.displayTestTitle(this, TEST_NAME); - + Collection nativeCapabilitiesCollection = ResourceTypeUtil.getNativeCapabilitiesCollection(resourceType); display("Native capabilities", nativeCapabilitiesCollection); - + assertTrue("No native activation capability", ResourceTypeUtil.hasResourceNativeActivationCapability(resourceType)); assertTrue("No native activation status capability", ResourceTypeUtil.hasResourceNativeActivationStatusCapability(resourceType)); // assertTrue("No native lockout capability", ResourceTypeUtil.hasResourceNativeActivationLockoutCapability(resourceType)); assertTrue("No native credentias capability", ResourceTypeUtil.isCredentialsCapabilityEnabled(resourceType)); } - + protected void assertAccountDisabled(PrismObject shadow) { assertAdministrativeStatus(shadow, ActivationStatusType.DISABLED); } - + protected void assertAccountEnabled(PrismObject shadow) { assertAdministrativeStatus(shadow, ActivationStatusType.ENABLED); } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractAdLdapMultidomainTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractAdLdapMultidomainTest.java index 32f2f2d5a4a..beec76467d4 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractAdLdapMultidomainTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractAdLdapMultidomainTest.java @@ -93,40 +93,40 @@ */ @Listeners({com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class}) public abstract class AbstractAdLdapMultidomainTest extends AbstractLdapTest { - + 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"; - + public static final String ATTRIBUTE_OBJECT_GUID_NAME = "objectGUID"; public static final String ATTRIBUTE_SAM_ACCOUNT_NAME_NAME = "sAMAccountName"; public static final String ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME = "userAccountControl"; public static final QName ATTRIBUTE_USER_ACCOUNT_CONTROL_QNAME = new QName(MidPointConstants.NS_RI, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME); public static final String ATTRIBUTE_UNICODE_PWD_NAME = "unicodePwd"; public static final String ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME = "msExchHideFromAddressLists"; - + 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"; 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 = 17; private static final String ASSOCIATION_GROUP_NAME = "group"; @@ -145,7 +145,7 @@ public abstract class AbstractAdLdapMultidomainTest extends AbstractLdapTest { 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"; @@ -157,9 +157,9 @@ public abstract class AbstractAdLdapMultidomainTest extends AbstractLdapTest { private static final String INTENT_OU_TOP = "ou-top"; private static final String USER_EMPTYHEAD_NAME = "emptyhead"; - + private boolean allowDuplicateSearchResults = false; - + protected String jackAccountOid; protected String groupPiratesOid; protected long jackLockoutTimestamp; @@ -173,7 +173,7 @@ public abstract class AbstractAdLdapMultidomainTest extends AbstractLdapTest { private String accountSubmanOid; private String accountSubmarineOid; - + @Override public String getStartSystemCommand() { return null; @@ -193,7 +193,7 @@ protected File getBaseDir() { protected String getSyncTaskOid() { return "cd1e0ff2-0099-11e5-9e22-001e8c717e5b"; } - + @Override protected boolean useSsl() { return true; @@ -218,22 +218,22 @@ protected String getLdapBindPassword() { 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"; } @@ -241,7 +241,7 @@ protected String getLdapSubSuffix() { protected String getPeopleLdapSubSuffix() { return "CN=Users,"+getLdapSubSuffix(); } - + @Override protected String getLdapAccountObjectClass() { return "user"; @@ -256,25 +256,25 @@ protected String getLdapGroupObjectClass() { 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"); @@ -284,33 +284,33 @@ private UserLdapConnectionConfig getSubLdapConnectionConfig() { config.setBaseContext(getLdapSubSuffix()); return config; } - + @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_PIRATES_FILE, initResult); repoAddObjectFromFile(ROLE_SUBMISSIVE_FILE, initResult); repoAddObjectFromFile(ROLE_META_ORG_FILE, initResult); repoAddObjectFromFile(ROLE_META_ORG_GROUP_FILE, initResult); - + } - + @Test public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; displayTestTitle(TEST_NAME); - + 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)); @@ -331,59 +331,59 @@ public void test000Sanity() throws Exception { public void test020Schema() throws Exception { final String TEST_NAME = "test020Schema"; displayTestTitle(TEST_NAME); - + // IntegrationTestTools.displayXml("Resource XML", resource); accountObjectClassDefinition = AdUtils.assertAdResourceSchema(resource, getAccountObjectClass(), prismContext); AdUtils.assertAdRefinedSchema(resource, getAccountObjectClass(), prismContext); AdUtils.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 { final String TEST_NAME = "test100SeachJackBySamAccountName"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); 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 displayWhen(TEST_NAME); SearchResultList> shadows = modelService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN displayThen(TEST_NAME); 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(); - + // assertConnectorOperationIncrement(2); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + SearchResultMetadata metadata = shadows.getMetadata(); if (metadata != null) { assertFalse(metadata.isPartialResults()); } - + assertLdapConnectorInstances(1); } - + /** * MID-3730 */ @@ -391,161 +391,161 @@ public void test100SeachJackBySamAccountName() throws Exception { public void test101SeachJackByDn() throws Exception { final String TEST_NAME = "test101SeachJackByDn"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); 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 displayWhen(TEST_NAME); SearchResultList> shadows = modelService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertEquals("Unexpected search result: "+shadows, 1, shadows.size()); - + PrismObject shadow = shadows.get(0); display("Shadow", shadow); assertAccountShadow(shadow, jackDn); - + // 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 { final String TEST_NAME = "test102SeachNotExistByDn"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); 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 displayWhen(TEST_NAME); SearchResultList> shadows = modelService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.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 { final String TEST_NAME = "test105SeachPiratesByCn"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getGroupObjectClass(), prismContext); ObjectQueryUtil.filterAnd(query.getFilter(), createAttributeFilter("cn", GROUP_PIRATES_NAME)); - + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - + // WHEN displayWhen(TEST_NAME); 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(); - + // 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 { final String TEST_NAME = "test110GetJack"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - + // WHEN displayWhen(TEST_NAME); PrismObject shadow = modelService.getObject(ShadowType.class, jackAccountOid, null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); - TestUtil.assertSuccess(result); + 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=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); 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. */ @@ -553,32 +553,32 @@ public void test110GetJack() throws Exception { public void test150SeachAllAccounts() throws Exception { final String TEST_NAME = "test150SeachAllAccounts"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); 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(TEST_NAME, query, + SearchResultList> searchResultList = doSearch(TEST_NAME, query, NUMBER_OF_ACCOUNTS, task, result); - + // TODO: why 11? should be 1 // assertConnectorOperationIncrement(11); 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. */ @@ -586,30 +586,30 @@ public void test150SeachAllAccounts() throws Exception { public void test152SeachFirst2Accounts() throws Exception { final String TEST_NAME = "test152SeachFirst2Accounts"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - + ObjectPaging paging = ObjectPaging.createEmptyPaging(); paging.setMaxSize(2); query.setPaging(paging); - + SearchResultList> searchResultList = doSearch(TEST_NAME, query, 2, task, result); - + // assertConnectorOperationIncrement(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. // */ @@ -617,59 +617,59 @@ public void test152SeachFirst2Accounts() throws Exception { // public void test154SeachFirst11Accounts() throws Exception { // final String TEST_NAME = "test154SeachFirst11Accounts"; // displayTestTile(TEST_NAME); -// +// // // GIVEN // Task task = createTask(TEST_NAME); // OperationResult result = task.getResult(); -// +// // ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); -// +// // ObjectPaging paging = ObjectPaging.createEmptyPaging(); // paging.setMaxSize(11); // query.setPaging(paging); -// +// // SearchResultList> searchResultList = doSearch(TEST_NAME, query, 11, task, result); -// +// // assertConnectorOperationIncrement(1); // assertConnectorSimulatedPagingSearchIncrement(0); -// +// // SearchResultMetadata metadata = searchResultList.getMetadata(); // if (metadata != null) { // assertFalse(metadata.isPartialResults()); // } -// +// // assertLdapConnectorInstances(2); // } -// +// // @Test // public void test162SeachFirst2AccountsOffset0() throws Exception { // final String TEST_NAME = "test162SeachFirst2AccountsOffset0"; // displayTestTile(TEST_NAME); -// +// // // GIVEN // Task task = createTask(TEST_NAME); // OperationResult result = task.getResult(); -// +// // ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); -// +// // ObjectPaging paging = ObjectPaging.createEmptyPaging(); // paging.setOffset(0); // paging.setMaxSize(2); // query.setPaging(paging); -// +// // SearchResultList> searchResultList = doSearch(TEST_NAME, query, 2, task, result); -// +// // assertConnectorOperationIncrement(1); // assertConnectorSimulatedPagingSearchIncrement(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. @@ -679,29 +679,29 @@ public void test152SeachFirst2Accounts() throws Exception { // public void test172Search2AccountsOffset1() throws Exception { // final String TEST_NAME = "test172Search2AccountsOffset1"; // displayTestTile(TEST_NAME); -// +// // // GIVEN // Task task = createTask(TEST_NAME); // OperationResult result = task.getResult(); -// +// // ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); -// +// // ObjectPaging paging = ObjectPaging.createPaging(1, 2); // query.setPaging(paging); -// +// // SearchResultList> searchResultList = doSearch(TEST_NAME, query, 2, task, result); -// +// // assertConnectorOperationIncrement(1); // assertConnectorSimulatedPagingSearchIncrement(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. @@ -711,35 +711,35 @@ public void test152SeachFirst2Accounts() throws Exception { // public void test174SeachFirst11AccountsOffset2() throws Exception { // final String TEST_NAME = "test174SeachFirst11AccountsOffset2"; // displayTestTile(TEST_NAME); -// +// // // GIVEN // Task task = createTask(TEST_NAME); // OperationResult result = task.getResult(); -// +// // ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); -// +// // ObjectPaging paging = ObjectPaging.createPaging(2, 11); // query.setPaging(paging); -// +// // allowDuplicateSearchResults = true; -// +// // // WHEN // SearchResultList> searchResultList = doSearch(TEST_NAME, query, 11, task, result); -// +// // // THEN // allowDuplicateSearchResults = false; -// +// // assertConnectorOperationIncrement(1); // assertConnectorSimulatedPagingSearchIncrement(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. @@ -749,25 +749,25 @@ public void test152SeachFirst2Accounts() throws Exception { // public void test182Search2AccountsOffset1SortCn() throws Exception { // final String TEST_NAME = "test182Search2AccountsOffset1SortCn"; // displayTestTile(TEST_NAME); -// +// // // GIVEN // Task task = createTask(TEST_NAME); // OperationResult result = task.getResult(); -// +// // ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); -// +// // ObjectPaging paging = ObjectPaging.createPaging(1, 2); // paging.setOrdering(getAttributePath(resource, "cn"), OrderDirection.ASCENDING); // query.setPaging(paging); -// +// // SearchResultList> shadows = doSearch(TEST_NAME, query, 2, task, result); -// +// // assertAccountShadow(shadows.get(0), "CN=Adalbert Meduza,OU=evolveum,DC=win,DC=evolveum,DC=com"); // assertAccountShadow(shadows.get(1), "CN=Adalbert Meduza1,OU=evolveum,DC=win,DC=evolveum,DC=com"); -// +// // assertConnectorOperationIncrement(1); // assertConnectorSimulatedPagingSearchIncrement(0); -// +// // SearchResultMetadata metadata = shadows.getMetadata(); // if (metadata != null) { // assertFalse(metadata.isPartialResults()); @@ -775,31 +775,31 @@ public void test152SeachFirst2Accounts() throws Exception { // // assertLdapConnectorInstances(2); // } - + @Test public void test200AssignAccountBarbossa() throws Exception { final String TEST_NAME = "test200AssignAccountBarbossa"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); long tsStart = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); assignAccount(USER_BARBOSSA_OID, getResourceOid(), null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.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); @@ -808,15 +808,15 @@ public void test200AssignAccountBarbossa() throws Exception { Collection> identifiers = ShadowUtil.getPrimaryIdentifiers(shadow); String accountBarbossaIcfUid = (String) identifiers.iterator().next().getRealValue(); assertNotNull("No identifier in "+shadow, accountBarbossaIcfUid); - - assertEquals("Wrong ICFS UID", + + assertEquals("Wrong ICFS UID", AdUtils.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"); - + ResourceAttribute createTimestampAttribute = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, "createTimeStamp")); assertNotNull("No createTimestamp in "+shadow, createTimestampAttribute); String createTimestamp = createTimestampAttribute.getRealValue(); @@ -824,10 +824,10 @@ public void test200AssignAccountBarbossa() throws Exception { long createTimestampMillis = createTimestampGt.getCalendar().getTimeInMillis(); // 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 test210ModifyAccountBarbossaTitle() throws Exception { final String TEST_NAME = "test210ModifyAccountBarbossaTitle"; @@ -836,18 +836,18 @@ public void test210ModifyAccountBarbossaTitle() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta delta = ObjectDelta.createEmptyModifyDelta(ShadowType.class, accountBarbossaOid, prismContext); QName attrQName = new QName(MidPointConstants.NS_RI, "title"); ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); PropertyDelta attrDelta = PropertyDelta.createModificationReplaceProperty( new ItemPath(ShadowType.F_ATTRIBUTES, attrQName), attrDef, "Captain"); delta.addModification(attrDelta); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -856,14 +856,14 @@ public void test210ModifyAccountBarbossaTitle() throws Exception { 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 { final String TEST_NAME = "test212ModifyAccountBarbossaShowInAdvancedViewOnlyTrue"; @@ -872,18 +872,18 @@ public void test212ModifyAccountBarbossaShowInAdvancedViewOnlyTrue() throws Exce // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta delta = ObjectDelta.createEmptyModifyDelta(ShadowType.class, accountBarbossaOid, prismContext); QName attrQName = new QName(MidPointConstants.NS_RI, "showInAdvancedViewOnly"); ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); PropertyDelta attrDelta = PropertyDelta.createModificationReplaceProperty( new ItemPath(ShadowType.F_ATTRIBUTES, attrQName), attrDef, Boolean.TRUE); delta.addModification(attrDelta); - + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); @@ -891,14 +891,14 @@ public void test212ModifyAccountBarbossaShowInAdvancedViewOnlyTrue() throws Exce 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. */ @@ -910,21 +910,21 @@ public void test213ModifyUserBarbossaShowInAdvancedViewOnlyFalse() throws Except // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - - + + ObjectDelta delta = ObjectDelta.createEmptyModifyDelta(ShadowType.class, accountBarbossaOid, prismContext); QName attrQName = new QName(MidPointConstants.NS_RI, "showInAdvancedViewOnly"); ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); PropertyDelta attrDelta = PropertyDelta.createModificationReplaceProperty( new ItemPath(ShadowType.F_ATTRIBUTES, attrQName), attrDef, Boolean.TRUE); delta.addModification(attrDelta); - + // WHEN displayWhen(TEST_NAME); - modifyUserReplace(USER_BARBOSSA_OID, - new ItemPath(UserType.F_EXTENSION, EXTENSION_SHOW_IN_ADVANCED_VIEW_ONLY_QNAME), + modifyUserReplace(USER_BARBOSSA_OID, + new ItemPath(UserType.F_EXTENSION, EXTENSION_SHOW_IN_ADVANCED_VIEW_ONLY_QNAME), task, result, Boolean.FALSE); - + // THEN displayThen(TEST_NAME); assertSuccess(result); @@ -932,14 +932,14 @@ public void test213ModifyUserBarbossaShowInAdvancedViewOnlyFalse() throws Except 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 { final String TEST_NAME = "test220ModifyUserBarbossaPassword"; @@ -948,25 +948,25 @@ public void test220ModifyUserBarbossaPassword() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ProtectedStringType userPasswordPs = new ProtectedStringType(); userPasswordPs.setClearValue("here.There.Be.Monsters"); - + // WHEN displayWhen(TEST_NAME); - modifyUserReplace(USER_BARBOSSA_OID, - new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), + modifyUserReplace(USER_BARBOSSA_OID, + new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), task, result, userPasswordPs); - + // THEN displayThen(TEST_NAME); assertSuccess(result); assertBarbossaEnabled(); - + assertLdapConnectorInstances(2); } - + @Test public void test230DisableUserBarbossa() throws Exception { final String TEST_NAME = "test230DisableUserBarbossa"; @@ -975,20 +975,20 @@ public void test230DisableUserBarbossa() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); - modifyUserReplace(USER_BARBOSSA_OID, - SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, + modifyUserReplace(USER_BARBOSSA_OID, + SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, task, result, ActivationStatusType.DISABLED); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + assertBarbossaDisabled(); } - + /** * MID-4041 */ @@ -1000,15 +1000,15 @@ public void test232ReconcileBarbossa() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_BARBOSSA_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + assertBarbossaDisabled(); } @@ -1023,22 +1023,22 @@ public void test236EnableUserBarbossa() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); - modifyUserReplace(USER_BARBOSSA_OID, - SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, + modifyUserReplace(USER_BARBOSSA_OID, + SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, task, result, ActivationStatusType.ENABLED); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + assertBarbossaEnabled(); - + assertLdapConnectorInstances(2); } - + /** * MID-4041 */ @@ -1050,20 +1050,20 @@ public void test237ReconcileBarbossa() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_BARBOSSA_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + assertBarbossaEnabled(); - + assertLdapConnectorInstances(2); } - + /** * MID-4041 */ @@ -1075,23 +1075,23 @@ public void test238DisableUserBarbossaRawAndReconcile() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + modifyUserReplace(USER_BARBOSSA_OID, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, ModelExecuteOptions.createRaw(), task, result, ActivationStatusType.DISABLED); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_BARBOSSA_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + assertBarbossaDisabled(); - + assertLdapConnectorInstances(2); } - + /** * MID-4041 */ @@ -1103,65 +1103,65 @@ public void test239EnableUserBarbossaRawAndReconcile() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + modifyUserReplace(USER_BARBOSSA_OID, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, ModelExecuteOptions.createRaw(), task, result, ActivationStatusType.ENABLED); - + // WHEN displayWhen(TEST_NAME); reconcileUser(USER_BARBOSSA_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + assertBarbossaEnabled(); - + assertLdapConnectorInstances(2); } - + private PrismObject assertBarbossaEnabled() 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"); + assertAttribute(entry, ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME, "FALSE"); assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, "here.There.Be.Monsters"); - + String shadowOid = getSingleLinkOid(user); PrismObject shadow = getObject(ShadowType.class, shadowOid); assertAccountEnabled(shadow); - + assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - + return user; } - + private void assertBarbossaDisabled() 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(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, "here.There.Be.Monsters"); AssertJUnit.fail("Password authentication works, but it should fail"); } catch (SecurityException e) { // this is expected } - + assertLdapConnectorInstances(2); } @@ -1172,19 +1172,19 @@ private void assertBarbossaDisabled() throws Exception { public void test250AssignGuybrushPirates() throws Exception { final String TEST_NAME = "test250AssignGuybrushPirates"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - - modifyUserReplace(USER_GUYBRUSH_OID, - SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, + + modifyUserReplace(USER_GUYBRUSH_OID, + SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, task, result, ActivationStatusType.DISABLED); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_PIRATES_OID, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); @@ -1192,20 +1192,20 @@ public void test250AssignGuybrushPirates() throws Exception { 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 { final String TEST_NAME = "test255ModifyUserGuybrushPassword"; @@ -1214,16 +1214,16 @@ public void test255ModifyUserGuybrushPassword() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ProtectedStringType userPasswordPs = new ProtectedStringType(); userPasswordPs.setClearValue("wanna.be.a.123"); - + // WHEN displayWhen(TEST_NAME); - modifyUserReplace(USER_GUYBRUSH_OID, - new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), + modifyUserReplace(USER_GUYBRUSH_OID, + new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), task, result, userPasswordPs); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1238,10 +1238,10 @@ public void test255ModifyUserGuybrushPassword() throws Exception { } catch (SecurityException e) { // this is expected, account is disabled } - + // assertLdapConnectorInstances(2); } - + @Test public void test260EnableGyubrush() throws Exception { final String TEST_NAME = "test260EnableGyubrush"; @@ -1250,32 +1250,32 @@ public void test260EnableGyubrush() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); - modifyUserReplace(USER_GUYBRUSH_OID, - SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, + modifyUserReplace(USER_GUYBRUSH_OID, + SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, task, result, ActivationStatusType.ENABLED); - + // THEN displayThen(TEST_NAME); 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. @@ -1285,29 +1285,29 @@ public void test260EnableGyubrush() throws Exception { public void test270AssignAccountToEmptyhead() throws Exception { final String TEST_NAME = "test270AssignAccountToEmptyhead"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); 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 displayWhen(TEST_NAME); assignAccount(userEmptyheadOid, getResourceOid(), null, task, result); - + // THEN displayThen(TEST_NAME); 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. @@ -1320,16 +1320,16 @@ public void test295TestConnection() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); OperationResult testResult = modelService.testResource(getResourceOid(), task); - + // THEN displayThen(TEST_NAME); display("Test connection result", testResult); TestUtil.assertSuccess("Test connection result", testResult); - + assertLdapConnectorInstances(2); } @@ -1337,15 +1337,15 @@ public void test295TestConnection() throws Exception { public void test300AssignBarbossaPirates() throws Exception { final String TEST_NAME = "test300AssignBarbossaPirates"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_BARBOSSA_OID, ROLE_PIRATES_OID, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1354,19 +1354,19 @@ public void test300AssignBarbossaPirates() throws Exception { 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 { final String TEST_NAME = "test390ModifyUserBarbossaRename"; @@ -1375,18 +1375,18 @@ public void test390ModifyUserBarbossaRename() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - - ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_BARBOSSA_OID, UserType.F_NAME, + + 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 displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1394,39 +1394,39 @@ public void test390ModifyUserBarbossaRename() throws Exception { 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 { final String TEST_NAME = "test395UnAssignBarbossaPirates"; displayTestTitle(TEST_NAME); // TODO: do this on another account. There is a bad interference with rename. - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_BARBOSSA_OID, ROLE_PIRATES_OID, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1435,19 +1435,19 @@ public void test395UnAssignBarbossaPirates() throws Exception { 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 { final String TEST_NAME = "test399UnAssignAccountBarbossa"; @@ -1456,11 +1456,11 @@ public void test399UnAssignAccountBarbossa() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); unassignAccount(USER_BARBOSSA_OID, getResourceOid(), null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1468,13 +1468,13 @@ public void test399UnAssignAccountBarbossa() throws Exception { 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 { final String TEST_NAME = "test500AddOrgMeleeIsland"; @@ -1483,7 +1483,7 @@ public void test500AddOrgMeleeIsland() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject org = instantiateObject(OrgType.class); OrgType orgType = org.asObjectable(); orgType.setName(new PolyStringType(GROUP_MELEE_ISLAND_NAME)); @@ -1493,11 +1493,11 @@ public void test500AddOrgMeleeIsland() throws Exception { metaroleRef.setType(RoleType.COMPLEX_TYPE); metaroleAssignment.setTargetRef(metaroleRef); orgType.getAssignment().add(metaroleAssignment); - + // WHEN displayWhen(TEST_NAME); addObject(org, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1506,53 +1506,53 @@ public void test500AddOrgMeleeIsland() throws Exception { orgMeleeIslandOid = org.getOid(); Entry entryGroup = assertLdapGroup(GROUP_MELEE_ISLAND_NAME); Entry entryOu = 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 { final String TEST_NAME = "test510AssignGuybrushMeleeIsland"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); assignOrg(USER_GUYBRUSH_OID, orgMeleeIslandOid, task, result); - + // THEN displayThen(TEST_NAME); 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. */ @@ -1564,29 +1564,29 @@ public void test515AddOrgGroupMeleeIslandPirates() throws Exception { // GIVEN Task task = createTask(TEST_NAME); 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 displayWhen(TEST_NAME); addObject(role, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1594,18 +1594,18 @@ public void test515AddOrgGroupMeleeIslandPirates() throws Exception { roleMeleeIslandPiratesOid = role.getOid(); // TODO: assert LDAP object - + Entry entryOrgGroup = 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); - + // assertLdapConnectorInstances(2); } - + /** * Rename org unit. MidPoint should rename OU and ordinary group. * AD will rename the group in the orgstruct automatically. We need to @@ -1615,88 +1615,88 @@ public void test515AddOrgGroupMeleeIslandPirates() throws Exception { public void test520RenameMeleeIsland() throws Exception { final String TEST_NAME = "test520RenameMeleeIsland"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); renameObject(OrgType.class, orgMeleeIslandOid, GROUP_MELEE_ISLAND_ALT_NAME, task, result); - + // THEN displayThen(TEST_NAME); 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); - + Entry groupEntry = assertLdapGroup(GROUP_MELEE_ISLAND_ALT_NAME); assertNoLdapGroup(GROUP_MELEE_ISLAND_NAME); - + Entry entryOu = assertLdapOrg(GROUP_MELEE_ISLAND_ALT_NAME); assertNoLdapOrg(GROUP_MELEE_ISLAND_NAME); - + Entry entryOrgGroup = 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. + * for that. It will transparently fix the situation. */ @Test public void test522ModifyMeleeIslandPirates() throws Exception { final String TEST_NAME = "test522GetMeleeIslandPirates"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); - modifyObjectReplaceProperty(ShadowType.class, groupMeleeIslandPiratesOid, + modifyObjectReplaceProperty(ShadowType.class, groupMeleeIslandPiratesOid, new ItemPath(ShadowType.F_ATTRIBUTES, new QName(MidPointConstants.NS_RI, "description")), task, result, GROUP_MELEE_ISLAND_PIRATES_DESCRIPTION); - + // THEN displayThen(TEST_NAME); 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); } @@ -1704,30 +1704,30 @@ public void test522ModifyMeleeIslandPirates() throws Exception { public void test524GetMeleeIslandPirates() throws Exception { final String TEST_NAME = "test524GetMeleeIslandPirates"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); PrismObject shadow = modelService.getObject(ShadowType.class, groupMeleeIslandPiratesOid, null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + display("Shadow after", shadow); assertNotNull(shadow); - + Entry groupEntry = assertLdapGroup(GROUP_MELEE_ISLAND_ALT_NAME); assertNoLdapGroup(GROUP_MELEE_ISLAND_NAME); Entry entryOu = assertLdapOrg(GROUP_MELEE_ISLAND_ALT_NAME); assertNoLdapOrg(GROUP_MELEE_ISLAND_NAME); Entry entryOrgGroup = assertLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_ALT_NAME); assertNoLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_NAME); - + // assertLdapConnectorInstances(2); } @@ -1739,11 +1739,11 @@ public void test595DeleteOrgGroupMeleeIslandPirates() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); deleteObject(RoleType.class, roleMeleeIslandPiratesOid, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1751,12 +1751,12 @@ public void test595DeleteOrgGroupMeleeIslandPirates() throws Exception { 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); } - + @Test public void test599DeleteOrgMeleeIsland() throws Exception { final String TEST_NAME = "test599DeleteOrgMeleeIsland"; @@ -1765,11 +1765,11 @@ public void test599DeleteOrgMeleeIsland() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); deleteObject(OrgType.class, orgMeleeIslandOid, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1779,39 +1779,39 @@ public void test599DeleteOrgMeleeIsland() throws Exception { 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); } - + @Test public void test600AssignAccountSubman() throws Exception { final String TEST_NAME = "test600AssignAccountSubman"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + long tsStart = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_SUBMAN_OID, ROLE_SUBMISSIVE_OID, task, result); - + // THEN displayThen(TEST_NAME); 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); @@ -1820,15 +1820,15 @@ public void test600AssignAccountSubman() throws Exception { Collection> identifiers = ShadowUtil.getPrimaryIdentifiers(shadow); String accountBarbossaIcfUid = (String) identifiers.iterator().next().getRealValue(); assertNotNull("No identifier in "+shadow, accountBarbossaIcfUid); - - assertEquals("Wrong ICFS UID", + + assertEquals("Wrong ICFS UID", AdUtils.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"); - + ResourceAttribute createTimestampAttribute = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, "createTimeStamp")); assertNotNull("No createTimestamp in "+shadow, createTimestampAttribute); String createTimestamp = createTimestampAttribute.getRealValue(); @@ -1836,10 +1836,10 @@ public void test600AssignAccountSubman() throws Exception { long createTimestampMillis = createTimestampGt.getCalendar().getTimeInMillis(); // 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 { final String TEST_NAME = "test610ModifyUserSubmanTitle"; @@ -1848,29 +1848,29 @@ public void test610ModifyUserSubmanTitle() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); - modifyUserReplace(USER_SUBMAN_OID, UserType.F_TITLE, task, result, + modifyUserReplace(USER_SUBMAN_OID, UserType.F_TITLE, task, result, PrismTestUtil.createPolyString("Underdog")); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.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 { final String TEST_NAME = "test620ModifyUserSubmanPassword"; @@ -1879,16 +1879,16 @@ public void test620ModifyUserSubmanPassword() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ProtectedStringType userPasswordPs = new ProtectedStringType(); userPasswordPs.setClearValue("SuB.321"); - + // WHEN displayWhen(TEST_NAME); - modifyUserReplace(USER_SUBMAN_OID, - new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), + modifyUserReplace(USER_SUBMAN_OID, + new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), task, result, userPasswordPs); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1898,14 +1898,14 @@ public void test620ModifyUserSubmanPassword() throws Exception { 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 { final String TEST_NAME = "test630DisableUserSubman"; @@ -1914,37 +1914,37 @@ public void test630DisableUserSubman() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); - modifyUserReplace(USER_SUBMAN_OID, - SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, + modifyUserReplace(USER_SUBMAN_OID, + SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, task, result, ActivationStatusType.DISABLED); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.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); } @@ -1956,31 +1956,31 @@ public void test639EnableUserSubman() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); - modifyUserReplace(USER_SUBMAN_OID, - SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, + modifyUserReplace(USER_SUBMAN_OID, + SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, task, result, ActivationStatusType.ENABLED); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.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 { final String TEST_NAME = "test690ModifyUserSubmanRename"; @@ -1989,18 +1989,18 @@ public void test690ModifyUserSubmanRename() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - - ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_SUBMAN_OID, UserType.F_NAME, + + ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_SUBMAN_OID, UserType.F_NAME, PrismTestUtil.createPolyString(USER_SUBDOG_USERNAME)); objectDelta.addModificationReplaceProperty(UserType.F_FULL_NAME, PrismTestUtil.createPolyString(USER_SUBDOG_FULL_NAME)); Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); - - + + // WHEN displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -2008,21 +2008,21 @@ public void test690ModifyUserSubmanRename() throws Exception { 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 { final String TEST_NAME = "test699UnAssignAccountSubdog"; @@ -2031,11 +2031,11 @@ public void test699UnAssignAccountSubdog() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_SUBMAN_OID, ROLE_SUBMISSIVE_OID, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -2043,13 +2043,13 @@ public void test699UnAssignAccountSubdog() throws Exception { 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 @@ -2060,31 +2060,31 @@ public void test699UnAssignAccountSubdog() throws Exception { public void test700AssignAccountSubmarineAndModify() throws Exception { final String TEST_NAME = "test700AssignAccountSubmarineAndModify"; displayTestTitle(TEST_NAME); - + // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + long tsStart = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_SUBMARINE_OID, ROLE_SUBMISSIVE_OID, task, result); - - modifyUserReplace(USER_SUBMARINE_OID, UserType.F_TITLE, task, result, + + modifyUserReplace(USER_SUBMARINE_OID, UserType.F_TITLE, task, result, PrismTestUtil.createPolyString("Underseadog")); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + long tsEnd = System.currentTimeMillis(); 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); @@ -2093,16 +2093,16 @@ public void test700AssignAccountSubmarineAndModify() throws Exception { Collection> identifiers = ShadowUtil.getPrimaryIdentifiers(shadow); String accountIcfUid = (String) identifiers.iterator().next().getRealValue(); assertNotNull("No identifier in "+shadow, accountIcfUid); - - assertEquals("Wrong ICFS UID", + + assertEquals("Wrong ICFS UID", AdUtils.formatGuidToDashedNotation(MiscUtil.binaryToHex(entry.get(getPrimaryIdentifierAttributeName()).getBytes())), accountIcfUid); - + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - + // assertLdapConnectorInstances(2); } - + @Test public void test809UnAssignAccountSubmarine() throws Exception { final String TEST_NAME = "test809UnAssignAccountSubmarine"; @@ -2111,24 +2111,24 @@ public void test809UnAssignAccountSubmarine() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_SUBMARINE_OID, ROLE_SUBMISSIVE_OID, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); assertNoLdapSubAccount(USER_SUBMARINE_USERNAME, USER_SUBMARINE_FULL_NAME); - + PrismObject user = getUser(USER_SUBMARINE_OID); assertNoLinkedAccount(user); - + // assertLdapConnectorInstances(2); } - + @Override protected void assertAccountShadow(PrismObject shadow, String dn) throws SchemaException { super.assertAccountShadow(shadow, dn); @@ -2145,7 +2145,7 @@ protected Entry assertLdapAccount(String samAccountName, String cn) throws LdapE 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); @@ -2157,15 +2157,15 @@ protected Entry assertLdapSubAccount(String samAccountName, String cn) throws Ld protected void assertNoLdapAccount(String uid) throws LdapException, IOException, CursorException { 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+")"); @@ -2180,16 +2180,16 @@ protected void assertNoLdapAccount(UserLdapConnectionConfig config, String uid, 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 { @@ -2198,11 +2198,11 @@ protected Rdn toAccountRdn(String username, String fullName) { 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); } @@ -2214,14 +2214,14 @@ protected Entry assertLdapOrg(String orgName) throws LdapException, IOException, 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); @@ -2229,18 +2229,18 @@ protected Entry assertLdapOrgGroup(String groupCn, String orgName) throws LdapEx 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); @@ -2255,7 +2255,7 @@ protected ObjectQuery createSamAccountNameQuery(String samAccountName) throws Sc ObjectQueryUtil.filterAnd(query.getFilter(), createAttributeFilter(ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, samAccountName)); return query; } - + @Override protected Entry createAccountEntry(String uid, String cn, String givenName, String sn) throws LdapException { byte[] password = encodePassword("Secret.123"); @@ -2269,7 +2269,7 @@ protected Entry createAccountEntry(String uid, String cn, String givenName, Stri ATTRIBUTE_UNICODE_PWD_NAME, password); return entry; } - + private byte[] encodePassword(String password) { String quotedPassword = "\"" + password + "\""; try { @@ -2282,13 +2282,13 @@ private byte[] encodePassword(String password) { 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/AbstractAdLdapRawTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractAdLdapRawTest.java index 01e31aceec2..1f94c2bc72f 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractAdLdapRawTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractAdLdapRawTest.java @@ -33,30 +33,30 @@ /** * Test for Active Directory LDAP-based access. This test is using raw userAccountControl. - * + * * @author semancik */ public abstract class AbstractAdLdapRawTest extends AbstractAdLdapTest { - + @Test public void test050Capabilities() throws Exception { final String TEST_NAME = "test050Capabilities"; TestUtil.displayTestTitle(this, TEST_NAME); - + Collection nativeCapabilitiesCollection = ResourceTypeUtil.getNativeCapabilitiesCollection(resourceType); display("Native capabilities", nativeCapabilitiesCollection); - + assertFalse("No native activation capability", ResourceTypeUtil.hasResourceNativeActivationCapability(resourceType)); assertFalse("No native activation status capability", ResourceTypeUtil.hasResourceNativeActivationStatusCapability(resourceType)); assertFalse("No native lockout capability", ResourceTypeUtil.hasResourceNativeActivationLockoutCapability(resourceType)); assertTrue("No native credentias capability", ResourceTypeUtil.isCredentialsCapabilityEnabled(resourceType)); } - + protected void assertAccountDisabled(PrismObject shadow) { PrismAsserts.assertPropertyValue(shadow, new ItemPath(ShadowType.F_ATTRIBUTES, ATTRIBUTE_USER_ACCOUNT_CONTROL_QNAME), 514); } - + protected void assertAccountEnabled(PrismObject shadow) { PrismAsserts.assertPropertyValue(shadow, new ItemPath(ShadowType.F_ATTRIBUTES, ATTRIBUTE_USER_ACCOUNT_CONTROL_QNAME), 512); } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractAdLdapTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractAdLdapTest.java index 75cd1d07646..db16e86a8e0 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractAdLdapTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractAdLdapTest.java @@ -96,41 +96,41 @@ */ @Listeners({com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class}) public abstract class AbstractAdLdapTest extends AbstractLdapSynchronizationTest { - + 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 = 25; 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 long jackLockoutTimestamp; protected String accountBarbossaOid; protected String orgMeleeIslandOid; protected String groupMeleeOid; - + @Override public String getStartSystemCommand() { return null; @@ -150,7 +150,7 @@ protected File getBaseDir() { protected String getSyncTaskOid() { return "cd1e0ff2-0099-11e5-9e22-001e8c717e5b"; } - + @Override protected boolean useSsl() { return true; @@ -175,17 +175,17 @@ protected String getLdapBindPassword() { 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(); @@ -205,50 +205,50 @@ protected String getLdapGroupObjectClass() { 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; } - + @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 { final String TEST_NAME = "test000Sanity"; TestUtil.displayTestTitle(this, TEST_NAME); super.test000Sanity(); - + 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)); @@ -262,133 +262,133 @@ public void test000Sanity() throws Exception { public void test020Schema() throws Exception { final String TEST_NAME = "test020Schema"; TestUtil.displayTestTitle(this, TEST_NAME); - + accountObjectClassDefinition = AdUtils.assertAdResourceSchema(resource, getAccountObjectClass(), prismContext); - + assertLdapConnectorInstances(1); } - + // test050 in subclasses - + @Test public void test100SeachJackBySamAccountName() throws Exception { final String TEST_NAME = "test100SeachJackBySamAccountName"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); 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 TestUtil.displayWhen(TEST_NAME); 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 { final String TEST_NAME = "test105SeachPiratesByCn"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getGroupObjectClass(), prismContext); ObjectQueryUtil.filterAnd(query.getFilter(), createAttributeFilter("cn", GROUP_PIRATES_NAME)); - + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); 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 { final String TEST_NAME = "test110GetJack"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject shadow = modelService.getObject(ShadowType.class, jackAccountOid, null, task, result); - + // THEN result.computeStatus(); - TestUtil.assertSuccess(result); + 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. */ @@ -396,32 +396,32 @@ public void test110GetJack() throws Exception { public void test150SeachAllAccounts() throws Exception { final String TEST_NAME = "test150SeachAllAccounts"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); 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(TEST_NAME, query, + SearchResultList> searchResultList = doSearch(TEST_NAME, query, NUMBER_OF_ACCOUNTS, task, result); - + // TODO: why 11? should be 1 assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 12); 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. */ @@ -429,30 +429,30 @@ public void test150SeachAllAccounts() throws Exception { public void test152SeachFirst2Accounts() throws Exception { final String TEST_NAME = "test152SeachFirst2Accounts"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - + ObjectPaging paging = ObjectPaging.createEmptyPaging(); paging.setMaxSize(2); query.setPaging(paging); - + SearchResultList> searchResultList = doSearch(TEST_NAME, 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. */ @@ -460,59 +460,59 @@ public void test152SeachFirst2Accounts() throws Exception { public void test154SeachFirst11Accounts() throws Exception { final String TEST_NAME = "test154SeachFirst11Accounts"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - + ObjectPaging paging = ObjectPaging.createEmptyPaging(); paging.setMaxSize(11); query.setPaging(paging); - + SearchResultList> searchResultList = doSearch(TEST_NAME, 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 { final String TEST_NAME = "test162SeachFirst2AccountsOffset0"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - + ObjectPaging paging = ObjectPaging.createEmptyPaging(); paging.setOffset(0); paging.setMaxSize(2); query.setPaging(paging); - + SearchResultList> searchResultList = doSearch(TEST_NAME, 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. @@ -522,29 +522,29 @@ public void test162SeachFirst2AccountsOffset0() throws Exception { public void test172Search2AccountsOffset1() throws Exception { final String TEST_NAME = "test172Search2AccountsOffset1"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - + ObjectPaging paging = ObjectPaging.createPaging(1, 2); query.setPaging(paging); - + SearchResultList> searchResultList = doSearch(TEST_NAME, 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. @@ -554,35 +554,35 @@ public void test172Search2AccountsOffset1() throws Exception { public void test174SeachFirst11AccountsOffset2() throws Exception { final String TEST_NAME = "test174SeachFirst11AccountsOffset2"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - + ObjectPaging paging = ObjectPaging.createPaging(2, 11); query.setPaging(paging); - + allowDuplicateSearchResults = true; - + // WHEN SearchResultList> searchResultList = doSearch(TEST_NAME, 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. @@ -592,25 +592,25 @@ public void test174SeachFirst11AccountsOffset2() throws Exception { public void test182Search2AccountsOffset1SortCn() throws Exception { final String TEST_NAME = "test182Search2AccountsOffset1SortCn"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - + ObjectPaging paging = ObjectPaging.createPaging(1, 2); paging.setOrdering(getAttributePath(resource, "cn"), OrderDirection.ASCENDING); query.setPaging(paging); - + SearchResultList> shadows = doSearch(TEST_NAME, query, 2, task, result); - + assertAccountShadow(shadows.get(0), "CN=Adalbert Meduza,OU=evolveum,DC=win,DC=evolveum,DC=com"); assertAccountShadow(shadows.get(1), "CN=Adalbert Meduza1,OU=evolveum,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()); @@ -618,31 +618,31 @@ public void test182Search2AccountsOffset1SortCn() throws Exception { assertLdapConnectorInstances(2); } - + @Test public void test200AssignAccountBarbossa() throws Exception { final String TEST_NAME = "test200AssignAccountBarbossa"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); long tsStart = System.currentTimeMillis(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignAccount(USER_BARBOSSA_OID, getResourceOid(), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.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); @@ -651,24 +651,24 @@ public void test200AssignAccountBarbossa() throws Exception { Collection> identifiers = ShadowUtil.getPrimaryIdentifiers(shadow); String accountBarbossaIcfUid = (String) identifiers.iterator().next().getRealValue(); assertNotNull("No identifier in "+shadow, accountBarbossaIcfUid); - - assertEquals("Wrong ICFS UID", + + assertEquals("Wrong ICFS UID", AdUtils.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"); - + ResourceAttribute createTimestampAttribute = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, "createTimeStamp")); assertNotNull("No createTimestamp in "+shadow, createTimestampAttribute); Long 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, createTimestamp); - + assertLdapConnectorInstances(2); } - + @Test public void test210ModifyAccountBarbossaTitle() throws Exception { final String TEST_NAME = "test210ModifyAccountBarbossaTitle"; @@ -677,18 +677,18 @@ public void test210ModifyAccountBarbossaTitle() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta delta = ObjectDelta.createEmptyModifyDelta(ShadowType.class, accountBarbossaOid, prismContext); QName attrQName = new QName(MidPointConstants.NS_RI, "title"); ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); PropertyDelta attrDelta = PropertyDelta.createModificationReplaceProperty( new ItemPath(ShadowType.F_ATTRIBUTES, attrQName), attrDef, "Captain"); delta.addModification(attrDelta); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -697,14 +697,14 @@ public void test210ModifyAccountBarbossaTitle() throws Exception { 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 { final String TEST_NAME = "test212ModifyAccountBarbossaShowInAdvancedViewOnlyTrue"; @@ -713,18 +713,18 @@ public void test212ModifyAccountBarbossaShowInAdvancedViewOnlyTrue() throws Exce // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta delta = ObjectDelta.createEmptyModifyDelta(ShadowType.class, accountBarbossaOid, prismContext); QName attrQName = new QName(MidPointConstants.NS_RI, "showInAdvancedViewOnly"); ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); PropertyDelta attrDelta = PropertyDelta.createModificationReplaceProperty( new ItemPath(ShadowType.F_ATTRIBUTES, attrQName), attrDef, Boolean.TRUE); delta.addModification(attrDelta); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -733,14 +733,14 @@ public void test212ModifyAccountBarbossaShowInAdvancedViewOnlyTrue() throws Exce 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. */ @@ -752,21 +752,21 @@ public void test213ModifyUserBarbossaShowInAdvancedViewOnlyFalse() throws Except // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - - + + ObjectDelta delta = ObjectDelta.createEmptyModifyDelta(ShadowType.class, accountBarbossaOid, prismContext); QName attrQName = new QName(MidPointConstants.NS_RI, "showInAdvancedViewOnly"); ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); PropertyDelta attrDelta = PropertyDelta.createModificationReplaceProperty( new ItemPath(ShadowType.F_ATTRIBUTES, attrQName), attrDef, Boolean.TRUE); delta.addModification(attrDelta); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyUserReplace(USER_BARBOSSA_OID, - new ItemPath(UserType.F_EXTENSION, EXTENSION_SHOW_IN_ADVANCED_VIEW_ONLY_QNAME), + modifyUserReplace(USER_BARBOSSA_OID, + new ItemPath(UserType.F_EXTENSION, EXTENSION_SHOW_IN_ADVANCED_VIEW_ONLY_QNAME), task, result, Boolean.FALSE); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -775,14 +775,14 @@ public void test213ModifyUserBarbossaShowInAdvancedViewOnlyFalse() throws Except 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 { final String TEST_NAME = "test220ModifyUserBarbossaPassword"; @@ -791,16 +791,16 @@ public void test220ModifyUserBarbossaPassword() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ProtectedStringType userPasswordPs = new ProtectedStringType(); userPasswordPs.setClearValue("here.There.Be.Monsters"); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyUserReplace(USER_BARBOSSA_OID, - new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), + modifyUserReplace(USER_BARBOSSA_OID, + new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), task, result, userPasswordPs); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -810,14 +810,14 @@ public void test220ModifyUserBarbossaPassword() throws Exception { assertAttribute(entry, "title", "Captain"); assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, "here.There.Be.Monsters"); 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 { final String TEST_NAME = "test230DisableUserBarbossa"; @@ -826,37 +826,37 @@ public void test230DisableUserBarbossa() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyUserReplace(USER_BARBOSSA_OID, - new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), + modifyUserReplace(USER_BARBOSSA_OID, + new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), task, result, ActivationStatusType.DISABLED); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.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 { assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, "here.There.Be.Monsters"); AssertJUnit.fail("Password authentication works, but it should fail"); } catch (SecurityException e) { // this is expected } - + assertLdapConnectorInstances(2); } @@ -868,28 +868,28 @@ public void test239EnableUserBarbossa() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyUserReplace(USER_BARBOSSA_OID, - new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), + modifyUserReplace(USER_BARBOSSA_OID, + new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), task, result, ActivationStatusType.ENABLED); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.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); } @@ -900,19 +900,19 @@ public void test239EnableUserBarbossa() throws Exception { public void test250AssignGuybrushPirates() throws Exception { final String TEST_NAME = "test250AssignGuybrushPirates"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - - modifyUserReplace(USER_GUYBRUSH_OID, - new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), + + modifyUserReplace(USER_GUYBRUSH_OID, + new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), task, result, ActivationStatusType.DISABLED); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_PIRATES_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -921,20 +921,20 @@ public void test250AssignGuybrushPirates() throws Exception { 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 { final String TEST_NAME = "test255ModifyUserGuybrushPassword"; @@ -943,16 +943,16 @@ public void test255ModifyUserGuybrushPassword() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ProtectedStringType userPasswordPs = new ProtectedStringType(); userPasswordPs.setClearValue("wanna.be.a.123"); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyUserReplace(USER_GUYBRUSH_OID, - new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), + modifyUserReplace(USER_GUYBRUSH_OID, + new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), task, result, userPasswordPs); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -967,10 +967,10 @@ public void test255ModifyUserGuybrushPassword() throws Exception { } catch (SecurityException e) { // this is expected, account is disabled } - + assertLdapConnectorInstances(2); } - + @Test public void test260EnableGyubrush() throws Exception { final String TEST_NAME = "test260EnableGyubrush"; @@ -979,30 +979,30 @@ public void test260EnableGyubrush() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyUserReplace(USER_GUYBRUSH_OID, - new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), + modifyUserReplace(USER_GUYBRUSH_OID, + new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), task, result, ActivationStatusType.ENABLED); - + // THEN TestUtil.displayThen(TEST_NAME); 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); - + assertLdapPassword(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, "wanna.be.a.123"); - + assertLdapConnectorInstances(2); } @@ -1010,15 +1010,15 @@ public void test260EnableGyubrush() throws Exception { public void test300AssignBarbossaPirates() throws Exception { final String TEST_NAME = "test300AssignBarbossaPirates"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_BARBOSSA_OID, ROLE_PIRATES_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -1027,19 +1027,19 @@ public void test300AssignBarbossaPirates() throws Exception { 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 { final String TEST_NAME = "test390ModifyUserBarbossaRename"; @@ -1048,18 +1048,18 @@ public void test390ModifyUserBarbossaRename() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - - ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_BARBOSSA_OID, UserType.F_NAME, + + 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 TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -1067,39 +1067,39 @@ public void test390ModifyUserBarbossaRename() throws Exception { 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 { final String TEST_NAME = "test395UnAssignBarbossaPirates"; TestUtil.displayTestTitle(this, TEST_NAME); // TODO: do this on another account. There is a bad interference with rename. - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); unassignRole(USER_BARBOSSA_OID, ROLE_PIRATES_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -1108,19 +1108,19 @@ public void test395UnAssignBarbossaPirates() throws Exception { 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 { final String TEST_NAME = "test399UnAssignAccountBarbossa"; @@ -1129,11 +1129,11 @@ public void test399UnAssignAccountBarbossa() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); unassignAccount(USER_BARBOSSA_OID, getResourceOid(), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -1141,13 +1141,13 @@ public void test399UnAssignAccountBarbossa() throws Exception { 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 { final String TEST_NAME = "test500AddOrgMeleeIsland"; @@ -1156,7 +1156,7 @@ public void test500AddOrgMeleeIsland() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject org = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(OrgType.class).instantiate(); OrgType orgType = org.asObjectable(); orgType.setName(new PolyStringType(GROUP_MELEE_ISLAND_NAME)); @@ -1166,11 +1166,11 @@ public void test500AddOrgMeleeIsland() throws Exception { metaroleRef.setType(RoleType.COMPLEX_TYPE); metaroleAssignment.setTargetRef(metaroleRef); orgType.getAssignment().add(metaroleAssignment); - + // WHEN TestUtil.displayWhen(TEST_NAME); addObject(org, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -1178,61 +1178,61 @@ public void test500AddOrgMeleeIsland() throws Exception { orgMeleeIslandOid = org.getOid(); Entry entry = 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 { final String TEST_NAME = "test510AssignGuybrushMeleeIsland"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignOrg(USER_GUYBRUSH_OID, orgMeleeIslandOid, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); 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(), groupMeleeOid); - + assertLdapConnectorInstances(2); } - + @Override protected void doAdditionalRenameModifications(LdapNetworkConnection connection) throws LdapException { - Modification mod = new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, + 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 + + 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); @@ -1254,7 +1254,7 @@ protected Entry assertLdapAccount(String samAccountName, String cn) throws LdapE protected void assertNoLdapAccount(String uid) throws LdapException, IOException, CursorException { 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+")"); @@ -1269,12 +1269,12 @@ protected void assertNoLdapAccount(String uid, String cn) throws LdapException, 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 { @@ -1298,7 +1298,7 @@ protected ObjectQuery createSamAccountNameQuery(String samAccountName) throws Sc ObjectQueryUtil.filterAnd(query.getFilter(), createAttributeFilter(ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, samAccountName)); return query; } - + @Override protected Entry createAccountEntry(String uid, String cn, String givenName, String sn) throws LdapException { byte[] password = encodePassword("Secret.123"); @@ -1312,7 +1312,7 @@ protected Entry createAccountEntry(String uid, String cn, String givenName, Stri ATTRIBUTE_UNICODE_PWD_NAME, password); return entry; } - + private byte[] encodePassword(String password) { String quotedPassword = "\"" + password + "\""; try { @@ -1338,13 +1338,13 @@ protected void assertStepSyncToken(String syncTaskOid, int step, long tsStart, l 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/AbstractAdTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractAdTest.java index 268e9b477b2..29ce79a9b6c 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractAdTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractAdTest.java @@ -52,40 +52,40 @@ */ @Listeners({com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class}) public abstract class AbstractAdTest extends AbstractLdapTest { - + protected static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "ad"); - + protected ConnectorHostType connectorHostType; 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"; - + public static final String ATTRIBUTE_LOCKOUT_LOCKED_NAME = "lockedByIntruder"; public static final String ATTRIBUTE_LOCKOUT_RESET_TIME_NAME = "loginIntruderResetTime"; public static final String ATTRIBUTE_GROUP_MEMBERSHIP_NAME = "groupMembership"; public static final String ATTRIBUTE_EQUIVALENT_TO_ME_NAME = "equivalentToMe"; public static final String ATTRIBUTE_SECURITY_EQUALS_NAME = "securityEquals"; - + protected static final String ACCOUNT_JACK_UID = "jack"; protected static final String ACCOUNT_JACK_PASSWORD = "qwe123"; - + 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 = 4; protected static final int LOCKOUT_EXPIRATION_SECONDS = 65; private static final String ASSOCIATION_GROUP_NAME = "group"; - + protected String jackAccountOid; protected String groupPiratesOid; protected long jackLockoutTimestamp; private String accountBarbossaOid; private String orgMeleeIslandOid; protected String groupMeleeOid; - + @Override public String getStartSystemCommand() { return null; @@ -100,28 +100,28 @@ public String getStopSystemCommand() { protected File getBaseDir() { return TEST_DIR; } - + @Override protected String getResourceOid() { return "188ec322-4bd7-11e5-b919-001e8c717e5b"; } - + @Override protected File getResourceFile() { return new File(getBaseDir(), "resource-medusa.xml"); } - + protected String getConnectorHostOid() { return "08e687b6-4bd7-11e5-8484-001e8c717e5b"; } - + protected abstract File getConnectorHostFile(); @Override protected String getSyncTaskOid() { return null; } - + @Override protected boolean useSsl() { return true; @@ -146,12 +146,12 @@ protected String getLdapBindPassword() { protected int getSearchSizeLimit() { return -1; } - + @Override public String getPrimaryIdentifierAttributeName() { return "GUID"; } - + @Override protected QName getAccountObjectClass() { return new QName(MidPointConstants.NS_RI, "AccountObjectClass"); @@ -166,35 +166,35 @@ protected String getLdapGroupObjectClass() { protected String getLdapGroupMemberAttribute() { return "member"; } - + private QName getAssociationGroupQName() { return new QName(MidPointConstants.NS_RI, ASSOCIATION_GROUP_NAME); } - + @Override protected boolean isImportResourceAtInit() { return false; } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + // binaryAttributeDetector.addBinaryAttribute("GUID"); // Connector host connectorHostType = repoAddObjectFromFile(getConnectorHostFile(), ConnectorHostType.class, initResult).asObjectable(); - + // Users repoAddObjectFromFile(USER_BARBOSSA_FILE, initResult); repoAddObjectFromFile(USER_GUYBRUSH_FILE, initResult); - + // Roles // repoAddObjectFromFile(ROLE_PIRATES_FILE, RoleType.class, initResult); // repoAddObjectFromFile(ROLE_META_ORG_FILE, RoleType.class, initResult); - + } - + @Test public void test000Sanity() throws Exception { // assertLdapPassword(ACCOUNT_JACK_UID, ACCOUNT_JACK_PASSWORD); @@ -209,20 +209,20 @@ public void test000Sanity() throws Exception { public void test001ConnectorHostDiscovery() throws Exception { final String TEST_NAME = "test001ConnectorHostDiscovery"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.discoverConnectors(connectorHostType, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + SearchResultList> connectors = modelService.searchObjects(ConnectorType.class, null, null, task, result); - + boolean found = false; for (PrismObject connector: connectors) { if (CONNECTOR_AD_TYPE.equals(connector.asObjectable().getConnectorType())) { @@ -232,70 +232,70 @@ public void test001ConnectorHostDiscovery() throws Exception { } assertTrue("AD Connector not found", found); } - + @Test public void test002ImportResource() throws Exception { final String TEST_NAME = "test002ImportResource"; TestUtil.displayTestTitle(this, TEST_NAME); - + Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); resource = importAndGetObjectFromFile(ResourceType.class, getResourceFile(), getResourceOid(), task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + resourceType = resource.asObjectable(); } - + @Test public void test020Schema() throws Exception { final String TEST_NAME = "test020Schema"; TestUtil.displayTestTitle(this, TEST_NAME); - - // GIVEN + + // GIVEN ResourceSchema resourceSchema = RefinedResourceSchema.getResourceSchema(resource, prismContext); display("Resource schema", resourceSchema); - + RefinedResourceSchema refinedSchema = RefinedResourceSchema.getRefinedSchema(resource); display("Refined schema", refinedSchema); accountObjectClassDefinition = refinedSchema.findObjectClassDefinition(getAccountObjectClass()); assertNotNull("No definition for object class "+getAccountObjectClass(), 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()); assertFalse("cn modify", cnDef.canModify()); assertFalse("cn add", cnDef.canAdd()); - + ResourceAttributeDefinition userPrincipalNameDef = accountObjectClassDefinition.findAttributeDefinition("userPrincipalName"); PrismAsserts.assertDefinition(userPrincipalNameDef, new QName(MidPointConstants.NS_RI, "userPrincipalName"), DOMUtil.XSD_STRING, 0, 1); assertTrue("o read", userPrincipalNameDef.canRead()); assertTrue("o modify", userPrincipalNameDef.canModify()); assertTrue("o add", userPrincipalNameDef.canAdd()); - + } - + @Test public void test050Capabilities() throws Exception { final String TEST_NAME = "test050Capabilities"; TestUtil.displayTestTitle(this, TEST_NAME); - + Collection nativeCapabilitiesCollection = ResourceTypeUtil.getNativeCapabilitiesCollection(resourceType); display("Native capabilities", nativeCapabilitiesCollection); - + assertTrue("No native activation capability", ResourceTypeUtil.hasResourceNativeActivationCapability(resourceType)); assertTrue("No native activation status capability", ResourceTypeUtil.hasResourceNativeActivationStatusCapability(resourceType)); assertTrue("No native lockout capability", ResourceTypeUtil.hasResourceNativeActivationLockoutCapability(resourceType)); assertTrue("No native credentias capability", ResourceTypeUtil.isCredentialsCapabilityEnabled(resourceType)); } - + } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractEDirTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractEDirTest.java index 8ca1b4b257b..8cfceb90e60 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractEDirTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractEDirTest.java @@ -78,39 +78,39 @@ */ @Listeners({com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class}) public abstract class AbstractEDirTest extends AbstractLdapTest { - + protected static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "edir"); - + 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"; - + public static final String ATTRIBUTE_LOCKOUT_LOCKED_NAME = "lockedByIntruder"; public static final String ATTRIBUTE_LOCKOUT_RESET_TIME_NAME = "loginIntruderResetTime"; public static final String ATTRIBUTE_GROUP_MEMBERSHIP_NAME = "groupMembership"; public static final String ATTRIBUTE_EQUIVALENT_TO_ME_NAME = "equivalentToMe"; public static final String ATTRIBUTE_SECURITY_EQUALS_NAME = "securityEquals"; - + protected static final String ACCOUNT_JACK_UID = "jack"; protected static final String ACCOUNT_JACK_PASSWORD = "qwe123"; - + 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_MELA_NOVA_NAME = "Mela Nova"; - + protected static final int NUMBER_OF_ACCOUNTS = 4; protected static final int LOCKOUT_EXPIRATION_SECONDS = 65; private static final String ASSOCIATION_GROUP_NAME = "group"; - + protected String jackAccountOid; protected String groupPiratesOid; protected long jackLockoutTimestamp; private String accountBarbossaOid; private String orgMeleeIslandOid; protected String groupMeleeOid; - + @Override public String getStartSystemCommand() { return null; @@ -130,7 +130,7 @@ protected File getBaseDir() { protected String getSyncTaskOid() { return null; } - + @Override protected boolean useSsl() { return true; @@ -155,7 +155,7 @@ protected String getLdapBindPassword() { protected int getSearchSizeLimit() { return -1; } - + @Override public String getPrimaryIdentifierAttributeName() { return "GUID"; @@ -170,37 +170,37 @@ protected String getLdapGroupObjectClass() { protected String getLdapGroupMemberAttribute() { return "member"; } - + private QName getAssociationGroupQName() { return new QName(MidPointConstants.NS_RI, ASSOCIATION_GROUP_NAME); } - + protected String getOrgGroupsLdapSuffix() { return "ou=orggroups,"+getLdapSuffix(); } - - + + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + binaryAttributeDetector.addBinaryAttribute("GUID"); - + // Users repoAddObjectFromFile(USER_BARBOSSA_FILE, initResult); repoAddObjectFromFile(USER_GUYBRUSH_FILE, initResult); - + // Roles repoAddObjectFromFile(ROLE_PIRATES_FILE, initResult); repoAddObjectFromFile(ROLE_META_ORG_FILE, initResult); - + } - + @Test public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; TestUtil.displayTestTitle(this, TEST_NAME); - + assertLdapPassword(ACCOUNT_JACK_UID, ACCOUNT_JACK_PASSWORD); assertEDirGroupMember(ACCOUNT_JACK_UID, GROUP_PIRATES_NAME); cleanupDelete(toAccountDn(USER_BARBOSSA_USERNAME)); @@ -214,173 +214,173 @@ public void test000Sanity() throws Exception { public void test050Capabilities() throws Exception { final String TEST_NAME = "test050Capabilities"; TestUtil.displayTestTitle(this, TEST_NAME); - + Collection nativeCapabilitiesCollection = ResourceTypeUtil.getNativeCapabilitiesCollection(resourceType); display("Native capabilities", nativeCapabilitiesCollection); - + assertTrue("No native activation capability", ResourceTypeUtil.hasResourceNativeActivationCapability(resourceType)); assertTrue("No native activation status capability", ResourceTypeUtil.hasResourceNativeActivationStatusCapability(resourceType)); assertTrue("No native lockout capability", ResourceTypeUtil.hasResourceNativeActivationLockoutCapability(resourceType)); assertTrue("No native credentias capability", ResourceTypeUtil.isCredentialsCapabilityEnabled(resourceType)); } - + @Test public void test100SeachJackByLdapUid() throws Exception { final String TEST_NAME = "test100SeachJackByLdapUid"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = createUidQuery(ACCOUNT_JACK_UID); - + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); 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_UID)); assertShadowLockout(shadow, LockoutStatusType.NORMAL); jackAccountOid = shadow.getOid(); assertNotNull("Null OID in "+shadow, jackAccountOid); - + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 2); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + SearchResultMetadata metadata = shadows.getMetadata(); if (metadata != null) { assertFalse(metadata.isPartialResults()); } } - + @Test public void test105SeachPiratesByCn() throws Exception { final String TEST_NAME = "test105SeachPiratesByCn"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getGroupObjectClass(), prismContext); ObjectQueryUtil.filterAnd(query.getFilter(), createAttributeFilter("cn", GROUP_PIRATES_NAME)); - + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); 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, 2); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + SearchResultMetadata metadata = shadows.getMetadata(); if (metadata != null) { assertFalse(metadata.isPartialResults()); } } - + @Test public void test110GetJack() throws Exception { final String TEST_NAME = "test110GetJack"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = createUidQuery(ACCOUNT_JACK_UID); - + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject shadow = modelService.getObject(ShadowType.class, jackAccountOid, null, task, result); - + // THEN result.computeStatus(); - TestUtil.assertSuccess(result); + TestUtil.assertSuccess(result); display("Shadow", shadow); assertAccountShadow(shadow, toAccountDn(ACCOUNT_JACK_UID)); assertShadowLockout(shadow, LockoutStatusType.NORMAL); assertPasswordAllowChange(shadow, null); jackAccountOid = shadow.getOid(); - + IntegrationTestTools.assertAssociation(shadow, getAssociationGroupQName(), groupPiratesOid); - + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); } - + @Test public void test120JackLockout() throws Exception { final String TEST_NAME = "test120JackLockout"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + makeBadLoginAttempt(ACCOUNT_JACK_UID); makeBadLoginAttempt(ACCOUNT_JACK_UID); makeBadLoginAttempt(ACCOUNT_JACK_UID); makeBadLoginAttempt(ACCOUNT_JACK_UID); - + jackLockoutTimestamp = System.currentTimeMillis(); - + ObjectQuery query = createUidQuery(ACCOUNT_JACK_UID); - + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); SearchResultList> shadows = modelService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); 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_UID)); assertShadowLockout(shadow, LockoutStatusType.LOCKED); - + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + SearchResultMetadata metadata = shadows.getMetadata(); if (metadata != null) { assertFalse(metadata.isPartialResults()); } } - + /** * No paging. It should return all accounts. */ @@ -388,29 +388,29 @@ public void test120JackLockout() throws Exception { public void test150SeachAllAccounts() throws Exception { final String TEST_NAME = "test150SeachAllAccounts"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - + SearchResultList> searchResultList = doSearch(TEST_NAME, query, NUMBER_OF_ACCOUNTS, 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()); } } - + @Test public void test190SeachLockedAccounts() throws Exception { final String TEST_NAME = "test190SeachLockedAccounts"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); @@ -420,45 +420,45 @@ public void test190SeachLockedAccounts() throws Exception { .build(); SearchResultList> searchResultList = doSearch(TEST_NAME, query, 1, task, result); - + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + PrismObject shadow = searchResultList.get(0); display("Shadow", shadow); assertAccountShadow(shadow, toAccountDn(ACCOUNT_JACK_UID)); assertShadowLockout(shadow, LockoutStatusType.LOCKED); - + SearchResultMetadata metadata = searchResultList.getMetadata(); if (metadata != null) { assertFalse(metadata.isPartialResults()); } } - + @Test public void test200AssignAccountBarbossa() throws Exception { final String TEST_NAME = "test200AssignAccountBarbossa"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); long tsStart = System.currentTimeMillis(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignAccount(USER_BARBOSSA_OID, getResourceOid(), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.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); @@ -467,19 +467,19 @@ public void test200AssignAccountBarbossa() throws Exception { Collection> identifiers = ShadowUtil.getPrimaryIdentifiers(shadow); String accountBarbossaIcfUid = (String) identifiers.iterator().next().getRealValue(); assertNotNull("No identifier in "+shadow, accountBarbossaIcfUid); - + assertEquals("Wrong ICFS UID", MiscUtil.binaryToHex(entry.get(getPrimaryIdentifierAttributeName()).getBytes()), accountBarbossaIcfUid); - + assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_PASSWORD); assertPasswordAllowChange(shadow, null); - + ResourceAttribute createTimestampAttribute = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, "createTimestamp")); assertNotNull("No createTimestamp in "+shadow, createTimestampAttribute); Long createTimestamp = createTimestampAttribute.getRealValue(); // LDAP server may be on a different host. Allow for some clock offset. TestUtil.assertBetween("Wrong createTimestamp in "+shadow, roundTsDown(tsStart)-1000, roundTsUp(tsEnd)+1000, createTimestamp); } - + @Test public void test210ModifyAccountBarbossaTitle() throws Exception { final String TEST_NAME = "test210ModifyAccountBarbossaTitle"; @@ -488,18 +488,18 @@ public void test210ModifyAccountBarbossaTitle() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta delta = ObjectDelta.createEmptyModifyDelta(ShadowType.class, accountBarbossaOid, prismContext); QName attrQName = new QName(MidPointConstants.NS_RI, "title"); ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); PropertyDelta attrDelta = PropertyDelta.createModificationReplaceProperty( new ItemPath(ShadowType.F_ATTRIBUTES, attrQName), attrDef, "Captain"); delta.addModification(attrDelta); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -507,12 +507,12 @@ public void test210ModifyAccountBarbossaTitle() throws Exception { Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); assertAttribute(entry, "title", "Captain"); - + PrismObject user = getUser(USER_BARBOSSA_OID); String shadowOid = getSingleLinkOid(user); assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); } - + @Test public void test220ModifyUserBarbossaPassword() throws Exception { final String TEST_NAME = "test220ModifyUserBarbossaPassword"; @@ -521,16 +521,16 @@ public void test220ModifyUserBarbossaPassword() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ProtectedStringType userPasswordPs = new ProtectedStringType(); userPasswordPs.setClearValue("hereThereBeMonsters"); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyUserReplace(USER_BARBOSSA_OID, - new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), + modifyUserReplace(USER_BARBOSSA_OID, + new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), task, result, userPasswordPs); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -539,12 +539,12 @@ public void test220ModifyUserBarbossaPassword() throws Exception { Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); assertAttribute(entry, "title", "Captain"); assertLdapPassword(USER_BARBOSSA_USERNAME, "hereThereBeMonsters"); - + PrismObject user = getUser(USER_BARBOSSA_OID); String shadowOid = getSingleLinkOid(user); assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); } - + @Test public void test230DisableBarbossa() throws Exception { final String TEST_NAME = "test230DisableBarbossa"; @@ -553,29 +553,29 @@ public void test230DisableBarbossa() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyUserReplace(USER_BARBOSSA_OID, - new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), + modifyUserReplace(USER_BARBOSSA_OID, + new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), task, result, ActivationStatusType.DISABLED); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject user = getUser(USER_BARBOSSA_OID); assertAdministrativeStatus(user, ActivationStatusType.DISABLED); Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); assertAttribute(entry, "loginDisabled", "TRUE"); - + String shadowOid = getSingleLinkOid(user); PrismObject shadow = getObject(ShadowType.class, shadowOid); assertAdministrativeStatus(shadow, ActivationStatusType.DISABLED); } - + @Test public void test239EnableBarbossa() throws Exception { final String TEST_NAME = "test239EnableBarbossa"; @@ -584,24 +584,24 @@ public void test239EnableBarbossa() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyUserReplace(USER_BARBOSSA_OID, - new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), + modifyUserReplace(USER_BARBOSSA_OID, + new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), task, result, ActivationStatusType.ENABLED); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject user = getUser(USER_BARBOSSA_OID); assertAdministrativeStatus(user, ActivationStatusType.ENABLED); Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); assertAttribute(entry, "loginDisabled", "FALSE"); - + String shadowOid = getSingleLinkOid(user); PrismObject shadow = getObject(ShadowType.class, shadowOid); assertAdministrativeStatus(shadow, ActivationStatusType.ENABLED); @@ -618,18 +618,18 @@ public void test240ModifyAccountBarbossaPasswordAllowChangeFalse() throws Except // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta delta = ObjectDelta.createEmptyModifyDelta(ShadowType.class, accountBarbossaOid, prismContext); QName attrQName = new QName(MidPointConstants.NS_RI, "passwordAllowChange"); ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); PropertyDelta attrDelta = PropertyDelta.createModificationReplaceProperty( new ItemPath(ShadowType.F_ATTRIBUTES, attrQName), attrDef, Boolean.FALSE); delta.addModification(attrDelta); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -637,7 +637,7 @@ public void test240ModifyAccountBarbossaPasswordAllowChangeFalse() throws Except Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); assertAttribute(entry, "passwordAllowChange", "FALSE"); - + PrismObject user = getUser(USER_BARBOSSA_OID); String shadowOid = getSingleLinkOid(user); assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); @@ -655,19 +655,19 @@ public void test240ModifyAccountBarbossaPasswordAllowChangeFalse() throws Except public void test250AssignGuybrushPirates() throws Exception { final String TEST_NAME = "test250AssignGuybrushPirates"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - - modifyUserReplace(USER_GUYBRUSH_OID, - new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), + + modifyUserReplace(USER_GUYBRUSH_OID, + new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), task, result, ActivationStatusType.DISABLED); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_PIRATES_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -676,18 +676,18 @@ public void test250AssignGuybrushPirates() throws Exception { Entry entry = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); display("Entry", entry); assertAttribute(entry, "loginDisabled", "TRUE"); - + assertEDirGroupMember(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); assertAdministrativeStatus(shadow, ActivationStatusType.DISABLED); } - + @Test public void test260EnableGyubrush() throws Exception { final String TEST_NAME = "test260EnableGyubrush"; @@ -696,44 +696,44 @@ public void test260EnableGyubrush() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyUserReplace(USER_GUYBRUSH_OID, - new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), + modifyUserReplace(USER_GUYBRUSH_OID, + new ItemPath(UserType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), task, result, ActivationStatusType.ENABLED); - + // THEN TestUtil.displayThen(TEST_NAME); 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, "loginDisabled", "FALSE"); - + String shadowOid = getSingleLinkOid(user); PrismObject shadow = getObject(ShadowType.class, shadowOid); assertAdministrativeStatus(shadow, ActivationStatusType.ENABLED); } // TODO: search for disabled accounts - + @Test public void test300AssignBarbossaPirates() throws Exception { final String TEST_NAME = "test300AssignBarbossaPirates"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_BARBOSSA_OID, ROLE_PIRATES_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -742,18 +742,18 @@ public void test300AssignBarbossaPirates() throws Exception { Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); display("Entry", entry); assertAttribute(entry, "title", "Captain"); - + Entry groupEntry = assertEDirGroupMember(entry, GROUP_PIRATES_NAME); display("Group entry", groupEntry); - + 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); + IntegrationTestTools.assertAssociation(shadow, getAssociationGroupQName(), groupPiratesOid); } - + @Test public void test390ModifyUserBarbossaRename() throws Exception { final String TEST_NAME = "test390ModifyUserBarbossaRename"; @@ -762,11 +762,11 @@ public void test390ModifyUserBarbossaRename() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); renameObject(UserType.class, USER_BARBOSSA_OID, USER_CPTBARBOSSA_USERNAME, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -774,21 +774,21 @@ public void test390ModifyUserBarbossaRename() throws Exception { Entry entry = assertLdapAccount(USER_CPTBARBOSSA_USERNAME, USER_BARBOSSA_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); } - + // TODO: create account with a group membership - + @Test public void test500AddOrgMeleeIsland() throws Exception { final String TEST_NAME = "test500AddOrgMeleeIsland"; @@ -797,7 +797,7 @@ public void test500AddOrgMeleeIsland() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject org = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(OrgType.class).instantiate(); OrgType orgType = org.asObjectable(); orgType.setName(new PolyStringType(GROUP_MELEE_ISLAND_NAME)); @@ -807,11 +807,11 @@ public void test500AddOrgMeleeIsland() throws Exception { metaroleRef.setType(RoleType.COMPLEX_TYPE); metaroleAssignment.setTargetRef(metaroleRef); orgType.getAssignment().add(metaroleAssignment); - + // WHEN TestUtil.displayWhen(TEST_NAME); addObject(org, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -819,43 +819,43 @@ public void test500AddOrgMeleeIsland() throws Exception { orgMeleeIslandOid = org.getOid(); Entry entry = assertLdapGroup(GROUP_MELEE_ISLAND_NAME); - + org = getObject(OrgType.class, orgMeleeIslandOid); groupMeleeOid = getSingleLinkOid(org); PrismObject shadow = getShadowModel(groupMeleeOid); display("Shadow (model)", shadow); } - + @Test public void test510AssignGuybrushMeleeIsland() throws Exception { final String TEST_NAME = "test510AssignGuybrushMeleeIsland"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignOrg(USER_GUYBRUSH_OID, orgMeleeIslandOid, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); 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); - + assertEDirGroupMember(entry, GROUP_MELEE_ISLAND_NAME); IntegrationTestTools.assertAssociation(shadow, getAssociationGroupQName(), groupMeleeOid); } - + @Test public void test520RenameOrgMeleeIsland() throws Exception { final String TEST_NAME = "test520RenameOrgMeleeIsland"; @@ -864,34 +864,34 @@ public void test520RenameOrgMeleeIsland() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); renameObject(OrgType.class, orgMeleeIslandOid, GROUP_MELA_NOVA_NAME, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); Entry entry = assertLdapGroup(GROUP_MELA_NOVA_NAME); - + PrismObject org = getObject(OrgType.class, orgMeleeIslandOid); String groupMeleeOidAfter = getSingleLinkOid(org); PrismObject shadow = getShadowModel(groupMeleeOidAfter); display("Shadow (model)", shadow); } - + // Wait until the lockout of Jack expires, check status @Test public void test800JackLockoutExpires() throws Exception { final String TEST_NAME = "test800JackLockoutExpires"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + long now = System.currentTimeMillis(); long lockoutExpires = jackLockoutTimestamp + LOCKOUT_EXPIRATION_SECONDS*1000; if (now < lockoutExpires) { @@ -900,73 +900,73 @@ public void test800JackLockoutExpires() throws Exception { } now = System.currentTimeMillis(); display("Time is now "+now); - + ObjectQuery query = createUidQuery(ACCOUNT_JACK_UID); - + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); SearchResultList> shadows = modelService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); 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_UID)); assertShadowLockout(shadow, LockoutStatusType.NORMAL); - + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + SearchResultMetadata metadata = shadows.getMetadata(); if (metadata != null) { assertFalse(metadata.isPartialResults()); } } - + @Test public void test810SeachLockedAccounts() throws Exception { final String TEST_NAME = "test810SeachLockedAccounts"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassFilterPrefix(getResourceOid(), getAccountObjectClass(), prismContext) .and().item(ShadowType.F_ACTIVATION, ActivationType.F_LOCKOUT_STATUS).eq(LockoutStatusType.LOCKED) .build(); SearchResultList> searchResultList = doSearch(TEST_NAME, query, 0, task, result); - + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); } - + @Test public void test820JackLockoutAndUnlock() throws Exception { final String TEST_NAME = "test820JackLockoutAndUnlock"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + makeBadLoginAttempt(ACCOUNT_JACK_UID); makeBadLoginAttempt(ACCOUNT_JACK_UID); makeBadLoginAttempt(ACCOUNT_JACK_UID); makeBadLoginAttempt(ACCOUNT_JACK_UID); - + jackLockoutTimestamp = System.currentTimeMillis(); - + ObjectQuery query = createUidQuery(ACCOUNT_JACK_UID); - + // precondition SearchResultList> shadows = modelService.searchObjects(ShadowType.class, query, null, task, result); result.computeStatus(); @@ -976,16 +976,16 @@ public void test820JackLockoutAndUnlock() throws Exception { display("Locked shadow", shadowLocked); assertAccountShadow(shadowLocked, toAccountDn(ACCOUNT_JACK_UID)); assertShadowLockout(shadowLocked, LockoutStatusType.LOCKED); - + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyObjectReplaceProperty(ShadowType.class, shadowLocked.getOid(), + modifyObjectReplaceProperty(ShadowType.class, shadowLocked.getOid(), new ItemPath(ShadowType.F_ACTIVATION, ActivationType.F_LOCKOUT_STATUS), task, result, LockoutStatusType.NORMAL); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -993,40 +993,40 @@ public void test820JackLockoutAndUnlock() throws Exception { assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + PrismObject shadowAfter = getObject(ShadowType.class, shadowLocked.getOid()); display("Shadow after", shadowAfter); assertAccountShadow(shadowAfter, toAccountDn(ACCOUNT_JACK_UID)); assertShadowLockout(shadowAfter, LockoutStatusType.NORMAL); assertLdapPassword(ACCOUNT_JACK_UID, ACCOUNT_JACK_PASSWORD); - + SearchResultMetadata metadata = shadows.getMetadata(); if (metadata != null) { assertFalse(metadata.isPartialResults()); } } - + // Let's do this at the very end. // We need to wait after rename, otherwise the delete fail with: // NDS error: previous move in progress (-637) // So ... let's give some time to eDirectory to sort the things out - + @Test public void test890UnAssignBarbossaPirates() throws Exception { final String TEST_NAME = "test890UnAssignBarbossaPirates"; TestUtil.displayTestTitle(this, TEST_NAME); // TODO: do this on another account. There is a bad interference with rename. - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); unassignRole(USER_BARBOSSA_OID, ROLE_PIRATES_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -1035,18 +1035,18 @@ public void test890UnAssignBarbossaPirates() throws Exception { Entry entry = assertLdapAccount(USER_CPTBARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); display("Entry", entry); assertAttribute(entry, "title", "Captain"); - + assertEDirNoGroupMember(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); - + } - + @Test public void test899UnAssignAccountBarbossa() throws Exception { final String TEST_NAME = "test899UnAssignAccountBarbossa"; @@ -1055,11 +1055,11 @@ public void test899UnAssignAccountBarbossa() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); unassignAccount(USER_BARBOSSA_OID, getResourceOid(), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -1067,11 +1067,11 @@ public void test899UnAssignAccountBarbossa() throws Exception { assertNoLdapAccount(USER_BARBOSSA_USERNAME); assertNoLdapAccount(USER_CPTBARBOSSA_USERNAME); - + PrismObject user = getUser(USER_BARBOSSA_OID); assertNoLinkedAccount(user); } - + // TODO: lock out jack again, explicitly reset the lock, see that he can login @Override @@ -1082,12 +1082,12 @@ protected void assertAccountShadow(PrismObject shadow, String dn) th String primaryId = primaryIdAttr.getRealValue(); assertTrue("Unexpected chars in primary ID: '"+primaryId+"'", primaryId.matches("[a-z0-9]+")); } - + protected void assertPasswordAllowChange(PrismObject shadow, Boolean expected) throws SchemaException { Boolean passwordAllowChange = ShadowUtil.getAttributeValue(shadow, new QName(MidPointConstants.NS_RI, "passwordAllowChange")); assertEquals("Wrong passwordAllowChange in "+shadow, expected, passwordAllowChange); } - + private void makeBadLoginAttempt(String uid) throws LdapException, IOException { try { LdapNetworkConnection conn = ldapConnect(toAccountDn(uid), "thisIsAwRoNgPASSW0RD"); @@ -1098,12 +1098,12 @@ private void makeBadLoginAttempt(String uid) throws LdapException, IOException { // this is expected } } - + private void assertEDirGroupMember(String accountUid, String groupName) throws LdapException, IOException, CursorException, SchemaException { Entry accountEntry = getLdapAccountByUid(accountUid); assertEDirGroupMember(accountEntry, groupName); } - + private Entry assertEDirGroupMember(Entry accountEntry, String groupName) throws LdapException, IOException, CursorException, SchemaException { Entry groupEntry = getLdapGroupByName(groupName); assertAttributeContains(groupEntry, getLdapGroupMemberAttribute(), accountEntry.getDn().toString()); @@ -1112,7 +1112,7 @@ private Entry assertEDirGroupMember(Entry accountEntry, String groupName) throws assertAttributeContains(accountEntry, ATTRIBUTE_SECURITY_EQUALS_NAME, groupEntry.getDn().toString()); return groupEntry; } - + private void assertEDirNoGroupMember(Entry accountEntry, String groupName) throws LdapException, IOException, CursorException, SchemaException { Entry groupEntry = getLdapGroupByName(groupName); assertAttributeNotContains(groupEntry, getLdapGroupMemberAttribute(), accountEntry.getDn().toString()); @@ -1120,7 +1120,7 @@ private void assertEDirNoGroupMember(Entry accountEntry, String groupName) throw assertAttributeNotContains(accountEntry, ATTRIBUTE_GROUP_MEMBERSHIP_NAME, groupEntry.getDn().toString()); assertAttributeNotContains(accountEntry, ATTRIBUTE_SECURITY_EQUALS_NAME, groupEntry.getDn().toString()); } - + protected String toOrgGroupDn(String cn) { return "cn="+cn+","+getOrgGroupsLdapSuffix(); } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractLdapConnTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractLdapConnTest.java index c6073dd0191..fca3c4c06e9 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractLdapConnTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractLdapConnTest.java @@ -91,9 +91,9 @@ @ContextConfiguration(locations = {"classpath:ctx-conntest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public abstract class AbstractLdapConnTest extends AbstractLdapSynchronizationTest { - + private static final Trace LOGGER = TraceManager.getTrace(AbstractLdapConnTest.class); - + protected static final String ACCOUNT_IDM_DN = "uid=idm,ou=Administrators,dc=example,dc=com"; protected static final String ACCOUNT_0_UID = "u00000000"; protected static final String ACCOUNT_19_UID = "u00000019"; @@ -113,7 +113,7 @@ public abstract class AbstractLdapConnTest extends AbstractLdapSynchronizationTe private static final String USER_LARGO_NAME = "LarGO"; private static final String USER_LARGO_GIVEN_NAME = "Largo"; private static final String USER_LARGO_FAMILY_NAME = "LaGrande"; - + protected static final File ROLE_UNDEAD_FILE = new File (COMMON_DIR, "role-undead.xml"); protected static final String ROLE_UNDEAD_OID = "54885c40-ffcc-11e5-b782-63b3e4e2a69d"; @@ -122,7 +122,7 @@ public abstract class AbstractLdapConnTest extends AbstractLdapSynchronizationTe protected static final String GROUP_UNDEAD_CN = "undead"; protected static final String GROUP_UNDEAD_DESCRIPTION = "Death is for loosers"; - + protected static final String GROUP_EVIL_CN = "evil"; protected static final String GROUP_EVIL_DESCRIPTION = "No pain no gain"; @@ -136,28 +136,28 @@ public abstract class AbstractLdapConnTest extends AbstractLdapSynchronizationTe protected String accountLechuckDn; protected String groupEvilShadowOid; - + @Autowired protected ReconciliationTaskHandler reconciliationTaskHandler; - + protected boolean isIdmAdminInteOrgPerson() { return false; } - + protected File getResourceFile() { return new File(getBaseDir(), "resource.xml"); } - + protected abstract String getAccount0Cn(); - + protected int getNumberOfAllAccounts() { return NUMBER_OF_GENERATED_ACCOUNTS + (isIdmAdminInteOrgPerson()?1:0); } - + protected boolean hasAssociationShortcut() { return true; } - + protected boolean isVlvSearchBeyondEndResurnsLastEntry() { return false; } @@ -165,33 +165,33 @@ protected boolean isVlvSearchBeyondEndResurnsLastEntry() { @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + // Users repoAddObjectFromFile(USER_BARBOSSA_FILE, initResult); repoAddObjectFromFile(USER_GUYBRUSH_FILE, initResult); repoAddObjectFromFile(USER_LECHUCK_FILE, initResult); - + // Roles repoAddObjectFromFileReplaceResource(ROLE_UNDEAD_FILE, RoleType.class, initResult); repoAddObjectFromFileReplaceResource(ROLE_EVIL_FILE, RoleType.class, initResult); } - + protected void repoAddObjectFromFileReplaceResource(File file, Class type, OperationResult result) throws IOException, SchemaException, ObjectAlreadyExistsException { String fileContent = MiscUtil.readFile(file); String xmlString = fileContent.replaceAll(REGEXP_RESOURCE_OID_PLACEHOLDER, getResourceOid()); PrismObject object = PrismTestUtil.parseObject(xmlString); repositoryService.addObject(object, null, result); } - + @Test public void test000Sanity() throws Exception { super.test000Sanity(); cleanupDelete(toAccountDn(USER_BARBOSSA_USERNAME)); cleanupDelete(toAccountDn(USER_CPTBARBOSSA_USERNAME)); - + cleanupDelete(toGroupDn(GROUP_UNDEAD_CN)); cleanupDelete(toGroupDn(GROUP_EVIL_CN)); - + if (needsGroupFakeMemeberEntry()) { addLdapGroup(GROUP_UNDEAD_CN, GROUP_UNDEAD_DESCRIPTION, "uid=fake,"+getPeopleLdapSuffix()); addLdapGroup(GROUP_EVIL_CN, GROUP_EVIL_DESCRIPTION, "uid=fake,"+getPeopleLdapSuffix()); @@ -200,38 +200,38 @@ public void test000Sanity() throws Exception { addLdapGroup(GROUP_EVIL_CN, GROUP_EVIL_DESCRIPTION); } } - + @Test public void test100SeachAccount0ByLdapUid() throws Exception { final String TEST_NAME = "test100SeachAccount0ByLdapUid"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = createUidQuery(ACCOUNT_0_UID); - + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); SearchResultList> shadows = modelService.searchObjects(ShadowType.class, query, null, task, result); - + assertEquals("Unexpected search result: "+shadows, 1, shadows.size()); - + PrismObject shadow = shadows.get(0); assertAccountShadow(shadow, toAccountDn(ACCOUNT_0_UID)); - + assertConnectorOperationIncrement(1, 2); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + SearchResultMetadata metadata = shadows.getMetadata(); if (metadata != null) { assertFalse(metadata.isPartialResults()); } - + assertLdapConnectorInstances(1); } @@ -242,26 +242,26 @@ public void test100SeachAccount0ByLdapUid() throws Exception { public void test150SeachAllAccounts() throws Exception { final String TEST_NAME = "test150SeachAllAccounts"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - + SearchResultList> searchResultList = doSearch(TEST_NAME, query, getNumberOfAllAccounts(), task, result); - + assertConnectorOperationIncrement(1, getNumberOfAllAccounts() + 1); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + SearchResultMetadata metadata = searchResultList.getMetadata(); if (metadata != null) { assertFalse(metadata.isPartialResults()); } - + assertLdapConnectorInstances(1, 2); } - + /** * Blocksize is 100, so this is in one block. */ @@ -269,30 +269,30 @@ public void test150SeachAllAccounts() throws Exception { public void test152SeachFirst50Accounts() throws Exception { final String TEST_NAME = "test152SeachFirst50Accounts"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - + ObjectPaging paging = ObjectPaging.createEmptyPaging(); paging.setMaxSize(50); query.setPaging(paging); - + SearchResultList> searchResultList = doSearch(TEST_NAME, query, 50, task, result); - + assertConnectorOperationIncrement(1, 51); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + SearchResultMetadata metadata = searchResultList.getMetadata(); if (metadata != null) { assertFalse(metadata.isPartialResults()); } - + assertLdapConnectorInstances(1, 2); } - + /** * Blocksize is 100, so this gets more than two blocks. */ @@ -300,30 +300,30 @@ public void test152SeachFirst50Accounts() throws Exception { public void test154SeachFirst222Accounts() throws Exception { final String TEST_NAME = "test154SeachFirst222Accounts"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - + ObjectPaging paging = ObjectPaging.createEmptyPaging(); paging.setMaxSize(222); query.setPaging(paging); - + SearchResultList> searchResultList = doSearch(TEST_NAME, query, 222, task, result); - + assertConnectorOperationIncrement(1, 223); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + SearchResultMetadata metadata = searchResultList.getMetadata(); if (metadata != null) { assertFalse(metadata.isPartialResults()); } - + assertLdapConnectorInstances(1, 2); } - + /** * Make a search that starts in the list of all accounts but goes beyond the end. */ @@ -331,28 +331,28 @@ public void test154SeachFirst222Accounts() throws Exception { public void test156SeachThroughEnd() throws Exception { final String TEST_NAME = "test156SeachBeyondEnd"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - + ObjectPaging paging = ObjectPaging.createEmptyPaging(); paging.setOffset(getNumberOfAllAccounts() - 150); paging.setMaxSize(333); query.setPaging(paging); - + SearchResultList> searchResultList = doSearch(TEST_NAME, query, 150, task, result); - + assertConnectorOperationIncrement(1, 151); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + SearchResultMetadata metadata = searchResultList.getMetadata(); if (metadata != null) { assertFalse(metadata.isPartialResults()); } - + assertLdapConnectorInstances(1, 2); } @@ -363,66 +363,66 @@ public void test156SeachThroughEnd() throws Exception { public void test158SeachBeyondEnd() throws Exception { final String TEST_NAME = "test158SeachBeyondEnd"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - + ObjectPaging paging = ObjectPaging.createEmptyPaging(); paging.setOffset(getNumberOfAllAccounts() + 50); paging.setMaxSize(123); query.setPaging(paging); - + int expectedEntries = 0; if (isVlvSearchBeyondEndResurnsLastEntry()) { expectedEntries = 1; } SearchResultList> searchResultList = doSearch(TEST_NAME, query, expectedEntries, task, result); - + // Fails for 389ds tests. For some unknown reason. And this is not that important. There are similar asserts in other tests that are passing. // assertConnectorOperationIncrement(1); - + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + SearchResultMetadata metadata = searchResultList.getMetadata(); if (metadata != null) { assertFalse(metadata.isPartialResults()); } - + assertLdapConnectorInstances(1, 2); - } + } @Test public void test162SeachFirst50AccountsOffset0() throws Exception { final String TEST_NAME = "test152SeachFirst50Accounts"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - + ObjectPaging paging = ObjectPaging.createEmptyPaging(); paging.setOffset(0); paging.setMaxSize(50); query.setPaging(paging); - + SearchResultList> searchResultList = doSearch(TEST_NAME, query, 50, task, result); - + assertConnectorOperationIncrement(1, 51); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + SearchResultMetadata metadata = searchResultList.getMetadata(); if (metadata != null) { assertFalse(metadata.isPartialResults()); } - + assertLdapConnectorInstances(1, 2); } - + /** * Blocksize is 100, so this is in one block. * There is offset, so VLV should be used. @@ -432,26 +432,26 @@ public void test162SeachFirst50AccountsOffset0() throws Exception { public void test172Search50AccountsOffset20() throws Exception { final String TEST_NAME = "test172Search50AccountsOffset20"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - + ObjectPaging paging = ObjectPaging.createPaging(20, 50); query.setPaging(paging); - + SearchResultList> searchResultList = doSearch(TEST_NAME, query, 50, task, result); - + assertConnectorOperationIncrement(1, 51); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + SearchResultMetadata metadata = searchResultList.getMetadata(); if (metadata != null) { assertFalse(metadata.isPartialResults()); } - + assertLdapConnectorInstances(1, 2); } @@ -464,21 +464,21 @@ public void test172Search50AccountsOffset20() throws Exception { public void test174SeachFirst222AccountsOffset20() throws Exception { final String TEST_NAME = "test174SeachFirst222AccountsOffset20"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - + ObjectPaging paging = ObjectPaging.createPaging(20, 222); query.setPaging(paging); - + SearchResultList> searchResultList = doSearch(TEST_NAME, query, 222, task, result); - + assertConnectorOperationIncrement(1, 223); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + SearchResultMetadata metadata = searchResultList.getMetadata(); if (metadata != null) { assertFalse(metadata.isPartialResults()); @@ -486,7 +486,7 @@ public void test174SeachFirst222AccountsOffset20() throws Exception { assertLdapConnectorInstances(1, 2); } - + /** * Blocksize is 100, so this is in one block. * There is offset, so VLV should be used. @@ -496,25 +496,25 @@ public void test174SeachFirst222AccountsOffset20() throws Exception { public void test182Search50AccountsOffset20SortUid() throws Exception { final String TEST_NAME = "test182Search50AccountsOffset20SortUid"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - + ObjectPaging paging = ObjectPaging.createPaging(20, 50); paging.setOrdering(getAttributePath(resource, "uid"), OrderDirection.ASCENDING); query.setPaging(paging); - + SearchResultList> shadows = doSearch(TEST_NAME, query, 50, task, result); - + assertAccountShadow(shadows.get(0), toAccountDn(isIdmAdminInteOrgPerson()?ACCOUNT_19_UID:ACCOUNT_20_UID)); assertAccountShadow(shadows.get(49), toAccountDn(isIdmAdminInteOrgPerson()?ACCOUNT_68_UID:ACCOUNT_69_UID)); - + assertConnectorOperationIncrement(1, 51); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + SearchResultMetadata metadata = shadows.getMetadata(); if (metadata != null) { assertFalse(metadata.isPartialResults()); @@ -532,33 +532,33 @@ public void test182Search50AccountsOffset20SortUid() throws Exception { public void test184SearchFirst222AccountsOffset20SortUid() throws Exception { final String TEST_NAME = "test184SeachFirst222AccountsOffset20SortUid"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - + ObjectPaging paging = ObjectPaging.createPaging(20, 222); paging.setOrdering(getAttributePath(resource, "uid"), OrderDirection.ASCENDING); query.setPaging(paging); - + SearchResultList> shadows = doSearch(TEST_NAME, query, 222, task, result); - + assertAccountShadow(shadows.get(0), toAccountDn(isIdmAdminInteOrgPerson()?ACCOUNT_19_UID:ACCOUNT_20_UID)); assertAccountShadow(shadows.get(221), toAccountDn(isIdmAdminInteOrgPerson()?ACCOUNT_240_UID:ACCOUNT_241_UID)); - + assertConnectorOperationIncrement(1, 223); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + SearchResultMetadata metadata = shadows.getMetadata(); if (metadata != null) { assertFalse(metadata.isPartialResults()); } - + assertLdapConnectorInstances(1, 2); } - + /** * No paging. Allow incomplete results. This should violate sizelimit, but some results should * be returned anyway. @@ -567,26 +567,26 @@ public void test184SearchFirst222AccountsOffset20SortUid() throws Exception { public void test190SeachAllAccountsSizelimit() throws Exception { final String TEST_NAME = "test190SeachAllAccountsSizelimit"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); query.setAllowPartialResults(true); - + SearchResultList> resultList = doSearch(TEST_NAME, query, getSearchSizeLimit(), task, result); - + assertConnectorOperationIncrement(1, getSearchSizeLimit() + 1); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + SearchResultMetadata metadata = resultList.getMetadata(); assertNotNull("No search metadata", metadata); assertTrue("Partial results not indicated", metadata.isPartialResults()); - + assertLdapConnectorInstances(1, 2); } - + /** * Do many searches with different sorting and paging options. This test is designed * to deplete SSS/VLV resources on the LDAP server side, so the server may reach with @@ -597,12 +597,12 @@ public void test190SeachAllAccountsSizelimit() throws Exception { public void test195SearchInferno() throws Exception { final String TEST_NAME = "test195SearchInferno"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - + // WHEN TestUtil.displayWhen(TEST_NAME); singleInfernoSearch(query, 30, 10, 30, "uid", task, result); @@ -610,18 +610,18 @@ public void test195SearchInferno() throws Exception { singleInfernoSearch(query, 15, 2, 15, "sn", task, result); singleInfernoSearch(query, 42, 200, 42, "uid", task, result); singleInfernoSearch(query, 200, 30, 200, "sn", task, result); - + assertConnectorOperationIncrement(5, 332); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + assertLdapConnectorInstances(1, 2); } - + private void singleInfernoSearch(ObjectQuery query, int expectedNumberOfResults, Integer offset, Integer maxSize, String sortAttrName, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { ObjectPaging paging = ObjectPaging.createPaging(offset, maxSize); paging.setOrdering(getAttributePath(resource, sortAttrName), OrderDirection.ASCENDING); query.setPaging(paging); - + final MutableInt count = new MutableInt(); ResultHandler handler = new ResultHandler() { @Override @@ -630,16 +630,16 @@ public boolean handle(PrismObject object, OperationResult parentResu return true; } }; - + modelService.searchObjectsIterative(ShadowType.class, query, handler, null, task, result); - + assertEquals("Unexpected number of search results", expectedNumberOfResults, count.intValue()); } - + // TODO: scoped search // TODO: count shadows - + @Test public void test200AssignAccountToBarbossa() throws Exception { final String TEST_NAME = "test200AssignAccountToBarbossa"; @@ -649,23 +649,23 @@ public void test200AssignAccountToBarbossa() throws Exception { Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); long tsStart = System.currentTimeMillis(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignAccount(USER_BARBOSSA_OID, getResourceOid(), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + long tsEnd = System.currentTimeMillis(); assertLdapConnectorInstances(1, 2); - + 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); @@ -674,17 +674,17 @@ public void test200AssignAccountToBarbossa() throws Exception { Collection> identifiers = ShadowUtil.getPrimaryIdentifiers(shadow); accountBarbossaEntryId = (String) identifiers.iterator().next().getRealValue(); assertNotNull("No identifier in "+shadow, accountBarbossaEntryId); - + assertEquals("Wrong ICFS UID", getAttributeAsString(entry, getPrimaryIdentifierAttributeName()), accountBarbossaEntryId); - + assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_PASSWORD); - + ResourceAttribute createTimestampAttribute = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, "createTimestamp")); assertNotNull("No createTimestamp in "+shadow, createTimestampAttribute); Long createTimestamp = createTimestampAttribute.getRealValue(); // LDAP server may be on a different host. Allow for some clock offset. TestUtil.assertBetween("Wrong createTimestamp in "+shadow, roundTsDown(tsStart)-1000, roundTsUp(tsEnd)+1000, createTimestamp); - + assertLdapConnectorInstances(1, 2); } @@ -696,18 +696,18 @@ public void test210ModifyAccountBarbossaReplaceTitle() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta delta = ObjectDelta.createEmptyModifyDelta(ShadowType.class, accountBarbossaOid, prismContext); QName attrQName = new QName(MidPointConstants.NS_RI, "title"); ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); PropertyDelta attrDelta = PropertyDelta.createModificationReplaceProperty( new ItemPath(ShadowType.F_ATTRIBUTES, attrQName), attrDef, "Captain"); delta.addModification(attrDelta); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -715,14 +715,14 @@ public void test210ModifyAccountBarbossaReplaceTitle() throws Exception { Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); assertAttribute(entry, "title", "Captain"); - + PrismObject user = getUser(USER_BARBOSSA_OID); String shadowOid = getSingleLinkOid(user); assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - + assertLdapConnectorInstances(1, 2); } - + /** * Make a duplicate modification. Add a title value that is already there. * Normal LDAP should fail. So check that connector and midPoint handles that. @@ -735,18 +735,18 @@ public void test212ModifyAccountBarbossaAddTitleDuplicate() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta delta = ObjectDelta.createEmptyModifyDelta(ShadowType.class, accountBarbossaOid, prismContext); QName attrQName = new QName(MidPointConstants.NS_RI, "title"); ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); PropertyDelta attrDelta = PropertyDelta.createModificationAddProperty( new ItemPath(ShadowType.F_ATTRIBUTES, attrQName), attrDef, "Captain"); delta.addModification(attrDelta); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -754,14 +754,14 @@ public void test212ModifyAccountBarbossaAddTitleDuplicate() throws Exception { Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); assertAttribute(entry, "title", "Captain"); - + PrismObject user = getUser(USER_BARBOSSA_OID); String shadowOid = getSingleLinkOid(user); assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - + assertLdapConnectorInstances(1, 2); } - + /** * Make another duplicate modification. Add a title value that is already there, * but with a different capitalization. @@ -774,18 +774,18 @@ public void test213ModifyAccountBarbossaAddTitleDuplicateCapitalized() throws Ex // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ObjectDelta delta = ObjectDelta.createEmptyModifyDelta(ShadowType.class, accountBarbossaOid, prismContext); QName attrQName = new QName(MidPointConstants.NS_RI, "title"); ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); PropertyDelta attrDelta = PropertyDelta.createModificationAddProperty( new ItemPath(ShadowType.F_ATTRIBUTES, attrQName), attrDef, "CAPTAIN"); delta.addModification(attrDelta); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -793,14 +793,14 @@ public void test213ModifyAccountBarbossaAddTitleDuplicateCapitalized() throws Ex Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); assertAttribute(entry, "title", "Captain"); - + PrismObject user = getUser(USER_BARBOSSA_OID); String shadowOid = getSingleLinkOid(user); assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - + assertLdapConnectorInstances(1, 2); } - + @Test public void test220ModifyUserBarbossaPassword() throws Exception { final String TEST_NAME = "test220ModifyUserBarbossaPassword"; @@ -809,16 +809,16 @@ public void test220ModifyUserBarbossaPassword() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + ProtectedStringType userPasswordPs = new ProtectedStringType(); userPasswordPs.setClearValue(USER_BARBOSSA_PASSWORD_2); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyUserReplace(USER_BARBOSSA_OID, - new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), + modifyUserReplace(USER_BARBOSSA_OID, + new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE), task, result, userPasswordPs); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -827,14 +827,14 @@ public void test220ModifyUserBarbossaPassword() throws Exception { Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); assertAttribute(entry, "title", "Captain"); assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_PASSWORD_2); - + PrismObject user = getUser(USER_BARBOSSA_OID); String shadowOid = getSingleLinkOid(user); assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - + assertLdapConnectorInstances(1, 2); } - + @Test public void test230ModifyUserBarbossaEmployeeType() throws Exception { final String TEST_NAME = "test230ModifyUserBarbossaEmployeeType"; @@ -843,11 +843,11 @@ public void test230ModifyUserBarbossaEmployeeType() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserReplace(USER_BARBOSSA_OID, UserType.F_EMPLOYEE_TYPE, task, result, "Pirate"); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -855,14 +855,14 @@ public void test230ModifyUserBarbossaEmployeeType() throws Exception { Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); assertAttribute(entry, "employeeType", "Pirate"); - + PrismObject user = getUser(USER_BARBOSSA_OID); String shadowOid = getSingleLinkOid(user); assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - + assertLdapConnectorInstances(1, 2); } - + @Test public void test232ModifyUserBarbossaEmployeeTypeAgain() throws Exception { final String TEST_NAME = "test232ModifyUserBarbossaEmployeeTypeAgain"; @@ -871,11 +871,11 @@ public void test232ModifyUserBarbossaEmployeeTypeAgain() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserReplace(USER_BARBOSSA_OID, UserType.F_EMPLOYEE_TYPE, task, result, "Pirate"); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -883,11 +883,11 @@ public void test232ModifyUserBarbossaEmployeeTypeAgain() throws Exception { Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); assertAttribute(entry, "employeeType", "Pirate"); - + PrismObject user = getUser(USER_BARBOSSA_OID); String shadowOid = getSingleLinkOid(user); assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - + assertLdapConnectorInstances(1, 2); } @@ -899,11 +899,11 @@ public void test234ModifyUserBarbossaEmployeeTypeAgainCapitalized() throws Excep // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserReplace(USER_BARBOSSA_OID, UserType.F_EMPLOYEE_TYPE, task, result, "PIRATE"); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -911,14 +911,14 @@ public void test234ModifyUserBarbossaEmployeeTypeAgainCapitalized() throws Excep Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); assertAttribute(entry, "employeeType", "Pirate"); - + PrismObject user = getUser(USER_BARBOSSA_OID); String shadowOid = getSingleLinkOid(user); assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - + assertLdapConnectorInstances(1, 2); } - + @Test public void test290ModifyUserBarbossaRename() throws Exception { final String TEST_NAME = "test290ModifyUserBarbossaRename"; @@ -927,11 +927,11 @@ public void test290ModifyUserBarbossaRename() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserReplace(USER_BARBOSSA_OID, UserType.F_NAME, task, result, PrismTestUtil.createPolyString(USER_CPTBARBOSSA_USERNAME)); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -941,24 +941,24 @@ public void test290ModifyUserBarbossaRename() throws Exception { display("LDAP entry after", entry); assertEquals("Wrong DN", toAccountDn(USER_CPTBARBOSSA_USERNAME), entry.getDn().toString()); assertAttribute(entry, "title", "Captain"); - + PrismObject user = getUser(USER_BARBOSSA_OID); String shadowOid = getSingleLinkOid(user); assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - + PrismObject repoShadow = repositoryService.getObject(ShadowType.class, shadowOid, null, result); display("Repo shadow after rename", repoShadow); - + String repoPrimaryIdentifier = ShadowUtil.getAttributeValue(repoShadow, getPrimaryIdentifierAttributeQName()); if ("dn".equals(getPrimaryIdentifierAttributeName())) { assertEquals("Entry DN (primary identifier) was not updated in the shadow", toAccountDn(USER_CPTBARBOSSA_USERNAME).toLowerCase(), repoPrimaryIdentifier); } else { assertEquals("Entry ID changed after rename", accountBarbossaEntryId, repoPrimaryIdentifier); } - + assertLdapConnectorInstances(1, 2); } - + /** * Try the rename again. This time just as a capitalization of the original name. * The DN should not change. @@ -971,43 +971,43 @@ public void test292ModifyUserBarbossaRenameCapitalized() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); - modifyUserReplace(USER_BARBOSSA_OID, UserType.F_NAME, task, result, + modifyUserReplace(USER_BARBOSSA_OID, UserType.F_NAME, task, result, PrismTestUtil.createPolyString(USER_CPTBARBOSSA_USERNAME.toUpperCase())); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + Entry entry = assertLdapAccount(USER_CPTBARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); display("LDAP entry after", entry); assertAttribute(entry, "title", "Captain"); assertEquals("Wrong DN", toAccountDn(USER_CPTBARBOSSA_USERNAME), entry.getDn().toString()); - + assertConnectorOperationIncrement(1, 2); // Just account read, no modify - + PrismObject user = getUser(USER_BARBOSSA_OID); String shadowOid = getSingleLinkOid(user); assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - + PrismObject repoShadow = repositoryService.getObject(ShadowType.class, shadowOid, null, result); display("Repo shadow after rename", repoShadow); - + String repoPrimaryIdentifier = ShadowUtil.getAttributeValue(repoShadow, getPrimaryIdentifierAttributeQName()); if ("dn".equals(getPrimaryIdentifierAttributeName())) { assertEquals("Entry DN (primary identifier) was not updated in the shadow", toAccountDn(USER_CPTBARBOSSA_USERNAME).toLowerCase(), repoPrimaryIdentifier); } else { assertEquals("Entry ID changed after rename", accountBarbossaEntryId, repoPrimaryIdentifier); } - + assertLdapConnectorInstances(1, 2); } - + @Test public void test299UnAssignAccountBarbossa() throws Exception { final String TEST_NAME = "test299UnAssignAccountBarbossa"; @@ -1016,11 +1016,11 @@ public void test299UnAssignAccountBarbossa() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); unassignAccount(USER_BARBOSSA_OID, getResourceOid(), null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -1028,13 +1028,13 @@ public void test299UnAssignAccountBarbossa() throws Exception { assertNoLdapAccount(USER_BARBOSSA_USERNAME); assertNoLdapAccount(USER_CPTBARBOSSA_USERNAME); - + PrismObject user = getUser(USER_BARBOSSA_OID); assertNoLinkedAccount(user); - + assertLdapConnectorInstances(1, 2); } - + /** * MID-2853: Unexpected association behaviour - removing roles does not always remove from groups */ @@ -1046,18 +1046,18 @@ public void test300AssignRoleEvilToLechuck() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_LECHUCK_OID, ROLE_EVIL_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + Entry entry = assertLdapAccount(USER_LECHUCK_USERNAME, USER_LECHUCK_FULL_NAME); - + PrismObject user = getUser(USER_LECHUCK_OID); String shadowOid = getSingleLinkOid(user); PrismObject shadow = getShadowModel(shadowOid); @@ -1065,18 +1065,18 @@ public void test300AssignRoleEvilToLechuck() throws Exception { accountLechuckOid = shadow.getOid(); accountLechuckDn = entry.getDn().toString(); assertNotNull(accountLechuckDn); - + assertLdapGroupMember(entry, GROUP_EVIL_CN); assertLdapNoGroupMember(entry, GROUP_UNDEAD_CN); - + Entry ldapEntryEvil = getLdapEntry(toGroupDn(GROUP_EVIL_CN)); display("Evil group", ldapEntryEvil); Entry ldapEntryUndead = getLdapEntry(toGroupDn(GROUP_UNDEAD_CN)); display("Undead group", ldapEntryUndead); - + assertLdapConnectorInstances(1, 2); } - + /** * MID-2853: Unexpected association behaviour - removing roles does not always remove from groups */ @@ -1088,34 +1088,34 @@ public void test302AssignRoleUndeadToLechuck() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_LECHUCK_OID, ROLE_UNDEAD_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + Entry entry = assertLdapAccount(USER_LECHUCK_USERNAME, USER_LECHUCK_FULL_NAME); - + PrismObject user = getUser(USER_LECHUCK_OID); String shadowOid = getSingleLinkOid(user); PrismObject shadow = getShadowModel(shadowOid); display("Shadow (model)", shadow); - + assertLdapGroupMember(entry, GROUP_EVIL_CN); assertLdapGroupMember(entry, GROUP_UNDEAD_CN); - + Entry ldapEntryEvil = getLdapEntry(toGroupDn(GROUP_EVIL_CN)); display("Evil group", ldapEntryEvil); Entry ldapEntryUndead = getLdapEntry(toGroupDn(GROUP_UNDEAD_CN)); display("Undead group", ldapEntryUndead); - + assertLdapConnectorInstances(1, 2); } - + /** * MID-2853: Unexpected association behaviour - removing roles does not always remove from groups */ @@ -1127,34 +1127,34 @@ public void test306UnassignRoleEvilFromLechuck() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); unassignRole(USER_LECHUCK_OID, ROLE_EVIL_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + Entry entry = assertLdapAccount(USER_LECHUCK_USERNAME, USER_LECHUCK_FULL_NAME); - + PrismObject user = getUser(USER_LECHUCK_OID); String shadowOid = getSingleLinkOid(user); PrismObject shadow = getShadowModel(shadowOid); display("Shadow (model)", shadow); - + assertLdapNoGroupMember(entry, GROUP_EVIL_CN); assertLdapGroupMember(entry, GROUP_UNDEAD_CN); - + Entry ldapEntryEvil = getLdapEntry(toGroupDn(GROUP_EVIL_CN)); display("Evil group", ldapEntryEvil); Entry ldapEntryUndead = getLdapEntry(toGroupDn(GROUP_UNDEAD_CN)); display("Undead group", ldapEntryUndead); - + assertLdapConnectorInstances(1, 2); } - + /** * MID-2853: Unexpected association behaviour - removing roles does not always remove from groups */ @@ -1166,70 +1166,70 @@ public void test309UnassignRoleUndeadFromLechuck() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); unassignRole(USER_LECHUCK_OID, ROLE_UNDEAD_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject user = getUser(USER_LECHUCK_OID); assertNoLinkedAccount(user); assertNoEntry(accountLechuckDn); - + assertNoObject(ShadowType.class, accountLechuckOid, task, result); - + assertLdapNoGroupMember(accountLechuckDn, GROUP_EVIL_CN); assertLdapNoGroupMember(accountLechuckDn, GROUP_UNDEAD_CN); - + Entry ldapEntryEvil = getLdapEntry(toGroupDn(GROUP_EVIL_CN)); display("Evil group", ldapEntryEvil); Entry ldapEntryUndead = getLdapEntry(toGroupDn(GROUP_UNDEAD_CN)); display("Undead group", ldapEntryUndead); - + assertLdapConnectorInstances(1, 2); } - + @Test public void test310SeachGroupEvilByCn() throws Exception { final String TEST_NAME = "test310SeachGroupEvilByCn"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getGroupObjectClass(), prismContext); ObjectQueryUtil.filterAnd(query.getFilter(), createAttributeFilter("cn", GROUP_EVIL_CN)); - + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); SearchResultList> shadows = modelService.searchObjects(ShadowType.class, query, null, task, result); - + assertEquals("Unexpected search result: "+shadows, 1, shadows.size()); - + PrismObject shadow = shadows.get(0); assertGroupShadow(shadow, toGroupDn(GROUP_EVIL_CN)); groupEvilShadowOid = shadow.getOid(); assertNotNull(groupEvilShadowOid); - + assertConnectorOperationIncrement(1, 1); assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - + SearchResultMetadata metadata = shadows.getMetadata(); if (metadata != null) { assertFalse(metadata.isPartialResults()); } - + assertLdapConnectorInstances(1, 2); } - + /** * MID-3209: Rename does not change group membership for associations, when resource does not implement its own referential integrity */ @@ -1241,19 +1241,19 @@ public void test312AssignRoleEvilToBarbossa() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_BARBOSSA_OID, ROLE_EVIL_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + Entry entry = assertLdapAccount(USER_CPTBARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); display("Account LDAP entry", entry); - + PrismObject user = getUser(USER_BARBOSSA_OID); String shadowOid = getSingleLinkOid(user); PrismObject shadow = getShadowModel(shadowOid); @@ -1261,7 +1261,7 @@ public void test312AssignRoleEvilToBarbossa() throws Exception { accountBarbossaOid = shadow.getOid(); accountBarbossaDn = entry.getDn().toString(); assertNotNull(accountBarbossaDn); - + Collection> identifiers = ShadowUtil.getPrimaryIdentifiers(shadow); accountBarbossaEntryId = (String) identifiers.iterator().next().getRealValue(); assertNotNull("No identifier in "+shadow, accountBarbossaEntryId); @@ -1270,12 +1270,12 @@ public void test312AssignRoleEvilToBarbossa() throws Exception { display("Evil group", ldapEntryEvil); Entry ldapEntryUndead = getLdapEntry(toGroupDn(GROUP_UNDEAD_CN)); display("Undead group", ldapEntryUndead); - + assertLdapGroupMember(entry, GROUP_EVIL_CN); assertLdapNoGroupMember(entry, GROUP_UNDEAD_CN); IntegrationTestTools.assertAssociation(shadow, getAssociationGroupName(), groupEvilShadowOid); - + assertLdapConnectorInstances(1, 2); } @@ -1290,15 +1290,15 @@ public void test314ModifyUserBarbossaRenameBack() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_BARBOSSA_OID); display("user defore", userBefore); assertNotNull(userBefore); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserReplace(USER_BARBOSSA_OID, UserType.F_NAME, task, result, PrismTestUtil.createPolyString(USER_BARBOSSA_USERNAME)); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -1307,33 +1307,33 @@ public void test314ModifyUserBarbossaRenameBack() throws Exception { Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); display("LDAP entry after", entry); assertEquals("Wrong DN", toAccountDn(USER_BARBOSSA_USERNAME), entry.getDn().toString()); - + PrismObject user = getUser(USER_BARBOSSA_OID); String shadowOid = getSingleLinkOid(user); assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - + PrismObject repoShadow = repositoryService.getObject(ShadowType.class, shadowOid, null, result); display("Repo shadow after rename", repoShadow); - + String repoPrimaryIdentifier = ShadowUtil.getAttributeValue(repoShadow, getPrimaryIdentifierAttributeQName()); if ("dn".equals(getPrimaryIdentifierAttributeName())) { assertEquals("Entry DN (primary identifier) was not updated in the shadow", toAccountDn(USER_BARBOSSA_USERNAME).toLowerCase(), repoPrimaryIdentifier); } else { assertEquals("Entry ID changed after rename", accountBarbossaEntryId, repoPrimaryIdentifier); } - + Entry ldapEntryEvil = getLdapEntry(toGroupDn(GROUP_EVIL_CN)); display("Evil group", ldapEntryEvil); Entry ldapEntryUndead = getLdapEntry(toGroupDn(GROUP_UNDEAD_CN)); display("Undead group", ldapEntryUndead); - + assertLdapGroupMember(entry, GROUP_EVIL_CN); assertLdapNoGroupMember(accountBarbossaDn, GROUP_EVIL_CN); assertLdapNoGroupMember(entry, GROUP_UNDEAD_CN); assertLdapConnectorInstances(1, 2); } - + /** * Add user that has role evil, check association. Use mixed lower/upper chars in the username. * MID-3713 @@ -1346,21 +1346,21 @@ public void test320AddEvilUserLargo() throws Exception { // GIVEN Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = createUser(USER_LARGO_NAME, USER_LARGO_GIVEN_NAME, USER_LARGO_FAMILY_NAME, true); AssignmentType assignmentType = createTargetAssignment(ROLE_EVIL_OID, RoleType.COMPLEX_TYPE); userBefore.asObjectable().getAssignment().add(assignmentType); display("user before", userBefore); - + // WHEN TestUtil.displayWhen(TEST_NAME); addObject(userBefore, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_LARGO_NAME); display("user after", userAfter); assertAssignedRole(userAfter, ROLE_EVIL_OID); @@ -1372,26 +1372,26 @@ public void test320AddEvilUserLargo() throws Exception { Entry entry = assertLdapAccount(USER_LARGO_NAME, userAfter.asObjectable().getFullName().getOrig()); display("account after", entry); - + assertLdapGroupMember(entry, GROUP_EVIL_CN); assertLdapNoGroupMember(entry, GROUP_UNDEAD_CN); - + Entry ldapEntryEvil = getLdapEntry(toGroupDn(GROUP_EVIL_CN)); display("Evil group", ldapEntryEvil); Entry ldapEntryUndead = getLdapEntry(toGroupDn(GROUP_UNDEAD_CN)); display("Undead group", ldapEntryUndead); - + assertAssociation(shadow, ASSOCIATION_GROUP_NAME, groupEvilShadowOid); - + assertLdapConnectorInstances(1, 2); - } - + } + protected void assertConnectorOperationIncrement(int shortcutIncrement, int noShortcutIncrement) { if (hasAssociationShortcut()) { assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, shortcutIncrement); } else { assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, noShortcutIncrement); - } + } } } 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 53830923be2..05c5e489eff 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 @@ -129,7 +129,7 @@ @ContextConfiguration(locations = {"classpath:ctx-conntest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public abstract class AbstractLdapSynchronizationTest extends AbstractLdapTest { - + private static final Trace LOGGER = TraceManager.getTrace(AbstractLdapSynchronizationTest.class); protected static final String ACCOUNT_HT_UID = "ht"; @@ -147,18 +147,18 @@ public abstract class AbstractLdapSynchronizationTest extends AbstractLdapTest { 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); + super.initSystem(initTask, initResult); } - + @Test public void test000Sanity() throws Exception { cleanupDelete(toAccountDn(ACCOUNT_HT_UID, ACCOUNT_HT_CN)); @@ -166,14 +166,14 @@ public void test000Sanity() throws Exception { 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 { final String TEST_NAME = "test800ImportSyncTask"; @@ -182,25 +182,25 @@ public void test800ImportSyncTask() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + long tsStart = System.currentTimeMillis(); - + // WHEN TestUtil.displayWhen(TEST_NAME); addObject(getSyncTaskFile(), task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); - + long tsEnd = System.currentTimeMillis(); - + assertStepSyncToken(getSyncTaskOid(), 0, tsStart, tsEnd); } - + @Test public void test801SyncAddAccountHt() throws Exception { final String TEST_NAME = "test801SyncAddAccountHt"; @@ -209,30 +209,30 @@ public void test801SyncAddAccountHt() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + long tsStart = System.currentTimeMillis(); - + // WHEN TestUtil.displayWhen(TEST_NAME); addLdapAccount(ACCOUNT_HT_UID, ACCOUNT_HT_CN, ACCOUNT_HT_GIVENNAME, ACCOUNT_HT_SN); waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); - + // THEN TestUtil.displayThen(TEST_NAME); 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(), 1, tsStart, tsEnd); } - + // Do not change cn here. This triggers rename in the AD case. @Test public void test802ModifyAccountHt() throws Exception { @@ -242,9 +242,9 @@ public void test802ModifyAccountHt() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + long tsStart = System.currentTimeMillis(); - + // WHEN TestUtil.displayWhen(TEST_NAME); LdapNetworkConnection connection = ldapConnect(); @@ -253,14 +253,14 @@ public void test802ModifyAccountHt() throws Exception { ldapDisconnect(connection); waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); - + // THEN TestUtil.displayThen(TEST_NAME); 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); @@ -268,7 +268,7 @@ public void test802ModifyAccountHt() throws Exception { assertStepSyncToken(getSyncTaskOid(), 2, tsStart, tsEnd); } - + @Test public void test810SyncAddGroupMonkeys() throws Exception { final String TEST_NAME = "test810SyncAddGroupMonkeys"; @@ -277,9 +277,9 @@ public void test810SyncAddGroupMonkeys() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + long tsStart = System.currentTimeMillis(); - + // WHEN TestUtil.displayWhen(TEST_NAME); if (needsGroupFakeMemeberEntry()) { @@ -288,14 +288,14 @@ public void test810SyncAddGroupMonkeys() throws Exception { addLdapGroup(GROUP_MONKEYS_CN, GROUP_MONKEYS_DESCRIPTION); } waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + long tsEnd = System.currentTimeMillis(); - + PrismObject role = findObjectByName(RoleType.class, GROUP_MONKEYS_CN); display("Role", role); assertNotNull("no role "+GROUP_MONKEYS_CN, role); @@ -304,7 +304,7 @@ public void test810SyncAddGroupMonkeys() throws Exception { assertStepSyncToken(getSyncTaskOid(), 3, tsStart, tsEnd); } - + @Test public void test817RenameAccount() throws Exception { final String TEST_NAME = "test817RenameAccount"; @@ -313,33 +313,33 @@ public void test817RenameAccount() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + long tsStart = System.currentTimeMillis(); - + // WHEN TestUtil.displayWhen(TEST_NAME); 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 TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.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); @@ -348,7 +348,7 @@ public void test817RenameAccount() throws Exception { assertStepSyncToken(getSyncTaskOid(), 4, tsStart, tsEnd); } - + protected String getAccountHtmCnAfterRename() { return ACCOUNT_HT_CN; } @@ -365,24 +365,24 @@ public void test818DeleteAccountHtm() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject user = findUserByUsername(ACCOUNT_HTM_UID); - + long tsStart = System.currentTimeMillis(); - + // WHEN TestUtil.displayWhen(TEST_NAME); deleteLdapEntry(toAccountDn(ACCOUNT_HTM_UID, ACCOUNT_HTM_CN)); waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); - + // THEN TestUtil.displayThen(TEST_NAME); 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)); @@ -393,10 +393,10 @@ public void test818DeleteAccountHtm() throws Exception { assertStepSyncToken(getSyncTaskOid(), 5, tsStart, tsEnd); } - - + + // TODO: sync with "ALL" object class - + @Test public void test819DeleteSyncTask() throws Exception { final String TEST_NAME = "test819DeleteSyncTask"; @@ -405,7 +405,7 @@ public void test819DeleteSyncTask() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); deleteObject(TaskType.class, getSyncTaskOid(), task, result); @@ -414,10 +414,10 @@ public void test819DeleteSyncTask() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertNoObject(TaskType.class, getSyncTaskOid(), task, result); } - + @Test public void test820ImportSyncTaskInetOrgPerson() throws Exception { final String TEST_NAME = "test820ImportSyncTaskInetOrgPerson"; @@ -426,25 +426,25 @@ public void test820ImportSyncTaskInetOrgPerson() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + long tsStart = System.currentTimeMillis(); - + // WHEN TestUtil.displayWhen(TEST_NAME); addObject(getSyncTaskInetOrgPersonFile(), task, result); - + // THEN TestUtil.displayThen(TEST_NAME); 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); } @@ -456,30 +456,30 @@ public void test821SyncAddAccountHt() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + long tsStart = System.currentTimeMillis(); - + // WHEN TestUtil.displayWhen(TEST_NAME); addLdapAccount(ACCOUNT_HT_UID, ACCOUNT_HT_CN, ACCOUNT_HT_GIVENNAME, ACCOUNT_HT_SN); waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); - + // THEN TestUtil.displayThen(TEST_NAME); 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 { final String TEST_NAME = "test822ModifyAccountHt"; @@ -488,9 +488,9 @@ public void test822ModifyAccountHt() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + long tsStart = System.currentTimeMillis(); - + // WHEN TestUtil.displayWhen(TEST_NAME); LdapNetworkConnection connection = ldapConnect(); @@ -499,21 +499,21 @@ public void test822ModifyAccountHt() throws Exception { ldapDisconnect(connection); waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); - + // THEN TestUtil.displayThen(TEST_NAME); 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. */ @@ -525,27 +525,27 @@ public void test830AddGroupFools() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + long tsStart = System.currentTimeMillis(); - + // WHEN TestUtil.displayWhen(TEST_NAME); addLdapGroup(GROUP_FOOLS_CN, GROUP_FOOLS_DESCRIPTION, toGroupDn("nobody")); waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.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 { final String TEST_NAME = "test837RenameAccount"; @@ -554,33 +554,33 @@ public void test837RenameAccount() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + long tsStart = System.currentTimeMillis(); - + // WHEN TestUtil.displayWhen(TEST_NAME); 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 TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.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); @@ -589,9 +589,9 @@ public void test837RenameAccount() throws Exception { 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 { final String TEST_NAME = "test838DeleteAccountHtm"; @@ -600,24 +600,24 @@ public void test838DeleteAccountHtm() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject user = findUserByUsername(ACCOUNT_HTM_UID); - + long tsStart = System.currentTimeMillis(); - + // WHEN TestUtil.displayWhen(TEST_NAME); deleteLdapEntry(toAccountDn(ACCOUNT_HTM_UID,ACCOUNT_HTM_CN)); waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); - + // THEN TestUtil.displayThen(TEST_NAME); 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)); @@ -637,7 +637,7 @@ public void test839DeleteSyncTask() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); deleteObject(TaskType.class, getSyncTaskOid(), task, result); @@ -646,8 +646,8 @@ public void test839DeleteSyncTask() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertNoObject(TaskType.class, getSyncTaskOid(), task, result); } - + } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractLdapTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractLdapTest.java index 047995bba32..fb104851bca 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractLdapTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractLdapTest.java @@ -136,77 +136,77 @@ @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public abstract class AbstractLdapTest extends AbstractModelIntegrationTest { - + private static final Trace LOGGER = TraceManager.getTrace(AbstractLdapTest.class); - + 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 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 USER_BARBOSSA_FILE = new File(COMMON_DIR, "user-barbossa.xml"); protected static final String USER_BARBOSSA_OID = "c0c010c0-d34d-b33f-f00d-111111111112"; protected static final String USER_BARBOSSA_USERNAME = "barbossa"; protected static final String USER_BARBOSSA_FULL_NAME = "Hector Barbossa"; protected static final String USER_BARBOSSA_PASSWORD = "deadjack.tellnotales123"; protected static final String USER_BARBOSSA_PASSWORD_2 = "hereThereBeMonsters"; - + // Barbossa after rename protected static final String USER_CPTBARBOSSA_USERNAME = "cptbarbossa"; - + protected static final File USER_GUYBRUSH_FILE = new File (COMMON_DIR, "user-guybrush.xml"); protected static final String USER_GUYBRUSH_OID = "c0c010c0-d34d-b33f-f00d-111111111116"; protected static final String USER_GUYBRUSH_USERNAME = "guybrush"; protected static final String USER_GUYBRUSH_FULL_NAME = "Guybrush Threepwood"; - + protected static final File USER_LECHUCK_FILE = new File (COMMON_DIR, "user-lechuck.xml"); protected static final String USER_LECHUCK_OID = "0201583e-ffca-11e5-a949-affff1aa5a60"; protected static final String USER_LECHUCK_USERNAME = "lechuck"; protected static final String USER_LECHUCK_FULL_NAME = "LeChuck"; - + protected static final String LDAP_INETORGPERSON_OBJECTCLASS = "inetOrgPerson"; - + protected static final QName ASSOCIATION_GROUP_NAME = new QName(MidPointConstants.NS_RI, "group"); - + @Autowired(required = true) protected MatchingRuleRegistry matchingRuleRegistry; - + @Autowired protected ReconciliationTaskHandler reconciliationTaskHandler; - + protected ResourceType resourceType; protected PrismObject resource; - + protected MatchingRule dnMatchingRule; protected MatchingRule ciMatchingRule; - + private static String stopCommand; - + protected ObjectClassComplexTypeDefinition accountObjectClassDefinition; - + protected DefaultConfigurableBinaryAttributeDetector binaryAttributeDetector = new DefaultConfigurableBinaryAttributeDetector(); - + protected Lsof lsof; - + @Override protected void startResources() throws Exception { super.startResources(); - + String command = getStartSystemCommand(); if (command != null) { TestUtil.execSystemCommand(command); } stopCommand = getStopSystemCommand(); } - + public abstract String getStartSystemCommand(); - + public abstract String getStopSystemCommand(); @AfterClass @@ -214,64 +214,64 @@ public static void stopResources() throws Exception { //end profiling ProfilingDataManager.getInstance().printMapAfterTest(); ProfilingDataManager.getInstance().stopProfilingAfterTest(); - + if (stopCommand != null) { TestUtil.execSystemCommand(stopCommand); } } - + protected abstract String getResourceOid(); protected abstract File getBaseDir(); - + protected File getResourceFile() { return new File(getBaseDir(), "resource.xml"); } - + protected File getSyncTaskFile() { return new File(getBaseDir(), "task-sync.xml"); } - + protected String getResourceNamespace() { return MidPointConstants.NS_RI; } - + protected File getSyncTaskInetOrgPersonFile() { return new File(getBaseDir(), "task-sync-inetorgperson.xml"); } - + protected abstract String getSyncTaskOid(); - + protected QName getAccountObjectClass() { return new QName(MidPointConstants.NS_RI, getLdapAccountObjectClass()); } - + protected String getLdapAccountObjectClass() { return LDAP_INETORGPERSON_OBJECTCLASS; } - + protected QName getGroupObjectClass() { return new QName(MidPointConstants.NS_RI, getLdapGroupObjectClass()); } - + protected abstract String getLdapServerHost(); - + protected abstract int getLdapServerPort(); - + protected boolean useSsl() { return false; } - + protected abstract String getLdapBindDn(); - + protected abstract String getLdapBindPassword(); - + protected abstract int getSearchSizeLimit(); protected String getLdapSuffix() { return "dc=example,dc=com"; } - + protected String getPeopleLdapSuffix() { return "ou=People,"+getLdapSuffix(); } @@ -279,55 +279,55 @@ protected String getPeopleLdapSuffix() { protected String getGroupsLdapSuffix() { return "ou=groups,"+getLdapSuffix(); } - + public String getPrimaryIdentifierAttributeName() { return "entryUUID"; } - + public QName getPrimaryIdentifierAttributeQName() { return new QName(MidPointConstants.NS_RI,getPrimaryIdentifierAttributeName()); } - + protected abstract String getLdapGroupObjectClass(); - + protected abstract String getLdapGroupMemberAttribute(); - + protected boolean needsGroupFakeMemeberEntry() { return false; } - + protected boolean isUsingGroupShortcutAttribute() { return true; } - + protected String getScriptDirectoryName() { return "/opt/Bamboo/local/conntest"; } - + protected boolean isImportResourceAtInit() { return true; } - + protected boolean allowDuplicateSearchResults() { return false; } - + protected boolean isGroupMemberMandatory() { return true; } - + protected boolean isAssertOpenFiles() { return false; } - + protected QName getAssociationGroupName() { return new QName(MidPointConstants.NS_RI, "group"); } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + // System Configuration PrismObject config; try { @@ -336,7 +336,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti throw new ObjectAlreadyExistsException("System configuration already exists in repository;" + "looks like the previous test haven't cleaned it up", e); } - + modelService.postInit(initResult); // to get profiling facilities (until better API is available) @@ -348,15 +348,15 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti PrismObject userAdministrator = repoAddObjectFromFile(USER_ADMINISTRATOR_FILE, initResult); repoAddObjectFromFile(ROLE_SUPERUSER_FILE, initResult); login(userAdministrator); - + // Roles - + // Resources if (isImportResourceAtInit()) { resource = importAndGetObjectFromFile(ResourceType.class, getResourceFile(), getResourceOid(), initTask, initResult); resourceType = resource.asObjectable(); } - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); //initProfiling - start @@ -369,12 +369,12 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti profilingManager.appendProfilingToTest(); //initProfiling - end - + ciMatchingRule = matchingRuleRegistry.getMatchingRule(StringIgnoreCaseMatchingRule.NAME, DOMUtil.XSD_STRING); dnMatchingRule = matchingRuleRegistry.getMatchingRule(DistinguishedNameMatchingRule.NAME, DOMUtil.XSD_STRING); - + logTrustManagers(); - + if (isAssertOpenFiles()) { lsof = new Lsof(TestUtil.getPid()); } @@ -385,14 +385,14 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti public void test010Connection() throws Exception { final String TEST_NAME = "test010Connection"; TestUtil.displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); - + OperationResult testResult = provisioningService.testResource(getResourceOid(), task); - + display("Test connection result",testResult); TestUtil.assertSuccess("Test connection failed",testResult); - + if (isAssertOpenFiles()) { // Set lsof baseline only after the first connection. // We will have more reasonable number here. @@ -400,73 +400,73 @@ public void test010Connection() throws Exception { display("lsof baseline", lsof); } } - + @Test public void test020Schema() throws Exception { final String TEST_NAME = "test020Schema"; TestUtil.displayTestTitle(this, TEST_NAME); - + ResourceSchema resourceSchema = RefinedResourceSchema.getResourceSchema(resource, prismContext); display("Resource schema", resourceSchema); - + RefinedResourceSchema refinedSchema = RefinedResourceSchema.getRefinedSchema(resource); display("Refined schema", refinedSchema); accountObjectClassDefinition = refinedSchema.findObjectClassDefinition(getAccountObjectClass()); assertNotNull("No definition for object class "+getAccountObjectClass(), accountObjectClassDefinition); display("Account object class def", accountObjectClassDefinition); - + ResourceAttributeDefinition cnDef = accountObjectClassDefinition.findAttributeDefinition("cn"); PrismAsserts.assertDefinition(cnDef, new QName(MidPointConstants.NS_RI, "cn"), DOMUtil.XSD_STRING, 1, 1); assertTrue("cn read", cnDef.canRead()); assertTrue("cn modify", cnDef.canModify()); assertTrue("cn add", cnDef.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 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 read", createTimestampDef.canModify()); assertFalse("createTimestampDef read", createTimestampDef.canAdd()); - + assertStableSystem(); } - + @Test public void test030Capabilities() throws Exception { final String TEST_NAME = "test030Capabilities"; TestUtil.displayTestTitle(this, TEST_NAME); - + CapabilitiesType capabilities = resourceType.getCapabilities(); display("Resource capabilities", capabilities); assertNotNull("Null capabilities", capabilities); - + CapabilityCollectionType nativeCapabilitiesCollectionType = capabilities.getNative(); assertNotNull("Null native capabilities type", nativeCapabilitiesCollectionType); List nativeCapabilities = nativeCapabilitiesCollectionType.getAny(); assertNotNull("Null native capabilities", nativeCapabilities); assertFalse("Empty native capabilities", nativeCapabilities.isEmpty()); - + assertCapability(nativeCapabilities, ReadCapabilityType.class); assertCapability(nativeCapabilities, CreateCapabilityType.class); assertCapability(nativeCapabilities, UpdateCapabilityType.class); assertCapability(nativeCapabilities, DeleteCapabilityType.class); - + // TODO: assert password capability. Check password readability. - + ActivationCapabilityType activationCapabilityType = CapabilityUtil.getCapability(nativeCapabilities, ActivationCapabilityType.class); assertActivationCapability(activationCapabilityType); - + assertAdditionalCapabilities(nativeCapabilities); - + assertStableSystem(); } - + protected void assertActivationCapability(ActivationCapabilityType activationCapabilityType) { // for subclasses } @@ -488,17 +488,17 @@ protected ObjectFilter createAttributeFilter(String attrName, T attrVal) thr .itemWithDef(ldapAttrDef, ShadowType.F_ATTRIBUTES, ldapAttrDef.getName()).eq(attrVal) .buildFilter(); } - + protected ObjectQuery createUidQuery(String uid) throws SchemaException { ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); ObjectQueryUtil.filterAnd(query.getFilter(), createAttributeFilter("uid", uid)); return query; } - + protected SearchResultList> doSearch(final String TEST_NAME, ObjectQuery query, int expectedSize, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { return doSearch(TEST_NAME, query, null, expectedSize, task, result); } - + protected SearchResultList> doSearch(final String TEST_NAME, ObjectQuery query, GetOperationOptions rootOptions, int expectedSize, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { final List> foundObjects = new ArrayList>(expectedSize); ResultHandler handler = new ResultHandler() { @@ -515,24 +515,24 @@ public boolean handle(PrismObject object, OperationResult parentResu return true; } }; - + Collection> options = null; if (rootOptions != null) { options = SelectorOptions.createCollection(rootOptions); } - + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("Searching shadows, options="+options+", query", query); SearchResultMetadata searchResultMetadata = modelService.searchObjectsIterative(ShadowType.class, query, handler, options, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + if (expectedSize != foundObjects.size()) { if (foundObjects.size() < 10) { display("Found objects", foundObjects); @@ -541,28 +541,28 @@ public boolean handle(PrismObject object, OperationResult parentResu AssertJUnit.fail("Unexpected number of accounts. Expected "+expectedSize+", found "+foundObjects.size()+" (too many to display)"); } } - + SearchResultList> resultList = new SearchResultList<>(foundObjects, searchResultMetadata); - + return resultList; } - + protected Entry getLdapAccountByUid(String uid) throws LdapException, IOException, CursorException { return searchLdapAccount("(uid="+uid+")"); } - + protected Entry getLdapAccountByCn(String cn) throws LdapException, IOException, CursorException { return getLdapAccountByCn(null, cn); } - + protected Entry getLdapAccountByCn(UserLdapConnectionConfig config, String cn) throws LdapException, IOException, CursorException { return searchLdapAccount(config, "(cn="+cn+")"); } - + protected Entry searchLdapAccount(String filter) throws LdapException, IOException, CursorException { return searchLdapAccount(null, filter); } - + protected Entry searchLdapAccount(UserLdapConnectionConfig config, String filter) throws LdapException, IOException, CursorException { LdapNetworkConnection connection = ldapConnect(config); List entries = ldapSearch(config, connection, filter); @@ -573,13 +573,13 @@ protected Entry searchLdapAccount(UserLdapConnectionConfig config, String filter return entry; } - + protected Entry assertLdapAccount(String uid, String cn) throws LdapException, IOException, CursorException { Entry entry = getLdapAccountByUid(uid); assertAttribute(entry, "cn", cn); return entry; } - + protected Entry getLdapGroupByName(String name) throws LdapException, IOException, CursorException { LdapNetworkConnection connection = ldapConnect(); List entries = ldapSearch(connection, "(&(cn="+name+")(objectClass="+getLdapGroupObjectClass()+"))"); @@ -590,20 +590,20 @@ protected Entry getLdapGroupByName(String name) throws LdapException, IOExceptio return entry; } - + protected Entry assertLdapGroup(String cn) throws LdapException, IOException, CursorException { Entry entry = getLdapGroupByName(cn); assertAttribute(entry, "cn", cn); return entry; } - + protected void assertNoLdapGroup(String cn) throws LdapException, IOException, CursorException { LdapNetworkConnection connection = ldapConnect(); List entries = ldapSearch(connection, "(&(cn="+cn+")(objectClass="+getLdapGroupObjectClass()+"))"); ldapDisconnect(connection); assertEquals("Unexpected LDAP group "+cn+": "+entries, 0, entries.size()); } - + protected void assertAttribute(Entry entry, String attrName, String expectedValue) throws LdapInvalidAttributeValueException { String dn = entry.getDn().toString(); Attribute ldapAttribute = entry.get(attrName); @@ -617,7 +617,7 @@ protected void assertAttribute(Entry entry, String attrName, String expectedValu assertEquals("Wrong attribute "+attrName+" in "+dn, expectedValue, ldapAttribute.getString()); } } - + protected void assertNoAttribute(Entry entry, String attrName) throws LdapInvalidAttributeValueException { String dn = entry.getDn().toString(); Attribute ldapAttribute = entry.get(attrName); @@ -625,11 +625,11 @@ protected void assertNoAttribute(Entry entry, String attrName) throws LdapInvali AssertJUnit.fail("Unexpected attribute "+attrName+" in "+dn+": "+ldapAttribute); } } - + protected void assertAttributeContains(Entry entry, String attrName, String expectedValue) throws LdapInvalidAttributeValueException, SchemaException { assertAttributeContains(entry, attrName, expectedValue, null); } - + protected void assertAttributeContains(Entry entry, String attrName, String expectedValue, MatchingRule matchingRule) throws LdapInvalidAttributeValueException, SchemaException { String dn = entry.getDn().toString(); Attribute ldapAttribute = entry.get(attrName); @@ -658,11 +658,11 @@ protected void assertAttributeContains(Entry entry, String attrName, String expe AssertJUnit.fail("Wrong attribute "+attrName+" in "+dn+" expected to contain value " + expectedValue + " but it has values " + vals); } } - + protected void assertAttributeNotContains(Entry entry, String attrName, String expectedValue) throws LdapInvalidAttributeValueException, SchemaException { assertAttributeNotContains(entry, attrName, expectedValue, null); } - + protected void assertAttributeNotContains(Entry entry, String attrName, String expectedValue, MatchingRule matchingRule) throws LdapInvalidAttributeValueException, SchemaException { String dn = entry.getDn().toString(); Attribute ldapAttribute = entry.get(attrName); @@ -684,14 +684,14 @@ protected void assertAttributeNotContains(Entry entry, String attrName, String e } } } - + protected Entry getLdapEntry(String dn) throws LdapException, IOException, CursorException { LdapNetworkConnection connection = ldapConnect(); Entry entry = getLdapEntry(connection, dn); ldapDisconnect(connection); return entry; } - + protected Entry getLdapEntry(LdapNetworkConnection connection, String dn) throws LdapException, IOException, CursorException { List entries = ldapSearch(connection, dn, "(objectclass=*)", SearchScope.OBJECT, "*"); if (entries.isEmpty()) { @@ -699,7 +699,7 @@ protected Entry getLdapEntry(LdapNetworkConnection connection, String dn) throws } return entries.get(0); } - + protected void assertNoLdapAccount(String uid) throws LdapException, IOException, CursorException { LdapNetworkConnection connection = ldapConnect(); List entries = ldapSearch(connection, "(uid="+uid+")"); @@ -707,34 +707,34 @@ protected void assertNoLdapAccount(String uid) throws LdapException, IOException assertEquals("Unexpected number of entries for uid="+uid+": "+entries, 0, entries.size()); } - + protected void assertNoEntry(String dn) throws LdapException, IOException, CursorException { Entry entry = getLdapEntry(dn); assertNull("Expected no entry "+dn+", but found "+entry, entry); } - + protected void assertLdapGroupMember(Entry accountEntry, String groupName) throws LdapException, IOException, CursorException, SchemaException { assertLdapGroupMember(accountEntry.getDn().toString(), groupName); } - + protected void assertLdapGroupMember(String accountEntryDn, String groupName) throws LdapException, IOException, CursorException, SchemaException { Entry groupEntry = getLdapGroupByName(groupName); assertAttributeContains(groupEntry, getLdapGroupMemberAttribute(), accountEntryDn, dnMatchingRule); } - + protected void assertLdapNoGroupMember(Entry accountEntry, String groupName) throws LdapException, IOException, CursorException, SchemaException { assertLdapNoGroupMember(accountEntry.getDn().toString(), groupName); } - + protected void assertLdapNoGroupMember(String accountEntryDn, String groupName) throws LdapException, IOException, CursorException, SchemaException { Entry groupEntry = getLdapGroupByName(groupName); assertAttributeNotContains(groupEntry, getLdapGroupMemberAttribute(), accountEntryDn, dnMatchingRule); } - + protected List ldapSearch(LdapNetworkConnection connection, String filter) throws LdapException, CursorException { return ldapSearch(null, connection, filter); } - + protected List ldapSearch(UserLdapConnectionConfig config, LdapNetworkConnection connection, String filter) throws LdapException, CursorException { String baseContext = getLdapSuffix(); if (config != null && config.getBaseContext() != null) { @@ -742,18 +742,18 @@ protected List ldapSearch(UserLdapConnectionConfig config, LdapNetworkCon } return ldapSearch(connection, baseContext, filter, SearchScope.SUBTREE, "*", "isMemberOf", "memberof", "isMemberOf", getPrimaryIdentifierAttributeName()); } - + protected List ldapSearch(LdapNetworkConnection connection, String baseDn, String filter, SearchScope scope, String... attributes) throws LdapException, CursorException { LOGGER.trace("LDAP search base={}, filter={}, scope={}, attributes={}", new Object[]{baseDn, filter, scope, attributes}); - + SearchRequest searchRequest = new SearchRequestImpl(); searchRequest.setBase(new Dn(baseDn)); searchRequest.setFilter(filter); searchRequest.setScope(scope); searchRequest.addAttributes(attributes); searchRequest.ignoreReferrals(); - + List entries = new ArrayList(); try { SearchCursor searchCursor = connection.search(searchRequest); @@ -772,16 +772,16 @@ protected List ldapSearch(LdapNetworkConnection connection, String baseDn } return entries; } - + protected void assertLdapPassword(String uid, String password) throws LdapException, IOException, CursorException { Entry entry = getLdapAccountByUid(uid); assertLdapPassword(entry, password); } - + protected void assertLdapPassword(Entry entry, String password) throws LdapException, IOException, CursorException { assertLdapPassword(null, entry, password); } - + protected void assertLdapPassword(UserLdapConnectionConfig config, Entry entry, String password) throws LdapException, IOException, CursorException { LdapNetworkConnection conn = ldapConnect(config, entry.getDn().toString(), password); assertTrue("Not connected", conn.isConnected()); @@ -813,7 +813,7 @@ protected Entry createAccountEntry(String uid, String cn, String givenName, Stri "sn", sn); return entry; } - + protected Entry addLdapGroup(String cn, String description, String... memberDns) throws LdapException, IOException, CursorException { LdapNetworkConnection connection = ldapConnect(); Entry entry = createGroupEntry(cn, description, memberDns); @@ -841,14 +841,14 @@ protected void deleteLdapEntry(String dn) throws LdapException, IOException { display("Deleted LDAP entry: "+dn); ldapDisconnect(connection); } - + /** * Silent delete. Used to clean up after previous test runs. */ protected void cleanupDelete(String dn) throws LdapException, IOException, CursorException { cleanupDelete(null, dn); } - + /** * Silent delete. Used to clean up after previous test runs. */ @@ -861,15 +861,15 @@ protected void cleanupDelete(UserLdapConnectionConfig config, String dn) throws } ldapDisconnect(connection); } - + protected String toAccountDn(String username, String fullName) { return toAccountDn(username); } - + protected String toAccountDn(String username) { return "uid="+username+","+getPeopleLdapSuffix(); } - + protected Rdn toAccountRdn(String username, String fullName) { try { return new Rdn(new Ava("uid", username)); @@ -877,11 +877,11 @@ protected Rdn toAccountRdn(String username, String fullName) { throw new IllegalStateException(e.getMessage(),e); } } - + protected String toGroupDn(String cn) { return "cn="+cn+","+getGroupsLdapSuffix(); } - + protected String getAttributeAsString(Entry entry, String primaryIdentifierAttributeName) throws LdapInvalidAttributeValueException { if ("dn".equals(primaryIdentifierAttributeName)) { return entry.getDn().toString(); @@ -889,18 +889,18 @@ protected String getAttributeAsString(Entry entry, String primaryIdentifierAttri return entry.get(primaryIdentifierAttributeName).getString(); } } - + protected LdapNetworkConnection ldapConnect() throws LdapException, IOException { return ldapConnect(getLdapBindDn(), getLdapBindPassword()); } - + protected LdapNetworkConnection ldapConnect(String bindDn, String bindPassword) throws LdapException, IOException { UserLdapConnectionConfig config = new UserLdapConnectionConfig(); config.setLdapHost(getLdapServerHost()); config.setLdapPort(getLdapServerPort()); config.setBindDn(bindDn); config.setBindPassword(bindPassword); - + return ldapConnect(config); } @@ -912,10 +912,10 @@ protected LdapNetworkConnection ldapConnect(UserLdapConnectionConfig config, Str } config.setBindDn(bindDn); config.setBindPassword(bindPassword); - + return ldapConnect(config); } - + protected LdapNetworkConnection ldapConnect(UserLdapConnectionConfig config) throws LdapException, IOException { if (config == null) { config = new UserLdapConnectionConfig(); @@ -926,13 +926,13 @@ protected LdapNetworkConnection ldapConnect(UserLdapConnectionConfig config) thr } LOGGER.trace("LDAP connect to {}:{} as {}", config.getLdapHost(), config.getLdapPort(), config.getBindDn()); - + if (useSsl()) { config.setUseSsl(true); TrustManager trustManager = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - + } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { @@ -943,9 +943,9 @@ public X509Certificate[] getAcceptedIssuers() { }; config.setTrustManagers(trustManager); } - + config.setBinaryAttributeDetector(binaryAttributeDetector); - + LdapNetworkConnection connection = new LdapNetworkConnection(config); boolean connected = connection.connect(); if (!connected) { @@ -971,15 +971,15 @@ protected void ldapDisconnect(LdapNetworkConnection connection) throws IOExcepti LOGGER.trace("LDAP disconnect {}", connection); connection.close(); } - + protected void assertAccountShadow(PrismObject shadow, String dn) throws SchemaException { assertShadowCommon(shadow, null, dn, resourceType, getAccountObjectClass(), ciMatchingRule, false); } - + protected void assertAccountRepoShadow(PrismObject shadow, String dn) throws SchemaException { assertShadowCommon(shadow, null, dnMatchingRule.normalize(dn), resourceType, getAccountObjectClass(), ciMatchingRule, false); } - + protected void assertGroupShadow(PrismObject shadow, String dn) throws SchemaException { assertShadowCommon(shadow, null, dn, resourceType, getGroupObjectClass(), ciMatchingRule, false, true); } @@ -987,17 +987,17 @@ protected void assertGroupShadow(PrismObject shadow, String dn) thro protected long roundTsDown(long ts) { return (((long)(ts/1000))*1000); } - + protected long roundTsUp(long ts) { return (((long)(ts/1000))*1000)+1; } - + protected void assertStableSystem() throws NumberFormatException, IOException, InterruptedException { if (isAssertOpenFiles()) { lsof.assertStable(); } } - + protected void assertLdapConnectorInstances(int expectedConnectorInstancesShortcut, int expectedConnectorInstancesNoShortcut) throws NumberFormatException, IOException, InterruptedException, SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException { if (isUsingGroupShortcutAttribute()) { assertLdapConnectorInstances(expectedConnectorInstancesShortcut); @@ -1013,13 +1013,13 @@ protected void assertLdapConnectorInstances(int expectedConnectorInstances) thro display("Resource connector stats", stats); result.computeStatus(); TestUtil.assertSuccess(result); - + assertEquals("unexpected number of stats", 1, stats.size()); ConnectorOperationalStatus stat = stats.get(0); - - assertEquals("Unexpected number of LDAP connector instances", expectedConnectorInstances, + + assertEquals("Unexpected number of LDAP connector instances", expectedConnectorInstances, stat.getPoolStatusNumIdle() + stat.getPoolStatusNumActive()); - + if (!isAssertOpenFiles()) { return; } @@ -1034,5 +1034,5 @@ protected void assertLdapConnectorInstances(int expectedConnectorInstances) thro protected int getNumberOfFdsPerLdapConnectorInstance() { return 7; } - + } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AdUtils.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AdUtils.java index f7c45425277..c5504403c5c 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AdUtils.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AdUtils.java @@ -42,7 +42,7 @@ * */ public class AdUtils { - + public static final String ATTRIBUTE_OBJECT_GUID_NAME = "objectGUID"; public static final String ATTRIBUTE_SAM_ACCOUNT_NAME_NAME = "sAMAccountName"; public static final String ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME = "userAccountControl"; @@ -50,12 +50,12 @@ public class AdUtils { public static final String ATTRIBUTE_UNICODE_PWD_NAME = "unicodePwd"; public static final String ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME = "msExchHideFromAddressLists"; public static final QName ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_QNAME = new QName(MidPointConstants.NS_RI, ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME); - + public static final QName OBJECT_CLASS_MS_EXCH_BASE_CLASS_QNAME = new QName(MidPointConstants.NS_RI, "msExchBaseClass"); - + /** * Returns dashed GUID notation formatted from simple hex-encoded binary. - * + * * E.g. "2f01c06bb1d0414e9a69dd3841a13506" -> "6bc0012f-d0b1-4e41-9a69-dd3841a13506" */ public static String formatGuidToDashedNotation(String hexValue) { @@ -95,16 +95,16 @@ public static ObjectClassComplexTypeDefinition assertAdRefinedSchema(PrismObject ObjectClassComplexTypeDefinition accountObjectClassDef = assertAdSchema(refinedSchema, resource, accountObjectClass, prismContext); return accountObjectClassDef; } - + public static ObjectClassComplexTypeDefinition assertAdSchema(ResourceSchema resourceSchema, PrismObject resource, QName accountObjectClass, PrismContext prismContext) 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()); @@ -112,73 +112,73 @@ public static ObjectClassComplexTypeDefinition assertAdSchema(ResourceSchema res assertTrue("cn add", cnDef.canAdd()); ResourceAttributeDefinition samAccountNameDef = accountObjectClassDefinition.findAttributeDefinition(ATTRIBUTE_SAM_ACCOUNT_NAME_NAME); - PrismAsserts.assertDefinition(samAccountNameDef, + 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 createTimestampDef = accountObjectClassDefinition.findAttributeDefinition("createTimeStamp"); PrismAsserts.assertDefinition(createTimestampDef, new QName(MidPointConstants.NS_RI, "createTimeStamp"), DOMUtil.XSD_STRING, 0, 1); assertTrue("createTimeStampDef read", createTimestampDef.canRead()); assertFalse("createTimeStampDef modify", createTimestampDef.canModify()); assertFalse("createTimeStampDef add", createTimestampDef.canAdd()); - + ResourceAttributeDefinition isCriticalSystemObjectDef = accountObjectClassDefinition.findAttributeDefinition("isCriticalSystemObject"); PrismAsserts.assertDefinition(isCriticalSystemObjectDef, new QName(MidPointConstants.NS_RI, "isCriticalSystemObject"), DOMUtil.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"), DOMUtil.XSD_BASE64BINARY, 0, 1); assertTrue("nTSecurityDescriptor read", nTSecurityDescriptorDef.canRead()); assertTrue("nTSecurityDescriptor modify", nTSecurityDescriptorDef.canModify()); assertTrue("nTSecurityDescriptor add", nTSecurityDescriptorDef.canAdd()); - + ResourceAttributeDefinition lastLogonDef = accountObjectClassDefinition.findAttributeDefinition("lastLogon"); PrismAsserts.assertDefinition(lastLogonDef, new QName(MidPointConstants.NS_RI, "lastLogon"), DOMUtil.XSD_LONG, 0, 1); assertTrue("lastLogonDef read", lastLogonDef.canRead()); assertTrue("lastLogonDef modify", lastLogonDef.canModify()); assertTrue("lastLogonDef add", lastLogonDef.canAdd()); - + return accountObjectClassDefinition; } - + public static void assertExchangeSchema(PrismObject resource, QName accountObjectClassQName, PrismContext prismContext) throws SchemaException { - + ResourceSchema resourceSchema = RefinedResourceSchema.getResourceSchema(resource, prismContext); assertExchangeSchema(resourceSchema, resource, accountObjectClassQName, prismContext); - + RefinedResourceSchema refinedSchema = RefinedResourceSchema.getRefinedSchema(resource); assertExchangeSchema(refinedSchema, resource, accountObjectClassQName, prismContext); } - + public static void assertExchangeSchema(ResourceSchema resourceSchema, PrismObject resource, QName accountObjectClassQName, PrismContext prismContext) throws SchemaException { 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()); diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Test389DsDnLocalhost.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Test389DsDnLocalhost.java index 5e2001fabd2..a0057d20865 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Test389DsDnLocalhost.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Test389DsDnLocalhost.java @@ -31,7 +31,7 @@ @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class Test389DsDnLocalhost extends Abstract389DsDnTest { - + @Override protected File getResourceFile() { return new File(getBaseDir(), "resource-dn-localhost.xml"); @@ -46,7 +46,7 @@ public String getStartSystemCommand() { public String getStopSystemCommand() { return null; } - + @Override protected String getLdapServerHost() { return "localhost"; diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Test389DsDnPhobos.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Test389DsDnPhobos.java index 8492a509ec6..26647d5d014 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Test389DsDnPhobos.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Test389DsDnPhobos.java @@ -31,7 +31,7 @@ @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class Test389DsDnPhobos extends Abstract389DsDnTest { - + @Override protected File getResourceFile() { return new File(getBaseDir(), "resource-dn-phobos.xml"); @@ -46,7 +46,7 @@ public String getStartSystemCommand() { public String getStopSystemCommand() { return getScriptDirectoryName()+"/389ds-phobos-stop"; } - + @Override protected String getLdapServerHost() { return "phobos.lab.evolveum.com"; diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Test389DsNsUniqueIdLocalhost.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Test389DsNsUniqueIdLocalhost.java index eb5db8e60d0..8b5b9c22cb5 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Test389DsNsUniqueIdLocalhost.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Test389DsNsUniqueIdLocalhost.java @@ -31,7 +31,7 @@ @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class Test389DsNsUniqueIdLocalhost extends Abstract389DsNsUniqueIdTest { - + @Override protected File getResourceFile() { return new File(getBaseDir(), "resource-nsuniqueid-localhost.xml"); @@ -46,7 +46,7 @@ public String getStartSystemCommand() { public String getStopSystemCommand() { return null; } - + @Override protected String getLdapServerHost() { return "localhost"; diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Test389DsNsUniqueIdPhobos.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Test389DsNsUniqueIdPhobos.java index ba23ca6f2e0..53eed258b5f 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Test389DsNsUniqueIdPhobos.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/Test389DsNsUniqueIdPhobos.java @@ -29,7 +29,7 @@ */ public class Test389DsNsUniqueIdPhobos extends Abstract389DsNsUniqueIdTest { - + @Override protected File getResourceFile() { return new File(getBaseDir(), "resource-nsuniqueid-phobos.xml"); @@ -44,7 +44,7 @@ public String getStartSystemCommand() { public String getStopSystemCommand() { return getScriptDirectoryName()+"/389ds-phobos-stop"; } - + @Override protected String getLdapServerHost() { return "phobos.lab.evolveum.com"; diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLdapChimera.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLdapChimera.java index 22b332af3e6..86314bf80fe 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLdapChimera.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLdapChimera.java @@ -39,7 +39,7 @@ public class TestAdLdapChimera extends AbstractAdLdapMultidomainTest { protected String getResourceOid() { return "eced6d24-73e3-11e5-8457-93eff15a6b85"; } - + @Override protected File getResourceFile() { return new File(getBaseDir(), "resource-chimera.xml"); @@ -64,5 +64,5 @@ protected void assertAccountDisabled(PrismObject shadow) { protected void assertAccountEnabled(PrismObject shadow) { assertAdministrativeStatus(shadow, ActivationStatusType.ENABLED); } - + } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLdapLocalhost.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLdapLocalhost.java index e8291a5e1f7..ad839258190 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLdapLocalhost.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLdapLocalhost.java @@ -34,7 +34,7 @@ public class TestAdLdapLocalhost extends AbstractAdLdapCookedTest { protected String getResourceOid() { return "eced6d24-73e3-11e5-8457-93eff15a6b85"; } - + @Override protected File getResourceFile() { return new File(getBaseDir(), "resource-localhost.xml"); @@ -49,5 +49,5 @@ protected String getLdapServerHost() { protected int getLdapServerPort() { return 9636; } - + } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLdapMedusa.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLdapMedusa.java index 59f070caea8..f85814f994f 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLdapMedusa.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLdapMedusa.java @@ -34,7 +34,7 @@ public class TestAdLdapMedusa extends AbstractAdLdapCookedTest { protected String getResourceOid() { return "eced6d24-73e3-11e5-8457-93eff15a6b85"; } - + @Override protected File getResourceFile() { return new File(getBaseDir(), "resource-medusa.xml"); @@ -49,5 +49,5 @@ protected String getLdapServerHost() { protected int getLdapServerPort() { return 636; } - + } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLdapRawLocalhost.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLdapRawLocalhost.java index 7946ca3785d..2b8bf7645c1 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLdapRawLocalhost.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLdapRawLocalhost.java @@ -34,7 +34,7 @@ public class TestAdLdapRawLocalhost extends AbstractAdLdapRawTest { protected String getResourceOid() { return "eced6d24-73e3-11e5-8457-93eff15a6b85"; } - + @Override protected File getResourceFile() { return new File(getBaseDir(), "resource-raw-localhost.xml"); @@ -49,5 +49,5 @@ protected String getLdapServerHost() { protected int getLdapServerPort() { return 9636; } - + } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLdapRawMedusa.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLdapRawMedusa.java index bd8b114fba7..9eca2cc9a9f 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLdapRawMedusa.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLdapRawMedusa.java @@ -34,7 +34,7 @@ public class TestAdLdapRawMedusa extends AbstractAdLdapRawTest { protected String getResourceOid() { return "eced6d24-73e3-11e5-8457-93eff15a6b85"; } - + @Override protected File getResourceFile() { return new File(getBaseDir(), "resource-raw-medusa.xml"); @@ -49,5 +49,5 @@ protected String getLdapServerHost() { protected int getLdapServerPort() { return 636; } - + } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLocalhost.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLocalhost.java index 6e5e9a73c63..d4238c117a5 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLocalhost.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestAdLocalhost.java @@ -26,7 +26,7 @@ /** * AD test to run manually. Assumess connector server on localhost (or a tunneled connection). - * + * * @author semancik * */ @@ -46,5 +46,5 @@ protected String getLdapServerHost() { protected int getLdapServerPort() { return 44389; } - + } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestEDirAthena.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestEDirAthena.java index d77099a4ee1..29feba53f86 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestEDirAthena.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestEDirAthena.java @@ -34,7 +34,7 @@ public class TestEDirAthena extends AbstractEDirTest { protected String getResourceOid() { return "0893372c-3c42-11e5-9179-001e8c717e5b"; } - + @Override protected File getResourceFile() { return new File(getBaseDir(), "resource-athena.xml"); @@ -49,5 +49,5 @@ protected String getLdapServerHost() { protected int getLdapServerPort() { return 33636; } - + } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestEDirDeimos.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestEDirDeimos.java index a80fa59e889..bf171a6062d 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestEDirDeimos.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestEDirDeimos.java @@ -26,7 +26,7 @@ /** * @author semancik - * + * * This configuration is supposed to be executed in bamboo (behind firewall). * */ @@ -37,7 +37,7 @@ public class TestEDirDeimos extends AbstractEDirTest { protected String getResourceOid() { return "0893372c-3c42-11e5-9179-001e8c717e5b"; } - + @Override protected File getResourceFile() { return new File(getBaseDir(), "resource-deimos.xml"); @@ -52,5 +52,5 @@ protected String getLdapServerHost() { protected int getLdapServerPort() { return 3636; } - + } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenDj.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenDj.java index 4222ed78bfb..6d83d3fb1c5 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenDj.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenDj.java @@ -30,7 +30,7 @@ public class TestOpenDj extends AbstractLdapConnTest { private static final String OPENDJ_TEMPLATE_NAME = "opendj-4000.template"; - + private static final int INITIAL_SYNC_TOKEN = 23; @Override @@ -52,13 +52,13 @@ public String getStartSystemCommand() { public String getStopSystemCommand() { return null; } - + @Override protected void startResources() throws Exception { super.startResources(); openDJController.startCleanServer(OPENDJ_TEMPLATE_NAME); } - + @AfterClass public static void stopResources() throws Exception { AbstractLdapConnTest.stopResources(); @@ -84,12 +84,12 @@ protected String getLdapBindDn() { protected String getLdapBindPassword() { return "secret"; } - + @Override protected String getPeopleLdapSuffix() { return "ou=people,"+getLdapSuffix(); } - + @Override protected String getAccount0Cn() { return "Warlaz Kunjegjul (00000000)"; @@ -114,7 +114,7 @@ protected String getLdapGroupObjectClass() { protected String getLdapGroupMemberAttribute() { return "uniqueMember"; } - + @Override protected boolean needsGroupFakeMemeberEntry() { return true; @@ -124,11 +124,11 @@ protected boolean needsGroupFakeMemeberEntry() { protected String getSyncTaskOid() { return "cd1e0ff2-0099-11e5-9e22-001e8c717e5b"; } - + protected int getInitialSyncToken() { return INITIAL_SYNC_TOKEN; } - + @Override protected boolean isAssertOpenFiles() { // Cannot do this here. OpenDJ is embedded, the @@ -136,11 +136,11 @@ protected boolean isAssertOpenFiles() { // vary significantly because of OpenDJ. return false; } - + @Override protected void assertStepSyncToken(String syncTaskOid, int step, long tsStart, long tsEnd) throws ObjectNotFoundException, SchemaException { assertSyncToken(syncTaskOid, (Integer)(step + getInitialSyncToken())); } - + } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenDjDumber.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenDjDumber.java index 59b715d5722..5f9498c235c 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenDjDumber.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenDjDumber.java @@ -21,28 +21,28 @@ /** * OpenDJ, but without permissive modify, shortcut attributes, with manual matching rules, etc. - * + * * @author semancik */ public class TestOpenDjDumber extends TestOpenDj { - + private static final int INITIAL_SYNC_TOKEN = 21; - + @Override protected File getBaseDir() { return new File(MidPointTestConstants.TEST_RESOURCES_DIR, "opendj-dumber"); } - + @Override protected boolean hasAssociationShortcut() { return false; } - + @Override protected int getInitialSyncToken() { return INITIAL_SYNC_TOKEN; } - + @Override protected boolean isUsingGroupShortcutAttribute() { return false; diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenDjUnsafe.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenDjUnsafe.java index e2ef918e309..49581eb027b 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenDjUnsafe.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenDjUnsafe.java @@ -26,14 +26,14 @@ /** * Almost same sa TestOpenDj, but there is unsafeNameHint setting and maybe * some other possibly risky and alternative connector settings. - * + * * @author semancik */ public class TestOpenDjUnsafe extends TestOpenDj { - + @Override protected File getResourceFile() { return new File(getBaseDir(), "resource-unsafe.xml"); } - + } 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 ad0eb3c19b1..0dae5ce91c9 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 @@ -112,7 +112,7 @@ protected String getAccount0Cn() { protected int getSearchSizeLimit() { return 500; } - + @Override protected String getPeopleLdapSuffix() { return "ou=people,"+getLdapSuffix(); @@ -123,7 +123,7 @@ protected String getGroupsLdapSuffix() { return "ou=groups,"+getLdapSuffix(); } - + @Override protected String getLdapGroupObjectClass() { return "groupOfNames"; @@ -138,12 +138,12 @@ protected String getLdapGroupMemberAttribute() { protected String getSyncTaskOid() { return "cd1e0ff2-0099-11e5-9e22-001e8c717e5b"; } - + @Override protected boolean syncCanDetectDelete() { return false; } - + @Override protected boolean needsGroupFakeMemeberEntry() { return true; @@ -152,12 +152,12 @@ protected boolean needsGroupFakeMemeberEntry() { @Override protected void assertActivationCapability(ActivationCapabilityType activationCapabilityType) { assertNotNull("No activation capability", activationCapabilityType); - + ActivationLockoutStatusCapabilityType lockoutCapability = CapabilityUtil.getEffectiveActivationLockoutStatus(activationCapabilityType); assertNotNull("No lockout capability", lockoutCapability); display("Lockout capability", lockoutCapability); } - + @Override protected void assertStepSyncToken(String syncTaskOid, int step, long tsStart, long tsEnd) throws ObjectNotFoundException, SchemaException { @@ -165,13 +165,13 @@ protected void assertStepSyncToken(String syncTaskOid, int step, long tsStart, l Task task = taskManager.getTask(syncTaskOid, result); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismProperty syncTokenProperty = task.getExtensionProperty(SchemaConstants.SYNC_TOKEN); assertNotNull("No sync token in "+task, syncTokenProperty); String syncToken = syncTokenProperty.getRealValue(); assertNotNull("No sync token in "+task, syncToken); IntegrationTestTools.display("Sync token", syncToken); - + GeneralizedTime syncTokenGt; try { syncTokenGt = new GeneralizedTime(syncToken); @@ -179,9 +179,9 @@ protected void assertStepSyncToken(String syncTaskOid, int step, long tsStart, l throw new RuntimeException(e.getMessage(),e); } TestUtil.assertBetween("Wrong time in sync token: "+syncToken, roundTsDown(tsStart), roundTsUp(tsEnd), syncTokenGt.getCalendar().getTimeInMillis()); - + } - + @Test public void test700CheckBarbossaLockoutStatus() throws Exception { final String TEST_NAME = "test700CheckBarbossaLockoutStatus"; @@ -190,7 +190,7 @@ public void test700CheckBarbossaLockoutStatus() throws Exception { // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject shadow = getShadowModel(accountBarbossaOid); - + // THEN TestUtil.displayThen(TEST_NAME); display("Shadow (model)", shadow); @@ -204,12 +204,12 @@ public void test700CheckBarbossaLockoutStatus() throws Exception { assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_PASSWORD_2); } - + @Test public void test702LockOutBarbossa() throws Exception { final String TEST_NAME = "test702LockOutBarbossa"; TestUtil.displayTestTitle(this, TEST_NAME); - + Entry entry = getLdapAccountByUid(USER_BARBOSSA_USERNAME); display("LDAP Entry before", entry); @@ -225,13 +225,13 @@ public void test702LockOutBarbossa() throws Exception { } assertNotReached(); } - + // THEN TestUtil.displayThen(TEST_NAME); - + entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); display("LDAP Entry after", entry); - + PrismObject shadow = getShadowModel(accountBarbossaOid); display("Shadow (model)", shadow); ActivationType activation = shadow.asObjectable().getActivation(); @@ -239,7 +239,7 @@ public void test702LockOutBarbossa() throws Exception { LockoutStatusType lockoutStatus = shadow.asObjectable().getActivation().getLockoutStatus(); assertEquals("Wrong lockout status", LockoutStatusType.LOCKED, lockoutStatus); } - + @Test public void test705UnlockBarbossaAccount() throws Exception { @@ -249,22 +249,22 @@ public void test705UnlockBarbossaAccount() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(this.getClass().getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - - ObjectDelta accountDelta = createModifyAccountShadowReplaceDelta(accountBarbossaOid, null, + + ObjectDelta accountDelta = createModifyAccountShadowReplaceDelta(accountBarbossaOid, null, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, LockoutStatusType.NORMAL); - + // WHEN TestUtil.displayWhen(TEST_NAME); executeChanges(accountDelta, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject shadow = getShadowModel(accountBarbossaOid); display("Shadow (model)", shadow); - + ActivationType activation = shadow.asObjectable().getActivation(); if (activation != null) { LockoutStatusType lockoutStatus = shadow.asObjectable().getActivation().getLockoutStatus(); @@ -272,11 +272,11 @@ public void test705UnlockBarbossaAccount() throws Exception { AssertJUnit.fail("Barbossa is locked!"); } } - + Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); display("LDAP Entry", entry); assertNoAttribute(entry, "pwdAccountLockedTime"); - + assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_PASSWORD_2); } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenLdapDumber.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenLdapDumber.java index 8abc3282fc6..24cb0e79d8a 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenLdapDumber.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenLdapDumber.java @@ -41,7 +41,7 @@ /** * OpenLDAP, but without permissive modify, shortcut attributes, etc. - * + * * @author semancik */ public class TestOpenLdapDumber extends TestOpenLdap { @@ -55,10 +55,10 @@ protected File getBaseDir() { protected boolean hasAssociationShortcut() { return false; } - + @Override protected boolean isUsingGroupShortcutAttribute() { return false; } - + } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/UserLdapConnectionConfig.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/UserLdapConnectionConfig.java index 2b3e0f7f4e0..d0d57508478 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/UserLdapConnectionConfig.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/UserLdapConnectionConfig.java @@ -22,23 +22,23 @@ * */ public class UserLdapConnectionConfig extends LdapConnectionConfig { - + private String bindDn; private String bindPassword; private String baseContext; - + public String getBindDn() { return bindDn; } - + public void setBindDn(String bindDn) { this.bindDn = bindDn; } - + public String getBindPassword() { return bindPassword; } - + public void setBindPassword(String bindPassword) { this.bindPassword = bindPassword; } @@ -50,5 +50,5 @@ public String getBaseContext() { public void setBaseContext(String baseContext) { this.baseContext = baseContext; } - + } diff --git a/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestGenericSynchronization.java b/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestGenericSynchronization.java index b0cf2eeec6a..ee101e8d98d 100644 --- a/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestGenericSynchronization.java +++ b/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestGenericSynchronization.java @@ -69,7 +69,7 @@ public class TestGenericSynchronization extends AbstractModelIntegrationTest { private static final String RESOURCE_OPENDJ_NAME = "Localhost OpenDJ"; private static final String RESOURCE_OPENDJ_OID = "10000000-0000-0000-0000-000000000030"; private static final String RESOURCE_OPENDJ_NAMESPACE = MidPointConstants.NS_RI; - + public static final File OBJECT_TEMPLATE_ORG_FILE = new File(COMMON_DIR, "object-template-org.xml"); public static final String OBJECT_TEMPLATE_ORG_OID = "10000000-0000-0000-0000-000000000231"; @@ -120,7 +120,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti PrismObject userAdministrator = repoAddObjectFromFile(USER_ADMINISTRATOR_FILE, initResult); repoAddObjectFromFile(ROLE_SUPERUSER_FILE, initResult); login(userAdministrator); - + importObjectFromFile(OBJECT_TEMPLATE_ORG_FILE, initResult); setDefaultObjectTemplate(OrgType.COMPLEX_TYPE, OBJECT_TEMPLATE_ORG_OID); diff --git a/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdap.java b/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdap.java index 3196294c34e..a243dde6247 100644 --- a/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdap.java +++ b/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdap.java @@ -87,69 +87,69 @@ /** * Mix of various tests for issues that are difficult to replicate using dummy resources. - * + * * @author Radovan Semancik * */ @ContextConfiguration(locations = {"classpath:ctx-longtest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestLdap extends AbstractModelIntegrationTest { - + public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "ldap"); - + 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 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 ROLE_PIRATE_FILE = new File(TEST_DIR, "role-pirate.xml"); protected static final String ROLE_PIRATE_OID = "12345678-d34d-b33f-f00d-555555556666"; - + protected static final File RESOURCE_OPENDJ_FILE = new File(COMMON_DIR, "resource-opendj.xml"); protected static final String RESOURCE_OPENDJ_NAME = "Localhost OpenDJ"; 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 File USER_BARBOSSA_FILE = new File(COMMON_DIR, "user-barbossa.xml"); protected static final String USER_BARBOSSA_OID = "c0c010c0-d34d-b33f-f00d-111111111112"; protected static final String USER_BARBOSSA_USERNAME = "barbossa"; protected static final String USER_BARBOSSA_FULL_NAME = "Hector Barbossa"; - + protected static final File USER_GUYBRUSH_FILE = new File (COMMON_DIR, "user-guybrush.xml"); protected static final String USER_GUYBRUSH_OID = "c0c010c0-d34d-b33f-f00d-111111111116"; protected static final String USER_GUYBRUSH_USERNAME = "guybrush"; protected static final String USER_GUYBRUSH_FULL_NAME = "Guybrush Threepwood"; - + private static final String USER_LECHUCK_NAME = "lechuck"; private static final String ACCOUNT_LECHUCK_NAME = "lechuck"; private static final String ACCOUNT_CHARLES_NAME = "charles"; - + protected static final File TASK_DELETE_OPENDJ_SHADOWS_FILE = new File(TEST_DIR, "task-delete-opendj-shadows.xml"); protected static final String TASK_DELETE_OPENDJ_SHADOWS_OID = "412218e4-184b-11e5-9c9b-3c970e467874"; - + protected static final File TASK_DELETE_OPENDJ_ACCOUNTS_FILE = new File(TEST_DIR, "task-delete-opendj-accounts.xml"); protected static final String TASK_DELETE_OPENDJ_ACCOUNTS_OID = "b22c5d72-18d4-11e5-b266-001e8c717e5b"; - + public static final String DOT_JPG_FILENAME = "src/test/resources/common/dot.jpg"; - + private static final int NUM_INITIAL_USERS = 3; // Make it at least 1501 so it will go over the 3000 entries size limit private static final int NUM_LDAP_ENTRIES = 1600; // private static final int NUM_LDAP_ENTRIES = 100; private static final String LDAP_GROUP_PIRATES_DN = "cn=Pirates,ou=groups,dc=example,dc=com"; - + protected ResourceType resourceOpenDjType; protected PrismObject resourceOpenDj; @Autowired private ReconciliationTaskHandler reconciliationTaskHandler; - + @Override protected void startResources() throws Exception { openDJController.startCleanServer(); @@ -168,7 +168,7 @@ public static void stopResources() throws Exception { public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); modelService.postInit(initResult); - + // System Configuration PrismObject config; try { @@ -187,19 +187,19 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti PrismObject userAdministrator = repoAddObjectFromFile(USER_ADMINISTRATOR_FILE, initResult); repoAddObjectFromFile(ROLE_SUPERUSER_FILE, initResult); login(userAdministrator); - + // Users repoAddObjectFromFile(USER_BARBOSSA_FILE, initResult); repoAddObjectFromFile(USER_GUYBRUSH_FILE, initResult); - + // Roles repoAddObjectFromFile(ROLE_PIRATE_FILE, initResult); - + // Resources resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, RESOURCE_OPENDJ_FILE, RESOURCE_OPENDJ_OID, initTask, initResult); resourceOpenDjType = resourceOpenDj.asObjectable(); openDJController.setResource(resourceOpenDj); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); //initProfiling - start @@ -223,7 +223,7 @@ public void test000Sanity() throws Exception { assertUsers(NUM_INITIAL_USERS); } - + /** * Barbossa is already member of LDAP group "pirates". The role adds this group as well. * This should go smoothly. No error expected. @@ -236,11 +236,11 @@ public void test200AssignRolePiratesToBarbossa() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestLdap.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_BARBOSSA_OID, ROLE_PIRATE_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -248,10 +248,10 @@ public void test200AssignRolePiratesToBarbossa() throws Exception { String accountDn = assertOpenDjAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, true).getDN().toString(); openDJController.assertUniqueMember(LDAP_GROUP_PIRATES_DN, accountDn); - + assertUsers(NUM_INITIAL_USERS); } - + /** * Just a first step for the following test. * Also, Guybrush has a photo. Check that binary property mapping works. @@ -264,12 +264,12 @@ public void test202AssignLdapAccountToGuybrush() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestLdap.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + byte[] photoIn = Files.readAllBytes(Paths.get(DOT_JPG_FILENAME)); display("Photo in", MiscUtil.binaryToHex(photoIn)); - modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_JPEG_PHOTO, task, result, + modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_JPEG_PHOTO, task, result, photoIn); - + Collection> options = SelectorOptions.createCollection( UserType.F_JPEG_PHOTO, GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE)); PrismObject userBefore = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, options, task, result); @@ -277,11 +277,11 @@ public void test202AssignLdapAccountToGuybrush() throws Exception { byte[] userJpegPhotoBefore = userBefore.asObjectable().getJpegPhoto(); assertEquals("Photo byte length changed (user before)", photoIn.length, userJpegPhotoBefore.length); assertTrue("Photo bytes do not match (user before)", Arrays.equals(photoIn, userJpegPhotoBefore)); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignAccount(USER_GUYBRUSH_OID, RESOURCE_OPENDJ_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -292,22 +292,22 @@ public void test202AssignLdapAccountToGuybrush() throws Exception { assertNotNull("No jpegPhoto in LDAP entry", jpegPhotoLdap); assertEquals("Byte length changed (LDAP)", photoIn.length, jpegPhotoLdap.length); assertTrue("Bytes do not match (LDAP)", Arrays.equals(photoIn, jpegPhotoLdap)); - + PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, options, task, result); display("User after", userAfter); String accountOid = getSingleLinkOid(userAfter); PrismObject shadow = getShadowModel(accountOid); - + PrismContainer attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES); QName jpegPhotoQName = new QName(RESOURCE_OPENDJ_NAMESPACE, "jpegPhoto"); PrismProperty jpegPhotoAttr = attributesContainer.findProperty(jpegPhotoQName); byte[] photoBytesOut = jpegPhotoAttr.getValues().get(0).getValue(); - + display("Photo bytes out", MiscUtil.binaryToHex(photoBytesOut)); - + assertEquals("Photo byte length changed (shadow)", photoIn.length, photoBytesOut.length); assertTrue("Photo bytes do not match (shadow)", Arrays.equals(photoIn, photoBytesOut)); - + assertUsers(NUM_INITIAL_USERS); } @@ -329,11 +329,11 @@ public void test204AssignRolePiratesToGuybrush() throws Exception { "add: uniqueMember\n" + "uniqueMember: uid=GuyBrush,ou=pEOPle,dc=EXAMPLE,dc=cOm" ); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_GUYBRUSH_OID, ROLE_PIRATE_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); @@ -341,11 +341,11 @@ public void test204AssignRolePiratesToGuybrush() throws Exception { String accountDn = assertOpenDjAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true).getDN().toString(); openDJController.assertUniqueMember(LDAP_GROUP_PIRATES_DN, accountDn); - + assertUsers(NUM_INITIAL_USERS); } - + @Test public void test400RenameLeChuckConflicting() throws Exception { final String TEST_NAME = "test400RenameLeChuckConflicting"; @@ -354,54 +354,54 @@ public void test400RenameLeChuckConflicting() throws Exception { // GIVEN Task task = taskManager.createTaskInstance(TestLdap.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userLechuck = createUser(USER_LECHUCK_NAME, "LeChuck", true); userLechuck.asObjectable().getAssignment().add(createAccountAssignment(RESOURCE_OPENDJ_OID, null)); userLechuck.asObjectable().setFamilyName(PrismTestUtil.createPolyStringType("LeChuck")); addObject(userLechuck); String userLechuckOid = userLechuck.getOid(); - + PrismObject accountCharles = createAccount(resourceOpenDj, toDn(ACCOUNT_CHARLES_NAME), true); addAttributeToShadow(accountCharles, resourceOpenDj, "sn", "Charles"); addAttributeToShadow(accountCharles, resourceOpenDj, "cn", "Charles L. Charles"); addObject(accountCharles); - + // preconditions assertOpenDjAccount(ACCOUNT_LECHUCK_NAME, "LeChuck", true); assertOpenDjAccount(ACCOUNT_CHARLES_NAME, "Charles L. Charles", true); - + // WHEN TestUtil.displayWhen(TEST_NAME); modifyUserReplace(userLechuckOid, UserType.F_NAME, task, result, PrismTestUtil.createPolyString(ACCOUNT_CHARLES_NAME)); - + // THEN TestUtil.displayThen(TEST_NAME); assertOpenDjAccount(ACCOUNT_CHARLES_NAME, "Charles L. Charles", true); assertOpenDjAccount(ACCOUNT_CHARLES_NAME + "1", "LeChuck", true); assertNoOpenDjAccount(ACCOUNT_LECHUCK_NAME); - + assertUsers(NUM_INITIAL_USERS + 1); } - + @Test public void test800BigLdapSearch() throws Exception { final String TEST_NAME = "test800BigLdapSearch"; TestUtil.displayTestTitle(this, TEST_NAME); // GIVEN - + assertUsers(NUM_INITIAL_USERS + 1); - + loadEntries("a"); - + Task task = taskManager.createTaskInstance(TestLdap.class.getName() + "." + TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_OPENDJ_OID, + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_OPENDJ_OID, new QName(RESOURCE_OPENDJ_NAMESPACE, "inetOrgPerson"), prismContext); - + final MutableInt count = new MutableInt(0); ResultHandler handler = new ResultHandler() { @Override @@ -411,21 +411,21 @@ public boolean handle(PrismObject shadow, OperationResult parentResu return true; } }; - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.searchObjectsIterative(ShadowType.class, query, handler, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + // THEN TestUtil.displayThen(TEST_NAME); - + assertEquals("Unexpected number of search results", NUM_LDAP_ENTRIES + 8, count.getValue()); - + assertUsers(NUM_INITIAL_USERS + 1); } @@ -435,31 +435,31 @@ public void test810BigImport() throws Exception { TestUtil.displayTestTitle(this, TEST_NAME); // GIVEN - + assertUsers(NUM_INITIAL_USERS + 1); - + loadEntries("u"); - + Task task = taskManager.createTaskInstance(TestLdap.class.getName() + "." + TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); //task.setExtensionPropertyValue(SchemaConstants.MODEL_EXTENSION_WORKER_THREADS, 2); - modelService.importFromResource(RESOURCE_OPENDJ_OID, + modelService.importFromResource(RESOURCE_OPENDJ_OID, new QName(RESOURCE_OPENDJ_NAMESPACE, "inetOrgPerson"), task, result); - + // THEN TestUtil.displayThen(TEST_NAME); OperationResult subresult = result.getLastSubresult(); TestUtil.assertInProgress("importAccountsFromResource result", subresult); - + waitForTaskFinish(task, true, 20000 + NUM_LDAP_ENTRIES*2000); - + // THEN TestUtil.displayThen(TEST_NAME); - + int userCount = modelService.countObjects(UserType.class, null, null, task, result); display("Users", userCount); assertEquals("Unexpected number of users", 2*NUM_LDAP_ENTRIES + 8, userCount); @@ -513,25 +513,25 @@ public void test900DeleteShadows() throws Exception { Task task = taskManager.createTaskInstance(TestLdap.class.getName() + "." + TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); // WHEN TestUtil.displayWhen(TEST_NAME); importObjectFromFile(TASK_DELETE_OPENDJ_SHADOWS_FILE); - + // THEN TestUtil.displayThen(TEST_NAME); - + waitForTaskFinish(TASK_DELETE_OPENDJ_SHADOWS_OID, true, 20000 + NUM_LDAP_ENTRIES*2000); - + // THEN TestUtil.displayThen(TEST_NAME); - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - - - + + + PrismObject deleteTask = getTask(TASK_DELETE_OPENDJ_SHADOWS_OID); OperationResultType deleteTaskResultType = deleteTask.asObjectable().getResult(); display("Final delete task result", deleteTaskResultType); @@ -544,15 +544,15 @@ public void test900DeleteShadows() throws Exception { TestUtil.assertSuccess(opExecResult); assertEquals("Wrong exec operation count", 2*NUM_LDAP_ENTRIES+8, opExecResult.getCount()); assertTrue("Too many subresults: "+deleteTaskResult.getSubresults().size(), deleteTaskResult.getSubresults().size() < 10); - + assertOpenDjAccountShadows(0, true, task, result); assertUsers(2*NUM_LDAP_ENTRIES + 8); - + // Check that the actual accounts were NOT deleted // (This also re-creates shadows) assertOpenDjAccountShadows(2*NUM_LDAP_ENTRIES+8, false, task, result); } - + @Test public void test910DeleteAccounts() throws Exception { final String TEST_NAME = "test910DeleteAccounts"; @@ -562,24 +562,24 @@ public void test910DeleteAccounts() throws Exception { Task task = taskManager.createTaskInstance(TestLdap.class.getName() + "." + TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); // WHEN TestUtil.displayWhen(TEST_NAME); importObjectFromFile(TASK_DELETE_OPENDJ_ACCOUNTS_FILE); - + // THEN TestUtil.displayThen(TEST_NAME); - + waitForTaskFinish(TASK_DELETE_OPENDJ_ACCOUNTS_OID, true, 20000 + NUM_LDAP_ENTRIES*3000); - + // THEN TestUtil.displayThen(TEST_NAME); - + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, (2*NUM_LDAP_ENTRIES)/100+2); - - + + PrismObject deleteTask = getTask(TASK_DELETE_OPENDJ_SHADOWS_OID); OperationResultType deleteTaskResultType = deleteTask.asObjectable().getResult(); display("Final delete task result", deleteTaskResultType); @@ -592,16 +592,16 @@ public void test910DeleteAccounts() throws Exception { TestUtil.assertSuccess(opExecResult); assertEquals("Wrong exec operation count", 2*NUM_LDAP_ENTRIES + 8, opExecResult.getCount()); assertTrue("Too many subresults: "+deleteTaskResult.getSubresults().size(), deleteTaskResult.getSubresults().size() < 10); - + assertOpenDjAccountShadows(1, true, task, result); assertUsers(2*NUM_LDAP_ENTRIES + 8); assertOpenDjAccountShadows(1, false, task, result); } - + private void assertOpenDjAccountShadows(int expected, boolean raw, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_OPENDJ_OID, + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_OPENDJ_OID, new QName(RESOURCE_OPENDJ_NAMESPACE, "inetOrgPerson"), prismContext); - + final MutableInt count = new MutableInt(0); ResultHandler handler = new ResultHandler() { @Override @@ -621,15 +621,15 @@ public boolean handle(PrismObject shadow, OperationResult parentResu private void loadEntries(String prefix) throws LDIFException, IOException { long ldapPopStart = System.currentTimeMillis(); - + for(int i=0; i < NUM_LDAP_ENTRIES; i++) { String name = "user"+i; Entry entry = createEntry(prefix+i, name); openDJController.addEntry(entry); } - + long ldapPopEnd = System.currentTimeMillis(); - + display("Loaded "+NUM_LDAP_ENTRIES+" LDAP entries (prefix "+prefix+") in "+((ldapPopEnd-ldapPopStart)/1000)+" seconds"); } @@ -646,7 +646,7 @@ private Entry createEntry(String uid, String name) throws IOException, LDIFExcep Entry ldifEntry = ldifReader.readEntry(); return ldifEntry; } - + private String toDn(String username) { return "uid="+username+","+OPENDJ_PEOPLE_SUFFIX; } diff --git a/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdapComplex.java b/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdapComplex.java index 7e1d4487e8b..3a5241a6bd5 100644 --- a/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdapComplex.java +++ b/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdapComplex.java @@ -55,16 +55,16 @@ /** * Mix of various tests for issues that are difficult to replicate using dummy resources. - * + * * @author Radovan Semancik * */ @ContextConfiguration(locations = {"classpath:ctx-longtest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestLdapComplex extends AbstractModelIntegrationTest { - + public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "ldap-complex"); - + 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(); @@ -73,10 +73,10 @@ public class TestLdapComplex extends AbstractModelIntegrationTest { 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 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 ROLE_CAPTAIN_FILE = new File(TEST_DIR, "role-captain.xml"); protected static final File ROLE_JUDGE_FILE = new File(TEST_DIR, "role-judge.xml"); protected static final File ROLE_PIRATE_FILE = new File(TEST_DIR, "role-pirate.xml"); @@ -84,23 +84,23 @@ public class TestLdapComplex extends AbstractModelIntegrationTest { protected static final String ROLE_PIRATE_OID = "12345678-d34d-b33f-f00d-555555556603"; protected static final File ROLES_LDIF_FILE = new File(TEST_DIR, "roles.ldif"); - + protected static final File RESOURCE_OPENDJ_FILE = new File(COMMON_DIR, "resource-opendj-complex.xml"); protected static final String RESOURCE_OPENDJ_NAME = "Localhost OpenDJ"; protected static final String RESOURCE_OPENDJ_OID = "10000000-0000-0000-0000-000000000003"; protected static final String RESOURCE_OPENDJ_NAMESPACE = MidPointConstants.NS_RI; - + // Make it at least 1501 so it will go over the 3000 entries size limit private static final int NUM_LDAP_ENTRIES = 1000; private static final String LDAP_GROUP_PIRATES_DN = "cn=Pirates,ou=groups,dc=example,dc=com"; - + protected ResourceType resourceOpenDjType; protected PrismObject resourceOpenDj; @Autowired private ReconciliationTaskHandler reconciliationTaskHandler; - + @Override protected void startResources() throws Exception { openDJController.startCleanServer(); @@ -115,7 +115,7 @@ public static void stopResources() throws Exception { public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); modelService.postInit(initResult); - + // System Configuration PrismObject config; try { @@ -133,7 +133,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti PrismObject userAdministrator = repoAddObjectFromFile(USER_ADMINISTRATOR_FILE, initResult); repoAddObjectFromFile(ROLE_SUPERUSER_FILE, initResult); login(userAdministrator); - + // Roles repoAddObjectFromFile(ROLE_CAPTAIN_FILE, initResult); repoAddObjectFromFile(ROLE_JUDGE_FILE, initResult); @@ -142,48 +142,48 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti // templates repoAddObjectFromFile(USER_TEMPLATE_FILE, initResult); - + // Resources resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, RESOURCE_OPENDJ_FILE, RESOURCE_OPENDJ_OID, initTask, initResult); resourceOpenDjType = resourceOpenDj.asObjectable(); openDJController.setResource(resourceOpenDj); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); openDJController.addEntriesFromLdifFile(ROLES_LDIF_FILE.getPath()); display("initial LDAP content", openDJController.dumpEntries()); } - + @Test public void test100BigImport() throws Exception { final String TEST_NAME = "test100BigImport"; TestUtil.displayTestTitle(this, TEST_NAME); // GIVEN - + loadEntries("u"); - + Task task = taskManager.createTaskInstance(TestLdapComplex.class.getName() + "." + TEST_NAME); task.setOwner(getUser(USER_ADMINISTRATOR_OID)); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); //task.setExtensionPropertyValue(SchemaConstants.MODEL_EXTENSION_WORKER_THREADS, 2); - modelService.importFromResource(RESOURCE_OPENDJ_OID, + modelService.importFromResource(RESOURCE_OPENDJ_OID, new QName(RESOURCE_OPENDJ_NAMESPACE, "AccountObjectClass"), task, result); - + // THEN TestUtil.displayThen(TEST_NAME); OperationResult subresult = result.getLastSubresult(); TestUtil.assertInProgress("importAccountsFromResource result", subresult); - + waitForTaskFinish(task, true, 20000 + NUM_LDAP_ENTRIES*2000); - + // THEN TestUtil.displayThen(TEST_NAME); - + int userCount = modelService.countObjects(UserType.class, null, null, task, result); display("Users", userCount); assertEquals("Unexpected number of users", NUM_LDAP_ENTRIES+4, userCount); @@ -237,15 +237,15 @@ public void test120BigReconciliation() throws Exception { private void loadEntries(String prefix) throws LDIFException, IOException { long ldapPopStart = System.currentTimeMillis(); - + for(int i=0; i < NUM_LDAP_ENTRIES; i++) { String name = "user"+i; Entry entry = createEntry(prefix+i, name); openDJController.addEntry(entry); } - + long ldapPopEnd = System.currentTimeMillis(); - + display("Loaded "+NUM_LDAP_ENTRIES+" LDAP entries in "+((ldapPopEnd-ldapPopStart)/1000)+" seconds"); } @@ -262,7 +262,7 @@ private Entry createEntry(String uid, String name) throws IOException, LDIFExcep Entry ldifEntry = ldifReader.readEntry(); return ldifEntry; } - + private String toDn(String username) { return "uid="+username+","+OPENDJ_PEOPLE_SUFFIX; } diff --git a/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdapUniversity.java b/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdapUniversity.java index 360af877652..eafb69a877f 100644 --- a/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdapUniversity.java +++ b/testing/longtest/src/test/java/com/evolveum/midpoint/testing/longtest/TestLdapUniversity.java @@ -64,35 +64,35 @@ @ContextConfiguration(locations = {"classpath:ctx-longtest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestLdapUniversity extends AbstractModelIntegrationTest { - + public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "ldap-university"); - + 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 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 RESOURCE_OPENDJ_FILE = new File(COMMON_DIR, "resource-opendj-university.xml"); protected static final String RESOURCE_OPENDJ_NAME = "Localhost OpenDJ"; protected static final String RESOURCE_OPENDJ_OID = "10000000-0000-0000-0000-000000000003"; protected static final String RESOURCE_OPENDJ_NAMESPACE = MidPointConstants.NS_RI; - + // Make it at least 1501 so it will go over the 3000 entries size limit private static final int NUM_LDAP_ENTRIES = 20000; private static final String LDAP_GROUP_PIRATES_DN = "cn=Pirates,ou=groups,dc=example,dc=com"; - + protected ResourceType resourceOpenDjType; protected PrismObject resourceOpenDj; @Autowired private ReconciliationTaskHandler reconciliationTaskHandler; - + @Override protected void startResources() throws Exception { openDJController.startCleanServer(); @@ -107,7 +107,7 @@ public static void stopResources() throws Exception { public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); modelService.postInit(initResult); - + // System Configuration PrismObject config; try { @@ -125,17 +125,17 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti PrismObject userAdministrator = repoAddObjectFromFile(USER_ADMINISTRATOR_FILE, initResult); repoAddObjectFromFile(ROLE_SUPERUSER_FILE, initResult); login(userAdministrator); - + // Resources resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, RESOURCE_OPENDJ_FILE, RESOURCE_OPENDJ_OID, initTask, initResult); resourceOpenDjType = resourceOpenDj.asObjectable(); openDJController.setResource(resourceOpenDj); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); display("initial LDAP content", openDJController.dumpEntries()); } - + @Test public void test100BigImportWithLinking() throws Exception { final String TEST_NAME = "test100BigImportWithLinking"; @@ -157,19 +157,19 @@ public void test100BigImportWithLinking() throws Exception { // WHEN TestUtil.displayWhen(TEST_NAME); //task.setExtensionPropertyValue(SchemaConstants.MODEL_EXTENSION_WORKER_THREADS, 5); - modelService.importFromResource(RESOURCE_OPENDJ_OID, + modelService.importFromResource(RESOURCE_OPENDJ_OID, new QName(RESOURCE_OPENDJ_NAMESPACE, "AccountObjectClass"), task, result); - + // THEN TestUtil.displayThen(TEST_NAME); OperationResult subresult = result.getLastSubresult(); TestUtil.assertInProgress("importAccountsFromResource result", subresult); - + waitForTaskFinish(task, true, 20000 + NUM_LDAP_ENTRIES*2000, 10000L); - + // THEN TestUtil.displayThen(TEST_NAME); - + int userCount = modelService.countObjects(UserType.class, null, null, task, result); display("Users", userCount); assertEquals("Unexpected number of users", NUM_LDAP_ENTRIES+1, userCount); @@ -272,9 +272,9 @@ private void loadEntries(String prefix) throws LDIFException, IOException { // if (!namesToAdd.isEmpty()) { // addToGroups(namesToAdd); // } - + long ldapPopEnd = System.currentTimeMillis(); - + display("Loaded "+NUM_LDAP_ENTRIES+" LDAP entries in "+((ldapPopEnd-ldapPopStart)/1000)+" seconds"); } @@ -298,7 +298,7 @@ private Entry createEntry(String uid, String empno, String name) throws IOExcept Entry ldifEntry = ldifReader.readEntry(); return ldifEntry; } - + private String toDn(String username) { return "uid="+username+","+OPENDJ_PEOPLE_SUFFIX; } diff --git a/testing/minipoint/src/main/java/com/evolveum/midpoint/testing/minipoint/Main.java b/testing/minipoint/src/main/java/com/evolveum/midpoint/testing/minipoint/Main.java index eccd8d8d7c7..c264ee4f3f8 100644 --- a/testing/minipoint/src/main/java/com/evolveum/midpoint/testing/minipoint/Main.java +++ b/testing/minipoint/src/main/java/com/evolveum/midpoint/testing/minipoint/Main.java @@ -35,7 +35,7 @@ public class Main { private static final Trace LOGGER = TraceManager.getTrace(Main.class); - + /** * @param args */ @@ -44,7 +44,7 @@ public static void main(String[] args) { // LOGGER.info("Spring context initialized."); System.out.println("##* STARTING *##"); ApplicationContext ctx = SpringApplication.run(Main.class, args); - + System.out.println("Let's inspect the beans provided by Spring Boot:"); String[] beanNames = ctx.getBeanDefinitionNames(); diff --git a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/RestServiceInitializer.java b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/RestServiceInitializer.java index fb5d39ca797..18ec7da373b 100644 --- a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/RestServiceInitializer.java +++ b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/RestServiceInitializer.java @@ -64,9 +64,9 @@ public abstract class RestServiceInitializer { private static final Trace LOGGER = TraceManager.getTrace(RestServiceInitializer.class); - + protected static final File BASE_REPO_DIR = new File("src/test/resources/repo/"); - + public static final File USER_ADMINISTRATOR_FILE = new File(BASE_REPO_DIR, "user-administrator.xml"); public static final String USER_ADMINISTRATOR_USERNAME = "administrator"; public static final String USER_ADMINISTRATOR_PASSWORD = "5ecr3t"; @@ -82,25 +82,25 @@ public abstract class RestServiceInitializer { public static final String USER_CYCLOPS_OID = "6020bb52-d48e-11e4-9eaf-001e8c717e5b"; public static final String USER_CYCLOPS_USERNAME = "cyclops"; public static final String USER_CYCLOPS_PASSWORD = "cyclopassword"; - + // REST and reader authorization public static final File USER_SOMEBODY_FILE = new File(BASE_REPO_DIR, "user-somebody.xml"); public static final String USER_SOMEBODY_OID = "a5f3e3c8-d48b-11e4-8d88-001e8c717e5b"; public static final String USER_SOMEBODY_USERNAME = "somebody"; public static final String USER_SOMEBODY_PASSWORD = "somepassword"; - + public static final File ROLE_SUPERUSER_FILE = new File(BASE_REPO_DIR, "role-superuser.xml"); public static final File ROLE_ENDUSER_FILE = new File(BASE_REPO_DIR, "role-enduser.xml"); public static final File ROLE_REST_FILE = new File(BASE_REPO_DIR, "role-rest.xml"); public static final File ROLE_READER_FILE = new File(BASE_REPO_DIR, "role-reader.xml"); - + public static final File SYSTEM_CONFIGURATION_FILE = new File(BASE_REPO_DIR, "system-configuration.xml"); public static final File VALUE_POLICY_GENERAL = new File(BASE_REPO_DIR, "value-policy-general.xml"); public static final File VALUE_POLICY_NUMERIC = new File(BASE_REPO_DIR, "value-policy-numeric.xml"); public static final File VALUE_POLICY_SIMPLE = new File(BASE_REPO_DIR, "value-policy-simple.xml"); public static final File SECURITY_POLICY = new File(BASE_REPO_DIR, "security-policy.xml"); - + ApplicationContext applicationContext = null; private PrismContext prismContext; @@ -120,7 +120,7 @@ public abstract class RestServiceInitializer { protected abstract String getAcceptHeader(); protected abstract String getContentType(); protected abstract MidpointAbstractProvider getProvider(); - + protected final static String ENDPOINT_ADDRESS = "http://localhost:18080/rest"; @BeforeClass @@ -154,10 +154,10 @@ public void startServer() throws Exception { InternalsConfig.encryptionChecks = false; prismContext = (PrismContext) applicationContext.getBean("prismContext"); - + Task initTask = getTaskManager().createTaskInstance(TestAbstractRestService.class.getName() + ".startServer"); OperationResult result = initTask.getResult(); - + addObject(ROLE_SUPERUSER_FILE, result); addObject(ROLE_ENDUSER_FILE, result); addObject(ROLE_REST_FILE, result); @@ -173,7 +173,7 @@ public void startServer() throws Exception { addObject(SYSTEM_CONFIGURATION_FILE, result); dummyAuditService = getDummyAuditService().getInstance(); - + InternalMonitor.reset(); getModelService().postInit(result); @@ -182,7 +182,7 @@ public void startServer() throws Exception { TestUtil.assertSuccessOrWarning("startServer failed (result)", result, 1); } - + protected PrismObject addObject(File file, OperationResult result) throws SchemaException, IOException, ObjectAlreadyExistsException { PrismObject object = getPrismContext().parseObject(file); String oid = getRepositoryService().addObject(object, null, result); 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 59fef74cb8a..0d99f38a702 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 @@ -65,27 +65,27 @@ public abstract class TestAbstractRestService extends RestServiceInitializer{ - + // 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 = "iamyouruncle"; - + // 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"; - - public static final String ROLE_MODIFIER_FILE = "role-modifier"; + + public static final String ROLE_MODIFIER_FILE = "role-modifier"; public static final String ROLE_MODIFIER_OID = "82005ae4-d90b-11e4-bdcc-001e8c717e5b"; - - public static final String POLICY_ITEM_DEFINITION_GENERATE = "policy-generate"; - public static final String POLICY_ITEM_DEFINITION_GENERATE_BAD_PATH = "policy-generate-bad-path"; + + public static final String POLICY_ITEM_DEFINITION_GENERATE = "policy-generate"; + public static final String POLICY_ITEM_DEFINITION_GENERATE_BAD_PATH = "policy-generate-bad-path"; public static final String POLICY_ITEM_DEFINITION_GENERATE_EXECUTE = "policy-generate-execute"; public static final String POLICY_ITEM_DEFINITION_GENERATE_PASSWORD_EXECUTE = "policy-generate-password-execute"; public static final String POLICY_ITEM_DEFINITION_GENERATE_HONORIFIC_PREFIX_EXECUTE = "policy-generate-honorific-prefix-execute"; @@ -108,23 +108,23 @@ public abstract class TestAbstractRestService extends RestServiceInitializer{ private static final Trace LOGGER = TraceManager.getTrace(TestAbstractRestService.class); - private static final String MODIFICATION_DISABLE = "modification-disable"; - private static final String MODIFICATION_ENABLE = "modification-enable"; + private static final String MODIFICATION_DISABLE = "modification-disable"; + private static final String MODIFICATION_ENABLE = "modification-enable"; private static final String MODIFICATION_ASSIGN_ROLE_MODIFIER = "modification-assign-role-modifier"; private static final String MODIFICATION_REPLACE_ANSWER = "modification-replace-answer"; private static final String MODIFICATION_FORCE_PASSWORD_CHANGE = "modification-force-password-change"; - + protected abstract File getRepoFile(String fileBaseName); protected abstract File getRequestFile(String fileBaseName); public static final String QUESTION_ID = "http://midpoint.evolveum.com/xml/ns/public/security/question-2#q001"; - - + + public TestAbstractRestService() { super(); } - + @Test public void test001GetUserAdministrator() { final String TEST_NAME = "test001GetUserAdministrator"; @@ -132,18 +132,18 @@ public void test001GetUserAdministrator() { WebClient client = prepareClient(); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); Response response = client.get(); - + TestUtil.displayThen(TEST_NAME); assertStatus(response, 200); UserType userType = response.readEntity(UserType.class); assertNotNull("Returned entity in body must not be null.", userType); LOGGER.info("Returned entity: {}", userType.asPrismObject().debugDump()); - + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); @@ -156,7 +156,7 @@ public void test002GetNonExistingUser() { WebClient client = prepareClient(); client.path("/users/12345"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -181,7 +181,7 @@ public void test003GetNoAuthHeaders() { WebClient client = prepareClient(null, null); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -202,7 +202,7 @@ public void test004GetAuthBadUsernameNullPassword() { WebClient client = prepareClient("NoSUCHuser", null); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -223,7 +223,7 @@ public void test005GetAuthBadUsernameEmptyPassword() { WebClient client = prepareClient("NoSUCHuser", ""); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -244,7 +244,7 @@ public void test006GetAuthBadUsernameBadPassword() { WebClient client = prepareClient("NoSUCHuser", "NoSuchPassword"); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -265,7 +265,7 @@ public void test007GetAuthNoPassword() { WebClient client = prepareClient(USER_ADMINISTRATOR_USERNAME, null); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -286,7 +286,7 @@ public void test016GetAuthBadPassword() { WebClient client = prepareClient(USER_ADMINISTRATOR_USERNAME, "forgot"); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -299,7 +299,7 @@ public void test016GetAuthBadPassword() { getDummyAuditService().assertRecords(1); getDummyAuditService().assertFailedLogin(SchemaConstants.CHANNEL_REST_URI); } - + @Test public void test017GetUnauthorizedUser() { final String TEST_NAME = "test017GetUnauthorizedUser"; @@ -307,7 +307,7 @@ public void test017GetUnauthorizedUser() { WebClient client = prepareClient(USER_NOBODY_USERNAME, USER_NOBODY_PASSWORD); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -320,7 +320,7 @@ public void test017GetUnauthorizedUser() { getDummyAuditService().assertRecords(1); getDummyAuditService().assertFailedLogin(SchemaConstants.CHANNEL_REST_URI); } - + @Test public void test018GetUserAdministratorByCyclops() { final String TEST_NAME = "test018GetUserAdministratorByCyclops"; @@ -328,7 +328,7 @@ public void test018GetUserAdministratorByCyclops() { WebClient client = prepareClient(USER_CYCLOPS_USERNAME, USER_CYCLOPS_PASSWORD); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -341,7 +341,7 @@ public void test018GetUserAdministratorByCyclops() { getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } - + @Test public void test019GetUserAdministratorBySomebody() { final String TEST_NAME = "test019GetUserAdministratorBySomebody"; @@ -349,20 +349,20 @@ public void test019GetUserAdministratorBySomebody() { WebClient client = prepareClient(USER_SOMEBODY_USERNAME, USER_SOMEBODY_PASSWORD); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); Response response = client.get(); TestUtil.displayThen(TEST_NAME); - + assertStatus(response, 200); - + UserType userType = response.readEntity(UserType.class); assertNotNull("Returned entity in body must not be null.", userType); LOGGER.info("Returned entity: {}", userType.asPrismObject().debugDump()); - + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); @@ -375,7 +375,7 @@ public void test102AddUserTemplate() throws Exception { WebClient client = prepareClient(); client.path("/objectTemplates/"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -399,7 +399,7 @@ public void test103AddUserBadTargetCollection() throws Exception { WebClient client = prepareClient(); client.path("/objectTemplates"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -427,7 +427,7 @@ public void test104AddAccountRawResourceDoesNotExist() throws Exception { WebClient client = prepareClient(); client.path("/shadows"); client.query("options", "raw"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -441,7 +441,7 @@ public void test104AddAccountRawResourceDoesNotExist() throws Exception { 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); - + OperationResult parentResult = new OperationResult("get"); try { getProvisioning().getObject(ShadowType.class, ACCOUT_CHUCK_OID, @@ -459,7 +459,7 @@ public void test104AddAccountRawResourceDoesNotExist() throws Exception { getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); getDummyAuditService().assertHasDelta(1, ChangeType.ADD, ShadowType.class); } - + @Test public void test120AddRoleAdder() throws Exception { final String TEST_NAME = "test120AddRoleAdder"; @@ -467,7 +467,7 @@ public void test120AddRoleAdder() throws Exception { WebClient client = prepareClient(); client.path("/roles"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -490,7 +490,7 @@ public void test121AddUserDarthAdder() throws Exception { WebClient client = prepareClient(); client.path("/users"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -506,7 +506,7 @@ public void test121AddUserDarthAdder() throws Exception { getDummyAuditService().assertHasDelta(1, ChangeType.ADD, UserType.class); } - + @Test public void test122AddRoleModifierAsDarthAdder() throws Exception { final String TEST_NAME = "test122AddRoleModifierAsDarthAdder"; @@ -514,7 +514,7 @@ public void test122AddRoleModifierAsDarthAdder() throws Exception { WebClient client = prepareClient(USER_DARTHADDER_USERNAME, USER_DARTHADDER_PASSWORD); client.path("/roles"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -529,7 +529,7 @@ public void test122AddRoleModifierAsDarthAdder() throws Exception { getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); getDummyAuditService().assertHasDelta(1, ChangeType.ADD, RoleType.class); } - + @Test public void test123DarthAdderAssignModifierHimself() throws Exception { final String TEST_NAME = "test123DarthAdderAssignModifierHimself"; @@ -537,7 +537,7 @@ public void test123DarthAdderAssignModifierHimself() throws Exception { WebClient client = prepareClient(USER_DARTHADDER_USERNAME, USER_DARTHADDER_PASSWORD); client.path("/users/"+USER_DARTHADDER_OID); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -556,7 +556,7 @@ public void test123DarthAdderAssignModifierHimself() throws Exception { getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); getDummyAuditService().assertExecutionOutcome(1, OperationResultStatus.FATAL_ERROR); } - + @Test public void test124DarthAdderAssignModifierByAdministrator() throws Exception { final String TEST_NAME = "test124DarthAdderAssignModifierByAdministrator"; @@ -564,7 +564,7 @@ public void test124DarthAdderAssignModifierByAdministrator() throws Exception { WebClient client = prepareClient(); client.path("/users/"+USER_DARTHADDER_OID); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -578,12 +578,12 @@ public void test124DarthAdderAssignModifierByAdministrator() throws Exception { getDummyAuditService().assertRecords(4); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); getDummyAuditService().assertHasDelta(1, ChangeType.MODIFY, UserType.class); - + OperationResult result = new OperationResult("test"); PrismObject user = getRepositoryService().getObject(UserType.class, USER_DARTHADDER_OID, null, result); assertEquals("Unexpected number of assignments", 4, user.asObjectable().getAssignment().size()); } - + @Test public void test130DarthAdderDisableHimself() throws Exception { final String TEST_NAME = "test130DarthAdderDisableHimself"; @@ -591,7 +591,7 @@ public void test130DarthAdderDisableHimself() throws Exception { WebClient client = prepareClient(USER_DARTHADDER_USERNAME, USER_DARTHADDER_PASSWORD); client.path("/users/"+USER_DARTHADDER_OID); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -605,12 +605,12 @@ public void test130DarthAdderDisableHimself() throws Exception { getDummyAuditService().assertRecords(4); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); getDummyAuditService().assertHasDelta(1, ChangeType.MODIFY, UserType.class); - + OperationResult result = new OperationResult("test"); PrismObject user = getRepositoryService().getObject(UserType.class, USER_DARTHADDER_OID, null, result); assertEquals("Wrong administrativeStatus", ActivationStatusType.DISABLED, user.asObjectable().getActivation().getAdministrativeStatus()); } - + @Test public void test131GetUserAdministratorByDarthAdder() { final String TEST_NAME = "test131GetUserAdministratorByDarthAdder"; @@ -618,7 +618,7 @@ public void test131GetUserAdministratorByDarthAdder() { WebClient client = prepareClient(USER_DARTHADDER_USERNAME, USER_DARTHADDER_PASSWORD); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -627,12 +627,12 @@ public void test131GetUserAdministratorByDarthAdder() { TestUtil.displayThen(TEST_NAME); assertStatus(response, 403); assertNoEmptyResponse(response); - + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(1); getDummyAuditService().assertFailedLogin(SchemaConstants.CHANNEL_REST_URI); } - + @Test public void test132DarthAdderEnableByAdministrator() throws Exception { final String TEST_NAME = "test132DarthAdderEnableByAdministrator"; @@ -640,7 +640,7 @@ public void test132DarthAdderEnableByAdministrator() throws Exception { WebClient client = prepareClient(); client.path("/users/"+USER_DARTHADDER_OID); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -654,12 +654,12 @@ public void test132DarthAdderEnableByAdministrator() throws Exception { getDummyAuditService().assertRecords(4); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); getDummyAuditService().assertHasDelta(1, ChangeType.MODIFY, UserType.class); - + OperationResult result = new OperationResult("test"); PrismObject user = getRepositoryService().getObject(UserType.class, USER_DARTHADDER_OID, null, result); assertEquals("Wrong administrativeStatus", ActivationStatusType.ENABLED, user.asObjectable().getActivation().getAdministrativeStatus()); } - + @Test public void test133GetUserAdministratorByDarthAdder() { final String TEST_NAME = "test133GetUserAdministratorByDarthAdder"; @@ -667,7 +667,7 @@ public void test133GetUserAdministratorByDarthAdder() { WebClient client = prepareClient(USER_DARTHADDER_USERNAME, USER_DARTHADDER_PASSWORD); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -678,12 +678,12 @@ public void test133GetUserAdministratorByDarthAdder() { UserType userType = response.readEntity(UserType.class); assertNotNull("Returned entity in body must not be null.", userType); LOGGER.info("Returned entity: {}", userType.asPrismObject().debugDump()); - + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } - + @Test public void test135AddUserNopasswordAsDarthAdder() throws Exception { final String TEST_NAME = "test135AddUserNopasswordAsDarthAdder"; @@ -691,7 +691,7 @@ public void test135AddUserNopasswordAsDarthAdder() throws Exception { WebClient client = prepareClient(USER_DARTHADDER_USERNAME, USER_DARTHADDER_PASSWORD); client.path("/users"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -706,7 +706,7 @@ public void test135AddUserNopasswordAsDarthAdder() throws Exception { getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); getDummyAuditService().assertHasDelta(1, ChangeType.ADD, UserType.class); } - + @Test public void test140GetUserAdministratorByNopassword() { final String TEST_NAME = "test140GetUserAdministratorByNopassword"; @@ -714,7 +714,7 @@ public void test140GetUserAdministratorByNopassword() { WebClient client = prepareClient(USER_NOPASSWORD_USERNAME, null); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -723,12 +723,12 @@ public void test140GetUserAdministratorByNopassword() { TestUtil.displayThen(TEST_NAME); assertStatus(response, 401); assertNoEmptyResponse(response); - + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(1); getDummyAuditService().assertFailedLogin(SchemaConstants.CHANNEL_REST_URI); } - + @Test public void test141GetUserAdministratorByNopasswordBadPassword() { final String TEST_NAME = "test140GetUserAdministratorByNopassword"; @@ -736,7 +736,7 @@ public void test141GetUserAdministratorByNopasswordBadPassword() { WebClient client = prepareClient(USER_NOPASSWORD_USERNAME, "bad"); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -745,20 +745,20 @@ public void test141GetUserAdministratorByNopasswordBadPassword() { TestUtil.displayThen(TEST_NAME); assertStatus(response, 403); assertNoEmptyResponse(response); - + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(1); getDummyAuditService().assertFailedLogin(SchemaConstants.CHANNEL_REST_URI); } - + @Test public void test200searchAllUsers() { final String TEST_NAME = "test200searchAllUsers"; displayTestTitle(this, TEST_NAME); - + WebClient client = prepareClient(); client.path("/users/search"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -766,15 +766,15 @@ public void test200searchAllUsers() { TestUtil.displayThen(TEST_NAME); displayResponse(response); - + assertStatus(response, 200); - + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } - + @Test public void test401AddUserTemplateOverwrite() throws Exception { @@ -784,7 +784,7 @@ public void test401AddUserTemplateOverwrite() throws Exception { WebClient client = prepareClient(); client.path("/objectTemplates"); client.query("options", "overwrite"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -796,18 +796,18 @@ public void test401AddUserTemplateOverwrite() throws Exception { assertEquals("Expected 201 but got " + response.getStatus(), 201, response.getStatus()); String location = response.getHeaderString("Location"); String expected = ENDPOINT_ADDRESS + "/objectTemplates/" + USER_TEMPLATE_OID; - assertEquals("Unexpected location, expected: " + expected + " but was " + location, + assertEquals("Unexpected location, expected: " + expected + " but was " + location, expected, location); - + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(4); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); getDummyAuditService().assertHasDelta(1, ChangeType.ADD, ObjectTemplateType.class); } - - + + @Test public void test501generateValue() throws Exception { final String TEST_NAME = "test501generateValue"; @@ -815,7 +815,7 @@ public void test501generateValue() throws Exception { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/generate"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -823,17 +823,17 @@ public void test501generateValue() throws Exception { TestUtil.displayThen(TEST_NAME); displayResponse(response); - + traceResponse(response); assertEquals("Expected 200 but got " + response.getStatus(), 200, response.getStatus()); - + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } - + @Test public void test502generateValueBadPath() throws Exception { final String TEST_NAME = "test502generateValueBadPath"; @@ -841,7 +841,7 @@ public void test502generateValueBadPath() throws Exception { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/generate"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -851,13 +851,13 @@ public void test502generateValueBadPath() throws Exception { displayResponse(response); assertEquals("Expected 400 but got " + response.getStatus(), 400, response.getStatus()); - + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } - + @Test public void test503generateValueExecute() throws Exception { final String TEST_NAME = "test503generateValueExecute"; @@ -865,7 +865,7 @@ public void test503generateValueExecute() throws Exception { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/generate"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -874,18 +874,18 @@ public void test503generateValueExecute() throws Exception { TestUtil.displayThen(TEST_NAME); displayResponse(response); traceResponse(response); - + assertEquals("Expected 200 but got " + response.getStatus(), 200, response.getStatus()); - + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(4); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); getDummyAuditService().assertHasDelta(1, ChangeType.MODIFY, UserType.class); - + //UserType user = loadObject(UserType.class, USER_DARTHADDER_OID); //TODO assert changed items } - + @Test public void test504checkGeneratedValue() throws Exception { final String TEST_NAME = "test503generateValueExecute"; @@ -893,7 +893,7 @@ public void test504checkGeneratedValue() throws Exception { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID ); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -903,12 +903,12 @@ public void test504checkGeneratedValue() throws Exception { displayResponse(response); assertEquals("Expected 200 but got " + response.getStatus(), 200, response.getStatus()); - + UserType user = response.readEntity(UserType.class); assertNotNull("EmployeeNumber must not be null", user.getEmployeeNumber()); } - - + + @Test public void test505generatePasswordExecute() throws Exception { final String TEST_NAME = "test505generatePasswordExecute"; @@ -916,7 +916,7 @@ public void test505generatePasswordExecute() throws Exception { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/generate"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -926,17 +926,17 @@ public void test505generatePasswordExecute() throws Exception { displayResponse(response); assertEquals("Expected 200 but got " + response.getStatus(), 200, response.getStatus()); - - + + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(4); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); getDummyAuditService().assertHasDelta(1, ChangeType.MODIFY, UserType.class); - + //UserType user = loadObject(UserType.class, USER_DARTHADDER_OID); //TODO assert changed items } - + @Test public void test506generateHonorificPrefixNameExecute() throws Exception { final String TEST_NAME = "test506generateHonorificPrefixNameExecute"; @@ -944,7 +944,7 @@ public void test506generateHonorificPrefixNameExecute() throws Exception { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/generate"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -952,19 +952,19 @@ public void test506generateHonorificPrefixNameExecute() throws Exception { TestUtil.displayThen(TEST_NAME); displayResponse(response); - traceResponse(response); - + traceResponse(response); + assertEquals("Expected 200 but got " + response.getStatus(), 200, response.getStatus()); - + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(4); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); getDummyAuditService().assertHasDelta(1, ChangeType.MODIFY, UserType.class); - + //UserType user = loadObject(UserType.class, USER_DARTHADDER_OID); //TODO assert changed items } - + private OperationResult traceResponse(Response response){ if (response.getStatus() != 200 && response.getStatus() != 201 && response.getStatus() != 204) { OperationResultType result = response.readEntity(OperationResultType.class); @@ -973,10 +973,10 @@ private OperationResult traceResponse(Response response){ LOGGER.info(opResult.debugDump()); return opResult; } - + return null; } - + @Test public void test510validateValueExplicit() throws Exception { final String TEST_NAME = "test510validateValueExplicit"; @@ -984,7 +984,7 @@ public void test510validateValueExplicit() throws Exception { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/validate"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -994,14 +994,14 @@ public void test510validateValueExplicit() throws Exception { displayResponse(response); assertEquals("Expected 200 but got " + response.getStatus(), 200, response.getStatus()); - + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); - - + + } - + @Test public void test511validateValueExplicitConflict() throws Exception { final String TEST_NAME = "test511validateValueExplicitConflict"; @@ -1009,7 +1009,7 @@ public void test511validateValueExplicitConflict() throws Exception { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/validate"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -1018,17 +1018,17 @@ public void test511validateValueExplicitConflict() throws Exception { TestUtil.displayThen(TEST_NAME); displayResponse(response); traceResponse(response); - + assertEquals("Expected 409 but got " + response.getStatus(), 409, response.getStatus()); - - + + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); - - + + } - + @Test public void test512validateValueImplicitSingle() throws Exception { final String TEST_NAME = "test512validateValueImplicitSingle"; @@ -1036,7 +1036,7 @@ public void test512validateValueImplicitSingle() throws Exception { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/validate"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -1044,17 +1044,17 @@ public void test512validateValueImplicitSingle() throws Exception { TestUtil.displayThen(TEST_NAME); displayResponse(response); - + assertEquals("Expected 200 but got " + response.getStatus(), 200, response.getStatus()); - - + + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); - - + + } - + @Test public void test513validateValueImplicitMulti() throws Exception { final String TEST_NAME = "test513validateValueImplicitMulti"; @@ -1062,7 +1062,7 @@ public void test513validateValueImplicitMulti() throws Exception { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/validate"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -1073,13 +1073,13 @@ public void test513validateValueImplicitMulti() throws Exception { traceResponse(response); assertEquals("Expected 200 but got " + response.getStatus(), 200, response.getStatus()); - + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); - + } - + @Test public void test514validateValueImplicitMultiConflict() throws Exception { final String TEST_NAME = "test514validateValueImplicitMultiConflict"; @@ -1087,7 +1087,7 @@ public void test514validateValueImplicitMultiConflict() throws Exception { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/validate"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -1096,16 +1096,16 @@ public void test514validateValueImplicitMultiConflict() throws Exception { TestUtil.displayThen(TEST_NAME); displayResponse(response); traceResponse(response); - + assertEquals("Expected 409 but got " + response.getStatus(), 409, response.getStatus()); - + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); - - + + } - + @Test public void test515validateValueImplicitPassword() throws Exception { final String TEST_NAME = "test515validateValueImplicitPassword"; @@ -1113,7 +1113,7 @@ public void test515validateValueImplicitPassword() throws Exception { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/validate"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -1121,17 +1121,17 @@ public void test515validateValueImplicitPassword() throws Exception { TestUtil.displayThen(TEST_NAME); displayResponse(response); - - + + assertEquals("Expected 200 but got " + response.getStatus(), 200, response.getStatus()); - - + + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } - - + + @Test public void test600modifySecurityQuestionAnswer() throws Exception { final String TEST_NAME = "test600modifySecurityQuestionAnswer"; @@ -1139,7 +1139,7 @@ public void test600modifySecurityQuestionAnswer() throws Exception { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -1148,21 +1148,21 @@ public void test600modifySecurityQuestionAnswer() throws Exception { TestUtil.displayThen(TEST_NAME); displayResponse(response); traceResponse(response); - + assertEquals("Expected 204 but got " + response.getStatus(), 204, response.getStatus()); - - + + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(4); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); getDummyAuditService().assertHasDelta(1, ChangeType.MODIFY, UserType.class); - + TestUtil.displayWhen(TEST_NAME); response = client.get(); - + TestUtil.displayThen(TEST_NAME); displayResponse(response); - + assertEquals("Expected 200 but got " + response.getStatus(), 200, response.getStatus()); UserType userDarthadder = response.readEntity(UserType.class); CredentialsType credentials = userDarthadder.getCredentials(); @@ -1171,15 +1171,15 @@ public void test600modifySecurityQuestionAnswer() throws Exception { assertNotNull("No security questions defined for user. Something is wrong.", securityQuestions); List secQuestionAnswers = securityQuestions.getQuestionAnswer(); assertEquals("Expected just one question-answer couple, but found " + secQuestionAnswers.size(), 1, secQuestionAnswers.size()); - + SecurityQuestionAnswerType secQuestionAnswer = secQuestionAnswers.iterator().next(); String decrypted = getPrismContext().getDefaultProtector().decryptString(secQuestionAnswer.getQuestionAnswer()); assertEquals("Unexpected answer " + decrypted + ". Expected 'newAnswer'." , "newAnswer", decrypted); - - + + } - - + + @Test public void test601modifyPasswordForceChange() throws Exception { final String TEST_NAME = "test601modifyPasswordForceChange"; @@ -1187,7 +1187,7 @@ public void test601modifyPasswordForceChange() throws Exception { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); @@ -1196,21 +1196,21 @@ public void test601modifyPasswordForceChange() throws Exception { TestUtil.displayThen(TEST_NAME); displayResponse(response); traceResponse(response); - + assertEquals("Expected 204 but got " + response.getStatus(), 204, response.getStatus()); - - + + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(4); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); getDummyAuditService().assertHasDelta(1, ChangeType.MODIFY, UserType.class); - + TestUtil.displayWhen(TEST_NAME); response = client.get(); - + TestUtil.displayThen(TEST_NAME); displayResponse(response); - + assertEquals("Expected 200 but got " + response.getStatus(), 200, response.getStatus()); UserType userDarthadder = response.readEntity(UserType.class); CredentialsType credentials = userDarthadder.getCredentials(); @@ -1219,24 +1219,24 @@ public void test601modifyPasswordForceChange() throws Exception { assertNotNull("No password defined for user. Something is wrong.", passwordType); assertNotNull("No value for password defined for user. Something is wrong.", passwordType.getValue()); assertTrue(BooleanUtils.isTrue(passwordType.isForceChange())); - + } - + 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/TestJsonProvider.java b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestJsonProvider.java index f4fad3d0756..3c4b3a33ef8 100644 --- a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestJsonProvider.java +++ b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestJsonProvider.java @@ -36,23 +36,23 @@ import com.evolveum.midpoint.prism.PrismObject; public class TestJsonProvider extends MidpointJsonProvider { - - + + @Override public T readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { - + if (String.class.isAssignableFrom(type.getClass())) { return (T) IOUtils.toString(entityStream); } - + T result = super.readFrom(type, genericType, annotations, mediaType, httpHeaders, entityStream); if (result instanceof PrismObject) { return (T) ((PrismObject) result).asObjectable(); } - + return result; } - + } \ No newline at end of file diff --git a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceJson.java b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceJson.java index 19ad19bebf8..9ef7dfb8347 100644 --- a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceJson.java +++ b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceJson.java @@ -38,12 +38,12 @@ protected String getContentType() { return MediaType.APPLICATION_JSON; } - + @Override protected File getRepoFile(String fileBaseName) { return new File(BASE_REPO_DIR + "/json", fileBaseName + ".json"); } - + @Override protected File getRequestFile(String fileBaseName) { return new File(BASE_REQ_DIR + "/json", fileBaseName + ".json"); @@ -53,5 +53,5 @@ protected File getRequestFile(String fileBaseName) { protected MidpointAbstractProvider getProvider() { return jsonProvider; } - + } diff --git a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceJsonSecQ.java b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceJsonSecQ.java index cbe84d1e336..e0d50471004 100644 --- a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceJsonSecQ.java +++ b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceJsonSecQ.java @@ -20,27 +20,27 @@ public class TestRestServiceJsonSecQ extends TestRestServiceJson{ - + @Override protected void createAuthorizationHeader(WebClient client, String username, String password) { - + if (username == null) { return; } - + String authzHeader = "{" + "\"user\" : \""+ username +"\"," + "\"answer\" : [" + "{ " - + "\"qid\" : \"http://midpoint.evolveum.com/xml/ns/public/security/question-2#q001\"," + + "\"qid\" : \"http://midpoint.evolveum.com/xml/ns/public/security/question-2#q001\"," + "\"qans\" : \"" + (password == null ? "" : password) + "\"" + "}" + "]" + "}"; - + String authorizationHeader = "SecQ " + org.apache.cxf.common.util.Base64Utility.encode((authzHeader).getBytes()); client.header("Authorization", authorizationHeader); - + } } 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 13506fb22ef..59d994772cc 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 @@ -40,7 +40,7 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; public class TestRestServiceProxyAuthentication extends RestServiceInitializer { - + private static final Trace LOGGER = TraceManager.getTrace(TestRestServiceProxyAuthentication.class); // REST and end user authorization @@ -56,27 +56,27 @@ public class TestRestServiceProxyAuthentication extends RestServiceInitializer { public static final String USER_HEAD_PASSWORD = "headPassw0rd"; public static final File ROLE_PROXY_FILE = new File(BASE_REPO_DIR, "role-proxy.xml"); - + // REST and end user authorization public static final File USER_PROXY_FILE = new File(BASE_REPO_DIR, "user-proxy.xml"); public static final String USER_PROXY_OID = "d8f3e3c8-d48b-11e4-8d88-001e8c717e5b"; public static final String USER_PROXY_USERNAME = "proxy"; public static final String USER_PROXY_PASSWORD = "proxyPassword"; - + @Override public void startServer() throws Exception { // TODO Auto-generated method stub super.startServer(); - + OperationResult result = new OperationResult("Init config"); addObject(ROLE_PROXY_FILE, result); addObject(USER_EGOIST_FILE, result); addObject(USER_HEAD_FILE, result); addObject(USER_PROXY_FILE, result); - + InternalMonitor.reset(); } - + @Test public void test001getUserSelfBySomebody() { final String TEST_NAME = "test001getUserSelfBySomebody"; @@ -84,23 +84,23 @@ public void test001getUserSelfBySomebody() { WebClient client = prepareClient(USER_SOMEBODY_OID); client.path("/self/"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); Response response = client.get(); - + TestUtil.displayThen(TEST_NAME); assertStatus(response, 200); UserType userType = response.readEntity(UserType.class); assertNotNull("Returned entity in body must not be null.", userType); LOGGER.info("Returned entity: {}", userType.asPrismObject().debugDump()); - + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } - + @Test public void test002getUserSelfByEgoist() { final String TEST_NAME = "test002getUserSelfByEgoist"; @@ -108,25 +108,25 @@ public void test002getUserSelfByEgoist() { WebClient client = prepareClient(USER_EGOIST_OID); client.path("/self/"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); Response response = client.get(); - + TestUtil.displayThen(TEST_NAME); assertStatus(response, 200); UserType userType = response.readEntity(UserType.class); assertNotNull("Returned entity in body must not be null.", userType); LOGGER.info("Returned entity: {}", userType.asPrismObject().debugDump()); - + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } - + /** - * egoist doesn't have authorization to read other object. ot has only end user role, + * egoist doesn't have authorization to read other object. ot has only end user role, * so he is allowed to performed defined actions on his own. */ @Test @@ -136,20 +136,20 @@ public void test003getUserAdministratorByEgoist() { WebClient client = prepareClient(USER_EGOIST_OID); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); Response response = client.get(); - + TestUtil.displayThen(TEST_NAME); assertStatus(response, 403); - + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } - + /** * user head is a super user and has also rest authorization so he can perform any action */ @@ -160,23 +160,23 @@ public void test004getUserSelfByHead() { WebClient client = prepareClient(null); client.path("/self"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); Response response = client.get(); - + TestUtil.displayThen(TEST_NAME); assertStatus(response, 200); UserType userType = response.readEntity(UserType.class); assertNotNull("Returned entity in body must not be null.", userType); LOGGER.info("Returned entity: {}", userType.asPrismObject().debugDump()); - + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } - + /** * even though head is a superuser, it is not allowed for service application to switch to this user, * therefore head is not allowed to read user administrator using inpersonation @@ -188,15 +188,15 @@ public void test005getUserSelfByProxyHead() { WebClient client = prepareClient(USER_HEAD_OID); client.path("/self"); - + getDummyAuditService().clear(); TestUtil.displayWhen(TEST_NAME); Response response = client.get(); - + TestUtil.displayThen(TEST_NAME); assertStatus(response, 403); - + IntegrationTestTools.display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertFailedProxyLogin(SchemaConstants.CHANNEL_REST_URI); @@ -216,7 +216,7 @@ protected String getContentType() { protected MidpointAbstractProvider getProvider() { return xmlProvider; } - + private WebClient prepareClient(String proxyUserOid) { WebClient client = prepareClient("proxy", "proxyPassword"); if (StringUtils.isNotBlank(proxyUserOid)){ @@ -224,6 +224,6 @@ private WebClient prepareClient(String proxyUserOid) { } return client; } - - + + } diff --git a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceXml.java b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceXml.java index 6e5cc286399..2f5da80c937 100644 --- a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceXml.java +++ b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceXml.java @@ -36,12 +36,12 @@ protected String getContentType() { return MediaType.APPLICATION_XML; } - + @Override protected File getRepoFile(String fileBaseName) { return new File(BASE_REPO_DIR + "/xml", fileBaseName + ".xml"); } - + @Override protected File getRequestFile(String fileBaseName) { return new File(BASE_REQ_DIR + "/xml", fileBaseName + ".xml"); diff --git a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceYaml.java b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceYaml.java index bf95afb025f..06ceedbcad3 100644 --- a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceYaml.java +++ b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceYaml.java @@ -43,13 +43,13 @@ protected String getAcceptHeader() { protected String getContentType() { return "application/yaml"; } - - + + @Override protected File getRepoFile(String fileBaseName) { return new File(BASE_REPO_DIR + "/yaml", fileBaseName + ".yml"); } - + @Override protected File getRequestFile(String fileBaseName) { return new File(BASE_REQ_DIR + "/yaml", fileBaseName + ".yml"); @@ -59,5 +59,5 @@ protected File getRequestFile(String fileBaseName) { protected MidpointAbstractProvider getProvider() { return yamlProvider; } - + } diff --git a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestSecurityQuestionChallengeResponse.java b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestSecurityQuestionChallengeResponse.java index 548bfd3ecb5..0fb11dc4c88 100644 --- a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestSecurityQuestionChallengeResponse.java +++ b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestSecurityQuestionChallengeResponse.java @@ -37,13 +37,13 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; public class TestSecurityQuestionChallengeResponse extends RestServiceInitializer{ - + private static final Trace LOGGER = TraceManager.getTrace(TestSecurityQuestionChallengeResponse.class); - + @Test public void testChallengeResponse(){ - Response response = getUserAdministrator("SecQ"); - + Response response = getUserAdministrator("SecQ"); + String challengeBase64 = assertAndGetChallenge(response); String usernameChallenge = null; try { @@ -52,10 +52,10 @@ public void testChallengeResponse(){ } catch (Base64Exception e) { fail("Failed to decode base64 username challenge"); } - + String secQusernameChallenge = usernameChallenge.replace("username", "administrator"); LOGGER.info("Username response: " +secQusernameChallenge); - + response = getUserAdministrator("SecQ " + Base64Utility.encode(secQusernameChallenge.getBytes())); challengeBase64 = assertAndGetChallenge(response); String answerChallenge = null; @@ -69,49 +69,49 @@ public void testChallengeResponse(){ + "\"user\" : \"administrator\"," + "\"answer\" : [" + "{ " - + "\"qid\" : \"http://midpoint.evolveum.com/xml/ns/public/security/question-2#q001\"," + + "\"qid\" : \"http://midpoint.evolveum.com/xml/ns/public/security/question-2#q001\"," + "\"qans\" : \"5ecr3t\"" + "}," + "{ " - + "\"qid\" : \"http://midpoint.evolveum.com/xml/ns/public/security/question-2#q002\"," + + "\"qid\" : \"http://midpoint.evolveum.com/xml/ns/public/security/question-2#q002\"," + "\"qans\" : \"black\"" + "}" + "]" + "}"; - + LOGGER.info("Answer response: " +secQAnswerChallenge); - + response = getUserAdministrator("SecQ " + Base64Utility.encode(secQAnswerChallenge.getBytes())); - + assertEquals("Unexpected status code. Expected 200 but got " + response.getStatus(), 200, response.getStatus()); UserType user = response.readEntity(UserType.class); assertNotNull("Returned entity in body must not be null.", user); LOGGER.info("Returned entity: {}", user.asPrismObject().debugDump()); - - + + } - + private String assertAndGetChallenge(Response response){ assertEquals("Unexpected status code. Expected 401 but was "+ response.getStatus(), 401, response.getStatus()); assertNotNull("Headers null. Somthing very strange happened", response.getHeaders()); - + List wwwAuthenticateHeaders = response.getHeaders().get("WWW-Authenticate"); assertNotNull("WWW-Authenticate headers null. Somthing very strange happened", wwwAuthenticateHeaders); LOGGER.info("WWW-Atuhenticate header: " + wwwAuthenticateHeaders); assertEquals("Expected WWW-Authenticate header, but the actual size is " + wwwAuthenticateHeaders.size(), 1, wwwAuthenticateHeaders.size()); String secQHeader = (String) wwwAuthenticateHeaders.iterator().next(); - + String[] headerSplitted = secQHeader.split(" "); assertEquals("Expected the challenge in the SecQ but haven't got one.", 2, headerSplitted.length); String challengeBase64 = headerSplitted[1]; assertNotNull("Unexpected null challenge in the SecQ header", challengeBase64); return challengeBase64; } - + private Response getUserAdministrator(String authorizationHeader){ WebClient client = WebClient.create(ENDPOINT_ADDRESS); client.authorization(authorizationHeader); - + client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); Response response = client.get(); return response; diff --git a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestXmlProvider.java b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestXmlProvider.java index 367d43081f3..cf58f5aef64 100644 --- a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestXmlProvider.java +++ b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestXmlProvider.java @@ -35,23 +35,23 @@ import com.evolveum.midpoint.prism.PrismObject; public class TestXmlProvider extends MidpointXmlProvider { - - + + @Override public T readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { - + if (String.class.isAssignableFrom(type.getClass())) { return (T) IOUtils.toString(entityStream); } - + T result = super.readFrom(type, genericType, annotations, mediaType, httpHeaders, entityStream); if (result instanceof PrismObject) { return (T) ((PrismObject) result).asObjectable(); } - + return result; } - + } \ No newline at end of file diff --git a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestYamlProvider.java b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestYamlProvider.java index 354acdbb07a..faa6bb754d0 100644 --- a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestYamlProvider.java +++ b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestYamlProvider.java @@ -39,9 +39,9 @@ public class TestYamlProvider extends MidpointYamlProvider { - + private static final Trace LOGGER = TraceManager.getTrace(TestYamlProvider.class); - + @Override public void writeTo(T object, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) @@ -50,22 +50,22 @@ public void writeTo(T object, Class type, Type genericType, Annotation[] anno LOGGER.trace("Object to write: {},\ntype: {},\ngenericType: {},\nhttpHeaders: {}", new Object[]{object, type, genericType, httpHeaders}); super.writeTo(object, type, genericType, annotations, mediaType, httpHeaders, entityStream); } - + @Override public T readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { - + if (String.class.isAssignableFrom(type.getClass())) { return (T) IOUtils.toString(entityStream); } - + T result = super.readFrom(type, genericType, annotations, mediaType, httpHeaders, entityStream); if (result instanceof PrismObject) { return (T) ((PrismObject) result).asObjectable(); } - + return result; } - + } \ No newline at end of file diff --git a/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/ModelClientUtil.java b/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/ModelClientUtil.java index 4358515a2e0..edc993c736e 100644 --- a/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/ModelClientUtil.java +++ b/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/ModelClientUtil.java @@ -47,20 +47,20 @@ * */ public class ModelClientUtil { - + // XML constants public static final String NS_COMMON = "http://midpoint.evolveum.com/xml/ns/public/common/common-3"; public static final QName COMMON_PATH = new QName(NS_COMMON, "path"); public static final QName COMMON_VALUE = new QName(NS_COMMON, "value"); public static final QName COMMON_GIVEN_NAME = new QName(NS_COMMON, "givenName"); public static final QName COMMON_ASSIGNMENT = new QName(NS_COMMON, "assignment"); - + public static final String NS_TYPES = "http://prism.evolveum.com/xml/ns/public/types-3"; private static final QName TYPES_POLYSTRING_ORIG = new QName(NS_TYPES, "orig"); public static final QName TYPES_CLEAR_VALUE = new QName(NS_TYPES, "clearValue"); private static final DocumentBuilder domDocumentBuilder; - + public static JAXBContext instantiateJaxbContext() throws JAXBException { return JAXBContext.newInstance("com.evolveum.midpoint.xml.ns._public.common.api_types_3:" + "com.evolveum.midpoint.xml.ns._public.common.common_3:" + @@ -74,7 +74,7 @@ public static JAXBContext instantiateJaxbContext() throws JAXBException { "org.w3._2000._09.xmldsig:" + "org.w3._2001._04.xmlenc"); } - + public static Element createPathElement(String stringPath, Document doc) { String pathDeclaration = "declare default namespace '" + NS_COMMON + "'; " + stringPath; return createTextElement(COMMON_PATH, pathDeclaration, doc); @@ -98,19 +98,19 @@ public static PolyStringType createPolyStringType(String string, Document doc) { polyStringType.setOrig(string); return polyStringType; } - + public static Element createTextElement(QName qname, String value, Document doc) { Element element = doc.createElementNS(qname.getNamespaceURI(), qname.getLocalPart()); element.setTextContent(value); return element; } - + public static CredentialsType createPasswordCredentials(String password) { CredentialsType credentialsType = new CredentialsType(); credentialsType.setPassword(createPasswordType(password)); return credentialsType; } - + public static PasswordType createPasswordType(String password) { PasswordType passwordType = new PasswordType(); passwordType.setValue(createProtectedString(password)); @@ -136,18 +136,18 @@ public static String getTypeUri(Class type) { String typeUri = NS_COMMON + "#" + type.getSimpleName(); return typeUri; } - + public static QName getTypeQName(Class type) { // QName typeQName = JAXBUtil.getTypeQName(type); QName typeQName = new QName(NS_COMMON, type.getSimpleName()); return typeQName; } - + public static Element parseElement(String stringXml) throws SAXException, IOException { Document document = domDocumentBuilder.parse(IOUtils.toInputStream(stringXml, "utf-8")); return getFirstChildElement(document); } - + public static Element getFirstChildElement(Node parent) { if (parent == null || parent.getChildNodes() == null) { return null; @@ -194,7 +194,7 @@ public static String getOidFromDeltaOperationList(ObjectDeltaOperationListType o } return null; } - + static { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 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 b2c7289e4b8..a6a62f7c8d0 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 @@ -192,7 +192,7 @@ public class TestSanity extends AbstractModelIntegrationTest { private static final String SYSTEM_CONFIGURATION_FILENAME = REPO_DIR_NAME + "system-configuration.xml"; private static final String SYSTEM_CONFIGURATION_OID = "00000000-0000-0000-0000-000000000001"; - + private static final String ROLE_SUPERUSER_FILENAME = REPO_DIR_NAME + "role-superuser.xml"; private static final String ROLE_SUPERUSER_OID = "00000000-0000-0000-0000-000000000004"; @@ -209,13 +209,13 @@ public class TestSanity extends AbstractModelIntegrationTest { private static final String RESOURCE_BROKEN_FILENAME = REPO_DIR_NAME + "resource-broken.xml"; private static final String RESOURCE_BROKEN_OID = "ef2bc95b-76e0-59e2-ffff-ffffffffffff"; - + private static final String RESOURCE_DUMMY_FILENAME = REPO_DIR_NAME + "resource-dummy.xml"; private static final String RESOURCE_DUMMY_OID = "10000000-0000-0000-0000-000000000004"; private 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"; private static final String CONNECTOR_DBTABLE_NAMESPACE = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.polygon.connector-databasetable/org.identityconnectors.databasetable.DatabaseTableConnector"; - + private static final String CONNECTOR_BROKEN_FILENAME = REPO_DIR_NAME + "connector-broken.xml"; private static final String CONNECTOR_BROKEN_OID = "cccccccc-76e0-59e2-ffff-ffffffffffff"; @@ -268,7 +268,7 @@ public class TestSanity extends AbstractModelIntegrationTest { private static final String ROLE_JUDGE_FILENAME = REPO_DIR_NAME + "role-judge.xml"; private static final String ROLE_JUDGE_OID = "12345111-1111-2222-1111-121212111111"; - + private static final String REQUEST_USER_MODIFY_ADD_ACCOUNT_OPENDJ_FILENAME = REQUEST_DIR_NAME + "user-modify-add-account.xml"; private static final String REQUEST_USER_MODIFY_ADD_ACCOUNT_DERBY_FILENAME = REQUEST_DIR_NAME + "user-modify-add-account-derby.xml"; @@ -298,20 +298,20 @@ public class TestSanity extends AbstractModelIntegrationTest { private static final File LDIF_WILL_MODIFY_FILE = new File (REQUEST_DIR_NAME, "will-modify.ldif"); private static final String LDIF_WILL_WITHOUT_LOCATION_FILENAME = REQUEST_DIR_NAME + "will-without-location.ldif"; private static final String WILL_NAME = "wturner"; - + private static final String LDIF_ANGELIKA_FILENAME = REQUEST_DIR_NAME + "angelika.ldif"; private static final String ANGELIKA_NAME = "angelika"; - + private static final String ACCOUNT_ANGELIKA_FILENAME = REQUEST_DIR_NAME + "account-angelika.xml"; - + private static final String LDIF_ELAINE_FILENAME = REQUEST_DIR_NAME + "elaine.ldif"; private static final String ELAINE_NAME = "elaine"; - + private static final File LDIF_GIBBS_MODIFY_FILE = new File (REQUEST_DIR_NAME, "gibbs-modify.ldif"); - + private static final String LDIF_HERMAN_FILENAME = REQUEST_DIR_NAME + "herman.ldif"; - + private static final Trace LOGGER = TraceManager.getTrace(TestSanity.class); private static final String NS_MY = "http://whatever.com/my"; @@ -319,7 +319,7 @@ public class TestSanity extends AbstractModelIntegrationTest { private static final QName MY_DEAD = new QName(NS_MY, "dead"); private static final long WAIT_FOR_LOOP_SLEEP_MILIS = 1000; - + /** * Unmarshalled resource definition to reach the embedded OpenDJ instance. * Used for convenience - the tests method may find it handy. @@ -334,17 +334,17 @@ public class TestSanity extends AbstractModelIntegrationTest { private static String lastJacksLdapPassword = null; private int lastSyncToken; - + @Autowired(required = true) private MatchingRuleRegistry matchingRuleRegistry; - + // This will get called from the superclass to init the repository // It will be called only once public void initSystem(Task initTask, OperationResult initResult) throws Exception { LOGGER.trace("initSystem"); try{ super.initSystem(initTask, initResult); - + repoAddObjectFromFile(ROLE_SUPERUSER_FILENAME, initResult); repoAddObjectFromFile(USER_ADMINISTRATOR_FILENAME, initResult); @@ -352,7 +352,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti LOGGER.trace("initSystem: trying modelService.postInit()"); modelService.postInit(initResult); LOGGER.trace("initSystem: modelService.postInit() done"); - + login(USER_ADMINISTRATOR_NAME); // We need to add config after calling postInit() so it will not be applied. @@ -417,7 +417,7 @@ public void test000Integrity() throws Exception { assertNotNull(repositoryService); assertTrue(isSystemInitialized()); assertNotNull(taskManager); - + assertNotNull(prismContext); SchemaRegistry schemaRegistry = prismContext.getSchemaRegistry(); assertNotNull(schemaRegistry); @@ -425,7 +425,7 @@ public void test000Integrity() throws Exception { PrismPropertyDefinition shipStateDefinition = schemaRegistry.findPropertyDefinitionByElementName(MY_SHIP_STATE); assertNotNull("No my:shipState definition", shipStateDefinition); assertEquals("Wrong maxOccurs in my:shipState definition", 1, shipStateDefinition.getMaxOccurs()); - + assertNoRepoCache(); Task task = taskManager.createTaskInstance(TestSanity.class.getName() + ".test000Integrity"); @@ -444,7 +444,7 @@ public void test000Integrity() throws Exception { display("LDAP Connector: ", ldapConnector); // TODO: test if OpenDJ and Derby are running - + repositoryService.getObject(GenericObjectType.class, SAMPLE_CONFIGURATION_OBJECT_OID, null, result); } @@ -477,7 +477,7 @@ public void test001SelfTests() throws Exception { } } - + /** * Test the testResource method. Expect a complete success for now. */ @@ -513,7 +513,7 @@ public void test001TestConnectionOpenDJ() throws Exception { Element resourceOpenDjXsdSchemaElement = ResourceTypeUtil.getResourceXsdSchema(resourceTypeOpenDjrepo); assertNotNull("Resource schema was not generated", resourceOpenDjXsdSchemaElement); - PrismObject openDjResourceProvisioninig = provisioningService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, + PrismObject openDjResourceProvisioninig = provisioningService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, null, opResult); display("Initialized OpenDJ resource resource (provisioning)", openDjResourceProvisioninig); @@ -521,11 +521,11 @@ public void test001TestConnectionOpenDJ() throws Exception { display("Initialized OpenDJ resource OpenDJ resource (model)", openDjResourceModel); checkOpenDjResource(resourceTypeOpenDjrepo, "repository"); - + System.out.println("------------------------------------------------------------------"); display("OpenDJ resource schema (repo XML)", DOMUtil.serializeDOMToString(ResourceTypeUtil.getResourceXsdSchema(resourceOpenDjRepo))); System.out.println("------------------------------------------------------------------"); - + checkOpenDjResource(openDjResourceProvisioninig.asObjectable(), "provisioning"); checkOpenDjResource(openDjResourceModel.asObjectable(), "model"); // TODO: model web @@ -535,7 +535,7 @@ public void test001TestConnectionOpenDJ() throws Exception { } } - + private void checkRepoOpenDjResource() throws ObjectNotFoundException, SchemaException { OperationResult result = new OperationResult(TestSanity.class.getName()+".checkRepoOpenDjResource"); PrismObject resource = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, result); @@ -563,7 +563,7 @@ private void checkOpenDjResource(ResourceType resource, String source) throws Sc if (!source.equals("repository")) { // This is generated on the fly in provisioning assertNotNull("Resource from " + source + " has null nativeCapabilities", resource.getCapabilities().getNative()); - assertFalse("Resource from " + source + " has empty nativeCapabilities", + assertFalse("Resource from " + source + " has empty nativeCapabilities", resource.getCapabilities().getNative().getAny().isEmpty()); } assertNotNull("Resource from " + source + " has null configured capabilities", resource.getCapabilities().getConfigured()); @@ -606,11 +606,11 @@ private void checkOpenDjSchemaHandling(ResourceType resource, String source) { } } } - + private void checkOpenDjConfiguration(PrismObject resource, String source) { checkOpenResourceConfiguration(resource, CONNECTOR_LDAP_NAMESPACE, "bindPassword", 8, source); } - + private void checkOpenResourceConfiguration(PrismObject resource, String connectorNamespace, String credentialsPropertyName, int numConfigProps, String source) { PrismContainer configurationContainer = resource.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); @@ -647,7 +647,7 @@ private void checkOpenResourceConfiguration(PrismObject resource, } // assertEquals("Wrong EncryptedData element namespace in "+resource+" from "+source, DOMUtil.NS_XML_ENC, encryptedDataType.getNamespaceURI()); // assertEquals("Wrong EncryptedData element local name in "+resource+" from "+source, "EncryptedData", encryptedDataType.getLocalName()); - } else { + } else { Object credentials = credentialsPropertyValue.getValue(); assertTrue("Wrong type of credentials configuration property in "+resource+" from "+source+": "+credentials.getClass(), credentials instanceof ProtectedStringType); ProtectedStringType credentialsPs = (ProtectedStringType)credentials; @@ -656,15 +656,15 @@ private void checkOpenResourceConfiguration(PrismObject resource, } } - + @Test public void test002AddDerbyResource() throws Exception { final String TEST_NAME = "test002AddDerbyResource"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); - + checkRepoOpenDjResource(); assertNoRepoCache(); @@ -680,7 +680,7 @@ public void test002AddDerbyResource() throws Exception { // WHEN addObjectViaModelWS(resource.asObjectable(), null, oidHolder, resultHolder); - + // THEN // Check if Derby resource was imported correctly PrismObject derbyResource = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, result); @@ -753,16 +753,16 @@ private void checkRepoDerbyResource() throws ObjectNotFoundException, SchemaExce PrismObject resource = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, result); checkDerbyResource(resource, "repository"); } - + private void checkDerbyResource(PrismObject resource, String source) { checkDerbyConfiguration(resource, source); } - + private void checkDerbyConfiguration(PrismObject resource, String source) { checkOpenResourceConfiguration(resource, CONNECTOR_DBTABLE_NAMESPACE, "password", 10, source); } - - + + /** * Test the testResource method. Expect a complete success for now. */ @@ -813,14 +813,14 @@ public void test003TestConnectionDerby() throws Exception { // TODO: model web } - + @Test public void test004Capabilities() throws ObjectNotFoundException, CommunicationException, SchemaException, FaultMessage { TestUtil.displayTestTitle("test004Capabilities"); // GIVEN - + checkRepoOpenDjResource(); assertNoRepoCache(); @@ -828,7 +828,7 @@ public void test004Capabilities() throws ObjectNotFoundException, CommunicationE Holder resultHolder = new Holder(); Holder objectHolder = new Holder(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); - + // WHEN modelWeb.getObject(ObjectTypes.RESOURCE.getTypeQName(), RESOURCE_OPENDJ_OID, options , objectHolder, resultHolder); @@ -873,79 +873,79 @@ public void test004Capabilities() throws ObjectNotFoundException, CommunicationE assertNotNull("activation capability not found", capAct); } - + @Test public void test005resolveConnectorRef() throws Exception{ - + TestUtil.displayTestTitle("test005resolveConnectorRef"); - + PrismObject resource = PrismTestUtil.parseObject(new File(RESOURCE_DUMMY_FILENAME)); ModelExecuteOptionsType options = new ModelExecuteOptionsType(); options.setIsImport(Boolean.TRUE); addObjectViaModelWS(resource.asObjectable(), options, new Holder(), new Holder()); - + OperationResult repoResult = new OperationResult("getObject"); PrismObject uObject = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, repoResult); assertNotNull(uObject); - + ResourceType resourceType = uObject.asObjectable(); assertNotNull("Reference on the connector must not be null in resource.",resourceType.getConnectorRef()); assertNotNull("Missing oid reference on the connector",resourceType.getConnectorRef().getOid()); - + } - + @Test public void test006reimportResourceDummy() throws Exception{ - + TestUtil.displayTestTitle("test006reimportResourceDummy"); - + //get object from repo (with version set and try to add it - it should be re-added, without error) OperationResult repoResult = new OperationResult("getObject"); PrismObject resource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, repoResult); assertNotNull(resource); - - + + ModelExecuteOptionsType options = new ModelExecuteOptionsType(); options.setOverwrite(Boolean.TRUE); options.setIsImport(Boolean.TRUE); addObjectViaModelWS(resource.asObjectable(), options, new Holder(), new Holder()); //TODO: add some asserts - - + + //parse object from file again and try to add it - this should fail, becasue the same object already exists) resource = PrismTestUtil.parseObject(new File(RESOURCE_DUMMY_FILENAME)); - + try { Holder resultHolder = new Holder(); options = new ModelExecuteOptionsType(); options.setIsImport(Boolean.TRUE); addObjectViaModelWS(resource.asObjectable(), options, new Holder(), resultHolder); - + OperationResultType result = resultHolder.value; TestUtil.assertFailure(result); - + fail("Expected object already exists exception, but haven't got one."); } catch (FaultMessage ex) { LOGGER.info("fault {}", ex.getFaultInfo()); LOGGER.info("fault {}", ex.getCause()); - if (ex.getFaultInfo() instanceof ObjectAlreadyExistsFaultType){ + if (ex.getFaultInfo() instanceof ObjectAlreadyExistsFaultType){ // this is OK, we expect this } else{ fail("Expected object already exists exception, but haven't got one."); } - - } - - + + } + + // ResourceType resourceType = uObject.asObjectable(); // assertNotNull("Reference on the connector must not be null in resource.",resourceType.getConnectorRef()); // assertNotNull("Missing oid reference on the connector",resourceType.getConnectorRef().getOid()); - + } /** @@ -964,7 +964,7 @@ public void test010AddUser() throws Exception { PrismObject user = PrismTestUtil.parseObject(USER_JACK_FILE); UserType userType = user.asObjectable(); assertParentConsistency(user); - + // Encrypt Jack's password protector.encrypt(userType.getCredentials().getPassword().getValue()); assertParentConsistency(user); @@ -1020,7 +1020,7 @@ public void test013AddOpenDjAccountToUser() throws Exception { ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ADD_ACCOUNT_OPENDJ_FILENAME, ObjectDeltaType.class); - + // WHEN TestUtil.displayWhen(TEST_NAME); OperationResultType result = modifyObjectViaModelWS(objectChange); @@ -1082,7 +1082,7 @@ public void test013AddOpenDjAccountToUser() throws Exception { // The "l" attribute is assigned indirectly through schemaHandling and // config object OpenDJController.assertAttribute(entry, "l", "Black Pearl"); - + assertTrue("LDAP account is not enabled", openDJController.isAccountEnabled(entry)); originalJacksLdapPassword = OpenDJController.getAttributeValue(entry, "userPassword"); @@ -1155,7 +1155,7 @@ public void test014AddDerbyAccountToUser() throws IOException, JAXBException, Fa ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ADD_ACCOUNT_DERBY_FILENAME, ObjectDeltaType.class); - // WHEN ObjectTypes.USER.getTypeQName(), + // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN @@ -1352,7 +1352,7 @@ public void test020ModifyUser() throws Exception { ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_FULLNAME_LOCALITY_FILENAME, ObjectDeltaType.class); - // WHEN ObjectTypes.USER.getTypeQName(), + // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN @@ -1364,7 +1364,7 @@ public void test020ModifyUser() throws Exception { OperationResult repoResult = new OperationResult("getObject"); PrismObject repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); - UserType repoUserType = repoUser.asObjectable(); + UserType repoUserType = repoUser.asObjectable(); display("repository user", repoUser); PrismAsserts.assertEqualsPolyString("wrong value for fullName", "Cpt. Jack Sparrow", repoUserType.getFullName()); @@ -1400,19 +1400,19 @@ public void test020ModifyUser() throws Exception { // Check if LDAP account was updated assertOpenDJAccountJack(uid, "jack"); } - + private Entry assertOpenDJAccountJack(String entryUuid, String uid) throws DirectoryException { Entry entry = openDJController.searchAndAssertByEntryUuid(entryUuid); return assertOpenDJAccountJack(entry, uid); } - + private Entry assertOpenDJAccountJack(Entry entry, String uid) throws DirectoryException { return assertOpenDJAccountJack(entry, uid, "Jack"); } - + private Entry assertOpenDJAccountJack(Entry entry, String uid, String givenName) throws DirectoryException { display(entry); - + OpenDJController.assertDn(entry, "uid="+uid+",ou=people,dc=example,dc=com"); OpenDJController.assertAttribute(entry, "uid", uid); if (givenName == null) { @@ -1431,7 +1431,7 @@ private Entry assertOpenDJAccountJack(Entry entry, String uid, String givenName) // evaluated from outbound expression OpenDJController.assertAttribute(entry, "l", "somewhere"); OpenDJController.assertAttribute(entry, "postalAddress", "Number 1"); - + return entry; } @@ -1451,13 +1451,13 @@ public void test022ChangeUserPassword() throws Exception { System.out.println("In modification: " + objectChange.getItemDelta().get(0).getValue().get(0)); assertNoRepoCache(); - // WHEN ObjectTypes.USER.getTypeQName(), + // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertUserPasswordChange("butUnd3dM4yT4lkAL0t", result); } - + /** * Similar to previous test just the request is constructed a bit differently. */ @@ -1465,16 +1465,16 @@ public void test022ChangeUserPassword() throws Exception { public void test023ChangeUserPasswordJAXB() throws Exception { final String TEST_NAME = "test023ChangeUserPasswordJAXB"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN final String NEW_PASSWORD = "abandonSHIP"; Document doc = ModelClientUtil.getDocumnent(); - + ObjectDeltaType userDelta = new ObjectDeltaType(); userDelta.setOid(USER_JACK_OID); userDelta.setChangeType(ChangeTypeType.MODIFY); userDelta.setObjectType(UserType.COMPLEX_TYPE); - + ItemDeltaType passwordDelta = new ItemDeltaType(); passwordDelta.setModificationType(ModificationTypeType.REPLACE); passwordDelta.setPath(ModelClientUtil.createItemPathType("credentials/password/value")); @@ -1485,14 +1485,14 @@ public void test023ChangeUserPasswordJAXB() throws Exception { RawType passwordValue = new RawType(passValue, prismContext); passwordDelta.getValue().add(passwordValue); userDelta.getItemDelta().add(passwordDelta); - - // WHEN ObjectTypes.USER.getTypeQName(), + + // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(userDelta); // THEN assertUserPasswordChange(NEW_PASSWORD, result); } - + private void assertUserPasswordChange(String expectedUserPassword, OperationResultType result) throws JAXBException, ObjectNotFoundException, SchemaException, DirectoryException, EncryptionException { assertNoRepoCache(); displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT); @@ -1513,7 +1513,7 @@ private void assertUserPasswordChange(String expectedUserPassword, OperationResu assertLinks(repoUser, 2); assertLinked(repoUser, accountShadowOidOpendj); assertLinked(repoUser, accountShadowOidDerby); - + assertPassword(repoUser, expectedUserPassword); // Check if shadow is still in the repo and that it is untouched @@ -1531,7 +1531,7 @@ private void assertUserPasswordChange(String expectedUserPassword, OperationResu // Check if LDAP account was updated Entry entry = assertOpenDJAccountJack(uid, "jack"); - + String ldapPasswordAfter = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull(ldapPasswordAfter); @@ -1543,7 +1543,7 @@ private void assertUserPasswordChange(String expectedUserPassword, OperationResu } lastJacksLdapPassword = ldapPasswordAfter; } - + @Test public void test027ModifyAccountDj() throws Exception { final String TEST_NAME = "test027ModifyAccountDj"; @@ -1571,7 +1571,7 @@ public void testModifyAccountDjRoomNumber(final String TEST_NAME, File reqFile, assertNoRepoCache(); displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); - + OperationResult repoResult = new OperationResult("getObject"); PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); repoResult.computeStatus(); @@ -1590,7 +1590,7 @@ public void testModifyAccountDjRoomNumber(final String TEST_NAME, File reqFile, OpenDJController.assertAttribute(jackLdapEntry, "roomNumber", expectedVal); } - + @Test public void test029ModifyAccountDjBadPath() throws Exception { final String TEST_NAME = "test029ModifyAccountDjBadPath"; @@ -1606,7 +1606,7 @@ public void test029ModifyAccountDjBadPath() throws Exception { try { // WHEN result = modifyObjectViaModelWS(objectChange); - + AssertJUnit.fail("Unexpected success"); } catch (FaultMessage f) { // this is expected @@ -1618,7 +1618,7 @@ public void test029ModifyAccountDjBadPath() throws Exception { assertNoRepoCache(); displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT); TestUtil.assertFailure(result); - + OperationResult repoResult = new OperationResult("getObject"); PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); repoResult.computeStatus(); @@ -1711,7 +1711,7 @@ public void test030DisableUser() throws Exception { pwpAccountDisabled = OpenDJController.getAttributeValue(entry, "ds-pwp-account-disabled"); display("ds-pwp-account-disabled after change", pwpAccountDisabled); assertFalse("LDAP account was not disabled", openDJController.isAccountEnabled(entry)); - + // Use getObject to test fetch of complete shadow Holder resultHolder = new Holder(); @@ -1763,7 +1763,7 @@ public void test031EnableUser() throws Exception { REQUEST_USER_MODIFY_ACTIVATION_ENABLE_FILENAME, ObjectDeltaType.class); assertNoRepoCache(); - // WHEN ObjectTypes.USER.getTypeQName(), + // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN @@ -1878,7 +1878,7 @@ public void test040UnlinkDerbyAccountFromUser() throws FileNotFoundException, JA displayJaxb("modifyObject input", objectChange, new QName(SchemaConstants.NS_C, "change")); assertNoRepoCache(); - // WHEN ObjectTypes.USER.getTypeQName(), + // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN @@ -1946,7 +1946,7 @@ public void test041DeleteDerbyAccount() throws FileNotFoundException, JAXBExcept } - private OperationResultType deleteObjectViaModelWS(QName typeQName, String oid) throws FaultMessage { + private OperationResultType deleteObjectViaModelWS(QName typeQName, String oid) throws FaultMessage { ObjectDeltaListType deltaList = new ObjectDeltaListType(); ObjectDeltaType objectDelta = new ObjectDeltaType(); objectDelta.setOid(oid); @@ -1968,7 +1968,7 @@ public void test047RenameUser() throws Exception { ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_NAME_FILENAME, ObjectDeltaType.class); - // WHEN ObjectTypes.USER.getTypeQName(), + // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN @@ -1980,7 +1980,7 @@ public void test047RenameUser() throws Exception { OperationResult repoResult = new OperationResult("getObject"); PrismObject repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); - UserType repoUserType = repoUser.asObjectable(); + UserType repoUserType = repoUser.asObjectable(); display("repository user", repoUser); PrismAsserts.assertEqualsPolyString("wrong value for User name", "jsparrow", repoUserType.getName()); @@ -2015,7 +2015,7 @@ public void test047RenameUser() throws Exception { assertOpenDJAccountJack(uid, "jsparrow"); } - + /** * 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). @@ -2026,14 +2026,14 @@ public void test047RenameUser() throws Exception { public void test048ModifyUserRemoveGivenName() throws Exception { final String TEST_NAME = "test048ModifyUserRemoveGivenName"; TestUtil.displayTestTitle(TEST_NAME); - + // GIVEN assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_GIVENNAME_FILENAME, ObjectDeltaType.class); displayJaxb("objectChange:", objectChange, SchemaConstants.T_OBJECT_DELTA); - // WHEN ObjectTypes.USER.getTypeQName(), + // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN @@ -2045,7 +2045,7 @@ public void test048ModifyUserRemoveGivenName() throws Exception { OperationResult repoResult = new OperationResult("getObject"); PrismObject repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); - UserType repoUserType = repoUser.asObjectable(); + UserType repoUserType = repoUser.asObjectable(); display("repository user", repoUser); PrismAsserts.assertEqualsPolyString("wrong value for fullName", "Cpt. Jack Sparrow", repoUserType.getFullName()); @@ -2159,7 +2159,7 @@ public void test100AssignRolePirate() throws Exception { ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ADD_ROLE_PIRATE_FILENAME, ObjectDeltaType.class); - // WHEN ObjectTypes.USER.getTypeQName(), + // WHEN ObjectTypes.USER.getTypeQName(), result = modifyObjectViaModelWS(objectChange); // THEN @@ -2261,7 +2261,7 @@ public void test102AssignRoleCaptain() throws Exception { ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_1_FILENAME, ObjectDeltaType.class); - // WHEN ObjectTypes.USER.getTypeQName(), + // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN @@ -2343,7 +2343,7 @@ public void test103AssignRoleCaptainAgain() throws Exception { ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_2_FILENAME, ObjectDeltaType.class); - // WHEN ObjectTypes.USER.getTypeQName(), + // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN @@ -2423,19 +2423,19 @@ public void test105ModifyAccount() throws Exception { REQUEST_ACCOUNT_MODIFY_ATTRS_FILE, ObjectDeltaType.class); objectChange.setOid(accountShadowOidGuybrushOpendj); - // WHEN ObjectTypes.SHADOW.getTypeQName(), + // WHEN ObjectTypes.SHADOW.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); - + Task task = taskManager.createTaskInstance(); OperationResult parentResult = new OperationResult(TEST_NAME + "-get after first modify"); PrismObject shadow= modelService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, task, parentResult); assertNotNull("shadow must not be null", shadow); - + ShadowType shadowType = shadow.asObjectable(); QName employeeTypeQName = new QName(resourceTypeOpenDjrepo.getNamespace(), "employeeType"); ItemPath employeeTypePath = new ItemPath(ShadowType.F_ATTRIBUTES, employeeTypeQName); PrismProperty item = shadow.findProperty(employeeTypePath); - + PropertyDelta deleteDelta = new PropertyDelta(new ItemPath(ShadowType.F_ATTRIBUTES), item.getDefinition().getName(), item.getDefinition(), prismContext); // PropertyDelta deleteDelta = PropertyDelta.createDelta(employeeTypePath, shadow.getDefinition()); // PrismPropertyValue valToDelte = new PrismPropertyValue("A"); @@ -2446,8 +2446,8 @@ public void test105ModifyAccount() throws Exception { deleteDelta.addValueToDelete(val.clone()); } } - - + + ObjectDelta delta = new ObjectDelta(ShadowType.class, ChangeType.MODIFY, prismContext); delta.addModification(deleteDelta); delta.setOid(accountShadowOidGuybrushOpendj); @@ -2455,7 +2455,7 @@ public void test105ModifyAccount() throws Exception { deltas.add(delta); LOGGER.info("-------->>EXECUTE DELETE MODIFICATION<<------------"); modelService.executeChanges(deltas, null, task, parentResult); - + // THEN assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); @@ -2493,9 +2493,9 @@ public void test105ModifyAccount() throws Exception { assertNotNull("Pasword disappeared", guybrushPassword); } - + /** - * Judge role excludes pirate role. This assignment should fail. + * Judge role excludes pirate role. This assignment should fail. */ @Test public void test104AssignRoleJudge() throws Exception { @@ -2512,8 +2512,8 @@ public void test104AssignRoleJudge() throws Exception { ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ADD_ROLE_JUDGE_FILENAME, ObjectDeltaType.class); try { - - // WHEN ObjectTypes.USER.getTypeQName(), + + // WHEN ObjectTypes.USER.getTypeQName(), result = modifyObjectViaModelWS(objectChange); // THEN @@ -2555,7 +2555,7 @@ public void test107UnassignRolePirate() throws Exception { ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_DELETE_ROLE_PIRATE_FILENAME, ObjectDeltaType.class); - // WHEN ObjectTypes.USER.getTypeQName(), + // WHEN ObjectTypes.USER.getTypeQName(), result = modifyObjectViaModelWS(objectChange); // THEN @@ -2620,7 +2620,7 @@ public void test107UnassignRolePirate() throws Exception { String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Pasword disappeared", guybrushPassword); - // TODO: Derby + // TODO: Derby } @@ -2638,7 +2638,7 @@ public void test108UnassignRoleCaptain() throws Exception { ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_1_FILENAME, ObjectDeltaType.class); - // WHEN ObjectTypes.USER.getTypeQName(), + // WHEN ObjectTypes.USER.getTypeQName(), result = modifyObjectViaModelWS(objectChange); // THEN @@ -2705,7 +2705,7 @@ public void test108UnassignRoleCaptain() throws Exception { String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Pasword disappeared", guybrushPassword); - // TODO: Derby + // TODO: Derby } @@ -2726,13 +2726,13 @@ public void test109UnassignRoleCaptainAgain() throws Exception { ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_2_FILENAME, ObjectDeltaType.class); - // WHEN ObjectTypes.USER.getTypeQName(), + // WHEN ObjectTypes.USER.getTypeQName(), result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); - + //TODO TODO TODO TODO operation result from repostiory.getObject is unknown...find out why.. // assertSuccess("modifyObject has failed", result); @@ -2773,7 +2773,7 @@ public void test109UnassignRoleCaptainAgain() throws Exception { } - + // Synchronization tests /** @@ -2787,9 +2787,9 @@ public void test300LiveSyncInit() throws Exception { // 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 - + checkAllShadows(); - + // IMPORTANT! Assignment enforcement is POSITIVE now setAssignmentEnforcement(AssignmentPolicyEnforcementType.POSITIVE); // This is not redundant. It checks that the previous command set the policy correctly @@ -2810,7 +2810,7 @@ public boolean check() throws ObjectNotFoundException, SchemaException { Task task = taskManager.getTask(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; + return task.getLastRunFinishTimestamp() != null; // if (TaskExclusivityStatus.CLAIMED == task.getExclusivityStatus()) { // // wait until the first run is finished // if (task.getLastRunFinishTimestamp() == null) { @@ -2826,7 +2826,7 @@ public void timeout() { // No reaction, the test will fail right after return from this } }, 20000); - + // Check task status Task task = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); @@ -2872,11 +2872,11 @@ public void timeout() { AssertJUnit.assertNotNull(taskResult); assertTrue(taskResult.isSuccess()); - + final Object tokenAfter = findSyncToken(task); display("Sync token after", tokenAfter.toString()); lastSyncToken = (Integer)tokenAfter; - + checkAllShadows(); } @@ -2918,7 +2918,7 @@ public void test301LiveSyncCreate() throws Exception { // AssertJUnit.assertEquals(user.getName(), WILL_NAME); // TODO: more checks - + assertAndStoreSyncTokenIncrement(syncCycle, 4); checkAllShadows(); } @@ -2951,7 +2951,7 @@ public void test302LiveSyncModify() throws Exception { // AssertJUnit.assertEquals(WILL_NAME, user.getName()); PrismAsserts.assertEqualsPolyString("Wrong name.", WILL_NAME, user.getName()); PrismAsserts.assertEqualsPolyString("wrong givenName", "asdf", user.getGivenName()); - + assertAndStoreSyncTokenIncrement(syncCycle, 1); checkAllShadows(); } @@ -3008,7 +3008,7 @@ public void test303LiveSyncLink() throws Exception { ShadowType account = searchAccountByOid(accountOid); assertEqualsPolyString("Name doesn't match", "uid=e,ou=People,dc=example,dc=com", account.getName()); - + assertAndStoreSyncTokenIncrement(syncCycle, 4); checkAllShadows(); } @@ -3057,7 +3057,7 @@ public void test304LiveSyncCreateNoLocation() throws Exception { assertNotNull("null value list for attribute 'l'", localities); assertEquals("unexpected number of values of attribute 'l'", 1, localities.size()); assertEquals("Locality doesn't match", "middle of nowhere", localities.iterator().next()); - + assertAndStoreSyncTokenIncrement(syncCycle, 3); checkAllShadows(); } @@ -3070,11 +3070,11 @@ private void assertAndStoreSyncTokenIncrement(Task syncCycle, int increment) { lastSyncToken = tokenAfterInt; assertEquals("Unexpected sync toke value", expectedToken, tokenAfterInt); } - + private int findSyncToken(Task syncCycle) { return (Integer)findSyncTokenObject(syncCycle); } - + private Object findSyncTokenObject(Task syncCycle) { Object token = null; PrismProperty tokenProperty = syncCycle.getExtension().findProperty(SchemaConstants.SYNC_TOKEN); @@ -3114,11 +3114,11 @@ public void test400ImportFromResource() throws Exception { OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); - + // 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); display("Entry from LDIF", entry); - + // Let's add an entry with multiple uids. Entry addEntry = openDJController.addEntryFromLdifFile(LDIF_HERMAN_FILENAME); display("Entry from LDIF", addEntry); @@ -3186,9 +3186,9 @@ public void timeout() { // wait a second until the task will be definitely saved Thread.sleep(1000); - + //### Check task state after the task is finished ### - + Holder objectHolder = new Holder(); Holder resultHolder = new Holder(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); @@ -3204,7 +3204,7 @@ public void timeout() { display("Import task after finish (fetched from model)", task); AssertJUnit.assertEquals(TaskExecutionStatus.CLOSED, task.getExecutionStatus()); - + assertNotNull("Null lastRunStartTimestamp in "+task, task.getLastRunStartTimestamp()); assertNotNull("Null lastRunFinishTimestamp in "+task, task.getLastRunFinishTimestamp()); @@ -3255,7 +3255,7 @@ public void timeout() { AssertJUnit.assertFalse("No users created", uobjects.getObject().isEmpty()); // TODO: use another account, not guybrush - + display("Users after import "+uobjects.getObject().size()); for (ObjectType oo : uobjects.getObject()) { @@ -3279,8 +3279,8 @@ public void timeout() { // skip the rest of checks for guybrush, he does not have LDAP account now continue; } - - assertTrue("User "+user.getName()+" is disabled ("+user.getActivation().getAdministrativeStatus()+")", user.getActivation() == null || + + assertTrue("User "+user.getName()+" is disabled ("+user.getActivation().getAdministrativeStatus()+")", user.getActivation() == null || user.getActivation().getAdministrativeStatus() == ActivationStatusType.ENABLED); List accountRefs = user.getLinkRef(); @@ -3298,25 +3298,25 @@ public void timeout() { if (!found) { AssertJUnit.fail("accountRef does not point to existing account " + accountRef.getOid()); } - + PrismObject aObject = modelService.getObject(ShadowType.class, accountRef.getOid(), null, task, result); ShadowType account = aObject.asObjectable(); - + display("Account after import ", account); - - String attributeValueL = ShadowUtil.getMultiStringAttributeValueAsSingle(account, + + String attributeValueL = ShadowUtil.getMultiStringAttributeValueAsSingle(account, new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeOpenDjrepo), "l")); // assertEquals("Unexcpected value of l", "middle of nowhere", attributeValueL); assertEquals("Unexcpected value of l", getUserLocality(user), attributeValueL); } - + // This also includes "idm" user imported from LDAP. Later we need to ignore that one. assertEquals("Wrong number of users after import", 10, uobjects.getObject().size()); - + checkAllShadows(); - + } - + private String getUserLocality(UserType user){ return user.getLocality() != null ? user.getLocality().getOrig() :"middle of nowhere"; } @@ -3366,7 +3366,7 @@ public void timeout() { // No reaction, the test will fail right after return from this } }, 40000); - + // wait a second until the task will be definitely saved Thread.sleep(1000); @@ -3682,7 +3682,7 @@ public void timeout() { checkAllShadows(); } - + @Test public void test480ListResources() throws Exception { final String TEST_NAME = "test480ListResources"; @@ -3690,26 +3690,26 @@ public void test480ListResources() throws Exception { // GIVEN OperationResultType result = new OperationResultType(); Holder resultHolder = new Holder(result); - + Holder objectListHolder = new Holder(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); // WHEN modelWeb.searchObjects(ObjectTypes.RESOURCE.getTypeQName(), null, options, objectListHolder, resultHolder); - + // THEN - + display("Resources", objectListHolder.value); assertEquals("Unexpected number of resources", 4, objectListHolder.value.getObject().size()); // TODO - + for(ObjectType object: objectListHolder.value.getObject()) { // Marshalling may fail even though the Java object is OK so test for it String xml = prismContext.serializeObjectToString(object.asPrismObject(), PrismContext.LANG_XML); } - + } - + @Test public void test485ListResourcesWithBrokenResource() throws Exception { TestUtil.displayTestTitle("test485ListResourcesWithBrokenResource"); @@ -3743,7 +3743,7 @@ public void test485ListResourcesWithBrokenResource() throws Exception { } } } - + @Test public void test500NotifyChangeCreateAccount() throws Exception{ final String TEST_NAME = "test500NotifyChangeCreateAccount"; @@ -3751,10 +3751,10 @@ public void test500NotifyChangeCreateAccount() throws Exception{ Entry ldifEntry = openDJController.addEntryFromLdifFile(LDIF_ANGELIKA_FILENAME); display("Entry from LDIF", ldifEntry); - + List attributes = ldifEntry.getAttributes(); List attrs = ldifEntry.getAttribute("entryUUID"); - + AttributeValue val = null; if (attrs == null){ for (Attribute a : attributes){ @@ -3765,17 +3765,17 @@ public void test500NotifyChangeCreateAccount() throws Exception{ } else{ val = attrs.get(0).iterator().next(); } - + String entryUuid = val.toString(); - + ShadowType anglicaAccount = parseObjectType(new File(ACCOUNT_ANGELIKA_FILENAME), ShadowType.class); PrismProperty prop = anglicaAccount.asPrismObject().findContainer(ShadowType.F_ATTRIBUTES).getValue().createProperty( new PrismPropertyDefinitionImpl<>(getOpenDjPrimaryIdentifierQName(), DOMUtil.XSD_STRING, prismContext)); prop.setValue(new PrismPropertyValue<>(entryUuid)); anglicaAccount.setResourceRef(ObjectTypeUtil.createObjectRef(RESOURCE_OPENDJ_OID, ObjectTypes.RESOURCE)); - + display("Angelica shadow: ", anglicaAccount.asPrismObject().debugDump()); - + ResourceObjectShadowChangeDescriptionType changeDescription = new ResourceObjectShadowChangeDescriptionType(); ObjectDeltaType delta = new ObjectDeltaType(); delta.setChangeType(ChangeTypeType.ADD); @@ -3783,26 +3783,26 @@ public void test500NotifyChangeCreateAccount() throws Exception{ delta.setObjectType(ShadowType.COMPLEX_TYPE); changeDescription.setObjectDelta(delta); changeDescription.setChannel(SchemaConstants.CHANNEL_WEB_SERVICE_URI); - + // WHEN TaskType task = modelWeb.notifyChange(changeDescription); - + // THEN OperationResult result = OperationResult.createOperationResult(task.getResult()); display(result); assertSuccess(result); - + PrismObject userAngelika = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelika); - + UserType user = userAngelika.asObjectable(); assertNotNull("User with the name angelika must have one link ref.", user.getLinkRef()); - + assertEquals("Expected one account ref in user", 1, user.getLinkRef().size()); String oid = user.getLinkRef().get(0).getOid(); - + PrismObject modelShadow = modelService.getObject(ShadowType.class, oid, null, taskManager.createTaskInstance(), result); - + assertAttributeNotNull(modelShadow, getOpenDjPrimaryIdentifierQName()); assertAttribute(modelShadow, "uid", "angelika"); assertAttribute(modelShadow, "givenName", "Angelika"); @@ -3810,135 +3810,135 @@ public void test500NotifyChangeCreateAccount() throws Exception{ assertAttribute(modelShadow, "cn", "Angelika Marley"); } - + @Test public void test501NotifyChangeModifyAccount() throws Exception{ final String TEST_NAME = "test501NotifyChangeModifyAccount"; TestUtil.displayTestTitle(TEST_NAME); - OperationResult parentResult = new OperationResult(TEST_NAME); + OperationResult parentResult = new OperationResult(TEST_NAME); PrismObject userAngelika = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelika); - + UserType user = userAngelika.asObjectable(); assertNotNull("User with the name angelika must have one link ref.", user.getLinkRef()); - + assertEquals("Expected one account ref in user", 1, user.getLinkRef().size()); String oid = user.getLinkRef().get(0).getOid(); - + ResourceObjectShadowChangeDescriptionType changeDescription = new ResourceObjectShadowChangeDescriptionType(); ObjectDeltaType delta = new ObjectDeltaType(); delta.setChangeType(ChangeTypeType.MODIFY); delta.setObjectType(ShadowType.COMPLEX_TYPE); - + ItemDeltaType mod1 = new ItemDeltaType(); mod1.setModificationType(ModificationTypeType.REPLACE); ItemPathType path = new ItemPathType(new ItemPath(ShadowType.F_ATTRIBUTES, new QName(resourceTypeOpenDjrepo.getNamespace(), "givenName"))); mod1.setPath(path); - + RawType value = new RawType(new PrimitiveXNode("newAngelika"), prismContext); mod1.getValue().add(value); - + delta.getItemDelta().add(mod1); delta.setOid(oid); - + LOGGER.info("item delta: {}", SchemaDebugUtil.prettyPrint(mod1)); - + LOGGER.info("delta: {}", DebugUtil.dump(mod1)); - + changeDescription.setObjectDelta(delta); - + changeDescription.setOldShadowOid(oid); changeDescription.setChannel(SchemaConstants.CHANNEL_WEB_SERVICE_URI); - + // WHEN TaskType task = modelWeb.notifyChange(changeDescription); - + // THEN OperationResult result = OperationResult.createOperationResult(task.getResult()); display(result); assertSuccess(result); - + PrismObject userAngelikaAfterSync = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelikaAfterSync); - + UserType userAfterSync = userAngelikaAfterSync.asObjectable(); - + PrismAsserts.assertEqualsPolyString("wrong given name in user angelika", PrismTestUtil.createPolyStringType("newAngelika"), userAfterSync.getGivenName()); - + } - + @Test public void test502NotifyChangeModifyAccountPassword() throws Exception{ final String TEST_NAME = "test502NotifyChangeModifyAccountPassword"; TestUtil.displayTestTitle(TEST_NAME); - + PrismObject userAngelika = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelika); - + UserType user = userAngelika.asObjectable(); assertNotNull("User with the name angelika must have one link ref.", user.getLinkRef()); - + assertEquals("Expected one account ref in user", 1, user.getLinkRef().size()); String oid = user.getLinkRef().get(0).getOid(); - + String newPassword = "newPassword"; - + openDJController.modifyReplace("uid="+ANGELIKA_NAME+","+openDJController.getSuffixPeople(), "userPassword", newPassword); - + ResourceObjectShadowChangeDescriptionType changeDescription = new ResourceObjectShadowChangeDescriptionType(); ObjectDeltaType delta = new ObjectDeltaType(); delta.setChangeType(ChangeTypeType.MODIFY); delta.setObjectType(ShadowType.COMPLEX_TYPE); - + ItemDeltaType passwordDelta = new ItemDeltaType(); passwordDelta.setModificationType(ModificationTypeType.REPLACE); passwordDelta.setPath(ModelClientUtil.createItemPathType("credentials/password/value")); RawType passwordValue = new RawType(((PrismContextImpl) prismContext).getBeanMarshaller().marshall(ModelClientUtil.createProtectedString(newPassword)), prismContext); passwordDelta.getValue().add(passwordValue); - + delta.getItemDelta().add(passwordDelta); delta.setOid(oid); - + LOGGER.info("item delta: {}", SchemaDebugUtil.prettyPrint(passwordDelta)); - + LOGGER.info("delta: {}", DebugUtil.dump(passwordDelta)); - + changeDescription.setObjectDelta(delta); - + changeDescription.setOldShadowOid(oid); // changeDescription.setCurrentShadow(angelicaShadowType); changeDescription.setChannel(SchemaConstants.CHANNEL_WEB_SERVICE_URI); - + // WHEN TaskType task = modelWeb.notifyChange(changeDescription); - + // THEN OperationResult result = OperationResult.createOperationResult(task.getResult()); display(result); assertSuccess(result); - + PrismObject userAngelikaAfterSync = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelikaAfterSync); - + assertUserLdapPassword(userAngelikaAfterSync, newPassword); - + } - + @Test public void test503NotifyChangeDeleteAccount() throws Exception{ final String TEST_NAME = "test503NotifyChangeDeleteAccount"; TestUtil.displayTestTitle(TEST_NAME); - + PrismObject userAngelika = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelika); - + UserType user = userAngelika.asObjectable(); assertNotNull("User with the name angelika must have one link ref.", user.getLinkRef()); - + assertEquals("Expected one account ref in user", 1, user.getLinkRef().size()); String oid = user.getLinkRef().get(0).getOid(); - + ResourceObjectShadowChangeDescriptionType changeDescription = new ResourceObjectShadowChangeDescriptionType(); ObjectDeltaType delta = new ObjectDeltaType(); delta.setChangeType(ChangeTypeType.DELETE); @@ -3947,28 +3947,28 @@ public void test503NotifyChangeDeleteAccount() throws Exception{ changeDescription.setObjectDelta(delta); changeDescription.setOldShadowOid(oid); changeDescription.setChannel(SchemaConstants.CHANNEL_WEB_SERVICE_URI); - + // WHEN TaskType task = modelWeb.notifyChange(changeDescription); - + // THEN OperationResult result = OperationResult.createOperationResult(task.getResult()); display(result); assertTrue(result.isAcceptable()); - + PrismObject userAngelikaAfterSync = findUserByUsername(ANGELIKA_NAME); display("User after", userAngelikaAfterSync); assertNotNull("User with the name angelika must exist.", userAngelikaAfterSync); - + UserType userType = userAngelikaAfterSync.asObjectable(); assertNotNull("User with the name angelika must have one link ref.", userType.getLinkRef()); - + assertEquals("Expected no account ref in user", 0, userType.getLinkRef().size()); - + } - - - + + + @Test public void test999Shutdown() throws Exception { taskManager.shutdown(); @@ -4016,10 +4016,10 @@ private String checkRepoShadow(PrismObject repoShadow) { assertFalse("Shadow "+repoShadow+" has unexpected elements", hasOthers); assertNotNull(uid); - + return uid; } - + private QName getOpenDjPrimaryIdentifierQName() { return new QName(RESOURCE_OPENDJ_NS, RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME); } @@ -4080,7 +4080,7 @@ private void basicWaitForSyncChangeDetection(Task syncCycle, Object tokenBefore, final OperationResult result) throws Exception { basicWaitForSyncChangeDetection(syncCycle, (int)((Integer)tokenBefore), increment, result); } - + private void basicWaitForSyncChangeDetection(Task syncCycle, int tokenBefore, int increment, final OperationResult result) throws Exception { basicWaitForSyncChangeDetection(syncCycle, tokenBefore, increment, result, 40000); @@ -4133,34 +4133,34 @@ private void assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnfor assertNotNull("assignmentPolicyEnforcement is null", assignmentPolicyEnforcement); assertEquals("Assignment policy mismatch", assignmentPolicy, assignmentPolicyEnforcement); } - + private void checkAllShadows() throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException { LOGGER.trace("Checking all shadows"); System.out.println("Checking all shadows"); ObjectChecker checker = null; - IntegrationTestTools.checkAllShadows(resourceTypeOpenDjrepo, repositoryService, checker, prismContext); - } - + IntegrationTestTools.checkAllShadows(resourceTypeOpenDjrepo, repositoryService, checker, prismContext); + } + public static String getNormalizedAttributeValue(ShadowType repoShadow, RefinedObjectClassDefinition objClassDef, QName name) { - + String value = getAttributeValue(repoShadow, name); - + RefinedAttributeDefinition idDef = objClassDef.getPrimaryIdentifiers().iterator().next(); if (idDef.getMatchingRuleQName() != null && idDef.getMatchingRuleQName().equals(StringIgnoreCaseMatchingRule.NAME)){ return value.toLowerCase(); } - + return value; } - + protected void assertAttribute(ShadowType shadowType, String attrName, T... expectedValues) { assertAttribute(resourceTypeOpenDjrepo, shadowType, attrName, expectedValues); } - + protected void assertAttribute(PrismObject shadow, String attrName, T... expectedValues) { assertAttribute(resourceTypeOpenDjrepo, shadow.asObjectable(), attrName, expectedValues); } - + protected void assertAttribute(ShadowType shadowType, QName attrName, T... expectedValues) { assertAttribute(resourceTypeOpenDjrepo, shadowType, attrName, expectedValues); } 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 ab595489879..36f66e29e48 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 @@ -54,29 +54,29 @@ @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"; protected static final String USER_JACK_USERNAME = "jack"; - + 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"; - + protected static final File TASK_VALIDITY_SCANNER_FILE = new File(COMMON_DIR, "task-validity-scanner.xml"); protected static final String TASK_VALIDITY_SCANNER_OID = "00000000-0000-0000-0000-000000000006"; protected MatchingRule caseIgnoreMatchingRule; - + @Autowired protected MatchingRuleRegistry matchingRuleRegistry; @@ -86,7 +86,7 @@ public class AbstractStoryTest extends AbstractModelIntegrationTest { public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); modelService.postInit(initResult); - + // System Configuration try { repoAddObjectFromFile(getSystemConfigurationFile(), initResult); @@ -94,17 +94,17 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti throw new ObjectAlreadyExistsException("System configuration already exists in repository;" + "looks like the previous test haven't cleaned it up", e); } - + // User administrator userAdministrator = repoAddObjectFromFile(USER_ADMINISTRATOR_FILE, initResult); repoAddObjectFromFile(USER_JACK_FILE, true, initResult).asObjectable(); repoAddObjectFromFile(ROLE_SUPERUSER_FILE, initResult); login(userAdministrator); - + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - + caseIgnoreMatchingRule = matchingRuleRegistry.getMatchingRule(StringIgnoreCaseMatchingRule.NAME, DOMUtil.XSD_STRING); - + importSystemTasks(initResult); } @@ -117,9 +117,9 @@ 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"); } - + } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/CountingInspector.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/CountingInspector.java index 81ce82ae4b4..b99e57bcc38 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/CountingInspector.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/CountingInspector.java @@ -39,9 +39,9 @@ public class CountingInspector implements InternalInspector, DebugDumpable { @SuppressWarnings("rawtypes") private Map readMap = new HashMap<>(); - + private Map roleEvaluationMap = new HashMap<>(); - + @Override public void inspectRepositoryRead(Class type, String oid) { Integer i = readMap.get(type); @@ -51,11 +51,11 @@ public void inspectRepositoryRead(Class type, String o i++; readMap.put(type, i); } - + public void assertRead(Class type, int expectedCount) { assertEquals("Unexpected number of reads of "+type.getSimpleName(), (Integer)expectedCount, readMap.get(type)); } - + @Override public void inspectRoleEvaluation(F target, boolean fullEvaluation) { NamedObjectKey key = new NamedObjectKey(target); @@ -96,7 +96,7 @@ public String debugDump(int indent) { private class NamedObjectKey { private String oid; private String name; - + public NamedObjectKey(ObjectType object) { this.oid = object.getOid(); this.name = object.getName().getOrig(); @@ -152,7 +152,7 @@ private CountingInspector getOuterType() { public String toString() { return "(" + oid + ":" + name + ")"; } - - + + } } 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 bf29360678f..24ef8337080 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 @@ -106,10 +106,10 @@ public class TestDependencyRename extends AbstractStoryTest { private static final String USER_CAPSIZE_USERNAME_FINAL = "kcapsize"; private static final String USER_CAPSIZE_GIVEN_NAME = "Kate"; private static final String USER_CAPSIZE_FAMILY_NAME = "Capsize"; - + protected ResourceType resourceOpenDjType; protected PrismObject resourceOpenDj; - + private String userHermanOid; private String accountHermanPhonebookOid; private String accountHermanOpenDjOid; @@ -157,8 +157,8 @@ public void test000Sanity() throws Exception { TestUtil.assertSuccess(testResultOpenDj); } - - + + @Test public void test100AddUserHerman() throws Exception { final String TEST_NAME = "test100AddUserHerman"; @@ -171,16 +171,16 @@ public void test100AddUserHerman() throws Exception { userType.setName(createPolyStringType(USER_HERMAN_USERNAME)); userType.setGivenName(createPolyStringType(USER_HERMAN_GIVEN_NAME)); userType.setFamilyName(createPolyStringType(USER_HERMAN_FAMILY_NAME)); - + display("User before", userBefore); - + // WHEN addObject(userBefore, task, result); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_HERMAN_USERNAME); assertNotNull("No herman user", userAfter); userHermanOid = userAfter.getOid(); @@ -188,22 +188,22 @@ public void test100AddUserHerman() throws Exception { assertUserHerman(userAfter, USER_HERMAN_USERNAME); assertNoAssignments(userAfter); } - - + + @Test public void test110HermanAssignRoleBasic() throws Exception { final String TEST_NAME = "test110HermanAssignRoleBasic"; TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignRole(userHermanOid, ROLE_BASIC_OID, task, result); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(userHermanOid); assertNotNull("No herman user", userAfter); userHermanOid = userAfter.getOid(); @@ -211,34 +211,34 @@ public void test110HermanAssignRoleBasic() throws Exception { assertUserHerman(userAfter, USER_HERMAN_USERNAME_FINAL); assertAssignedRole(userAfter, ROLE_BASIC_OID); assertAssignments(userAfter, 1); - + assertLinks(userAfter, 2); accountHermanPhonebookOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_PHONEBOOK_OID); PrismObject shadowPhonebook = getShadowModel(accountHermanPhonebookOid); display("Shadow phonebook after", shadowPhonebook); assertShadowSecondaryIdentifier(shadowPhonebook, USER_HERMAN_USERNAME_FINAL, getDummyResourceType(RESOURCE_DUMMY_PHONEBOOK_ID), null); - + accountHermanOpenDjOid = getLinkRefOid(userAfter, RESOURCE_OPENDJ_OID); PrismObject shadowOpenDj = getShadowModel(accountHermanOpenDjOid); display("Shadow opendj after", shadowOpenDj); assertShadowSecondaryIdentifier(shadowOpenDj, openDJController.getAccountDn(USER_HERMAN_USERNAME_FINAL), resourceOpenDjType, caseIgnoreMatchingRule); - + } - + @Test public void test112HermanRename() throws Exception { final String TEST_NAME = "test112HermanRename"; TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN modifyUserReplace(userHermanOid, UserType.F_FAMILY_NAME, task, result, createPolyString(USER_HERMAN_FAMILY_NAME_MARLEY)); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(userHermanOid); assertNotNull("No herman user", userAfter); userHermanOid = userAfter.getOid(); @@ -246,20 +246,20 @@ public void test112HermanRename() throws Exception { assertUser(userAfter, USER_HERMAN_USERNAME_MARLEY, USER_HERMAN_GIVEN_NAME, USER_HERMAN_FAMILY_NAME_MARLEY); assertAssignedRole(userAfter, ROLE_BASIC_OID); assertAssignments(userAfter, 1); - + assertLinks(userAfter, 2); accountHermanPhonebookOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_PHONEBOOK_OID); PrismObject shadowPhonebook = getShadowModel(accountHermanPhonebookOid); display("Shadow phonebook after", shadowPhonebook); assertShadowSecondaryIdentifier(shadowPhonebook, USER_HERMAN_USERNAME_MARLEY, getDummyResourceType(RESOURCE_DUMMY_PHONEBOOK_ID), null); - + accountHermanOpenDjOid = getLinkRefOid(userAfter, RESOURCE_OPENDJ_OID); PrismObject shadowOpenDj = getShadowModel(accountHermanOpenDjOid); display("Shadow opendj after", shadowOpenDj); assertShadowSecondaryIdentifier(shadowOpenDj, openDJController.getAccountDn(USER_HERMAN_USERNAME_MARLEY), resourceOpenDjType, caseIgnoreMatchingRule); - + } - + @Test public void test120AddUserCapsizeWithBasicRole() throws Exception { final String TEST_NAME = "test120AddUserCapsizeWithBasicRole"; @@ -273,35 +273,35 @@ public void test120AddUserCapsizeWithBasicRole() throws Exception { userType.setGivenName(createPolyStringType(USER_CAPSIZE_GIVEN_NAME)); userType.setFamilyName(createPolyStringType(USER_CAPSIZE_FAMILY_NAME)); userType.beginAssignment().targetRef(ROLE_BASIC_OID, RoleType.COMPLEX_TYPE).end(); - + display("User before", userBefore); - + // WHEN addObject(userBefore, task, result); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + String userCapsizeOid = userBefore.getOid(); PrismObject userAfter = getUser(userCapsizeOid); assertNotNull("No user", userAfter); display("User after", userAfter); assertUser(userAfter, USER_CAPSIZE_USERNAME_FINAL, USER_CAPSIZE_GIVEN_NAME, USER_CAPSIZE_FAMILY_NAME); - + assertLinks(userAfter, 2); String accountPhonebookOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_PHONEBOOK_OID); PrismObject shadowPhonebook = getShadowModel(accountPhonebookOid); display("Shadow phonebook after", shadowPhonebook); assertShadowSecondaryIdentifier(shadowPhonebook, USER_CAPSIZE_USERNAME_FINAL, getDummyResourceType(RESOURCE_DUMMY_PHONEBOOK_ID), null); - + String accountOpenDjOid = getLinkRefOid(userAfter, RESOURCE_OPENDJ_OID); PrismObject shadowOpenDj = getShadowModel(accountOpenDjOid); display("Shadow opendj after", shadowOpenDj); 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 43b21c29c5f..84d91ab196b 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 @@ -82,15 +82,15 @@ public static void stopResources() throws Exception { public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, RESOURCE_OPENDJ_FILE, RESOURCE_OPENDJ_OID, initTask, initResult); resourceOpenDjType = resourceOpenDj.asObjectable(); openDJController.setResource(resourceOpenDj); - + importObjectFromFile(ROLE_META_CREATE_ORG_GROUPS_FILE); - + } @@ -147,7 +147,7 @@ public void test001AddParentOrg() throws Exception { assertIntents(shadowType1, shadowType2); } - + @Test public void test002AddChildOrg() throws Exception { final String TEST_NAME = "test002AddChildOrg"; @@ -162,9 +162,9 @@ public void test002AddChildOrg() throws Exception { Collection uniqueMembers = openDJController.getGroupUniqueMembers("cn=Games,ou=groups,dc=example,dc=com"); assertNotNull("null unique members", uniqueMembers); assertEquals("Expected exactly one member", 1, uniqueMembers.size()); - + openDJController.assertUniqueMember("cn=Games,ou=groups,dc=example,dc=com", "cn=Poker,ou=groups,dc=example,dc=com"); - + PrismObject orgGames = modelService.getObject(OrgType.class, ORG_POKER_OID, null, task, result); assertNotNull("No top org for games found", orgGames); @@ -185,7 +185,7 @@ public void test002AddChildOrg() throws Exception { assertIntents(shadowType1, shadowType2); } - + private ShadowType getAndAssertShadowSuccess(ObjectReferenceType ort, Task task, OperationResult result) throws Exception { assertNotNull("Unexpected (null) reference to shadow", ort); PrismObject shadow = modelService.getObject(ShadowType.class, ort.getOid(), @@ -198,7 +198,7 @@ private ShadowType getAndAssertShadowSuccess(ObjectReferenceType ort, Task task, assertNull("Unexpected error in shadow: result", shadowType.getResult()); return shadowType; } - + private void assertIntents(ShadowType shadowType1, ShadowType shadowType2) { String intentShadow1 = shadowType1.getIntent(); String intentShadow2 = shadowType2.getIntent(); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestLdapDependency.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestLdapDependency.java index 6b4ea470f5e..dc46be2af28 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestLdapDependency.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestLdapDependency.java @@ -72,25 +72,25 @@ * 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"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestLdapDependency extends AbstractStoryTest { - + public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "ldap-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"; - + public static final String ROLE_META_ORG_OID = "10000000-0000-0000-0000-000000006601"; public static final String ROLE_META_ORG_VIP_OID = "10000000-0000-0000-0000-000000006602"; public static final String ROLE_META_ORG_SUPERVIP_OID = "10000000-0000-0000-0000-000000006603"; @@ -99,47 +99,47 @@ public class TestLdapDependency extends AbstractStoryTest { private static final String ORG_HR_NAME = "HR"; private static String orgItOid; private static String orgHrOid; - + private static final String ORG_TYPE_FUNCTIONAL = "functional"; private static final String LDAP_GROUP_INTENT = "group"; private static final String LDAP_GROUP_VIP_INTENT = "group-vip"; private static final String LDAP_GROUP_SUPERVIP_INTENT = "group-supervip"; - + private static final String LDAP_OU_INTENT = "ou"; private static final String LDAP_OU_VIP_INTENT = "ou-vip"; - + private ResourceType resourceOpenDjType; private PrismObject resourceOpenDj; - + @Override protected String getTopOrgOid() { return ORG_TOP_OID; } - + private File getTestDir() { return TEST_DIR; } - + private File getResourceOpenDjFile() { return new File(getTestDir(), "resource-opendj.xml"); } - + private File getOrgTopFile() { return new File(getTestDir(), "org-top.xml"); } - + private File getRoleMetaOrgFile() { return new File(getTestDir(), "role-meta-org.xml"); } - + private File getRoleMetaOrgVipFile() { return new File(getTestDir(), "role-meta-org-vip.xml"); } - + private File getRoleMetaOrgSuperVipFile() { return new File(getTestDir(), "role-meta-org-supervip.xml"); } @@ -153,13 +153,13 @@ protected void startResources() throws Exception { public static void stopResources() throws Exception { openDJController.stop(); } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - - - // Resources + + + // Resources resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, getResourceOpenDjFile(), RESOURCE_OPENDJ_OID, initTask, initResult); resourceOpenDjType = resourceOpenDj.asObjectable(); openDJController.setResource(resourceOpenDj); @@ -172,20 +172,20 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti importObjectFromFile(getRoleMetaOrgVipFile(), initResult); importObjectFromFile(getRoleMetaOrgSuperVipFile(), initResult); } - + @Test public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + OperationResult testResultOpenDj = modelService.testResource(RESOURCE_OPENDJ_OID, task); TestUtil.assertSuccess(testResultOpenDj); dumpOrgTree(); dumpLdap(); } - + @Test public void test100AddOrgIT() throws Exception { final String TEST_NAME = "test100AddOrgIT"; @@ -194,7 +194,7 @@ public void test100AddOrgIT() throws Exception { OperationResult result = task.getResult(); PrismObject orgBefore = createOrg(ORG_IT_NAME, ORG_TOP_OID); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("Adding org", orgBefore); @@ -204,17 +204,17 @@ public void test100AddOrgIT() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject orgAfter = getOrg(ORG_IT_NAME); orgItOid = orgAfter.getOid(); assertSubOrgs(orgAfter, 0); assertSubOrgs(ORG_TOP_OID, 1); } - + @Test public void test150AssignFunctionalRoleToITOrg() throws Exception { final String TEST_NAME = "test150AssignFunctionalRoleToITOrg"; @@ -223,7 +223,7 @@ public void test150AssignFunctionalRoleToITOrg() throws Exception { OperationResult result = task.getResult(); PrismObject orgBefore = getOrg(ORG_IT_NAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("orgBefore: ", orgBefore); @@ -233,10 +233,10 @@ public void test150AssignFunctionalRoleToITOrg() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject orgAfter = getOrg(ORG_IT_NAME); display("AFTER Assigning functional role org", orgAfter); assertSubOrgs(orgAfter, 0); @@ -245,7 +245,7 @@ public void test150AssignFunctionalRoleToITOrg() throws Exception { assertLdapObject(orgAfter, ShadowKindType.ENTITLEMENT, LDAP_GROUP_INTENT); assertLdapObject(orgAfter, ShadowKindType.GENERIC, LDAP_OU_INTENT); } - + @Test public void test170UnassignFunctionalRoleFromITOrg() throws Exception { final String TEST_NAME = "test170UnassignFunctionalRoleFromITOrg"; @@ -254,20 +254,20 @@ public void test170UnassignFunctionalRoleFromITOrg() throws Exception { OperationResult result = task.getResult(); PrismObject orgBefore = getOrg(ORG_IT_NAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("unassigning vip role org", orgBefore); unassignRoleFromOrg(orgItOid, ROLE_META_ORG_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject orgAfter = getOrg(ORG_IT_NAME); display("AFTER unassigning functional role org", orgAfter); assertSubOrgs(orgAfter, 0); @@ -276,8 +276,8 @@ public void test170UnassignFunctionalRoleFromITOrg() throws Exception { assertNotAssignedRole(orgAfter, ROLE_META_ORG_OID); //TODO: assert ldap objects deleted... } - - + + @Test public void test200AddOrgHR() throws Exception { final String TEST_NAME = "test200AddOrgHR"; @@ -286,7 +286,7 @@ public void test200AddOrgHR() throws Exception { OperationResult result = task.getResult(); PrismObject orgBefore = createOrg(ORG_HR_NAME, ORG_TOP_OID); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("Adding org", orgBefore); @@ -296,17 +296,17 @@ public void test200AddOrgHR() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject orgAfter = getOrg(ORG_HR_NAME); orgHrOid = orgAfter.getOid(); assertSubOrgs(orgAfter, 0); assertSubOrgs(ORG_TOP_OID, 2); } - + @Test public void test250AssignFunctionalAndVipRoleToHROrg() throws Exception { final String TEST_NAME = "test250AssignFunctionalAndVipRoleToHROrg"; @@ -315,7 +315,7 @@ public void test250AssignFunctionalAndVipRoleToHROrg() throws Exception { OperationResult result = task.getResult(); PrismObject orgBefore = getOrg(ORG_HR_NAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("orgBefore: ", orgBefore); @@ -326,10 +326,10 @@ public void test250AssignFunctionalAndVipRoleToHROrg() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject orgAfter = getOrg(ORG_HR_NAME); display("AFTER Assigning functional and vip role org", orgAfter); assertSubOrgs(orgAfter, 0); @@ -340,7 +340,7 @@ public void test250AssignFunctionalAndVipRoleToHROrg() throws Exception { assertLdapObject(orgAfter, ShadowKindType.ENTITLEMENT, LDAP_GROUP_VIP_INTENT); assertLdapObject(orgAfter, ShadowKindType.GENERIC, LDAP_OU_VIP_INTENT); } - + @Test public void test270UnassignVipRoleFromHROrg() throws Exception { final String TEST_NAME = "test270UnassignVipRoleFromHROrg"; @@ -349,20 +349,20 @@ public void test270UnassignVipRoleFromHROrg() throws Exception { OperationResult result = task.getResult(); PrismObject orgBefore = getOrg(ORG_HR_NAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("unassigning vip role org", orgBefore); unassignRoleFromOrg(orgHrOid, ROLE_META_ORG_VIP_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject orgAfter = getOrg(ORG_HR_NAME); display("AFTER unassigning vip role org", orgAfter); assertSubOrgs(orgAfter, 0); @@ -373,7 +373,7 @@ public void test270UnassignVipRoleFromHROrg() throws Exception { assertLdapObject(orgAfter, ShadowKindType.GENERIC, LDAP_OU_INTENT); //TODO: assert ldap vip objects deleted... } - + //test280AssignVipAndSuperVipRoleToHROrg required for test290UnassignVipRoleFromHROrg @Test public void test280AssignVipAndSuperVipRoleToHROrg() throws Exception { @@ -383,7 +383,7 @@ public void test280AssignVipAndSuperVipRoleToHROrg() throws Exception { OperationResult result = task.getResult(); PrismObject orgBefore = getOrg(ORG_HR_NAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("orgBefore: ", orgBefore); @@ -394,10 +394,10 @@ public void test280AssignVipAndSuperVipRoleToHROrg() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject orgAfter = getOrg(ORG_HR_NAME); display("AFTER Assigning supervip role org", orgAfter); assertSubOrgs(orgAfter, 0); @@ -418,28 +418,28 @@ public void test290UnassignVipRoleFromHROrg() throws Exception { OperationResult result = task.getResult(); PrismObject orgBefore = getOrg(ORG_HR_NAME); - + display("unassigning vip role org", orgBefore); - + try { // WHEN TestUtil.displayWhen(TEST_NAME); unassignRoleFromOrg(orgHrOid, ROLE_META_ORG_VIP_OID, task, result); - + assertNotReached(); - + } catch (PolicyViolationException e) { // this is expected } - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertFailure(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject orgAfter = getOrg(ORG_HR_NAME); display("AFTER unassigning vip role org", orgAfter); assertSubOrgs(orgAfter, 0); @@ -470,7 +470,7 @@ private PrismObject createOrg(String name, String parentOrgOid) throws 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); @@ -482,17 +482,17 @@ private void assertLdapObjectsFunctionalOrg(PrismObject org) throws Sch 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(); 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); // TODO assert shadow content - + String search = ""; if (kind.equals(ShadowKindType.ENTITLEMENT)){ if (LDAP_GROUP_INTENT.equals(intent)) search = "cn="+orgName; @@ -506,7 +506,7 @@ private void assertLdapObject(PrismObject org, ShadowKindType kind, Str Entry objEntry = openDJController.searchSingle(search); assertNotNull("No LDAP entry for "+orgName, objEntry);; display("LDAP entry kind " +kind + " inten " + intent +" ldapObj", objEntry); - + if (kind.equals(ShadowKindType.ENTITLEMENT)){ openDJController.assertObjectClass(objEntry, "groupOfUniqueNames"); } @@ -515,61 +515,61 @@ private void assertLdapObject(PrismObject org, ShadowKindType kind, Str } } - + private void dumpLdap() throws DirectoryException { display("LDAP server tree", openDJController.dumpTree()); display("LDAP server content", openDJController.dumpEntries()); } - + ////should be in AbstractModelIntegrationTest - - private void modifyOrgAssignment(String orgOid, String roleOid, QName refType, QName relation, Task task, - PrismContainer extension, ActivationType activationType, boolean add, OperationResult result) + + private void modifyOrgAssignment(String orgOid, String roleOid, QName refType, QName relation, Task task, + PrismContainer extension, ActivationType activationType, boolean add, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { ObjectDelta orgDelta = createAssignmentOrgDelta(orgOid, roleOid, refType, relation, extension, activationType, add); Collection> deltas = MiscSchemaUtil.createCollection(orgDelta); - modelService.executeChanges(deltas, null, task, result); + modelService.executeChanges(deltas, null, task, result); } - - private ObjectDelta createAssignmentOrgDelta(String orgOid, String roleOid, QName refType, QName relation, + + private ObjectDelta createAssignmentOrgDelta(String orgOid, String roleOid, QName refType, QName relation, PrismContainer extension, ActivationType activationType, boolean add) throws SchemaException { Collection> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(roleOid, refType, relation, extension, activationType, add))); ObjectDelta userDelta = ObjectDelta.createModifyDelta(orgOid, modifications, OrgType.class, prismContext); return userDelta; } - + private void assignRoleToOrg(String orgOid, String roleOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { assignRoleToOrg(orgOid, roleOid, (ActivationType) null, task, result); } - + private void assignRoleToOrg(String orgOid, String roleOid, ActivationType activationType, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyOrgAssignment(orgOid, roleOid, RoleType.COMPLEX_TYPE, null, task, null, activationType, true, result); } - + private void unassignRoleFromOrg(String orgOid, String roleOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { unassignRoleFromOrg(orgOid, roleOid, (ActivationType) null, task, result); } - + private void unassignRoleFromOrg(String orgOid, String roleOid, ActivationType activationType, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyOrgAssignment(orgOid, roleOid, RoleType.COMPLEX_TYPE, null, task, null, activationType, false, result); } - + public static void assertOrgNotAssignedRole(PrismObject focus, String roleOid) { assertNotAssigned(focus, roleOid, RoleType.COMPLEX_TYPE); //assertNotAssigned(user, roleOid, RoleType.COMPLEX_TYPE); } - + //TODO: maybe a replacement for MidpointAsserts.assertNotAssigned() //it can be used not only for user public static void assertNotAssigned(PrismObject focus, String targetOid, QName refType) { @@ -585,8 +585,8 @@ public static void assertNotAssigned(PrismObject focus, } } } - - - + + + } \ No newline at end of file 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 451d5a8075f..3f8dec5dcd0 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 @@ -73,55 +73,55 @@ @ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestMachineIntelligence extends AbstractStoryTest { - + public static 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"); private static final String RESOURCE_HR_OID = "10000000-0000-0000-0000-000000000001"; - + private static final File RESOURCE_CSV_CONTENT_FILE = new File(TEST_DIR, "HR.csv"); private static String sourceFilePath; - + private static final File SHADOW_RUR_FILE = new File(TEST_DIR, "shadow-rur.xml"); private static final String SHADOW_RUR_OID = "shadow00-0000-0000-0000-111111111111"; - + private static final File SHADOW_CHAPPIE_FILE = new File(TEST_DIR, "shadow-chappie.xml"); private static final String SHADOW_CHAPPIE_OID = "shadow00-0000-0000-0000-111111111112"; - + 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; - + @Override protected File getSystemConfigurationFile() { return super.getSystemConfigurationFile(); } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { String home = midPointConfig.getMidpointHome(); File resourceDir = new File(home, "machineintelligence"); resourceDir.mkdir(); - + 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()){ throw new SystemException("Source file for HR resource was not created"); } - + sourceFilePath = desticationFile.getAbsolutePath(); - + super.initSystem(initTask, initResult); - + importObjectFromFile(RESOURCE_HR_FILE); - + } - + @Test public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; @@ -129,25 +129,25 @@ public void test000Sanity() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); Object[] newRealValue = { sourceFilePath }; - + ObjectDelta objectDelta = ObjectDelta.createModificationReplaceProperty(ResourceType.class, RESOURCE_HR_OID, new ItemPath(ResourceType.F_CONNECTOR_CONFIGURATION, SchemaConstants.ICF_CONFIGURATION_PROPERTIES, new QName(NS_RESOURCE_CSV, "filePath")), prismContext, newRealValue); repositoryService.modifyObject(ResourceType.class, objectDelta.getOid(), objectDelta.getModifications(), result); - + OperationResult hrTestResult = modelService.testResource(RESOURCE_HR_OID, task); TestUtil.assertSuccess("HR resource test result", hrTestResult); - + OperationResult testResultOpenDj = modelService.testResource(RESOURCE_HR_OID, task); TestUtil.assertSuccess("OpenDJ resource test result", testResultOpenDj); - + SystemConfigurationType systemConfiguration = getSystemConfiguration(); assertNotNull("No system configuration", systemConfiguration); display("System config", systemConfiguration); - + } - + /** - * + * * 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 @@ -159,23 +159,23 @@ public void test010importActiveUserRUR() throws Exception { TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN PrismObject shadow = addObject(SHADOW_RUR_FILE, task, result); assertEquals(SHADOW_RUR_OID, shadow.getOid()); - - //AND + + //AND modelService.importFromResource(SHADOW_RUR_OID, task, result); - + //THEN - + //assert created organization SearchResultList> orgs = modelService.searchObjects( OrgType.class, QueryBuilder.queryFor(OrgType.class, prismContext).item(OrgType.F_NAME) .eq("Universe").matching(PolyStringNormMatchingRule.NAME).build(), null, task, result); assertEquals("Found unexpected number of organizations, expected 1, found " + orgs.size(), 1, orgs.size()); - + //assert created owner of shadow PrismObject userRur = assertShadowOwner(SHADOW_RUR_OID, "R.U.R", "Rossum", "Universal Robots", "Rossum's Universal Robots", task, result); @@ -183,25 +183,25 @@ public void test010importActiveUserRUR() throws Exception { assertAssignedOrg(userRur, orgs.iterator().next()); //assert assignment of or in more depth assertAssignment(userRur.asObjectable(), ActivationStatusType.ENABLED, null); - + } - + @Test public void test011importInactiveUserChappie() throws Exception { final String TEST_NAME = "test020ResourceOpenDjGet"; TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN PrismObject shadow = addObject(SHADOW_CHAPPIE_FILE, task, result); assertEquals(SHADOW_CHAPPIE_OID, shadow.getOid()); - - //AND + + //AND modelService.importFromResource(SHADOW_CHAPPIE_OID, task, result); - + //THEN - + //assert created organization SearchResultList> orgs = modelService .searchObjects( @@ -209,33 +209,33 @@ public void test011importInactiveUserChappie() throws Exception { .eq("Earth").matching(PolyStringNormMatchingRule.NAME).build(), null, task, result); assertEquals("Found unexpected number of organizations, expected 1, found " + orgs.size(), 1, orgs.size()); - + //assert created owner of shadow PrismObject userRur = assertShadowOwner(SHADOW_CHAPPIE_OID, "chappie", "Chappie", "von Tetravaal", "Chappie von Tetravaal", task, result); //assert assignment of org assertAssignedOrg(userRur, orgs.iterator().next()); //assert assignment of or in more depth - + XMLGregorianCalendar validTo = XmlTypeConverter .createXMLGregorianCalendar(2016, 12, 31, 23, 59, 59); assertAssignment(userRur.asObjectable(), ActivationStatusType.DISABLED, validTo); - + } - + 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()); - + return userRur; } - + private void assertAssignment(UserType userType, ActivationStatusType administrativeStatus, XMLGregorianCalendar validTo) { List assignments = userType.getAssignment(); assertEquals("Unexpected assignment in user, expected 1, found " + assignments.size(), 1, assignments.size()); 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 da2c83841c3..535ad1b8d7f 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 @@ -90,7 +90,7 @@ public class TestNullAttribute extends AbstractStoryTest { 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"; @@ -100,16 +100,16 @@ public class TestNullAttribute extends AbstractStoryTest { public static final File ROLE_ACCOUNTONLY_FILE = new File(TEST_DIR, "role-accountonly.xml"); public static final String ROLE_ACCOUNTONLY_OID = "10000000-0000-0000-0000-000000000601"; - + public static final File ROLE_SHIPNWEAPON_FILE = new File(TEST_DIR, "role-shipnweapon.xml"); public static final String ROLE_SHIPNWEAPON_OID = "10000000-0000-0000-0000-000000000602"; - + 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"; protected static final String EXTENSION_NS = "http://midpoint.evolveum.com/xml/ns/samples/piracy"; - + @Autowired(required = true) private ReconciliationTaskHandler reconciliationTaskHandler; @@ -140,18 +140,18 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti //when id is set it is required to be present in resource.xml (I guess) dummyResourceCtl = DummyResourceContoller.create(null, resourceDummy); DummyObjectClass dummyAdAccountObjectClass = dummyResourceCtl.getDummyResource().getAccountObjectClass(); - + //attributes dummyResourceCtl.addAttrDef(dummyAdAccountObjectClass, DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME, String.class, false, false); dummyResourceCtl.addAttrDef(dummyAdAccountObjectClass, DUMMY_ACCOUNT_ATTRIBUTE_SHIP, String.class, false, false); dummyResourceCtl.addAttrDef(dummyAdAccountObjectClass, DUMMY_ACCOUNT_ATTRIBUTE_WEAPON, String.class, false, false); - - dummyResource = dummyResourceCtl.getDummyResource(); + + dummyResource = dummyResourceCtl.getDummyResource(); resourceDummy = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_FILE, RESOURCE_DUMMY_OID, initTask, initResult); dummyResourceCtl.setResource(resourceDummy); // dummyResource.setSyncStyle(DummySyncStyle.SMART); - + // assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -164,10 +164,10 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti // Role importObjectFromFile(ROLE_ACCOUNTONLY_FILE, initResult); importObjectFromFile(ROLE_SHIPNWEAPON_FILE, initResult); - + PrismObject rolesw = getRole(ROLE_SHIPNWEAPON_OID); display("role shipNWeapon initial", rolesw); - + //User importObjectFromFile(USER_SMACK_FILE, initResult); @@ -180,12 +180,12 @@ public void test000Sanity() throws Exception { Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult testResult = modelService.testResource(RESOURCE_DUMMY_OID, task); - + TestUtil.assertSuccess(testResult); - + } - + /** * assign role "account only" * role should be assigned and fullname should be set in resource account @@ -194,43 +194,43 @@ public void test000Sanity() throws Exception { public void test010UserSmackAssignAccountOnlyRole() throws Exception { final String TEST_NAME = "test010UserSmackAssignAccountOnlyRole"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(TestNullAttribute.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // WHEN assignRole(USER_SMACK_OID, ROLE_ACCOUNTONLY_OID, task, result); - - + + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject user = getUser(USER_SMACK_OID); //display("User jack after role account only assignment", user); - + assertAssignedRole(user, ROLE_ACCOUNTONLY_OID); assertNotAssignedRole(user, ROLE_SHIPNWEAPON_OID); - + String accountOid = getLinkRefOid(user, RESOURCE_DUMMY_OID); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("accountShadow smack after role account only assignment", accountShadow); - + // Check account 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.assertNoItem(accountModel, dummyResourceCtl.getAttributePath(DUMMY_ACCOUNT_ATTRIBUTE_SHIP)); PrismAsserts.assertNoItem(accountModel, dummyResourceCtl.getAttributePath(DUMMY_ACCOUNT_ATTRIBUTE_WEAPON)); - + } - + /** * set extension/ship * role ShipNWeapon should be assigned (beacause of objecttemplate) @@ -240,16 +240,16 @@ public void test010UserSmackAssignAccountOnlyRole() throws Exception { public void test020UserSmackSetAttribute() throws Exception { final String TEST_NAME = "test020UserSmackSetAttribute"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(TestNullAttribute.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - - PrismObject smack = getUser(USER_SMACK_OID); + + PrismObject smack = getUser(USER_SMACK_OID); display("smack initial: "+smack.debugDump()); - - + + // WHEN @SuppressWarnings("unchecked, raw") Collection> deltas = @@ -261,30 +261,30 @@ public void test020UserSmackSetAttribute() throws Exception { // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject user = getUser(USER_SMACK_OID); display("User smack after setting attribute piracy:ship", user); - + assertAssignedRole(user, ROLE_ACCOUNTONLY_OID); assertAssignedRole(user, ROLE_SHIPNWEAPON_OID); - + String accountOid = getLinkRefOid(user, RESOURCE_DUMMY_OID); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("accountShadow smack after role shipnweapon assignment", accountShadow); - + // Check account 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"); // weapon is not in user's extension (MID-3326) //PrismAsserts.assertPropertyValue(accountModel, dummyResourceCtl.getAttributePath(DUMMY_ACCOUNT_ATTRIBUTE_WEAPON),"pistol"); } - + /** * remove extension/ship * role ShipNWeapon should be unassigned (beacause of objecttemplate) @@ -295,49 +295,49 @@ public void test020UserSmackSetAttribute() throws Exception { public void test030UserSmackRemoveAttribute() throws Exception { final String TEST_NAME = "test030UserSmackRemoveAttribute"; TestUtil.displayTestTitle(this, TEST_NAME); - + // GIVEN Task task = taskManager.createTaskInstance(TestNullAttribute.class.getName() + "." + TEST_NAME); 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(); + prismContext.adopt(userNewPrism); + if (userNewPrism.getExtension()==null)userNewPrism.createExtension(); PrismContainer ext = userNewPrism.getExtension(); ext.setPropertyRealValue(new QName(EXTENSION_NS, "ship"), null); ObjectDelta delta = userBefore.diff(userNewPrism); display("Modifying user with delta", delta); - + Collection> deltas = MiscSchemaUtil.createCollection(delta); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.executeChanges(deltas, null, task, result); - - + + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_SMACK_OID); display("User smack after deleting attribute piracy:ship", userAfter); - + assertAssignedRole(userAfter, ROLE_ACCOUNTONLY_OID); assertNotAssignedRole(userAfter, ROLE_SHIPNWEAPON_OID); - + String accountOid = getLinkRefOid(userAfter, RESOURCE_DUMMY_OID); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("accountShadow smack after attribute deletion", accountShadow); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("accountModel jack after attribute deletion", accountModel); 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 c6e859ee966..0010a6c586b 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 @@ -211,7 +211,7 @@ public class TestOrgSync extends AbstractStoryTest { 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"); - + protected static final int TASK_WAIT_TIMEOUT = 40000; @Autowired(required = true) @@ -237,7 +237,7 @@ public class TestOrgSync extends AbstractStoryTest { protected String getTopOrgOid() { return ORG_TOP_OID; } - + @Override protected void startResources() throws Exception { openDJController.startCleanServer(); @@ -1209,7 +1209,7 @@ public void test550ReconcileOpenDJAfterMembershipChange() throws Exception { System.out.println("group members after test = " + membersAfterTest); assertTrue(RESP_CANIBALISM_DN + " does not contain " + ACCOUNT_LEMONHEAD_DN, // ...it seems to get lowercased during the reconciliation - membersAfterTest.contains(ACCOUNT_LEMONHEAD_DN.toLowerCase())); + membersAfterTest.contains(ACCOUNT_LEMONHEAD_DN.toLowerCase())); } protected void assertUserGuybrush(PrismObject user) { 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 875a353c052..9962a248bbc 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 @@ -77,33 +77,33 @@ /** * MID-3938 - * + * * @author Radovan Semancik */ @ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestPlentyOfAssignments extends AbstractStoryTest { - + public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "plenty-of-assignments"); - + protected static final File RESOURCE_DUMMY_FILE = new File(TEST_DIR, "resource-dummy.xml"); protected static final String RESOURCE_DUMMY_OID = "10000000-0000-0000-0000-000000000004"; private static final String RESOURCE_DUMMY_NS = MidPointConstants.NS_RI; private static final QName RESOURCE_DUMMY_ASSOCIATION_GROUP_QNAME = new QName(RESOURCE_DUMMY_NS, "group"); - + public static final File USER_CHEESE_FILE = new File(TEST_DIR, "user-cheese.xml"); public static final String USER_CHEESE_OID = "9e796c76-45e0-11e7-9dfd-1792e56081d0"; - + protected static final File USER_ALICE_FILE = new File(TEST_DIR, "user-alice.xml"); protected static final String USER_ALICE_OID = "5e8fdb32-4c4c-11e7-86a8-9706c2f85f86"; protected static final String USER_ALICE_USERNAME = "alice"; protected static final String USER_ALICE_FULLNAME = "Alice"; - + protected static final File USER_BOB_FILE = new File(TEST_DIR, "user-bob.xml"); protected static final String USER_BOB_OID = "f5ffef5e-4b96-11e7-8e4c-1b0bc353a751"; protected static final String USER_BOB_USERNAME = "bob"; protected static final String USER_BOB_FULLNAME = "Bob"; - + public static final File ROLE_BASIC_FILE = new File(TEST_DIR, "role-basic.xml"); public static final String ROLE_BASIC_OID = "6909ff20-45e4-11e7-b0a3-0fe76ff4380e"; @@ -114,30 +114,30 @@ public class TestPlentyOfAssignments extends AbstractStoryTest { private static final String GENERATED_DUMMY_ROLE_OID_FORMAT = "00000000-0000-ffff-2000-d0000000%04d"; private static final int NUMBER_OF_GENERATED_DUMMY_GROUPS = 100; private static final String GENERATED_DUMMY_GROUP_ROLE_OID_FORMAT = "00000000-0000-ffff-2000-g0000000%04d"; - + private static final int NUMBER_OF_CHEESE_ASSIGNMENTS_APPROVER = 600; private static final int NUMBER_OF_CHEESE_ASSIGNMENTS_OWNER = 400; private static final int NUMBER_OF_CHEESE_ASSIGNMENTS_ORDINARY = 1; private static final int NUMBER_OF_CHEESE_ASSIGNMENTS = NUMBER_OF_CHEESE_ASSIGNMENTS_APPROVER + NUMBER_OF_CHEESE_ASSIGNMENTS_OWNER + NUMBER_OF_CHEESE_ASSIGNMENTS_ORDINARY; private static final int NUMBER_OF_BOB_DUMMY_ROLE_ASSIGNMENTS = NUMBER_OF_GENERATED_DUMMY_ROLES; - + private static final Trace LOGGER = TraceManager.getTrace(TestPlentyOfAssignments.class); - + private CountingInspector inspector; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + initDummyResourcePirate(null, RESOURCE_DUMMY_FILE, RESOURCE_DUMMY_OID, initTask, initResult); - + importObjectFromFile(ROLE_BASIC_FILE, initResult); - + ObjectFactory objectFactory = new ObjectFactory(); generateRoles(NUMBER_OF_GENERATED_EMPTY_ROLES, "Empty Role %04d", GENERATED_EMPTY_ROLE_OID_FORMAT, null, initResult); - generateRoles(NUMBER_OF_GENERATED_DUMMY_ROLES, "Dummy Role %04d", GENERATED_DUMMY_ROLE_OID_FORMAT, + generateRoles(NUMBER_OF_GENERATED_DUMMY_ROLES, "Dummy Role %04d", GENERATED_DUMMY_ROLE_OID_FORMAT, (role,i) -> { ItemPathType attrPath = new ItemPathType( new ItemPath(new QName(RESOURCE_DUMMY_NS, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME))); @@ -158,7 +158,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti // throw new SystemException(e); // } }, initResult); - + inspector = new CountingInspector(); InternalMonitor.setInspector(inspector); } @@ -166,26 +166,26 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti private String generateRoleOid(String format, int num) { return String.format(format, num); } - + private String formatRum(int num) { return String.format("bottle of rum #%04d", num); } - + private String formatGroupName(int num) { return String.format("G#%04d", num); } - + @Test public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; displayTestTitle(TEST_NAME); 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)); display("Object compares", InternalMonitor.getCount(InternalCounters.PRISM_OBJECT_COMPARE_COUNT)); } - + @Test public void test100AddCheese() throws Exception { final String TEST_NAME = "test100AddCheese"; @@ -193,43 +193,43 @@ public void test100AddCheese() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject cheeseBefore = prepareCheese(); display("Cheese before", assignmentSummary(cheeseBefore)); - + inspector.reset(); rememberCounter(InternalCounters.PRISM_OBJECT_COMPARE_COUNT); rememberCounter(InternalCounters.REPOSITORY_READ_COUNT); long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); - + addObject(cheeseBefore, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Added cheese in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/NUMBER_OF_CHEESE_ASSIGNMENTS)+"ms per assignment)"); - + PrismObject cheeseAfter = getUser(USER_CHEESE_OID); display("Cheese after", assignmentSummary(cheeseAfter)); assertCheeseRoleMembershipRef(cheeseAfter); - + display("Repo reads", InternalMonitor.getCount(InternalCounters.REPOSITORY_READ_COUNT)); display("Object compares", InternalMonitor.getCount(InternalCounters.PRISM_OBJECT_COMPARE_COUNT)); display("Inspector", inspector); - + // inspector.assertRead(RoleType.class, NUMBER_OF_CHEESE_ASSIGNMENTS); // assertRepositoryReadCount(xxx); // may be influenced by tasks - + assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - - + + @Test public void test110RecomputeCheese() throws Exception { final String TEST_NAME = "test110RecomputeCheese"; @@ -237,41 +237,41 @@ public void test110RecomputeCheese() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject cheeseBefore = prepareCheese(); display("Cheese before", assignmentSummary(cheeseBefore)); - + inspector.reset(); rememberCounter(InternalCounters.PRISM_OBJECT_COMPARE_COUNT); rememberCounter(InternalCounters.REPOSITORY_READ_COUNT); long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); - + recomputeUser(USER_CHEESE_OID, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Recomputed cheese in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/NUMBER_OF_CHEESE_ASSIGNMENTS)+"ms per assignment)"); - + PrismObject cheeseAfter = getUser(USER_CHEESE_OID); display("Cheese after", assignmentSummary(cheeseAfter)); assertCheeseRoleMembershipRef(cheeseAfter); - + display("Repo reads", InternalMonitor.getCount(InternalCounters.REPOSITORY_READ_COUNT)); display("Object compares", InternalMonitor.getCount(InternalCounters.PRISM_OBJECT_COMPARE_COUNT)); - + display("Inspector", inspector); inspector.assertRead(RoleType.class, 1); // assertRepositoryReadCount(4); // may be influenced by tasks assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + @Test public void test120CheesePreviewChanges() throws Exception { final String TEST_NAME = "test120CheesePreviewChanges"; @@ -279,37 +279,37 @@ public void test120CheesePreviewChanges() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject cheeseBefore = prepareCheese(); display("Cheese before", assignmentSummary(cheeseBefore)); - + ObjectDelta delta = cheeseBefore.createModifyDelta(); delta.addModificationReplaceProperty(UserType.F_EMPLOYEE_NUMBER, "123"); - + inspector.reset(); rememberCounter(InternalCounters.PRISM_OBJECT_COMPARE_COUNT); rememberCounter(InternalCounters.REPOSITORY_READ_COUNT); long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); - + ModelContext modelContext = modelInteractionService.previewChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Preview cheese in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/NUMBER_OF_CHEESE_ASSIGNMENTS)+"ms per assignment)"); - + PrismObject cheeseAfter = getUser(USER_CHEESE_OID); display("Cheese after", assignmentSummary(cheeseAfter)); assertCheeseRoleMembershipRef(cheeseAfter); - + display("Repo reads", InternalMonitor.getCount(InternalCounters.REPOSITORY_READ_COUNT)); display("Object compares", InternalMonitor.getCount(InternalCounters.PRISM_OBJECT_COMPARE_COUNT)); - + display("Inspector", inspector); inspector.assertRead(RoleType.class, 1); @@ -323,22 +323,22 @@ private PrismObject prepareCheese() throws Exception { addAssignments(cheese, GENERATED_EMPTY_ROLE_OID_FORMAT, SchemaConstants.ORG_OWNER, NUMBER_OF_CHEESE_ASSIGNMENTS_APPROVER, NUMBER_OF_CHEESE_ASSIGNMENTS_OWNER); return cheese; } - + private void assertCheeseRoleMembershipRef(PrismObject cheese) { - + assertRoleMembershipRefs(cheese, GENERATED_EMPTY_ROLE_OID_FORMAT, SchemaConstants.ORG_APPROVER, 0, NUMBER_OF_CHEESE_ASSIGNMENTS_APPROVER); assertRoleMembershipRefs(cheese, GENERATED_EMPTY_ROLE_OID_FORMAT, SchemaConstants.ORG_OWNER, NUMBER_OF_CHEESE_ASSIGNMENTS_APPROVER, NUMBER_OF_CHEESE_ASSIGNMENTS_OWNER); - + assertRoleMembershipRef(cheese, ROLE_BASIC_OID, SchemaConstants.ORG_DEFAULT); - + assertRoleMembershipRefs(cheese, NUMBER_OF_CHEESE_ASSIGNMENTS); } - - + + /** * Create dummy groups that can be used for associationTargetSearch later on. * Create them from midPoint so they have shadows. - * + * * MID-3938 #8 */ @Test @@ -348,7 +348,7 @@ public void test200DummyGroups() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + // WHEN displayWhen(TEST_NAME); @@ -356,7 +356,7 @@ public void test200DummyGroups() throws Exception { PrismObjectDefinition roleDef = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(RoleType.class); RefinedResourceSchema rSchema = RefinedResourceSchema.getRefinedSchema(getDummyResourceObject()); ObjectClassComplexTypeDefinition rOcDef = rSchema.findObjectClassDefinition(getDummyResourceController().getGroupObjectClass()); - + ObjectFactory objectFactory = new ObjectFactory(); ItemPath nameAttributePath = new ItemPath(ShadowType.F_ATTRIBUTES, SchemaConstants.ICFS_NAME); for (int i=0; i role = roleDef.instantiate(); RoleType roleType = role.asObjectable(); ItemPathType assPath = new ItemPathType(new ItemPath(RESOURCE_DUMMY_ASSOCIATION_GROUP_QNAME)); SearchObjectExpressionEvaluatorType associationTargetSearchType = new SearchObjectExpressionEvaluatorType(); EqualFilter filter = EqualFilter.createEqual(nameAttributePath, null, null, prismContext, groupName); - + SearchFilterType filterType = QueryJaxbConvertor.createSearchFilterType(filter, prismContext); associationTargetSearchType.setFilter(filterType); associationTargetSearchType.setSearchStrategy(ObjectSearchStrategyType.IN_REPOSITORY); @@ -401,18 +401,18 @@ public void test200DummyGroups() throws Exception { } addObject(role, task, result); } - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + Collection dummyGroups = getDummyResource().listGroups(); assertEquals("Wrong number of dummy groups", NUMBER_OF_GENERATED_DUMMY_GROUPS, dummyGroups.size()); assertShadows(NUMBER_OF_GENERATED_DUMMY_GROUPS); - + assertObjects(RoleType.class, NUMBER_OF_GENERATED_EMPTY_ROLES + NUMBER_OF_GENERATED_DUMMY_ROLES + NUMBER_OF_ORDINARY_ROLES + NUMBER_OF_GENERATED_DUMMY_GROUPS); } - + /** * MID-3938 #8 */ @@ -423,46 +423,46 @@ public void test210AddBob() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = PrismTestUtil.parseObject(USER_BOB_FILE); addAssignments(userBefore, GENERATED_DUMMY_ROLE_OID_FORMAT, null, 0, NUMBER_OF_BOB_DUMMY_ROLE_ASSIGNMENTS); display("User before", assignmentSummary(userBefore)); - + inspector.reset(); rememberCounter(InternalCounters.PRISM_OBJECT_COMPARE_COUNT); rememberCounter(InternalCounters.REPOSITORY_READ_COUNT); long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); - + addObject(userBefore, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Added bob in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/NUMBER_OF_BOB_DUMMY_ROLE_ASSIGNMENTS)+"ms per assignment)"); - + PrismObject userAfter = getUser(USER_BOB_OID); display("User after", assignmentSummary(userAfter)); assertBobRoleMembershipRef(userAfter); - + display("Repo reads", InternalMonitor.getCount(InternalCounters.REPOSITORY_READ_COUNT)); display("Object compares", InternalMonitor.getCount(InternalCounters.PRISM_OBJECT_COMPARE_COUNT)); display("Inspector", inspector); - + // TODO: why *3 ??? inspector.assertRead(RoleType.class, NUMBER_OF_BOB_DUMMY_ROLE_ASSIGNMENTS * 3); // assertRepositoryReadCount(xxx); // may be influenced by tasks - + assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); - + assertBobDummy(NUMBER_OF_BOB_DUMMY_ROLE_ASSIGNMENTS); } - + /** * MID-3938 #8 */ @@ -473,41 +473,41 @@ public void test212RecomputeBob() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + inspector.reset(); rememberCounter(InternalCounters.PRISM_OBJECT_COMPARE_COUNT); rememberCounter(InternalCounters.REPOSITORY_READ_COUNT); long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); - + recomputeUser(USER_BOB_OID, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Recomputed bob in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/NUMBER_OF_BOB_DUMMY_ROLE_ASSIGNMENTS)+"ms per assignment)"); - + PrismObject userAfter = getUser(USER_BOB_OID); display("User after", assignmentSummary(userAfter)); assertBobRoleMembershipRef(userAfter); - + display("Repo reads", InternalMonitor.getCount(InternalCounters.REPOSITORY_READ_COUNT)); display("Object compares", InternalMonitor.getCount(InternalCounters.PRISM_OBJECT_COMPARE_COUNT)); display("Inspector", inspector); - + inspector.assertRead(RoleType.class, NUMBER_OF_BOB_DUMMY_ROLE_ASSIGNMENTS); // assertRepositoryReadCount(xxx); // may be influenced by tasks - + assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); - + assertBobDummy(NUMBER_OF_BOB_DUMMY_ROLE_ASSIGNMENTS); } - + /** * MID-3938 #8 */ @@ -518,47 +518,47 @@ public void test2124ReconcileBob() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + inspector.reset(); rememberCounter(InternalCounters.PRISM_OBJECT_COMPARE_COUNT); rememberCounter(InternalCounters.REPOSITORY_READ_COUNT); long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); - + reconcileUser(USER_BOB_OID, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Reconciled bob in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/NUMBER_OF_BOB_DUMMY_ROLE_ASSIGNMENTS)+"ms per assignment)"); - + PrismObject userAfter = getUser(USER_BOB_OID); display("User after", assignmentSummary(userAfter)); assertBobRoleMembershipRef(userAfter); - + display("Repo reads", InternalMonitor.getCount(InternalCounters.REPOSITORY_READ_COUNT)); display("Object compares", InternalMonitor.getCount(InternalCounters.PRISM_OBJECT_COMPARE_COUNT)); display("Inspector", inspector); - + inspector.assertRead(RoleType.class, NUMBER_OF_BOB_DUMMY_ROLE_ASSIGNMENTS); // assertRepositoryReadCount(xxx); // may be influenced by tasks - + assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); - + assertBobDummy(NUMBER_OF_BOB_DUMMY_ROLE_ASSIGNMENTS); } private void assertBobRoleMembershipRef(PrismObject user) { - + assertRoleMembershipRefs(user, GENERATED_DUMMY_ROLE_OID_FORMAT, null, 0, NUMBER_OF_BOB_DUMMY_ROLE_ASSIGNMENTS); assertRoleMembershipRefs(user, NUMBER_OF_BOB_DUMMY_ROLE_ASSIGNMENTS); } - + private void assertBobDummy(int expectedBottlesOfRum) throws Exception { DummyAccount dummyAccount = assertDummyAccount(null, USER_BOB_USERNAME, USER_BOB_FULLNAME, true); display("Dummy account", dummyAccount); @@ -567,10 +567,10 @@ private void assertBobDummy(int expectedBottlesOfRum) throws Exception { expectedDrinks.add(formatRum(i)); } expectedDrinks.add("barrel of rum"); - assertDummyAccountAttribute(null, USER_BOB_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, + assertDummyAccountAttribute(null, USER_BOB_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, expectedDrinks.toArray()); } - + /** * MID-3938 #8 */ @@ -581,46 +581,46 @@ public void test220AddAlice() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = PrismTestUtil.parseObject(USER_ALICE_FILE); addAssignments(userBefore, GENERATED_DUMMY_GROUP_ROLE_OID_FORMAT, null, 0, NUMBER_OF_GENERATED_DUMMY_GROUPS); display("User before", assignmentSummary(userBefore)); - + inspector.reset(); rememberCounter(InternalCounters.PRISM_OBJECT_COMPARE_COUNT); rememberCounter(InternalCounters.REPOSITORY_READ_COUNT); long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); - + addObject(userBefore, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Added alice in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/NUMBER_OF_GENERATED_DUMMY_GROUPS)+"ms per assignment)"); - + PrismObject userAfter = getUser(USER_ALICE_OID); display("User after", assignmentSummary(userAfter)); assertAliceRoleMembershipRef(userAfter); - + display("Repo reads", InternalMonitor.getCount(InternalCounters.REPOSITORY_READ_COUNT)); display("Object compares", InternalMonitor.getCount(InternalCounters.PRISM_OBJECT_COMPARE_COUNT)); display("Inspector", inspector); - + // TODO: why *3 ??? inspector.assertRead(RoleType.class, NUMBER_OF_GENERATED_DUMMY_GROUPS * 3); // assertRepositoryReadCount(xxx); // may be influenced by tasks - + assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); - + assertAliceDummy(NUMBER_OF_GENERATED_DUMMY_GROUPS); } - + /** * MID-3938 #8 */ @@ -631,41 +631,41 @@ public void test222RecomputeAlice() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + inspector.reset(); rememberCounter(InternalCounters.PRISM_OBJECT_COMPARE_COUNT); rememberCounter(InternalCounters.REPOSITORY_READ_COUNT); long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); - + recomputeUser(USER_ALICE_OID, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Recomputed alice in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/NUMBER_OF_GENERATED_DUMMY_GROUPS)+"ms per assignment)"); - + PrismObject userAfter = getUser(USER_ALICE_OID); display("User after", assignmentSummary(userAfter)); assertAliceRoleMembershipRef(userAfter); - + display("Repo reads", InternalMonitor.getCount(InternalCounters.REPOSITORY_READ_COUNT)); display("Object compares", InternalMonitor.getCount(InternalCounters.PRISM_OBJECT_COMPARE_COUNT)); display("Inspector", inspector); - + inspector.assertRead(RoleType.class, NUMBER_OF_GENERATED_DUMMY_GROUPS); // assertRepositoryReadCount(xxx); // may be influenced by tasks - + assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); - + assertAliceDummy(NUMBER_OF_GENERATED_DUMMY_GROUPS); } - + /** * MID-3938 #8 */ @@ -676,47 +676,47 @@ public void test224ReconcileAlice() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + inspector.reset(); rememberCounter(InternalCounters.PRISM_OBJECT_COMPARE_COUNT); rememberCounter(InternalCounters.REPOSITORY_READ_COUNT); long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); - + reconcileUser(USER_ALICE_OID, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Reconciled alice in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/NUMBER_OF_GENERATED_DUMMY_GROUPS)+"ms per assignment)"); - + PrismObject userAfter = getUser(USER_ALICE_OID); display("User after", assignmentSummary(userAfter)); assertAliceRoleMembershipRef(userAfter); - + display("Repo reads", InternalMonitor.getCount(InternalCounters.REPOSITORY_READ_COUNT)); display("Object compares", InternalMonitor.getCount(InternalCounters.PRISM_OBJECT_COMPARE_COUNT)); - + display("Inspector", inspector); - + inspector.assertRead(RoleType.class, NUMBER_OF_GENERATED_DUMMY_GROUPS); // assertRepositoryReadCount(xxx); // may be influenced by tasks - + assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); - + assertAliceDummy(NUMBER_OF_GENERATED_DUMMY_GROUPS); } - + private void assertAliceRoleMembershipRef(PrismObject user) { - + assertRoleMembershipRefs(user, GENERATED_DUMMY_GROUP_ROLE_OID_FORMAT, null, 0, NUMBER_OF_GENERATED_DUMMY_GROUPS); assertRoleMembershipRefs(user, NUMBER_OF_GENERATED_DUMMY_GROUPS); } - + private void assertAliceDummy(int expectedGroups) throws Exception { DummyAccount dummyAccount = assertDummyAccount(null, USER_ALICE_USERNAME, USER_ALICE_FULLNAME, true); display("Dummy account", dummyAccount); @@ -724,7 +724,7 @@ private void assertAliceDummy(int expectedGroups) throws Exception { assertDummyGroupMember(null, formatGroupName(i), USER_ALICE_USERNAME); } } - + private void addAssignments(PrismObject user, String roleOidFormat, QName relation, int offset, int num) { UserType userType = user.asObjectable(); for (int i = 0; i < num; i++) { @@ -744,7 +744,7 @@ private void assertRoleMembershipRefs(PrismObject user, String roleOid private void assertRoleMembershipRef(PrismObject user, String roleOidFormat, QName relation, int num) { assertRoleMembershipRef(user, generateRoleOid(roleOidFormat, num), relation); } - + private void assertRoleMembershipRef(PrismObject user, String roleOid, QName relation) { List roleMembershipRefs = user.asObjectable().getRoleMembershipRef(); for (ObjectReferenceType roleMembershipRef: roleMembershipRefs) { 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 79dc877dfa8..d3656aec1b9 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 @@ -87,9 +87,9 @@ @ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestRetirement extends AbstractStoryTest { - + public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "retirement"); - + 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; @@ -97,11 +97,11 @@ public class TestRetirement extends AbstractStoryTest { 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"; @@ -119,7 +119,7 @@ public class TestRetirement extends AbstractStoryTest { protected static final String USER_TELEKE_USERNAME = "teleke"; protected static final String USER_TELEKE_GIVEN_NAME = "Felix"; 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"; @@ -128,7 +128,7 @@ public class TestRetirement extends AbstractStoryTest { protected static final String USER_DEZI_USERNAME = "dezi"; protected static final String USER_DEZI_GIVEN_NAME = "Vilja"; protected static final String USER_DEZI_FAMILY_NAME = "Dézi"; - + protected ResourceType resourceOpenDjType; protected PrismObject resourceOpenDj; @@ -137,12 +137,12 @@ public class TestRetirement extends AbstractStoryTest { protected String orgVysneVlkodlakyOid; protected String orgRolyulaDiabolicaOid; protected String userGorcOid; - + @Override protected String getTopOrgOid() { return ORG_TOP_OID; } - + @Override protected void startResources() throws Exception { openDJController.startCleanServerRI(); @@ -152,13 +152,13 @@ protected void startResources() throws Exception { public static void stopResources() throws Exception { openDJController.stop(); } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - - - // Resources + + + // Resources resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, RESOURCE_OPENDJ_FILE, RESOURCE_OPENDJ_OID, initTask, initResult); resourceOpenDjType = resourceOpenDj.asObjectable(); openDJController.setResource(resourceOpenDj); @@ -169,20 +169,20 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti // Role importObjectFromFile(ROLE_META_ORG_FILE, initResult); } - + @Test public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + OperationResult testResultOpenDj = modelService.testResource(RESOURCE_OPENDJ_OID, task); TestUtil.assertSuccess(testResultOpenDj); dumpOrgTree(); dumpLdap(); } - + @Test public void test050AddOrgRetired() throws Exception { final String TEST_NAME = "test050AddOrgRetired"; @@ -191,7 +191,7 @@ public void test050AddOrgRetired() throws Exception { OperationResult result = task.getResult(); PrismObject orgBefore = PrismTestUtil.parseObject(ORG_RETIRED_FILE); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("Adding org", orgBefore); @@ -201,10 +201,10 @@ public void test050AddOrgRetired() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject org = getObject(OrgType.class, ORG_RETIRED_OID); display("org", org); PrismAsserts.assertPropertyValue(org, OrgType.F_ORG_TYPE, ORG_TYPE_FUNCTIONAL); @@ -219,9 +219,9 @@ public void test050AddOrgRetired() throws Exception { display("OU retirement entry", openDJController.toHumanReadableLdifoid(ouEntry)); openDJController.assertObjectClass(ouEntry, "organizationalUnit"); - assertSubOrgs(org, 0); + assertSubOrgs(org, 0); } - + @Test public void test100AddOrgRoyulaCarpathia() throws Exception { final String TEST_NAME = "test100AddOrgRoyulaCarpathia"; @@ -230,7 +230,7 @@ public void test100AddOrgRoyulaCarpathia() throws Exception { OperationResult result = task.getResult(); PrismObject orgBefore = createOrg(ORG_ROYULA_CARPATHIA_NAME, ORG_TOP_OID); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("Adding org", orgBefore); @@ -240,17 +240,17 @@ public void test100AddOrgRoyulaCarpathia() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject orgAfter = getAndAssertFunctionalOrg(ORG_ROYULA_CARPATHIA_NAME, ORG_TOP_OID); orgRolyulaCarpathiaOid = orgAfter.getOid(); assertSubOrgs(orgAfter, 0); assertSubOrgs(ORG_TOP_OID, 1); } - + @Test public void test110AddUserTeleke() throws Exception { final String TEST_NAME = "test110AddUserTeleke"; @@ -258,9 +258,9 @@ public void test110AddUserTeleke() throws Exception { Task task = taskManager.createTaskInstance(TestRetirement.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - PrismObject userBefore = createUser(USER_TELEKE_USERNAME, + PrismObject userBefore = createUser(USER_TELEKE_USERNAME, USER_TELEKE_GIVEN_NAME, USER_TELEKE_FAMILY_NAME, orgRolyulaCarpathiaOid); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("Adding user", userBefore); @@ -270,9 +270,9 @@ public void test110AddUserTeleke() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getAndAssertUser(USER_TELEKE_USERNAME, ORG_ROYULA_CARPATHIA_NAME); - + PrismObject orgAfter = getAndAssertFunctionalOrg(ORG_ROYULA_CARPATHIA_NAME, ORG_TOP_OID); dumpOrgTree(); @@ -281,7 +281,7 @@ public void test110AddUserTeleke() throws Exception { assertSubOrgs(orgAfter, 0); assertSubOrgs(ORG_TOP_OID, 1); } - + @Test public void test200AddOrgCortuvHrad() throws Exception { final String TEST_NAME = "test200AddOrgCortuvHrad"; @@ -290,7 +290,7 @@ public void test200AddOrgCortuvHrad() throws Exception { OperationResult result = task.getResult(); PrismObject orgBefore = createOrg(ORG_CORTUV_HRAD_NAME, orgRolyulaCarpathiaOid); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("Adding org", orgBefore); @@ -300,7 +300,7 @@ public void test200AddOrgCortuvHrad() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject orgAfter = getAndAssertFunctionalOrg(ORG_CORTUV_HRAD_NAME, orgRolyulaCarpathiaOid); orgCortuvHradOid = orgAfter.getOid(); @@ -311,7 +311,7 @@ public void test200AddOrgCortuvHrad() throws Exception { assertSubOrgs(orgRolyulaCarpathiaOid, 1); assertSubOrgs(ORG_TOP_OID, 1); } - + @Test public void test210AddUserGorc() throws Exception { final String TEST_NAME = "test210AddUserGorc"; @@ -319,9 +319,9 @@ public void test210AddUserGorc() throws Exception { Task task = taskManager.createTaskInstance(TestRetirement.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - PrismObject userBefore = createUser(USER_GORC_USERNAME, + PrismObject userBefore = createUser(USER_GORC_USERNAME, USER_GORC_GIVEN_NAME, USER_GORC_FAMILY_NAME, orgCortuvHradOid); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("Adding user", userBefore); @@ -331,10 +331,10 @@ public void test210AddUserGorc() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getAndAssertUser(USER_GORC_USERNAME, ORG_CORTUV_HRAD_NAME, ORG_ROYULA_CARPATHIA_NAME); userGorcOid = userAfter.getOid(); - + dumpOrgTree(); dumpLdap(); } @@ -347,7 +347,7 @@ public void test220AddOrgVysneVlkodlaky() throws Exception { OperationResult result = task.getResult(); PrismObject orgBefore = createOrg(ORG_VYSNE_VLKODLAKY_NAME, orgCortuvHradOid); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("Adding org", orgBefore); @@ -357,7 +357,7 @@ public void test220AddOrgVysneVlkodlaky() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject orgAfter = getAndAssertFunctionalOrg(ORG_VYSNE_VLKODLAKY_NAME, orgCortuvHradOid); orgVysneVlkodlakyOid = orgAfter.getOid(); @@ -368,7 +368,7 @@ public void test220AddOrgVysneVlkodlaky() throws Exception { assertSubOrgs(orgRolyulaCarpathiaOid, 1); assertSubOrgs(ORG_TOP_OID, 1); } - + @Test public void test230AddUserViljaDezi() throws Exception { final String TEST_NAME = "test230AddUserViljaDezi"; @@ -376,9 +376,9 @@ public void test230AddUserViljaDezi() throws Exception { Task task = taskManager.createTaskInstance(TestRetirement.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - PrismObject userBefore = createUser(USER_DEZI_USERNAME, + PrismObject userBefore = createUser(USER_DEZI_USERNAME, USER_DEZI_GIVEN_NAME, USER_DEZI_FAMILY_NAME, orgVysneVlkodlakyOid); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("Adding user", userBefore); @@ -388,9 +388,9 @@ public void test230AddUserViljaDezi() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getAndAssertUser(USER_DEZI_USERNAME, ORG_VYSNE_VLKODLAKY_NAME, ORG_CORTUV_HRAD_NAME, ORG_ROYULA_CARPATHIA_NAME); - + dumpOrgTree(); dumpLdap(); } @@ -416,14 +416,14 @@ public void test300RetireUserGorc() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject userAfter = getAndAssertRetiredUser(USER_GORC_USERNAME); userGorcOid = userAfter.getOid(); } - + @Test public void test302ReconcileUserGorc() throws Exception { final String TEST_NAME = "test302ReconcileUserGorc"; @@ -439,14 +439,14 @@ public void test302ReconcileUserGorc() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject userAfter = getAndAssertRetiredUser(USER_GORC_USERNAME); userGorcOid = userAfter.getOid(); } - + @Test public void test303ReconcileUserGorcAgain() throws Exception { final String TEST_NAME = "test303ReconcileUserGorcAgain"; @@ -462,10 +462,10 @@ public void test303ReconcileUserGorcAgain() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject userAfter = getAndAssertRetiredUser(USER_GORC_USERNAME); userGorcOid = userAfter.getOid(); } @@ -524,10 +524,10 @@ private PrismObject getAndAssertUser(String username, String directOrg assertNotNull("No account LDAP entry for "+username, accountEntry); display("account entry", openDJController.toHumanReadableLdifoid(accountEntry)); openDJController.assertObjectClass(accountEntry, "inetOrgPerson"); - + return user; } - + private PrismObject getAndAssertRetiredUser(String username) throws SchemaException, CommonException, SecurityViolationException, CommunicationException, ConfigurationException, DirectoryException { PrismObject user = findUserByUsername(username); display("user", user); @@ -542,7 +542,7 @@ private PrismObject getAndAssertRetiredUser(String username) throws Sc assertNotNull("No account LDAP entry for "+username+" ("+dn+")", accountEntry); display("account entry", openDJController.toHumanReadableLdifoid(accountEntry)); openDJController.assertObjectClass(accountEntry, "inetOrgPerson"); - + return user; } @@ -567,12 +567,12 @@ private PrismObject getAndAssertFunctionalOrg(String orgName, String di return org; } - + 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); @@ -584,7 +584,7 @@ private void assertNoGroupMembers(PrismObject org) throws Exception { PrismObject groupShadow = getShadowModel(groupOid); assertNoAttribute(resourceOpenDj, groupShadow.asObjectable(), new QName(MidPointConstants.NS_RI, "uniqueMember")); } - + private void reconcileAllUsers() throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { final Task task = createTask("reconcileAllUsers"); OperationResult result = task.getResult(); @@ -605,7 +605,7 @@ public boolean handle(PrismObject object, OperationResult parentResult 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 = createTask("reconcileAllOrgs"); OperationResult result = task.getResult(); @@ -626,5 +626,5 @@ public boolean handle(PrismObject object, OperationResult parentResult) 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 ae5a50edba8..a49c4fbdc61 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 @@ -50,7 +50,7 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; /** - * + * * @author Katarina Valalikova * */ @@ -58,57 +58,57 @@ @ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestScience extends AbstractStoryTest { - + private static final String TEST_DIR = "src/test/resources/science"; - + public static final String NS_SCIENCE_EXT = "http://midpoint.evolveum.com/xml/ns/science/user/ext"; private static final QName SCIENCE_EXTENSION_UID_QNAME = new QName(NS_SCIENCE_EXT, "aixUserId"); - + 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"); private static final String RESOURCE_OPENDJ_AD_SIMULATION_OID = "10000000-0000-0000-0000-0000000001ad"; - + private static final File RESOURCE_DUMMY_STATS_FILE = new File(TEST_DIR, "resource-dummy-stats.xml"); private static final String RESOURCE_DUMMY_STATS_OID = "10000000-0000-0000-0000-0000000005sa"; protected static final String RESOURCE_DUMMY_STATS_ID = "stats"; - + private static final File RESOURCE_DUMMY_UNIX_FILE = new File(TEST_DIR, "resource-dummy-unix.xml"); private static final String RESOURCE_DUMMY_UNIX_OID = "10000000-0000-0000-0000-0000000004ax"; protected static final String RESOURCE_DUMMY_UNIX_ID = "unix"; - + private static final String DUMMY_ACCOUNT_ATTRIBUTE_UNIX_SHELL_NAME = "Shell"; private static final String DUMMY_ACCOUNT_ATTRIBUTE_UNIX_SYSTEM_NAME = "SYSTEM"; private static final String DUMMY_ACCOUNT_ATTRIBUTE_UNIX_DIR_NAME = "Dir"; private static final String DUMMY_ACCOUNT_ATTRIBUTE_UNIX_UID_NAME = "Uid"; private static final String DUMMY_ACCOUNT_ATTRIBUTE_UNIX_DESCRIPTION_NAME = "Description"; - + private static final String DUMMY_ACCOUNT_ATTRIBUTE_STATS_DESC_NAME = "Desc"; - + private static final String NS_RESOURCE_INSTANCE = "http://midpoint.evolveum.com/xml/ns/public/resource/instance-3"; - + private static final QName UNIX_INTERNAL_ID = new QName(NS_RESOURCE_INSTANCE, DummyAccount.ATTR_INTERNAL_ID); - - + + protected static DummyResource dummyResourceUnix; protected static DummyResourceContoller dummyResourceCtlUnix; protected ResourceType resourceDummyUnixType; protected PrismObject resourceDummyUnix; - + protected static DummyResource dummyResourceStats; protected static DummyResourceContoller dummyResourceCtlStats; protected ResourceType resourceDummyStatsType; protected PrismObject resourceDummyStats; - + protected ResourceType resourceOpenDjType; protected PrismObject resourceOpenDj; - + @Override protected void startResources() throws Exception { openDJController.startCleanServer(); @@ -118,21 +118,21 @@ protected void startResources() throws Exception { public static void stopResources() throws Exception { openDJController.stop(); } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + // Roles repoAddObjectFromFile(ROLE_STATISTICS_FILE, initResult); // repoAddObjectFromFile(ROLE_MATH_FILE, RoleType.class, initResult); - + resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, RESOURCE_OPENDJ_AD_SIMULATION_FILE, RESOURCE_OPENDJ_AD_SIMULATION_OID, initTask, initResult); resourceOpenDjType = resourceOpenDj.asObjectable(); openDJController.setResource(resourceOpenDj); - + openDJController.addEntryFromLdifFile(GROUP_STATS_USERS_LDIF_FILE); - + // Resources dummyResourceCtlUnix = DummyResourceContoller.create(RESOURCE_DUMMY_UNIX_ID, resourceDummyUnix); dummyResourceCtlUnix.populateWithDefaultSchema(); @@ -147,17 +147,17 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti resourceDummyUnix = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_UNIX_FILE, RESOURCE_DUMMY_UNIX_OID, initTask, initResult); resourceDummyUnixType = resourceDummyUnix.asObjectable(); dummyResourceCtlUnix.setResource(resourceDummyUnix); - + dummyResourceCtlStats = DummyResourceContoller.create(RESOURCE_DUMMY_STATS_ID, resourceDummyStats); dummyResourceCtlStats.populateWithDefaultSchema(); DummyObjectClass dummyStatsAccountObjectClass = dummyResourceCtlStats.getDummyResource().getAccountObjectClass(); dummyResourceCtlStats.addAttrDef(dummyStatsAccountObjectClass, DUMMY_ACCOUNT_ATTRIBUTE_STATS_DESC_NAME, String.class, false, false); - + dummyResourceStats = dummyResourceCtlStats.getDummyResource(); resourceDummyStats = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_STATS_FILE, RESOURCE_DUMMY_STATS_OID, initTask, initResult); resourceDummyStatsType = resourceDummyStats.asObjectable(); dummyResourceCtlStats.setResource(resourceDummyStats); - + } @Test @@ -165,130 +165,130 @@ public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestScience.class.getName() + "." + TEST_NAME); - + OperationResult testResultStats = modelService.testResource(RESOURCE_DUMMY_STATS_OID, task); TestUtil.assertSuccess(testResultStats); - + OperationResult testResultUnix = modelService.testResource(RESOURCE_DUMMY_UNIX_OID, task); TestUtil.assertSuccess(testResultUnix); - + OperationResult testResultAd = modelService.testResource(RESOURCE_OPENDJ_AD_SIMULATION_OID, task); TestUtil.assertSuccess(testResultAd); - + waitForTaskStart(TASK_TRIGGER_SCANNER_OID, true); waitForTaskStart(TASK_VALIDITY_SCANNER_OID, true); } - + @Test public void test100JackAssignRoleStatistics() throws Exception { final String TEST_NAME = "test100JackAssignRoleStatistics"; TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestScience.class.getName() + "." + TEST_NAME); - + OperationResult result = task.getResult(); - + assignRole(USER_JACK_OID, ROLE_STATISTICS_OID); - + PrismObject userJack = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); AssertJUnit.assertNotNull("User jack not found", userJack); UserType jackType = userJack.asObjectable(); - + IntegrationTestTools.display("User Jack", jackType); - + AssertJUnit.assertEquals("Wrong number of link refs", 3, jackType.getLinkRef().size()); - + assertUserJack(userJack); assertLinks(userJack, 3); String accountStatsOid = getLinkRefOid(userJack, RESOURCE_DUMMY_STATS_OID); String accountUnixOid = getLinkRefOid(userJack, RESOURCE_DUMMY_UNIX_OID); String accountOpenDjOid = getLinkRefOid(userJack, RESOURCE_OPENDJ_AD_SIMULATION_OID); - + PrismObject shadowStats = provisioningService.getObject(ShadowType.class, accountStatsOid, null, task, result); IntegrationTestTools.display("Stats account: ", shadowStats); PrismObject shadowUnix = provisioningService.getObject(ShadowType.class, accountUnixOid, null, task, result); IntegrationTestTools.display("Unix account: ", shadowUnix); PrismObject shadowOpenDj = provisioningService.getObject(ShadowType.class, accountOpenDjOid, null, task, result); IntegrationTestTools.display("AD account: ", shadowOpenDj); - - + + //internalId on unix dummy resource and title on openDJ simulation must be the same PrismProperty unixId = shadowUnix.findProperty(new ItemPath(ShadowType.F_ATTRIBUTES, UNIX_INTERNAL_ID)); assertNotNull("No "+UNIX_INTERNAL_ID+" in "+shadowUnix, unixId); PrismProperty openDjSyncedId = shadowOpenDj.findProperty(new ItemPath(ShadowType.F_ATTRIBUTES, new QName(NS_RESOURCE_INSTANCE, "title"))); assertNotNull("No 'title' in "+shadowOpenDj, openDjSyncedId); PrismAsserts.assertEquals("Unix id was not synced to the opendj properly.", String.valueOf(unixId.getAnyRealValue()), openDjSyncedId.getAnyRealValue()); - + PrismProperty generatedValue = userJack.findExtensionItem(SCIENCE_EXTENSION_UID_QNAME); assertNotNull("Generated id value must not be null", generatedValue); assertFalse("Generated value must not be empty", generatedValue.isEmpty()); - + } - + @Test public void test101UnassignRoleStats() throws Exception{ final String TEST_NAME = "test101UnassignRoleStats"; TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestScience.class.getName() + "." + TEST_NAME); - + OperationResult result = task.getResult(); - - + + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - + unassignRole(USER_JACK_OID, ROLE_STATISTICS_OID); - - + + PrismObject userJack = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); AssertJUnit.assertNotNull("User jack not found", userJack); UserType jackType = userJack.asObjectable(); - + IntegrationTestTools.display("User Jack", jackType); - + AssertJUnit.assertEquals("Wrong number of link refs", 3, jackType.getLinkRef().size()); - + assertUserJack(userJack); assertLinks(userJack, 3); String accountStatsOid = getLinkRefOid(userJack, RESOURCE_DUMMY_STATS_OID); String accountUnixOid = getLinkRefOid(userJack, RESOURCE_DUMMY_UNIX_OID); String accountOpenDjOid = getLinkRefOid(userJack, RESOURCE_OPENDJ_AD_SIMULATION_OID); - + PrismObject shadowStats = provisioningService.getObject(ShadowType.class, accountStatsOid, null, task, result); IntegrationTestTools.display("Stats account: ", shadowStats); PrismObject shadowUnix = provisioningService.getObject(ShadowType.class, accountUnixOid, null, task, result); IntegrationTestTools.display("Unix account: ", shadowUnix); PrismObject shadowOpenDj = provisioningService.getObject(ShadowType.class, accountOpenDjOid, null, task, result); IntegrationTestTools.display("AD account: ", shadowOpenDj); - + ObjectDelta delteStatsAccountDelta= ObjectDelta.createModificationDeleteReference(UserType.class, USER_JACK_OID, UserType.F_LINK_REF, prismContext, accountStatsOid); modelService.executeChanges((Collection) MiscUtil.createCollection(delteStatsAccountDelta), null, task, result); - + AssertJUnit.assertTrue("Expected empty assignment", jackType.getAssignment().isEmpty()); - + PrismObject userJackAfter = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); AssertJUnit.assertNotNull("User jack not found", userJackAfter); UserType jackTypeAfter = userJackAfter.asObjectable(); - + IntegrationTestTools.display("User Jack", jackTypeAfter); - + AssertJUnit.assertEquals("Wrong number of link refs", 2, jackTypeAfter.getLinkRef().size()); - + } - + @Test public void test102AssignRoleStats() throws Exception{ final String TEST_NAME = "test102AssignRoleStats"; TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestScience.class.getName() + "." + TEST_NAME); - + OperationResult result = task.getResult(); - - + + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); openDJController.stop(); - + // WHEN assignRole(USER_JACK_OID, ROLE_STATISTICS_OID, task, result); - + // THEN result.computeStatus(); if (!result.isSuccess() && !result.isPartialError()) { @@ -298,52 +298,52 @@ public void test102AssignRoleStats() throws Exception{ PrismObject userJack = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); AssertJUnit.assertNotNull("User jack not found", userJack); UserType jackType = userJack.asObjectable(); - + IntegrationTestTools.display("User Jack", jackType); - + AssertJUnit.assertEquals("Wrong number of link refs", 3, jackType.getLinkRef().size()); - + assertUserJack(userJack); assertLinks(userJack, 3); String accountStatsOid = getLinkRefOid(userJack, RESOURCE_DUMMY_STATS_OID); String accountUnixOid = getLinkRefOid(userJack, RESOURCE_DUMMY_UNIX_OID); String accountOpenDjOid = getLinkRefOid(userJack, RESOURCE_OPENDJ_AD_SIMULATION_OID); - + PrismObject shadowStats = provisioningService.getObject(ShadowType.class, accountStatsOid, null, task, result); IntegrationTestTools.display("Stats account: ", shadowStats); PrismObject shadowUnix = provisioningService.getObject(ShadowType.class, accountUnixOid, null, task, result); IntegrationTestTools.display("Unix account: ", shadowUnix); PrismObject shadowOpenDj = provisioningService.getObject(ShadowType.class, accountOpenDjOid, null, task, result); IntegrationTestTools.display("AD account: ", shadowOpenDj); - + openDJController.start(); - - + + } - - + + @Test public void test200DelteUserJack() throws Exception { final String TEST_NAME = "test200DelteUserJack"; TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestScience.class.getName() + "." + TEST_NAME); - + OperationResult result = task.getResult(); - + // WHEN deleteObject(UserType.class, USER_JACK_OID, task, result); - + // THEN result.computeStatus(); - + IntegrationTestTools.display("Result: ", result); if (!result.isSuccess() && !result.isHandledError()) { IntegrationTestTools.display(result); AssertJUnit.fail("Expected success or handled error, but got "+result.getStatus()); } - + assertNoObject(UserType.class, USER_JACK_OID, task, 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 c4c0914312f..d90d6b2e16a 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 @@ -68,7 +68,7 @@ import static org.testng.AssertJUnit.*; /** - * + * * @author mederly * */ @@ -156,7 +156,7 @@ public class TestStrings extends AbstractStoryTest { 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 TASK_WAIT_TIMEOUT = 40000; @Override @@ -1001,7 +1001,7 @@ public void test220FormRoleAssignmentStart() throws Exception { displayWorkItems("Work item after start", workItems); PrismObject wfTask = getTask(WfContextUtil.getTask(workItems.get(0)).getOid()); display("wfTask", wfTask); - + // assertTriggers(wfTask, 2); ItemApprovalProcessStateType info = WfContextUtil.getItemApprovalProcessInfo(wfTask.asObjectable().getWorkflowContext()); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestTrafo.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestTrafo.java index 63315dd26b4..75a36f08e88 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestTrafo.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestTrafo.java @@ -59,56 +59,56 @@ @ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestTrafo extends AbstractStoryTest { - + public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "trafo"); - + public static final String NS_TRAFO_EXT = "http://midpoint.evolveum.com/xml/ns/story/trafo/ext"; private static final File TRAFO_SCHEMA_EXTENSION_FILE = new File(TEST_DIR, "extension.xsd"); private static final QName TRAFO_EXTENSION_HOMEDIR_QNAME = new QName(NS_TRAFO_EXT, "homedir"); private static final QName TRAFO_EXTENSION_UID_QNAME = new QName(NS_TRAFO_EXT, "uid"); private static final ItemPath TRAFO_EXTENSION_HOMEDIR_PATH = new ItemPath(UserType.F_EXTENSION, TRAFO_EXTENSION_HOMEDIR_QNAME); - + private static final String TRAFO_MAIL_DOMAIN = "trafo.xx"; - + protected static final File USER_ANGELICA_FILE = new File(TEST_DIR, "user-angelica.xml"); protected static final String USER_ANGELICA_OID = "c0c010c0-d34d-b33f-f00d-11111111aaaa"; protected static final String USER_ANGELICA_USERNAME = "angelica"; - + protected static final File USER_SMITH111_FILE = new File(TEST_DIR, "user-smith-111.xml"); protected static final String USER_SMITH111_OID = "c0c010c0-d34d-b33f-f00d-555555551111"; protected static final String USER_SMITH111_USERNAME = "smith111"; - + protected static final File USER_SMITH222_FILE = new File(TEST_DIR, "user-smith-222.xml"); protected static final String USER_SMITH222_OID = "c0c010c0-d34d-b33f-f00d-555555552222"; protected static final String USER_SMITH222_USERNAME = "smith222"; - + protected static final String ACCOUNT_JACK_AD_DN = "CN=Sparrow Jack,OU=People,O=Trafo"; protected static final String ACCOUNT_JACK_AD_SAM_NAME = "jsparrow"; - + protected static final String ACCOUNT_JACK_MAIL_USERNAME = "Jack Sparrow/TRAFO/XX"; - + private static final String ACCOUNT_ANGELICA_AD_DN = "CN=Sparrow Jack2,OU=People,O=Trafo"; protected static final String ACCOUNT_ANGELICA_AD_SAM_NAME = "jsparrow2"; - + protected static final String ACCOUNT_ANGELICA_MAIL_USERNAME = "Jack Sparrow2/TRAFO/XX"; - + private static final String ACCOUNT_SMITH111_AD_DN = "CN=Smith John,OU=People,O=Trafo"; private static final Object ACCOUNT_SMITH111_AD_SAM_NAME = USER_SMITH111_USERNAME; private static final String ACCOUNT_SMITH111_AD_DN_AFTER_RENAME = "CN=Smither John,OU=People,O=Trafo"; - + private static final String ACCOUNT_SMITH111_MAIL_USERNAME = "John Smith/111/TRAFO/XX"; private static final String ACCOUNT_SMITH111_MAIL_USERNAME_AFTER_RENAME = "John Smither/111/TRAFO/XX"; - + private static final String ACCOUNT_SMITH222_AD_DN = "CN=Smith John2,OU=People,O=Trafo"; private static final Object ACCOUNT_SMITH222_AD_SAM_NAME = USER_SMITH222_USERNAME; private static final String ACCOUNT_SMITH222_AD_DN_AFTER_RENAME = "CN=Smither John2,OU=People,O=Trafo"; - + private static final String ACCOUNT_SMITH222_MAIL_USERNAME = "John Smith/222/TRAFO/XX"; private static final String ACCOUNT_SMITH222_MAIL_USERNAME_AFTER_RENAME = "John Smither/222/TRAFO/XX"; - + protected static final File ROLE_EMPLOYEE_FILE = new File(TEST_DIR, "role-employee.xml"); protected static final String ROLE_EMPLOYEE_OID = "6de5ff6a-5b61-11e3-adc5-001e8c717e5b"; - + protected static final File RESOURCE_DUMMY_AD_FILE = new File(TEST_DIR, "resource-dummy-ad.xml"); protected static final String RESOURCE_DUMMY_AD_ID = "AD"; protected static final String RESOURCE_DUMMY_AD_OID = "14400000-0000-0000-0000-000000000003"; @@ -118,7 +118,7 @@ public class TestTrafo extends AbstractStoryTest { protected static final String RESOURCE_DUMMY_MAIL_ID = "mail"; protected static final String RESOURCE_DUMMY_MAIL_OID = "14400000-0000-0000-0000-000000000001"; protected static final String RESOURCE_DUMMY_MAIL_NAMESPACE = MidPointConstants.NS_RI; - + private static final String DUMMY_ACCOUNT_ATTRIBUTE_MAIL_FIRST_NAME_NAME = "FirstName"; private static final String DUMMY_ACCOUNT_ATTRIBUTE_MAIL_LAST_NAME_NAME = "LastName"; private static final String DUMMY_ACCOUNT_ATTRIBUTE_MAIL_SHORT_NAME_NAME = "ShortName"; @@ -134,15 +134,15 @@ public class TestTrafo extends AbstractStoryTest { protected static DummyResourceContoller dummyResourceCtlAd; protected ResourceType resourceDummyAdType; protected PrismObject resourceDummyAd; - + protected static DummyResource dummyResourceMail; protected static DummyResourceContoller dummyResourceCtlMail; protected ResourceType resourceDummyMailType; protected PrismObject resourceDummyMail; - + private String jackAdIcfUid; private String jackMailIcfUid; - + private String angelicaAdIcfUid; private String smith111MailIcfUid; @@ -154,14 +154,14 @@ public class TestTrafo extends AbstractStoryTest { private String smith222AdIcfUid; private String smith222MailIcfUid; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + // Roles repoAddObjectFromFile(ROLE_EMPLOYEE_FILE, initResult); - + // Resources dummyResourceCtlAd = DummyResourceContoller.create(RESOURCE_DUMMY_AD_ID, resourceDummyAd); dummyResourceCtlAd.extendSchemaAd(); @@ -169,7 +169,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti resourceDummyAd = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_AD_FILE, RESOURCE_DUMMY_AD_OID, initTask, initResult); resourceDummyAdType = resourceDummyAd.asObjectable(); dummyResourceCtlAd.setResource(resourceDummyAd); - + dummyResourceCtlMail = DummyResourceContoller.create(RESOURCE_DUMMY_MAIL_ID, resourceDummyMail); dummyResourceCtlMail.populateWithDefaultSchema(); DummyObjectClass dummyAdAccountObjectClass = dummyResourceCtlMail.getDummyResource().getAccountObjectClass(); @@ -187,7 +187,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti resourceDummyMail = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_MAIL_FILE, RESOURCE_DUMMY_MAIL_OID, initTask, initResult); resourceDummyMailType = resourceDummyMail.asObjectable(); dummyResourceCtlMail.setResource(resourceDummyMail); - + } @Test @@ -195,17 +195,17 @@ public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + OperationResult testResultAd = modelService.testResource(RESOURCE_DUMMY_AD_OID, task); TestUtil.assertSuccess(testResultAd); - + OperationResult testResultMail = modelService.testResource(RESOURCE_DUMMY_MAIL_OID, task); TestUtil.assertSuccess(testResultMail); - + waitForTaskStart(TASK_TRIGGER_SCANNER_OID, true); waitForTaskStart(TASK_VALIDITY_SCANNER_OID, true); } - + @Test public void test100JackAssignAccountAd() throws Exception { final String TEST_NAME = "test100JackAssignAccountAd"; @@ -215,49 +215,49 @@ public void test100JackAssignAccountAd() throws Exception { Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignAccount(USER_JACK_OID, RESOURCE_DUMMY_AD_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); String accountOid = getSingleLinkRef(userJack).getOid(); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertAccountShadowRepo(accountShadow, accountOid, ACCOUNT_JACK_AD_DN, resourceDummyAdType, caseIgnoreMatchingRule); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("AD shadow", accountModel); assertAccountShadowModel(accountModel, accountOid, ACCOUNT_JACK_AD_DN, resourceDummyAdType, caseIgnoreMatchingRule); assertAdministrativeStatusEnabled(accountModel); - + jackAdIcfUid = getIcfUid(accountModel); - + // Check account in dummy resource assertDummyAccountById(RESOURCE_DUMMY_AD_ID, jackAdIcfUid); assertDummyAccount(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN); assertDummyAccountActivation(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_SAM_ACCOUNT_NAME_NAME, ACCOUNT_JACK_AD_SAM_NAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_USER_PRINCIPAL_NAME_NAME, ACCOUNT_JACK_AD_SAM_NAME + "@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_GIVEN_NAME_NAME, "Jack"); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_SN_NAME, "Sparrow"); assertDummyAccountNoAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_MAIL_NAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_TELEPHONE_NUMBER_NAME, "555-1234"); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -268,7 +268,7 @@ public void test100JackAssignAccountAd() throws Exception { dummyAuditService.assertHasDelta(ChangeType.ADD, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + /** * Account stays. Should be disabled. */ @@ -281,49 +281,49 @@ public void test105JackUnAssignAccountAd() throws Exception { Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); unassignAccount(USER_JACK_OID, RESOURCE_DUMMY_AD_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); String accountOid = getSingleLinkRef(userJack).getOid(); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertAccountShadowRepo(accountShadow, accountOid, ACCOUNT_JACK_AD_DN, resourceDummyAdType, caseIgnoreMatchingRule); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("AD shadow", accountModel); assertAccountShadowModel(accountModel, accountOid, ACCOUNT_JACK_AD_DN, resourceDummyAdType, caseIgnoreMatchingRule); assertAdministrativeStatusDisabled(accountModel); - + assertEquals("Jack AD ICF UID has changed", jackAdIcfUid, getIcfUid(accountModel)); - + // Check account in dummy resource assertDummyAccountById(RESOURCE_DUMMY_AD_ID, jackAdIcfUid); assertDummyAccount(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN); assertDummyAccountActivation(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, false); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_SAM_ACCOUNT_NAME_NAME, ACCOUNT_JACK_AD_SAM_NAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_USER_PRINCIPAL_NAME_NAME, ACCOUNT_JACK_AD_SAM_NAME + "@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_GIVEN_NAME_NAME, "Jack"); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_SN_NAME, "Sparrow"); assertDummyAccountNoAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_MAIL_NAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_TELEPHONE_NUMBER_NAME, "555-1234"); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -347,26 +347,26 @@ public void test109JackAccountAdGone() throws Exception { Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); clock.overrideDuration("P2D"); waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); assertLinks(userJack, 0); - + // Check account in dummy resource assertNoDummyAccountById(RESOURCE_DUMMY_AD_ID, jackAdIcfUid); assertNoDummyAccount(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -376,7 +376,7 @@ public void test109JackAccountAdGone() throws Exception { dummyAuditService.assertHasDelta(ChangeType.DELETE, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test120AJackssignAccountMail() throws Exception { final String TEST_NAME = "test120JackAssignAccountMail"; @@ -386,57 +386,57 @@ public void test120AJackssignAccountMail() throws Exception { Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignAccount(USER_JACK_OID, RESOURCE_DUMMY_MAIL_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); String accountOid = getSingleLinkRef(userJack).getOid(); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertAccountShadowRepo(accountShadow, accountOid, ACCOUNT_JACK_MAIL_USERNAME, resourceDummyMailType, caseIgnoreMatchingRule); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("Mail shadow", accountModel); assertAccountShadowModel(accountModel, accountOid, ACCOUNT_JACK_MAIL_USERNAME, resourceDummyMailType, caseIgnoreMatchingRule); assertAdministrativeStatusEnabled(accountModel); - + jackMailIcfUid = getIcfUid(accountModel); - + // Check account in dummy resource assertDummyAccountById(RESOURCE_DUMMY_MAIL_ID, jackMailIcfUid); assertDummyAccount(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME); assertDummyAccountActivation(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_INTERNET_ADDRESS_NAME, "Jack.Sparrow@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_FIRST_NAME_NAME, "Jack"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_LAST_NAME_NAME, "Sparrow"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_ID_FILE_NAME, "c:\\install\\test-id-folder\\jsparrow.id"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_SHORT_NAME_NAME, USER_JACK_USERNAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_MAIL_FILE_NAME_NAME, "mail\\"+USER_JACK_USERNAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_MAIL_DOMAIN_NAME, "TRAFO"); - + // Set by inbound mappings PrismAsserts.assertPropertyValue(userJack, UserType.F_EMAIL_ADDRESS, "Jack.Sparrow@" + TRAFO_MAIL_DOMAIN); - PrismAsserts.assertPropertyValue(userJack, + PrismAsserts.assertPropertyValue(userJack, new ItemPath(UserType.F_EXTENSION, TRAFO_EXTENSION_HOMEDIR_QNAME), "c:\\install\\test-id-folder"); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(3); @@ -451,7 +451,7 @@ public void test120AJackssignAccountMail() throws Exception { dummyAuditService.assertHasDelta(1,ChangeType.MODIFY, UserType.class); dummyAuditService.assertExecutionSuccess(); } - + @Test public void test125JackUnAssignAccountMail() throws Exception { final String TEST_NAME = "test125JackUnAssignAccountMail"; @@ -461,57 +461,57 @@ public void test125JackUnAssignAccountMail() throws Exception { Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); unassignAccount(USER_JACK_OID, RESOURCE_DUMMY_MAIL_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); String accountOid = getSingleLinkRef(userJack).getOid(); - + // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); assertAccountShadowRepo(accountShadow, accountOid, ACCOUNT_JACK_MAIL_USERNAME, resourceDummyMailType, caseIgnoreMatchingRule); - + // Check account PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("Mail shadow", accountModel); assertAccountShadowModel(accountModel, accountOid, ACCOUNT_JACK_MAIL_USERNAME, resourceDummyMailType, caseIgnoreMatchingRule); assertAdministrativeStatusDisabled(accountModel); - + assertEquals("Jack Mail ICF UID has changed", jackMailIcfUid, getIcfUid(accountModel)); - + // Check account in dummy resource assertDummyAccountById(RESOURCE_DUMMY_MAIL_ID, jackMailIcfUid); assertDummyAccount(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME); assertDummyAccountActivation(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, false); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_INTERNET_ADDRESS_NAME, "Jack.Sparrow@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_FIRST_NAME_NAME, "Jack"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_LAST_NAME_NAME, "Sparrow"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_ID_FILE_NAME, "c:\\install\\test-id-folder\\jsparrow.id"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_SHORT_NAME_NAME, USER_JACK_USERNAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_MAIL_FILE_NAME_NAME, "mail\\"+USER_JACK_USERNAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_MAIL_DOMAIN_NAME, "TRAFO"); - + // Set by inbound mappings PrismAsserts.assertPropertyValue(userJack, UserType.F_EMAIL_ADDRESS, "Jack.Sparrow@" + TRAFO_MAIL_DOMAIN); - PrismAsserts.assertPropertyValue(userJack, + PrismAsserts.assertPropertyValue(userJack, new ItemPath(UserType.F_EXTENSION, TRAFO_EXTENSION_HOMEDIR_QNAME), "c:\\install\\test-id-folder"); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -522,7 +522,7 @@ public void test125JackUnAssignAccountMail() throws Exception { dummyAuditService.assertHasDelta(0,ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertExecutionSuccess(); } - + /** * "Wait" a bit and the account should be gone. */ @@ -535,30 +535,30 @@ public void test129JackAccountMailGone() throws Exception { Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); clock.overrideDuration("P2D"); waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); assertLinks(userJack, 0); - + // Check account in dummy resource assertNoDummyAccountById(RESOURCE_DUMMY_MAIL_ID, jackMailIcfUid); assertNoDummyAccount(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME); - + // Set by inbound mappings, this should stay PrismAsserts.assertPropertyValue(userJack, UserType.F_EMAIL_ADDRESS, "Jack.Sparrow@" + TRAFO_MAIL_DOMAIN); PrismAsserts.assertPropertyValue(userJack, TRAFO_EXTENSION_HOMEDIR_PATH, "c:\\install\\test-id-folder"); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -567,15 +567,15 @@ public void test129JackAccountMailGone() throws Exception { dummyAuditService.assertHasDelta(ChangeType.MODIFY, UserType.class); dummyAuditService.assertHasDelta(ChangeType.DELETE, ShadowType.class); dummyAuditService.assertExecutionSuccess(); - + // Clean up the data set by inbound. These could ruin next tests modifyUserReplace(USER_JACK_OID, UserType.F_EMAIL_ADDRESS, task, result); modifyUserReplace(USER_JACK_OID, TRAFO_EXTENSION_HOMEDIR_PATH, task, result); - + userJack = getUser(USER_JACK_OID); display("Clean jack", userJack); } - + @Test public void test150JackAssignRoleEmployee() throws Exception { final String TEST_NAME = "test150JackAssignRoleEmployee"; @@ -585,93 +585,93 @@ public void test150JackAssignRoleEmployee() throws Exception { Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); assignRole(USER_JACK_OID, ROLE_EMPLOYEE_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); assertUserJack(userJack); assertLinks(userJack, 2); String accountAdOid = getLinkRefOid(userJack, RESOURCE_DUMMY_AD_OID); String accountMailOid = getLinkRefOid(userJack, RESOURCE_DUMMY_MAIL_OID); - + // AD ACCOUNT - + // Check shadow PrismObject accountAdShadow = repositoryService.getObject(ShadowType.class, accountAdOid, null, result); assertAccountShadowRepo(accountAdShadow, accountAdOid, ACCOUNT_JACK_AD_DN, resourceDummyAdType, caseIgnoreMatchingRule); - + // Check account PrismObject accountAdModel = modelService.getObject(ShadowType.class, accountAdOid, null, task, result); display("AD shadow", accountAdModel); assertAccountShadowModel(accountAdModel, accountAdOid, ACCOUNT_JACK_AD_DN, resourceDummyAdType, caseIgnoreMatchingRule); assertAdministrativeStatusEnabled(accountAdModel); - + jackAdIcfUid = getIcfUid(accountAdModel); - + // Check account in dummy resource assertDummyAccountById(RESOURCE_DUMMY_AD_ID, jackAdIcfUid); assertDummyAccount(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN); assertDummyAccountActivation(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_SAM_ACCOUNT_NAME_NAME, ACCOUNT_JACK_AD_SAM_NAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_USER_PRINCIPAL_NAME_NAME, ACCOUNT_JACK_AD_SAM_NAME + "@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_GIVEN_NAME_NAME, "Jack"); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_SN_NAME, "Sparrow"); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_MAIL_NAME, "Jack.Sparrow@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_JACK_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_TELEPHONE_NUMBER_NAME, "555-1234"); - - + + // MAIL ACCOUNT - + // Check shadow PrismObject accountMailShadow = repositoryService.getObject(ShadowType.class, accountMailOid, null, result); assertAccountShadowRepo(accountMailShadow, accountMailOid, ACCOUNT_JACK_MAIL_USERNAME, resourceDummyMailType, caseIgnoreMatchingRule); - + // Check account PrismObject accountMailModel = modelService.getObject(ShadowType.class, accountMailOid, null, task, result); display("Mail shadow", accountMailModel); assertAccountShadowModel(accountMailModel, accountMailOid, ACCOUNT_JACK_MAIL_USERNAME, resourceDummyMailType, caseIgnoreMatchingRule); assertAdministrativeStatusEnabled(accountMailModel); - + jackMailIcfUid = getIcfUid(accountMailModel); - + // Check account in dummy resource assertDummyAccountById(RESOURCE_DUMMY_MAIL_ID, jackMailIcfUid); assertDummyAccount(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME); assertDummyAccountActivation(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_INTERNET_ADDRESS_NAME, "Jack.Sparrow@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_FIRST_NAME_NAME, "Jack"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_LAST_NAME_NAME, "Sparrow"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_ID_FILE_NAME, "c:\\install\\test-id-folder\\jsparrow.id"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_SHORT_NAME_NAME, USER_JACK_USERNAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_MAIL_FILE_NAME_NAME, "mail\\"+USER_JACK_USERNAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_JACK_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_MAIL_DOMAIN_NAME, "TRAFO"); - + // Set by inbound mappings PrismAsserts.assertPropertyValue(userJack, UserType.F_EMAIL_ADDRESS, "Jack.Sparrow@" + TRAFO_MAIL_DOMAIN); - PrismAsserts.assertPropertyValue(userJack, + PrismAsserts.assertPropertyValue(userJack, new ItemPath(UserType.F_EXTENSION, TRAFO_EXTENSION_HOMEDIR_QNAME), "c:\\install\\test-id-folder"); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(4); @@ -688,7 +688,7 @@ public void test150JackAssignRoleEmployee() throws Exception { dummyAuditService.assertHasDelta(2,ChangeType.MODIFY, ShadowType.class); // AD account dummyAuditService.assertExecutionSuccess(); } - + /** * Angelica pretends to be Jack Sparrow. She has the same first and last name. There is a naming conflict. * The IDs and mail addresses should be correctly suffixed. @@ -702,92 +702,92 @@ public void test160AngelicaAdd() throws Exception { Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); addObject(USER_ANGELICA_FILE); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAngelica = getUser(USER_ANGELICA_OID); display("User angelica after change execution", userAngelica); assertUser(userAngelica, USER_ANGELICA_OID, USER_ANGELICA_USERNAME, "Jack Sparrow", "Jack", "Sparrow"); assertLinks(userAngelica, 2); String accountAdOid = getLinkRefOid(userAngelica, RESOURCE_DUMMY_AD_OID); String accountMailOid = getLinkRefOid(userAngelica, RESOURCE_DUMMY_MAIL_OID); - + // AD ACCOUNT - + // Check shadow PrismObject accountAdShadow = repositoryService.getObject(ShadowType.class, accountAdOid, null, result); assertAccountShadowRepo(accountAdShadow, accountAdOid, ACCOUNT_ANGELICA_AD_DN, resourceDummyAdType, caseIgnoreMatchingRule); - + // Check account PrismObject accountAdModel = modelService.getObject(ShadowType.class, accountAdOid, null, task, result); display("AD shadow", accountAdModel); assertAccountShadowModel(accountAdModel, accountAdOid, ACCOUNT_ANGELICA_AD_DN, resourceDummyAdType, caseIgnoreMatchingRule); assertAdministrativeStatusEnabled(accountAdModel); - + angelicaAdIcfUid = getIcfUid(accountAdModel); - + // Check account in dummy resource assertDummyAccountById(RESOURCE_DUMMY_AD_ID, angelicaAdIcfUid); assertDummyAccount(RESOURCE_DUMMY_AD_ID, ACCOUNT_ANGELICA_AD_DN); assertDummyAccountActivation(RESOURCE_DUMMY_AD_ID, ACCOUNT_ANGELICA_AD_DN, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_ANGELICA_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_ANGELICA_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_SAM_ACCOUNT_NAME_NAME, ACCOUNT_ANGELICA_AD_SAM_NAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_ANGELICA_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_ANGELICA_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_USER_PRINCIPAL_NAME_NAME, ACCOUNT_ANGELICA_AD_SAM_NAME + "@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_ANGELICA_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_ANGELICA_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_GIVEN_NAME_NAME, "Jack"); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_ANGELICA_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_ANGELICA_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_SN_NAME, "Sparrow"); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_ANGELICA_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_ANGELICA_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_MAIL_NAME, "Jack.Sparrow2@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountNoAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_ANGELICA_AD_DN, + assertDummyAccountNoAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_ANGELICA_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_TELEPHONE_NUMBER_NAME); - + // MAIL ACCOUNT - + // Check shadow PrismObject accountMailShadow = repositoryService.getObject(ShadowType.class, accountMailOid, null, result); assertAccountShadowRepo(accountMailShadow, accountMailOid, ACCOUNT_ANGELICA_MAIL_USERNAME, resourceDummyMailType, caseIgnoreMatchingRule); - + // Check account PrismObject accountMailModel = modelService.getObject(ShadowType.class, accountMailOid, null, task, result); display("Mail shadow", accountMailModel); assertAccountShadowModel(accountMailModel, accountMailOid, ACCOUNT_ANGELICA_MAIL_USERNAME, resourceDummyMailType, caseIgnoreMatchingRule); assertAdministrativeStatusEnabled(accountMailModel); - + angelicaMailIcfUid = getIcfUid(accountMailModel); - + // Check account in dummy resource assertDummyAccountById(RESOURCE_DUMMY_MAIL_ID, angelicaMailIcfUid); assertDummyAccount(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_ANGELICA_MAIL_USERNAME); assertDummyAccountActivation(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_ANGELICA_MAIL_USERNAME, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_ANGELICA_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_ANGELICA_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_INTERNET_ADDRESS_NAME, "Jack.Sparrow2@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_ANGELICA_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_ANGELICA_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_FIRST_NAME_NAME, "Jack"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_ANGELICA_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_ANGELICA_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_LAST_NAME_NAME, "Sparrow2"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_ANGELICA_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_ANGELICA_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_ID_FILE_NAME, "c:\\install\\test-id-folder\\jsparrow2.id"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_ANGELICA_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_ANGELICA_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_SHORT_NAME_NAME, USER_ANGELICA_USERNAME + "2"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_ANGELICA_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_ANGELICA_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_MAIL_FILE_NAME_NAME, "mail\\"+USER_ANGELICA_USERNAME+ "2"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_ANGELICA_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_ANGELICA_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_MAIL_DOMAIN_NAME, "TRAFO"); - + // Set by inbound mappings PrismAsserts.assertPropertyValue(userAngelica, UserType.F_EMAIL_ADDRESS, "Jack.Sparrow2@" + TRAFO_MAIL_DOMAIN); - PrismAsserts.assertPropertyValue(userAngelica, + PrismAsserts.assertPropertyValue(userAngelica, new ItemPath(UserType.F_EXTENSION, TRAFO_EXTENSION_HOMEDIR_QNAME), "c:\\install\\test-id-folder"); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(4); @@ -805,7 +805,7 @@ public void test160AngelicaAdd() throws Exception { dummyAuditService.assertHasDelta(2,ChangeType.MODIFY, ShadowType.class); // AD account dummyAuditService.assertExecutionSuccess(); } - + /** * Attempt to add two employees that are boh "John Smith". This is the first user. Everything shouyld do as normal. * Note: this is a different case than jack-angelica. Jack and Angelica are "externists". Smithes are employees (type "T") @@ -819,94 +819,94 @@ public void test200Smith111Add() throws Exception { Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); addObject(USER_SMITH111_FILE); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userSmith = getUser(USER_SMITH111_OID); display("User smith111 after change execution", userSmith); assertUser(userSmith, USER_SMITH111_OID, USER_SMITH111_USERNAME, "John Smith", "John", "Smith"); assertLinks(userSmith, 2); String accountAdOid = getLinkRefOid(userSmith, RESOURCE_DUMMY_AD_OID); String accountMailOid = getLinkRefOid(userSmith, RESOURCE_DUMMY_MAIL_OID); - + // AD ACCOUNT - + // Check shadow PrismObject accountAdShadow = repositoryService.getObject(ShadowType.class, accountAdOid, null, result); assertAccountShadowRepo(accountAdShadow, accountAdOid, ACCOUNT_SMITH111_AD_DN, resourceDummyAdType, caseIgnoreMatchingRule); - + // Check account PrismObject accountAdModel = modelService.getObject(ShadowType.class, accountAdOid, null, task, result); display("AD shadow", accountAdModel); assertAccountShadowModel(accountAdModel, accountAdOid, ACCOUNT_SMITH111_AD_DN, resourceDummyAdType, caseIgnoreMatchingRule); assertAdministrativeStatusEnabled(accountAdModel); - + smith111AdIcfUid = getIcfUid(accountAdModel); - + // Check account in dummy resource assertDummyAccountById(RESOURCE_DUMMY_AD_ID, smith111AdIcfUid); assertDummyAccount(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN); assertDummyAccountActivation(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_SAM_ACCOUNT_NAME_NAME, ACCOUNT_SMITH111_AD_SAM_NAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_USER_PRINCIPAL_NAME_NAME, ACCOUNT_SMITH111_AD_SAM_NAME + "@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_GIVEN_NAME_NAME, "John"); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_SN_NAME, "Smith"); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_MAIL_NAME, "John.Smith@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountNoAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN, + assertDummyAccountNoAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_TELEPHONE_NUMBER_NAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_USER_SHARED_FOLDER_OTHER_NAME, "\\\\medusa\\User\\Smith_smith111"); - + // MAIL ACCOUNT - + // Check shadow PrismObject accountMailShadow = repositoryService.getObject(ShadowType.class, accountMailOid, null, result); assertAccountShadowRepo(accountMailShadow, accountMailOid, ACCOUNT_SMITH111_MAIL_USERNAME, resourceDummyMailType, caseIgnoreMatchingRule); - + // Check account PrismObject accountMailModel = modelService.getObject(ShadowType.class, accountMailOid, null, task, result); display("Mail shadow", accountMailModel); assertAccountShadowModel(accountMailModel, accountMailOid, ACCOUNT_SMITH111_MAIL_USERNAME, resourceDummyMailType, caseIgnoreMatchingRule); assertAdministrativeStatusEnabled(accountMailModel); - + smith111MailIcfUid = getIcfUid(accountMailModel); - + // Check account in dummy resource assertDummyAccountById(RESOURCE_DUMMY_MAIL_ID, smith111MailIcfUid); assertDummyAccount(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME); assertDummyAccountActivation(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_INTERNET_ADDRESS_NAME, "John.Smith@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_FIRST_NAME_NAME, "John"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_LAST_NAME_NAME, "Smith"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_ID_FILE_NAME, "c:\\install\\test-id-folder\\jsmith.id"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_SHORT_NAME_NAME, "PS111", "jsmith"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_MAIL_FILE_NAME_NAME, "mail\\js111"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_MAIL_DOMAIN_NAME, "TRAFO"); - + // Set by inbound mappings PrismAsserts.assertPropertyValue(userSmith, UserType.F_EMAIL_ADDRESS, "John.Smith@" + TRAFO_MAIL_DOMAIN); - PrismAsserts.assertPropertyValue(userSmith, + PrismAsserts.assertPropertyValue(userSmith, new ItemPath(UserType.F_EXTENSION, TRAFO_EXTENSION_HOMEDIR_QNAME), "\\\\medusa\\User\\Smith_smith111"); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(5); @@ -926,7 +926,7 @@ public void test200Smith111Add() throws Exception { dummyAuditService.assertHasDelta(3,ChangeType.MODIFY, UserType.class); // inbound - SHOULD THIS BE HERE?? FIXME dummyAuditService.assertExecutionSuccess(); } - + /** * Attempt to add two employees that are boh "John Smith". This is the second user. There should be a naming conflict. * Note: this is a different case than jack-angelica. Jack and Angelica are "externists". Smithes are employees (type "T") @@ -940,94 +940,94 @@ public void test210Smith222Add() throws Exception { Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); addObject(USER_SMITH222_FILE); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userSmith = getUser(USER_SMITH222_OID); display("User smith222 after change execution", userSmith); assertUser(userSmith, USER_SMITH222_OID, USER_SMITH222_USERNAME, "John Smith", "John", "Smith"); assertLinks(userSmith, 2); String accountAdOid = getLinkRefOid(userSmith, RESOURCE_DUMMY_AD_OID); String accountMailOid = getLinkRefOid(userSmith, RESOURCE_DUMMY_MAIL_OID); - + // AD ACCOUNT - + // Check shadow PrismObject accountAdShadow = repositoryService.getObject(ShadowType.class, accountAdOid, null, result); assertAccountShadowRepo(accountAdShadow, accountAdOid, ACCOUNT_SMITH222_AD_DN, resourceDummyAdType, caseIgnoreMatchingRule); - + // Check account PrismObject accountAdModel = modelService.getObject(ShadowType.class, accountAdOid, null, task, result); display("AD shadow", accountAdModel); assertAccountShadowModel(accountAdModel, accountAdOid, ACCOUNT_SMITH222_AD_DN, resourceDummyAdType, caseIgnoreMatchingRule); assertAdministrativeStatusEnabled(accountAdModel); - + smith222AdIcfUid = getIcfUid(accountAdModel); - + // Check account in dummy resource assertDummyAccountById(RESOURCE_DUMMY_AD_ID, smith222AdIcfUid); assertDummyAccount(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN); assertDummyAccountActivation(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_SAM_ACCOUNT_NAME_NAME, ACCOUNT_SMITH222_AD_SAM_NAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_USER_PRINCIPAL_NAME_NAME, ACCOUNT_SMITH222_AD_SAM_NAME + "@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_GIVEN_NAME_NAME, "John"); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_SN_NAME, "Smith"); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_MAIL_NAME, "John.Smith2@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountNoAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN, + assertDummyAccountNoAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_TELEPHONE_NUMBER_NAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_USER_SHARED_FOLDER_OTHER_NAME, "\\\\medusa\\User\\Smith_smith222"); - + // MAIL ACCOUNT - + // Check shadow PrismObject accountMailShadow = repositoryService.getObject(ShadowType.class, accountMailOid, null, result); assertAccountShadowRepo(accountMailShadow, accountMailOid, ACCOUNT_SMITH222_MAIL_USERNAME, resourceDummyMailType, caseIgnoreMatchingRule); - + // Check account PrismObject accountMailModel = modelService.getObject(ShadowType.class, accountMailOid, null, task, result); display("Mail shadow", accountMailModel); assertAccountShadowModel(accountMailModel, accountMailOid, ACCOUNT_SMITH222_MAIL_USERNAME, resourceDummyMailType, caseIgnoreMatchingRule); assertAdministrativeStatusEnabled(accountMailModel); - + smith222MailIcfUid = getIcfUid(accountMailModel); - + // Check account in dummy resource assertDummyAccountById(RESOURCE_DUMMY_MAIL_ID, smith222MailIcfUid); assertDummyAccount(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME); assertDummyAccountActivation(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_INTERNET_ADDRESS_NAME, "John.Smith2@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_FIRST_NAME_NAME, "John"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_LAST_NAME_NAME, "Smith2"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_ID_FILE_NAME, "c:\\install\\test-id-folder\\jsmith2.id"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_SHORT_NAME_NAME, "PS222", "jsmith2"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_MAIL_FILE_NAME_NAME, "mail\\js222"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_MAIL_DOMAIN_NAME, "TRAFO"); - + // Set by inbound mappings PrismAsserts.assertPropertyValue(userSmith, UserType.F_EMAIL_ADDRESS, "John.Smith2@" + TRAFO_MAIL_DOMAIN); - PrismAsserts.assertPropertyValue(userSmith, + PrismAsserts.assertPropertyValue(userSmith, new ItemPath(UserType.F_EXTENSION, TRAFO_EXTENSION_HOMEDIR_QNAME), "\\\\medusa\\User\\Smith_smith222"); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(5); @@ -1061,102 +1061,102 @@ public void test300Smith111Rename() throws Exception { Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); // addObject(USER_SMITH111_FILE); - - + + // TestUtil.displayThen(TEST_NAME); // result.computeStatus(); // TestUtil.assertSuccess(result); - + PrismObject userSmith = getUser(USER_SMITH111_OID); display("User smith111 before change execution", userSmith); assertUser(userSmith, USER_SMITH111_OID, USER_SMITH111_USERNAME, "John Smith", "John", "Smith"); assertLinks(userSmith, 2); String accountAdOid = getLinkRefOid(userSmith, RESOURCE_DUMMY_AD_OID); String accountMailOid = getLinkRefOid(userSmith, RESOURCE_DUMMY_MAIL_OID); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + Collection fullNameModification = PropertyDelta.createModificationReplacePropertyCollection(UserType.F_FAMILY_NAME, userSmith.getDefinition(), new PolyString("Smither", "smither")); ObjectDelta.createModifyDelta(userSmith.getOid(), fullNameModification, UserType.class, prismContext); - - - + + + modifyUserReplace(userSmith.getOid(), UserType.F_FAMILY_NAME, task, result, new PolyString("Smither", "smither")); - + // AD ACCOUNT - + // Check shadow PrismObject accountAdShadow = repositoryService.getObject(ShadowType.class, accountAdOid, null, result); display("AD shadow", accountAdShadow); assertAccountShadowRepo(accountAdShadow, accountAdOid, ACCOUNT_SMITH111_AD_DN_AFTER_RENAME, resourceDummyAdType, caseIgnoreMatchingRule); - + // Check account PrismObject accountAdModel = modelService.getObject(ShadowType.class, accountAdOid, null, task, result); display("AD shadow", accountAdModel); assertAccountShadowModel(accountAdModel, accountAdOid, ACCOUNT_SMITH111_AD_DN_AFTER_RENAME, resourceDummyAdType, caseIgnoreMatchingRule); assertAdministrativeStatusEnabled(accountAdModel); - + smith111AdIcfUid = getIcfUid(accountAdModel); - + // Check account in dummy resource assertDummyAccountById(RESOURCE_DUMMY_AD_ID, smith111AdIcfUid); assertDummyAccount(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN_AFTER_RENAME); assertDummyAccountActivation(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN_AFTER_RENAME, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN_AFTER_RENAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_SAM_ACCOUNT_NAME_NAME, ACCOUNT_SMITH111_AD_SAM_NAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN_AFTER_RENAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_USER_PRINCIPAL_NAME_NAME, ACCOUNT_SMITH111_AD_SAM_NAME + "@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN_AFTER_RENAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_GIVEN_NAME_NAME, "John"); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN_AFTER_RENAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_SN_NAME, "Smither"); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN_AFTER_RENAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_MAIL_NAME, "John.Smither@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountNoAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN_AFTER_RENAME, + assertDummyAccountNoAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN_AFTER_RENAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_TELEPHONE_NUMBER_NAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH111_AD_DN_AFTER_RENAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_USER_SHARED_FOLDER_OTHER_NAME, "\\\\medusa\\User\\Smither_smith111"); - + // MAIL ACCOUNT - + // Check shadow PrismObject accountMailShadow = repositoryService.getObject(ShadowType.class, accountMailOid, null, result); assertAccountShadowRepo(accountMailShadow, accountMailOid, ACCOUNT_SMITH111_MAIL_USERNAME_AFTER_RENAME, resourceDummyMailType, caseIgnoreMatchingRule); - + // Check account PrismObject accountMailModel = modelService.getObject(ShadowType.class, accountMailOid, null, task, result); display("Mail shadow", accountMailModel); assertAccountShadowModel(accountMailModel, accountMailOid, ACCOUNT_SMITH111_MAIL_USERNAME_AFTER_RENAME, resourceDummyMailType, caseIgnoreMatchingRule); assertAdministrativeStatusEnabled(accountMailModel); - + smith111MailIcfUid = getIcfUid(accountMailModel); - + // Check account in dummy resource assertDummyAccountById(RESOURCE_DUMMY_MAIL_ID, smith111MailIcfUid); assertDummyAccount(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME_AFTER_RENAME); assertDummyAccountActivation(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME_AFTER_RENAME, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME_AFTER_RENAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_INTERNET_ADDRESS_NAME, "John.Smither@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME_AFTER_RENAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_FIRST_NAME_NAME, "John"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME_AFTER_RENAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_LAST_NAME_NAME, "Smither"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME_AFTER_RENAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_ID_FILE_NAME, "c:\\install\\test-id-folder\\jsmith.id"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME_AFTER_RENAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_SHORT_NAME_NAME, "PS111", "jsmither"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME_AFTER_RENAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_MAIL_FILE_NAME_NAME, "mail\\js111"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH111_MAIL_USERNAME_AFTER_RENAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_MAIL_DOMAIN_NAME, "TRAFO"); - + PrismObject userSmithAfter = getUser(USER_SMITH111_OID); display("User smith111 after change execution", userSmithAfter); // Set by inbound mappings @@ -1166,7 +1166,7 @@ public void test300Smith111Rename() throws Exception { // So it's hard to say which value will be there in the end. // PrismAsserts.assertPropertyValue(userSmithAfter, // new ItemPath(UserType.F_EXTENSION, TRAFO_EXTENSION_HOMEDIR_QNAME), "\\\\medusa\\User\\Smither_smith111"); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(5); @@ -1200,7 +1200,7 @@ public void test310Smith222Rename() throws Exception { Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); dummyAuditService.clear(); - + // WHEN TestUtil.displayWhen(TEST_NAME); PrismObject userSmith = getUser(USER_SMITH222_OID); @@ -1209,81 +1209,81 @@ public void test310Smith222Rename() throws Exception { assertLinks(userSmith, 2); String accountAdOid = getLinkRefOid(userSmith, RESOURCE_DUMMY_AD_OID); String accountMailOid = getLinkRefOid(userSmith, RESOURCE_DUMMY_MAIL_OID); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + modifyUserReplace(userSmith.getOid(), UserType.F_FAMILY_NAME, task, result, new PolyString("Smither", "smither")); - + // AD ACCOUNT - + // Check shadow PrismObject accountAdShadow = repositoryService.getObject(ShadowType.class, accountAdOid, null, result); display("AD shadow", accountAdShadow); assertAccountShadowRepo(accountAdShadow, accountAdOid, ACCOUNT_SMITH222_AD_DN_AFTER_RENAME, resourceDummyAdType, caseIgnoreMatchingRule); - + // Check account PrismObject accountAdModel = modelService.getObject(ShadowType.class, accountAdOid, null, task, result); display("AD shadow", accountAdModel); assertAccountShadowModel(accountAdModel, accountAdOid, ACCOUNT_SMITH222_AD_DN_AFTER_RENAME, resourceDummyAdType, caseIgnoreMatchingRule); assertAdministrativeStatusEnabled(accountAdModel); - + smith222AdIcfUid = getIcfUid(accountAdModel); - + // Check account in dummy resource assertDummyAccountById(RESOURCE_DUMMY_AD_ID, smith222AdIcfUid); assertDummyAccount(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN_AFTER_RENAME); assertDummyAccountActivation(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN_AFTER_RENAME, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN_AFTER_RENAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_SAM_ACCOUNT_NAME_NAME, ACCOUNT_SMITH222_AD_SAM_NAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN_AFTER_RENAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_USER_PRINCIPAL_NAME_NAME, ACCOUNT_SMITH222_AD_SAM_NAME + "@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN_AFTER_RENAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_GIVEN_NAME_NAME, "John"); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN_AFTER_RENAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_SN_NAME, "Smither"); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN_AFTER_RENAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_MAIL_NAME, "John.Smither2@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountNoAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN_AFTER_RENAME, + assertDummyAccountNoAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN_AFTER_RENAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_TELEPHONE_NUMBER_NAME); - assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_AD_ID, ACCOUNT_SMITH222_AD_DN_AFTER_RENAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_USER_SHARED_FOLDER_OTHER_NAME, "\\\\medusa\\User\\Smither_smith222"); - + // MAIL ACCOUNT - + // Check shadow PrismObject accountMailShadow = repositoryService.getObject(ShadowType.class, accountMailOid, null, result); assertAccountShadowRepo(accountMailShadow, accountMailOid, ACCOUNT_SMITH222_MAIL_USERNAME_AFTER_RENAME, resourceDummyMailType, caseIgnoreMatchingRule); - + // Check account PrismObject accountMailModel = modelService.getObject(ShadowType.class, accountMailOid, null, task, result); display("Mail shadow", accountMailModel); assertAccountShadowModel(accountMailModel, accountMailOid, ACCOUNT_SMITH222_MAIL_USERNAME_AFTER_RENAME, resourceDummyMailType, caseIgnoreMatchingRule); assertAdministrativeStatusEnabled(accountMailModel); - + smith222MailIcfUid = getIcfUid(accountMailModel); - + // Check account in dummy resource assertDummyAccountById(RESOURCE_DUMMY_MAIL_ID, smith222MailIcfUid); assertDummyAccount(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME_AFTER_RENAME); assertDummyAccountActivation(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME_AFTER_RENAME, true); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME_AFTER_RENAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_INTERNET_ADDRESS_NAME, "John.Smither2@" + TRAFO_MAIL_DOMAIN); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME_AFTER_RENAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_FIRST_NAME_NAME, "John"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME_AFTER_RENAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_LAST_NAME_NAME, "Smither2"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME_AFTER_RENAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_ID_FILE_NAME, "c:\\install\\test-id-folder\\jsmith2.id"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME_AFTER_RENAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_SHORT_NAME_NAME, "PS222", "jsmither2"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME_AFTER_RENAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_MAIL_FILE_NAME_NAME, "mail\\js222"); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME_AFTER_RENAME, + assertDummyAccountAttribute(RESOURCE_DUMMY_MAIL_ID, ACCOUNT_SMITH222_MAIL_USERNAME_AFTER_RENAME, DUMMY_ACCOUNT_ATTRIBUTE_MAIL_MAIL_DOMAIN_NAME, "TRAFO"); - + PrismObject userSmithAfter = getUser(USER_SMITH222_OID); display("User smith222 after change execution", userSmithAfter); // Set by inbound mappings @@ -1292,7 +1292,7 @@ public void test310Smith222Rename() throws Exception { // So it's hard to say which value will be there in the end. // PrismAsserts.assertPropertyValue(userSmithAfter, // new ItemPath(UserType.F_EXTENSION, TRAFO_EXTENSION_HOMEDIR_QNAME), "\\\\medusa\\User\\Smither_smith222"); - + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(5); 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 3b1b7f46de5..bc3631fdae3 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 @@ -76,12 +76,12 @@ @ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestUniversity extends AbstractStoryTest { - + public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "university"); - + public static final File OBJECT_TEMPLATE_ORG_FILE = new File(TEST_DIR, "object-template-org.xml"); public static final String OBJECT_TEMPLATE_ORG_OID = "10000000-0000-0000-0000-000000000231"; - + 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"; @@ -95,10 +95,10 @@ public class TestUniversity extends AbstractStoryTest { 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_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 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"; @@ -114,14 +114,14 @@ public class TestUniversity extends AbstractStoryTest { @Autowired private ReconciliationTaskHandler reconciliationTaskHandler; - + private DebugReconciliationTaskResultListener reconciliationTaskResultListener; - + protected static DummyResource dummyResourceHr; protected static DummyResourceContoller dummyResourceCtlHr; protected ResourceType resourceDummyHrType; protected PrismObject resourceDummyHr; - + protected ResourceType resourceOpenDjType; protected PrismObject resourceOpenDj; @@ -129,7 +129,7 @@ public class TestUniversity extends AbstractStoryTest { protected String getTopOrgOid() { return ORG_TOP_OID; } - + @Override protected void startResources() throws Exception { openDJController.startCleanServerRI(); @@ -139,14 +139,14 @@ protected void startResources() throws Exception { public static void stopResources() throws Exception { openDJController.stop(); } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + reconciliationTaskResultListener = new DebugReconciliationTaskResultListener(); reconciliationTaskHandler.setReconciliationTaskResultListener(reconciliationTaskResultListener); - + // Resources dummyResourceCtlHr = DummyResourceContoller.create(RESOURCE_DUMMY_HR_ID, resourceDummyHr); DummyObjectClass privilegeObjectClass = dummyResourceCtlHr.getDummyResource().getPrivilegeObjectClass(); @@ -156,7 +156,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti resourceDummyHrType = resourceDummyHr.asObjectable(); dummyResourceCtlHr.setResource(resourceDummyHr); dummyResourceHr.setSyncStyle(DummySyncStyle.SMART); - + resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, RESOURCE_OPENDJ_FILE, RESOURCE_OPENDJ_OID, initTask, initResult); resourceOpenDjType = resourceOpenDj.asObjectable(); openDJController.setResource(resourceOpenDj); @@ -179,16 +179,16 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti // Tasks importObjectFromFile(TASK_LIVE_SYNC_DUMMY_HR_FILE, initResult); } - + @Test public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + OperationResult testResultHr = modelService.testResource(RESOURCE_DUMMY_HR_OID, task); TestUtil.assertSuccess(testResultHr); - + OperationResult testResultOpenDj = modelService.testResource(RESOURCE_OPENDJ_OID, task); TestUtil.assertSuccess(testResultOpenDj); @@ -196,7 +196,7 @@ public void test000Sanity() throws Exception { dumpOrgTree(); } - + @Test public void test100AddComeniusUniversity() throws Exception { final String TEST_NAME = "test100AddComeniusUniversity"; @@ -543,5 +543,5 @@ private PrismObject getAndAssertFunctionalOrg(String orgName) throws Sc 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 88236d5a96d..8bbff25d710 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 @@ -76,13 +76,13 @@ @ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestUnix extends AbstractStoryTest { - + public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "unix"); - + protected static final String EXTENSION_NAMESPACE = "http://midpoint.evolveum.com/xml/ns/story/unix/ext"; protected static final QName EXTENSION_UID_NUMBER_NAME = new QName(EXTENSION_NAMESPACE, "uidNumber"); protected static final QName EXTENSION_GID_NUMBER_NAME = new QName(EXTENSION_NAMESPACE, "gidNumber"); - + 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; @@ -92,7 +92,7 @@ public class TestUnix extends AbstractStoryTest { protected static final QName OPENDJ_GROUP_STRUCTURAL_OBJECTCLASS_NAME = new QName(RESOURCE_OPENDJ_NAMESPACE, "groupOfUniqueNames"); protected static final QName OPENDJ_GROUP_UNIX_STRUCTURAL_OBJECTCLASS_NAME = new QName(RESOURCE_OPENDJ_NAMESPACE, "groupOfNames"); protected static final QName OPENDJ_GROUP_POSIX_AUXILIARY_OBJECTCLASS_NAME = new QName(RESOURCE_OPENDJ_NAMESPACE, "posixGroup"); - protected static final QName OPENDJ_ASSOCIATION_LDAP_GROUP_NAME = new QName(RESOURCE_OPENDJ_NAMESPACE, "ldapGroup"); + protected static final QName OPENDJ_ASSOCIATION_LDAP_GROUP_NAME = new QName(RESOURCE_OPENDJ_NAMESPACE, "ldapGroup"); protected static final QName OPENDJ_ASSOCIATION_UNIX_GROUP_NAME = new QName(RESOURCE_OPENDJ_NAMESPACE, "unixGroup"); protected static final String OPENDJ_UIDNUMBER_ATTRIBUTE_NAME = "uidNumber"; protected static final String OPENDJ_GIDNUMBER_ATTRIBUTE_NAME = "gidNumber"; @@ -100,7 +100,7 @@ public class TestUnix extends AbstractStoryTest { protected static final String OPENDJ_LABELED_URI_ATTRIBUTE_NAME = "labeledURI"; protected static final String OPENDJ_MODIFY_TIMESTAMP_ATTRIBUTE_NAME = "modifyTimestamp"; protected static final QName OPENDJ_MODIFY_TIMESTAMP_ATTRIBUTE_QNAME = new QName(RESOURCE_OPENDJ_NAMESPACE, OPENDJ_MODIFY_TIMESTAMP_ATTRIBUTE_NAME); - + public static final File ROLE_BASIC_FILE = new File(TEST_DIR, "role-basic.xml"); public static final String ROLE_BASIC_OID = "10000000-0000-0000-0000-000000000601"; @@ -109,13 +109,13 @@ public class TestUnix extends AbstractStoryTest { public static final File ROLE_META_UNIXGROUP_FILE = new File(TEST_DIR, "role-meta-unix-group.xml"); public static final String ROLE_META_UNIXGROUP_OID = "31ea66ac-1a8e-11e5-8ab8-001e8c717e5b"; - + public static final File ROLE_META_UNIXGROUP2_FILE = new File(TEST_DIR, "role-meta-unix-group2.xml"); public static final String ROLE_META_UNIXGROUP2_OID = "4ab1e1aa-d0c4-11e5-b0c2-3c970e44b9e2"; - + public static final File ROLE_META_LDAPGROUP_FILE = new File(TEST_DIR, "role-meta-ldap-group.xml"); public static final String ROLE_META_LDAPGROUP_OID = "9c6d1dbe-1a87-11e5-b107-001e8c717e5b"; - + protected static final String USER_HERMAN_USERNAME = "ht"; protected static final String USER_HERMAN_FIST_NAME = "Herman"; protected static final String USER_HERMAN_LAST_NAME = "Toothrot"; @@ -123,7 +123,7 @@ public class TestUnix extends AbstractStoryTest { protected static final String USER_MANCOMB_USERNAME = "mancomb"; protected static final String USER_MANCOMB_FIST_NAME = "Mancomb"; protected static final String USER_MANCOMB_LAST_NAME = "Seepgood"; - + protected static final String USER_LARGO_USERNAME = "largo"; protected static final String USER_LARGO_FIST_NAME = "Largo"; protected static final String USER_LARGO_LAST_NAME = "LaGrande"; @@ -133,7 +133,7 @@ public class TestUnix extends AbstractStoryTest { protected static final String USER_CAPSIZE_FIST_NAME = "Kate"; protected static final String USER_CAPSIZE_LAST_NAME = "Capsize"; protected static final int USER_CAPSIZE_UID_NUMBER = 1004; - + protected static final String USER_WALLY_USERNAME = "wally"; protected static final String USER_WALLY_FIST_NAME = "Wally"; protected static final String USER_WALLY_LAST_NAME = "Feed"; @@ -144,11 +144,11 @@ public class TestUnix extends AbstractStoryTest { protected static final String USER_RANGER_FIST_NAME = "Super"; protected static final String USER_RANGER_LAST_NAME = "Ranger"; protected static final int USER_RANGER_UID_NUMBER = 1003; - + protected static final File STRUCT_LDIF_FILE = new File(TEST_DIR, "struct.ldif"); protected static final String ROLE_MONKEY_ISLAND_NAME = "Monkey Island"; - + protected static final String ROLE_VILLAINS_NAME = "villains"; protected static final Integer ROLE_VILLAINS_GID = 999; protected static final String ROLE_RANGERS_NAME = "rangers"; @@ -156,10 +156,10 @@ public class TestUnix extends AbstractStoryTest { protected static final String ROLE_SEALS_NAME = "seals"; protected static final Integer ROLE_SEALS_GID = 997; protected static final String ROLE_WALRUSES_NAME = "walruses"; - + public static final File OBJECT_TEMPLATE_USER_FILE = new File(TEST_DIR, "object-template-user.xml"); public static final String OBJECT_TEMPLATE_USER_OID = "9cd03eda-66bd-11e5-866c-f3bc34108fdf"; - + public static final File SEQUENCE_UIDNUMBER_FILE = new File(TEST_DIR, "sequence-uidnumber.xml"); public static final String SEQUENCE_UIDNUMBER_OID = "7d4acb8c-65e3-11e5-9ef4-6382ba96fe6c"; @@ -177,7 +177,7 @@ public class TestUnix extends AbstractStoryTest { 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"; @@ -189,43 +189,43 @@ public class TestUnix extends AbstractStoryTest { 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) private ReconciliationTaskHandler reconciliationTaskHandler; - + private DebugReconciliationTaskResultListener reconciliationTaskResultListener; - + protected ResourceType resourceOpenDjType; protected PrismObject resourceOpenDj; protected String accountMancombOid; protected String accountMancombDn; - + protected String accountLargoOid; protected String accountLargoDn; - + protected String accountRangerOid; protected String accountRangerDn; - + protected String accountWallyOid; protected String accountWallyDn; - - protected String roleMonkeyIslandOid; + + protected String roleMonkeyIslandOid; protected String groupMonkeyIslandDn; protected String groupMonkeyIslandOid; protected String roleVillainsOid; protected String groupVillainsDn; - + protected String roleRangersOid; protected String groupRangersDn; protected String groupRangersOid; @@ -243,44 +243,44 @@ protected void startResources() throws Exception { public static void stopResources() throws Exception { openDJController.stop(); } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + reconciliationTaskResultListener = new DebugReconciliationTaskResultListener(); reconciliationTaskHandler.setReconciliationTaskResultListener(reconciliationTaskResultListener); - + // Resources resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, getResourceFile(), getResourceOid(), initTask, initResult); resourceOpenDjType = resourceOpenDj.asObjectable(); openDJController.setResource(resourceOpenDj); - + // LDAP content openDJController.addEntriesFromLdifFile(STRUCT_LDIF_FILE.getPath()); - + // Object Templates importObjectFromFile(OBJECT_TEMPLATE_USER_FILE, initResult); setDefaultUserTemplate(OBJECT_TEMPLATE_USER_OID); - + // Role importObjectFromFile(ROLE_BASIC_FILE, initResult); importObjectFromFile(ROLE_UNIX_FILE, initResult); importObjectFromFile(ROLE_META_LDAPGROUP_FILE, initResult); importObjectFromFile(ROLE_META_UNIXGROUP_FILE, initResult); importObjectFromFile(ROLE_META_UNIXGROUP2_FILE, initResult); - + // Sequence importObjectFromFile(SEQUENCE_UIDNUMBER_FILE, initResult); importObjectFromFile(SEQUENCE_GIDNUMBER_FILE, initResult); - + // DebugUtil.setDetailedDebugDump(true); } protected File getResourceFile() { return RESOURCE_OPENDJ_FILE; } - + protected String getResourceOid() { return RESOURCE_OPENDJ_OID; } @@ -290,14 +290,14 @@ public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; displayTestTitle(TEST_NAME); Task task = createTask(TEST_NAME); - + OperationResult testResultOpenDj = modelService.testResource(getResourceOid(), task); TestUtil.assertSuccess(testResultOpenDj); - + waitForTaskStart(TASK_TRIGGER_SCANNER_OID, true); waitForTaskStart(TASK_VALIDITY_SCANNER_OID, true); } - + @Test public void test010Schema() throws Exception { final String TEST_NAME = "test010Schema"; @@ -305,33 +305,33 @@ public void test010Schema() throws Exception { resourceOpenDj = getObject(ResourceType.class, getResourceOid()); resourceOpenDjType = resourceOpenDj.asObjectable(); - + IntegrationTestTools.displayXml("Initialized resource", resourceOpenDj); - + ResourceSchema resourceSchema = RefinedResourceSchema.getResourceSchema(resourceOpenDj, prismContext); 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()); - + 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()); - + 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()); - + 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()); - + } - + @Test public void test100AddUserHermanBasic() throws Exception { final String TEST_NAME = "test100AddUserHermanBasic"; @@ -340,21 +340,21 @@ public void test100AddUserHermanBasic() throws Exception { OperationResult result = task.getResult(); PrismObject user = createUser(USER_HERMAN_USERNAME, USER_HERMAN_FIST_NAME, USER_HERMAN_LAST_NAME, ROLE_BASIC_OID); - + // WHEN displayWhen(TEST_NAME); addObject(user, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_HERMAN_USERNAME); assertNotNull("No herman user", userAfter); display("User after", userAfter); assertUserHerman(userAfter); String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); assertBasicAccount(shadow); @@ -368,11 +368,11 @@ public void test110AddUserMancombUnix() throws Exception { OperationResult result = task.getResult(); PrismObject user = createUser(USER_MANCOMB_USERNAME, USER_MANCOMB_FIST_NAME, USER_MANCOMB_LAST_NAME, ROLE_UNIX_OID); - + // WHEN displayWhen(TEST_NAME); addObject(user, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -382,12 +382,12 @@ public void test110AddUserMancombUnix() throws Exception { display("User after", userAfter); assertUserPosix(userAfter, USER_MANCOMB_USERNAME, USER_MANCOMB_FIST_NAME, USER_MANCOMB_LAST_NAME, 1001); accountMancombOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountMancombOid); display("Shadow (model)", shadow); accountMancombDn = assertPosixAccount(shadow, 1001); } - + @Test public void test111AccountMancombEditObjectClassDefinition() throws Exception { final String TEST_NAME = "test111AccountMancombEditObjectClassDefinition"; @@ -397,27 +397,27 @@ public void test111AccountMancombEditObjectClassDefinition() throws Exception { PrismObject shadow = getShadowModel(accountMancombOid); display("shadow", shadow); - + // WHEN displayWhen(TEST_NAME); RefinedObjectClassDefinition editObjectClassDefinition = modelInteractionService.getEditObjectClassDefinition(shadow, resourceOpenDj, AuthorizationPhaseType.REQUEST); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); display("OC def", editObjectClassDefinition); - - PrismAsserts.assertPropertyDefinition(editObjectClassDefinition, + + PrismAsserts.assertPropertyDefinition(editObjectClassDefinition, new QName(RESOURCE_OPENDJ_NAMESPACE, "cn"), DOMUtil.XSD_STRING, 1, -1); - PrismAsserts.assertPropertyDefinition(editObjectClassDefinition, + PrismAsserts.assertPropertyDefinition(editObjectClassDefinition, new QName(RESOURCE_OPENDJ_NAMESPACE, "o"), DOMUtil.XSD_STRING, 0, -1); - PrismAsserts.assertPropertyDefinition(editObjectClassDefinition, + PrismAsserts.assertPropertyDefinition(editObjectClassDefinition, new QName(RESOURCE_OPENDJ_NAMESPACE, "uidNumber"), DOMUtil.XSD_INT, 1, 1); - PrismAsserts.assertPropertyDefinition(editObjectClassDefinition, + PrismAsserts.assertPropertyDefinition(editObjectClassDefinition, new QName(RESOURCE_OPENDJ_NAMESPACE, "gidNumber"), DOMUtil.XSD_INT, 1, 1); } - + @Test public void test119DeleteUserMancombUnix() throws Exception { final String TEST_NAME = "test119DeleteUserMancombUnix"; @@ -426,11 +426,11 @@ public void test119DeleteUserMancombUnix() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_MANCOMB_USERNAME); - + // WHEN displayWhen(TEST_NAME); deleteObject(UserType.class, userBefore.getOid(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -438,12 +438,12 @@ public void test119DeleteUserMancombUnix() throws Exception { PrismObject userAfter = findUserByUsername(USER_MANCOMB_USERNAME); display("User after", userAfter); assertNull("User mancomb sneaked in", userAfter); - + assertNoObject(ShadowType.class, accountMancombOid, task, result); - + openDJController.assertNoEntry(accountMancombDn); } - + @Test public void test120AddUserLargo() throws Exception { final String TEST_NAME = "test120AddUserLargo"; @@ -452,11 +452,11 @@ public void test120AddUserLargo() throws Exception { OperationResult result = task.getResult(); PrismObject user = createUser(USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME, (String)null); - + // WHEN displayWhen(TEST_NAME); addObject(user, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -467,7 +467,7 @@ public void test120AddUserLargo() throws Exception { assertUser(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME); assertLinks(userAfter, 0); } - + @Test public void test122AssignUserLargoBasic() throws Exception { final String TEST_NAME = "test122AssignUserLargoBasic"; @@ -476,27 +476,27 @@ public void test122AssignUserLargoBasic() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + // WHEN displayWhen(TEST_NAME); assignRole(userBefore.getOid(), ROLE_BASIC_OID); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_LARGO_USERNAME); assertNotNull("No user after", userAfter); display("User after", userAfter); assertUser(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME); - + accountLargoOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountLargoOid); display("Shadow (model)", shadow); accountLargoDn = assertBasicAccount(shadow); } - + @Test public void test124AssignUserLargoUnix() throws Exception { final String TEST_NAME = "test124AssignUserLargoUnix"; @@ -505,30 +505,30 @@ public void test124AssignUserLargoUnix() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + long startTs = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); assignRole(userBefore.getOid(), ROLE_UNIX_OID); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + long endTs = System.currentTimeMillis(); - + PrismObject userAfter = findUserByUsername(USER_LARGO_USERNAME); assertNotNull("No user after", userAfter); display("User after", userAfter); assertUserPosix(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME, USER_LARGO_UID_NUMBER); - + String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); assertPosixAccount(shadow, USER_LARGO_UID_NUMBER); - + assertModifyTimestamp(shadow, startTs, endTs); } @@ -540,11 +540,11 @@ public void test125RecomputeUserLargo() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + // WHEN displayWhen(TEST_NAME); recomputeUser(userBefore.getOid(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -553,14 +553,14 @@ public void test125RecomputeUserLargo() throws Exception { assertNotNull("No user after", userAfter); display("User after", userAfter); assertUserPosix(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME, USER_LARGO_UID_NUMBER); - + String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); assertPosixAccount(shadow, USER_LARGO_UID_NUMBER); } - + @Test public void test126UnAssignUserLargoUnix() throws Exception { final String TEST_NAME = "test126UnAssignUserLargoUnix"; @@ -569,11 +569,11 @@ public void test126UnAssignUserLargoUnix() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + // WHEN displayWhen(TEST_NAME); unassignRole(userBefore.getOid(), ROLE_UNIX_OID); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -582,14 +582,14 @@ public void test126UnAssignUserLargoUnix() throws Exception { assertNotNull("No user after", userAfter); display("User after", userAfter); assertUserPosix(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME, USER_LARGO_UID_NUMBER); - + String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); assertBasicAccount(shadow); } - + @Test public void test127RecomputeUserLargo() throws Exception { final String TEST_NAME = "test127RecomputeUserLargo"; @@ -598,27 +598,27 @@ public void test127RecomputeUserLargo() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + // WHEN displayWhen(TEST_NAME); recomputeUser(userBefore.getOid(), task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_LARGO_USERNAME); assertNotNull("No user after", userAfter); display("User after", userAfter); assertUserPosix(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME, USER_LARGO_UID_NUMBER); - + String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); assertBasicAccount(shadow); } - + @Test public void test128UnAssignUserLargoBasic() throws Exception { final String TEST_NAME = "test128UnAssignUserLargoBasic"; @@ -627,26 +627,26 @@ public void test128UnAssignUserLargoBasic() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + // WHEN displayWhen(TEST_NAME); unassignRole(userBefore.getOid(), ROLE_BASIC_OID); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_LARGO_USERNAME); assertNotNull("No user after", userAfter); display("User after", userAfter); assertUserPosix(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME, USER_LARGO_UID_NUMBER); assertLinks(userAfter, 0); - + assertNoObject(ShadowType.class, accountLargoOid, task, result); - + openDJController.assertNoEntry(accountLargoDn); } - + @Test public void test129RecomputeUserLargo() throws Exception { final String TEST_NAME = "test129RecomputeUserLargo"; @@ -655,26 +655,26 @@ public void test129RecomputeUserLargo() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + // WHEN displayWhen(TEST_NAME); recomputeUser(userBefore.getOid(), task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_LARGO_USERNAME); assertNotNull("No user after", userAfter); display("User after", userAfter); assertUserPosix(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME, USER_LARGO_UID_NUMBER); assertLinks(userAfter, 0); - + assertNoObject(ShadowType.class, accountLargoOid, task, result); - + openDJController.assertNoEntry(accountLargoDn); } - + @Test public void test130AssignUserLargoUnix() throws Exception { final String TEST_NAME = "test130AssignUserLargoUnix"; @@ -683,27 +683,27 @@ public void test130AssignUserLargoUnix() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + // WHEN displayWhen(TEST_NAME); assignRole(userBefore.getOid(), ROLE_UNIX_OID); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_LARGO_USERNAME); assertNotNull("No user after", userAfter); display("User after", userAfter); assertUserPosix(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME, USER_LARGO_UID_NUMBER); - + String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); accountLargoDn = assertPosixAccount(shadow, USER_LARGO_UID_NUMBER); } - + @Test public void test131ReconcileUserLargo() throws Exception { final String TEST_NAME = "test131ReconcileUserLargo"; @@ -712,34 +712,34 @@ public void test131ReconcileUserLargo() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + dummyAuditService.clear(); - + // WHEN displayWhen(TEST_NAME); reconcileUser(userBefore.getOid(), task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_LARGO_USERNAME); assertNotNull("No user after", userAfter); display("User after", userAfter); assertUserPosix(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME, USER_LARGO_UID_NUMBER); - + String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); assertPosixAccount(shadow, USER_LARGO_UID_NUMBER); - + display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); dummyAuditService.assertRecords(2); dummyAuditService.assertExecutionDeltas(0); } - + /** * Modify the account directly on resource: remove aux object class, remove the * attributes. Then reconcile the user. The recon should fix it. @@ -752,7 +752,7 @@ public void test132MeddleWithAccountAndReconcileUserLargo() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + openDJController.executeLdifChange( "dn: "+accountLargoDn+"\n"+ "changetype: modify\n" + @@ -766,33 +766,33 @@ public void test132MeddleWithAccountAndReconcileUserLargo() throws Exception { "uidNumber: "+ USER_LARGO_UID_NUMBER +"\n" + "-\n" + "delete: gidNumber\n" + - "gidNumber: "+ USER_LARGO_UID_NUMBER +"\n" + "gidNumber: "+ USER_LARGO_UID_NUMBER +"\n" ); - + Entry entryBefore = openDJController.fetchEntry(accountLargoDn); display("Entry before", entryBefore); - + dummyAuditService.clear(); - + // WHEN displayWhen(TEST_NAME); reconcileUser(userBefore.getOid(), task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_LARGO_USERNAME); assertNotNull("No user after", userAfter); display("User after", userAfter); assertTest132User(userAfter); - + String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); assertPosixAccount(shadow, USER_LARGO_UID_NUMBER); - + assertTest132Audit(); } @@ -809,7 +809,7 @@ protected void assertTest132Audit() { } /** - * Reconcile user again. Without any meddling. + * Reconcile user again. Without any meddling. * Just to make sure that the second run will not destroy anything. */ @Test @@ -820,31 +820,31 @@ public void test133ReconcileUserLargoAgain() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + Entry entryBefore = openDJController.fetchEntry(accountLargoDn); display("Entry before", entryBefore); - + dummyAuditService.clear(); - + // WHEN displayWhen(TEST_NAME); reconcileUser(userBefore.getOid(), task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_LARGO_USERNAME); assertNotNull("No user after", userAfter); display("User after", userAfter); assertUserPosix(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME, USER_LARGO_UID_NUMBER); - + String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); assertPosixAccount(shadow, USER_LARGO_UID_NUMBER); - + display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); dummyAuditService.assertRecords(2); @@ -859,35 +859,35 @@ public void test134AssignUserLargoBasic() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + dummyAuditService.clear(); - + // WHEN displayWhen(TEST_NAME); assignRole(userBefore.getOid(), ROLE_BASIC_OID); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_LARGO_USERNAME); assertNotNull("No user after", userAfter); display("User after", userAfter); assertUserPosix(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME, USER_LARGO_UID_NUMBER); - + String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); assertPosixAccount(shadow, USER_LARGO_UID_NUMBER); - + display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); dummyAuditService.assertRecords(2); dummyAuditService.assertExecutionDeltas(1); dummyAuditService.assertHasDelta(ChangeType.MODIFY, UserType.class); } - + @Test public void test135UnAssignUserLargoUnix() throws Exception { final String TEST_NAME = "test135UnAssignUserLargoUnix"; @@ -896,31 +896,31 @@ public void test135UnAssignUserLargoUnix() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + dummyAuditService.clear(); - + // WHEN displayWhen(TEST_NAME); unassignRole(userBefore.getOid(), ROLE_UNIX_OID); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_LARGO_USERNAME); assertNotNull("No user after", userAfter); display("User after", userAfter); assertUser(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME); - + accountLargoOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountLargoOid); display("Shadow (model)", shadow); assertBasicAccount(shadow); - + assertTest135Audit(); } - + protected void assertTest135Audit() { display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); @@ -942,7 +942,7 @@ public void test136MeddleWithAccountAndReconcileUserLargo() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + openDJController.executeLdifChange( "dn: "+accountLargoDn+"\n"+ "changetype: modify\n" + @@ -956,36 +956,36 @@ public void test136MeddleWithAccountAndReconcileUserLargo() throws Exception { "uidNumber: "+ USER_LARGO_UID_NUMBER +"\n" + "-\n" + "add: gidNumber\n" + - "gidNumber: "+ USER_LARGO_UID_NUMBER +"\n" + "gidNumber: "+ USER_LARGO_UID_NUMBER +"\n" ); - + Entry entryBefore = openDJController.fetchEntry(accountLargoDn); display("Entry before", entryBefore); - + dummyAuditService.clear(); - + // WHEN displayWhen(TEST_NAME); reconcileUser(userBefore.getOid(), task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_LARGO_USERNAME); assertNotNull("No user after", userAfter); display("User after", userAfter); assertUserPosix(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME, USER_LARGO_UID_NUMBER); - + String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); assertAccountTest136(shadow); - + // TODO: check audit } - + protected void assertAccountTest136(PrismObject shadow) throws Exception { assertBasicAccount(shadow); } @@ -1002,37 +1002,37 @@ public void test137ReconcileUserLargoAgain() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + Entry entryBefore = openDJController.fetchEntry(accountLargoDn); display("Entry before", entryBefore); - + dummyAuditService.clear(); - + // WHEN displayWhen(TEST_NAME); reconcileUser(userBefore.getOid(), task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_LARGO_USERNAME); assertNotNull("No user after", userAfter); display("User after", userAfter); assertTest137User(userAfter); - + String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); assertTest137Account(shadow); - + display("Audit", dummyAuditService); dummyAuditService.assertSimpleRecordSanity(); dummyAuditService.assertRecords(2); dummyAuditService.assertExecutionDeltas(0); } - + protected void assertTest137User(PrismObject userAfter) { assertUserPosix(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME, USER_LARGO_UID_NUMBER); } @@ -1040,7 +1040,7 @@ protected void assertTest137User(PrismObject userAfter) { protected void assertTest137Account(PrismObject shadow) throws Exception { assertBasicAccount(shadow); } - + @Test public void test138UnAssignUserLargoBasic() throws Exception { final String TEST_NAME = "test138UnAssignUserLargoUnix"; @@ -1049,28 +1049,28 @@ public void test138UnAssignUserLargoBasic() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + // WHEN displayWhen(TEST_NAME); unassignRole(userBefore.getOid(), ROLE_BASIC_OID); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_LARGO_USERNAME); assertNotNull("No user after", userAfter); display("User after", userAfter); assertUserPosix(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME, USER_LARGO_UID_NUMBER); assertLinks(userAfter, 0); - + assertNoObject(ShadowType.class, accountLargoOid, task, result); - + openDJController.assertNoEntry(accountLargoDn); } - + // test140-150 are in subclass - + @Test public void test200AddLdapGroupMonkeyIsland() throws Exception { final String TEST_NAME = "test200AddLdapGroupMonkeyIsland"; @@ -1079,27 +1079,27 @@ public void test200AddLdapGroupMonkeyIsland() throws Exception { OperationResult result = task.getResult(); PrismObject role = createLdapGroupRole(ROLE_MONKEY_ISLAND_NAME); - + // WHEN displayWhen(TEST_NAME); addObject(role, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject roleAfter = getObject(RoleType.class, role.getOid()); assertNotNull("No role", roleAfter); display("Role after", roleAfter); assertObject(roleAfter); roleMonkeyIslandOid = roleAfter.getOid(); groupMonkeyIslandOid = getSingleLinkOid(roleAfter); - + PrismObject shadow = getShadowModel(groupMonkeyIslandOid); display("Shadow (model)", shadow); groupMonkeyIslandDn = assertLdapGroup(shadow); } - + @Test public void test202AssignUserHermanMonkeyIsland() throws Exception { final String TEST_NAME = "test202AssignUserHermanMonkeyIsland"; @@ -1108,27 +1108,27 @@ public void test202AssignUserHermanMonkeyIsland() throws Exception { OperationResult result = task.getResult(); PrismObject user = findUserByUsername(USER_HERMAN_USERNAME); - + // WHEN displayWhen(TEST_NAME); assignRole(user.getOid(), roleMonkeyIslandOid); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_HERMAN_USERNAME); assertNotNull("No herman user", userAfter); display("User after", userAfter); assertUserHerman(userAfter); String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); String accountHermanDn = assertBasicAccount(shadow); openDJController.assertUniqueMember(groupMonkeyIslandDn, accountHermanDn); } - + @Test public void test210AddUnixGroupVillains() throws Exception { final String TEST_NAME = "test210AddUnixGroupVillains"; @@ -1137,27 +1137,27 @@ public void test210AddUnixGroupVillains() throws Exception { OperationResult result = task.getResult(); PrismObject role = createUnixGroupRole(ROLE_VILLAINS_NAME, ROLE_META_UNIXGROUP_OID); - + // WHEN displayWhen(TEST_NAME); addObject(role, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject roleAfter = getObject(RoleType.class, role.getOid()); assertNotNull("No role", roleAfter); display("Role after", roleAfter); assertObject(roleAfter); roleVillainsOid = roleAfter.getOid(); String ldapGroupOid = getSingleLinkOid(roleAfter); - + PrismObject shadow = getShadowModel(ldapGroupOid); display("Shadow (model)", shadow); groupVillainsDn = assertUnixGroup(shadow, ROLE_VILLAINS_GID); } - + @Test public void test211AssignUserLargoUnix() throws Exception { final String TEST_NAME = "test211AssignUserLargoUnix"; @@ -1166,27 +1166,27 @@ public void test211AssignUserLargoUnix() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + // WHEN displayWhen(TEST_NAME); assignRole(userBefore.getOid(), ROLE_UNIX_OID); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_LARGO_USERNAME); assertNotNull("No user after", userAfter); display("User after", userAfter); assertUser(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME); - + String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); assertPosixAccount(shadow, USER_LARGO_UID_NUMBER); } - + @Test public void test212AssignUserLargoVillains() throws Exception { final String TEST_NAME = "test212AssignUserLargoVillains"; @@ -1195,21 +1195,21 @@ public void test212AssignUserLargoVillains() throws Exception { OperationResult result = task.getResult(); PrismObject user = findUserByUsername(USER_LARGO_USERNAME); - + // WHEN displayWhen(TEST_NAME); assignRole(user.getOid(), roleVillainsOid); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_LARGO_USERNAME); assertNotNull("No user", userAfter); display("User after", userAfter); assertUser(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME); String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); String accountLArgoDn = assertPosixAccount(shadow, USER_LARGO_UID_NUMBER); @@ -1217,7 +1217,7 @@ public void test212AssignUserLargoVillains() throws Exception { 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"; @@ -1226,11 +1226,11 @@ public void test250AddUserRangerBasic() throws Exception { OperationResult result = task.getResult(); PrismObject user = createUser(USER_RANGER_USERNAME, USER_RANGER_FIST_NAME, USER_RANGER_LAST_NAME, ROLE_BASIC_OID); - + // WHEN displayWhen(TEST_NAME); addObject(user, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1240,7 +1240,7 @@ public void test250AddUserRangerBasic() throws Exception { display("User after", userAfter); assertUser(userAfter, USER_RANGER_USERNAME, USER_RANGER_FIST_NAME, USER_RANGER_LAST_NAME); String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); assertBasicAccount(shadow); @@ -1254,11 +1254,11 @@ public void test251AssignUserRangerBasic() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_RANGER_USERNAME); - + // WHEN displayWhen(TEST_NAME); assignRole(userBefore.getOid(), ROLE_BASIC_OID); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1267,9 +1267,9 @@ public void test251AssignUserRangerBasic() throws Exception { assertNotNull("No user after", userAfter); display("User after", userAfter); assertUser(userAfter, USER_RANGER_USERNAME, USER_RANGER_FIST_NAME, USER_RANGER_LAST_NAME); - + accountRangerOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountRangerOid); display("Shadow (model)", shadow); accountRangerDn = assertBasicAccount(shadow); @@ -1283,11 +1283,11 @@ public void test252AddUnixGroupRangers() throws Exception { OperationResult result = task.getResult(); PrismObject role = createUnixGroupRole(ROLE_RANGERS_NAME, ROLE_META_UNIXGROUP2_OID); - + // WHEN displayWhen(TEST_NAME); addObject(role, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1298,7 +1298,7 @@ public void test252AddUnixGroupRangers() throws Exception { assertObject(roleAfter); roleRangersOid = roleAfter.getOid(); groupRangersOid = getSingleLinkOid(roleAfter); - + PrismObject shadow = getShadowModel(groupRangersOid); display("Shadow (model)", shadow); groupRangersDn = assertUnixGroup(shadow, ROLE_RANGERS_GID); @@ -1312,11 +1312,11 @@ public void test253AddUnixGroupSeals() throws Exception { OperationResult result = task.getResult(); PrismObject role = createUnixGroupRole(ROLE_SEALS_NAME, ROLE_META_UNIXGROUP2_OID); - + // WHEN displayWhen(TEST_NAME); addObject(role, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1327,7 +1327,7 @@ public void test253AddUnixGroupSeals() throws Exception { assertObject(roleAfter); roleSealsOid = roleAfter.getOid(); groupSealsOid = getSingleLinkOid(roleAfter); - + PrismObject shadow = getShadowModel(groupSealsOid); display("Shadow (model)", shadow); PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, groupSealsOid, null, result); @@ -1343,11 +1343,11 @@ public void test254AssignUserRangerRangers() throws Exception { OperationResult result = task.getResult(); PrismObject user = findUserByUsername(USER_RANGER_USERNAME); - + // WHEN displayWhen(TEST_NAME); assignRole(user.getOid(), roleRangersOid); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1357,7 +1357,7 @@ public void test254AssignUserRangerRangers() throws Exception { display("User after", userAfter); assertUser(userAfter, USER_RANGER_USERNAME, USER_RANGER_FIST_NAME, USER_RANGER_LAST_NAME); String accountOid = getSingleLinkOid(userAfter); - + displayThen(TEST_NAME); PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); @@ -1365,9 +1365,9 @@ public void test254AssignUserRangerRangers() throws Exception { Entry groupRangers = openDJController.fetchEntry(groupRangersDn); //openDJController.assertAttribute(groupRangers, "memberUid", Integer.toString(USER_RANGER_UID_NUMBER)); openDJController.assertAttribute(groupRangers, "memberUid", USER_RANGER_USERNAME); - + assertGroupAssociation(shadow, groupRangersOid); - + PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); display("Shadow (repo)", repoShadow); //PrismProperty uidNumberRepoAttr = repoShadow.findProperty(new ItemPath(ShadowType.F_ATTRIBUTES, new QName(RESOURCE_OPENDJ_NAMESPACE, OPENDJ_UIDNUMBER_ATTRIBUTE_NAME))); @@ -1375,7 +1375,7 @@ public void test254AssignUserRangerRangers() throws Exception { PrismProperty uidRepoAttr = repoShadow.findProperty(new ItemPath(ShadowType.F_ATTRIBUTES, new QName(RESOURCE_OPENDJ_NAMESPACE, OPENDJ_UID_ATTRIBUTE_NAME))); PrismAsserts.assertPropertyValue(uidRepoAttr, USER_RANGER_USERNAME); } - + @Test public void test255AssignUserRangerSeals() throws Exception { final String TEST_NAME = "test255AssignUserRangerSeals"; @@ -1384,11 +1384,11 @@ public void test255AssignUserRangerSeals() throws Exception { OperationResult result = task.getResult(); PrismObject user = findUserByUsername(USER_RANGER_USERNAME); - + // WHEN displayWhen(TEST_NAME); assignRole(user.getOid(), roleSealsOid); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1398,14 +1398,14 @@ public void test255AssignUserRangerSeals() throws Exception { display("User after", userAfter); assertUser(userAfter, USER_RANGER_USERNAME, USER_RANGER_FIST_NAME, USER_RANGER_LAST_NAME); String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); 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); - + assertGroupAssociation(shadow, groupRangersOid); assertGroupAssociation(shadow, groupSealsOid); } @@ -1418,11 +1418,11 @@ public void test256UnAssignUserRangerSealsKeepRangers() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_RANGER_USERNAME); - + // WHEN displayWhen(TEST_NAME); unassignRole(userBefore.getOid(), roleSealsOid); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1431,9 +1431,9 @@ public void test256UnAssignUserRangerSealsKeepRangers() throws Exception { assertNotNull("No user after", userAfter); display("User after", userAfter); assertUserPosix(userAfter, USER_RANGER_USERNAME, USER_RANGER_FIST_NAME, USER_RANGER_LAST_NAME, USER_RANGER_UID_NUMBER); - + String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); assertPosixAccount(shadow, USER_RANGER_UID_NUMBER); @@ -1448,7 +1448,7 @@ public void test256UnAssignUserRangerSealsKeepRangers() throws Exception { Entry groupSeals = openDJController.fetchEntry(groupSealsDn); openDJController.assertNoAttribute(groupSeals, "memberUid"); } - + @Test public void test257RenameUserAndAccountsCheckGroupmembership() throws Exception { final String TEST_NAME = "test257RenameUserAndAccountsCheckGroupmembership"; @@ -1457,11 +1457,11 @@ public void test257RenameUserAndAccountsCheckGroupmembership() throws Exception OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_RANGER_USERNAME); - + // WHEN displayWhen(TEST_NAME); modifyUserReplace(userBefore.getOid(), UserType.F_NAME, task, result, new PolyString("usranger", "usranger")); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1470,9 +1470,9 @@ public void test257RenameUserAndAccountsCheckGroupmembership() throws Exception assertNotNull("User not renamed", userAfter); display("User after rename", userAfter); assertUserPosix(userAfter, USER_RANGER_USERNAME_RENAMED, USER_RANGER_FIST_NAME, USER_RANGER_LAST_NAME, USER_RANGER_UID_NUMBER); - + String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); assertPosixAccount(shadow, USER_RANGER_UID_NUMBER); @@ -1487,8 +1487,8 @@ public void test257RenameUserAndAccountsCheckGroupmembership() throws Exception openDJController.assertAttribute(groupRangers, "memberUid", USER_RANGER_USERNAME_RENAMED); } - - + + @Test public void test260DeleteUserUsrangerUnix() throws Exception { final String TEST_NAME = "test260DeleteUserUsrangerUnix"; @@ -1497,11 +1497,11 @@ public void test260DeleteUserUsrangerUnix() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_RANGER_USERNAME_RENAMED); - + // WHEN displayWhen(TEST_NAME); deleteObject(UserType.class, userBefore.getOid(), task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1509,12 +1509,12 @@ public void test260DeleteUserUsrangerUnix() throws Exception { PrismObject userAfter = findUserByUsername(USER_RANGER_USERNAME_RENAMED); display("User after", userAfter); assertNull("User usranger sneaked in", userAfter); - + assertNoObject(ShadowType.class, accountRangerOid, task, result); - + openDJController.assertNoEntry(accountRangerDn); } - + /** * MID-3535 */ @@ -1528,7 +1528,7 @@ public void test270RenameUnixGroupSeals() throws Exception { // WHEN displayWhen(TEST_NAME); renameObject(RoleType.class, roleSealsOid, ROLE_WALRUSES_NAME, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1538,15 +1538,15 @@ public void test270RenameUnixGroupSeals() throws Exception { display("Role after", roleAfter); assertObject(roleAfter); assertEquals("link OID changed", groupSealsOid, getSingleLinkOid(roleAfter)); - + PrismObject shadow = getShadowModel(groupSealsOid); display("Shadow (model)", shadow); PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, groupSealsOid, null, result); display("Shadow (repo)", shadowRepo); String newGroupSealsDn = assertUnixGroup(shadow, ROLE_SEALS_GID); - + } - + @Test public void test300AddUserCapsizeUnixFail() throws Exception { final String TEST_NAME = "test300AddUserCapsizeUnixFail"; @@ -1558,17 +1558,17 @@ public void test300AddUserCapsizeUnixFail() throws Exception { display("Sequence before", sequenceBefore); assertEquals("Wrong sequence counter (precondition)", USER_CAPSIZE_UID_NUMBER, sequenceBefore.asObjectable().getCounter().intValue()); assertTrue("Unexpected unused values in the sequence (precondition)", sequenceBefore.asObjectable().getUnusedValues().isEmpty()); - + PrismObject user = createUser(USER_CAPSIZE_USERNAME, USER_CAPSIZE_FIST_NAME, USER_CAPSIZE_LAST_NAME, ROLE_UNIX_OID); user.asObjectable().getEmployeeType().add("troublemaker"); - + try { // WHEN displayWhen(TEST_NAME); addObject(user, task, result); - + AssertJUnit.fail("Unexpected success"); - } catch (ExpressionEvaluationException e) { + } catch (ExpressionEvaluationException e) { display("Expected exception", e); // this is expected } @@ -1587,7 +1587,7 @@ public void test300AddUserCapsizeUnixFail() throws Exception { assertEquals("Sequence haven't moved", USER_CAPSIZE_UID_NUMBER + 1, sequenceAfter.asObjectable().getCounter().intValue()); assertFalse("No unused values in the sequence", sequenceAfter.asObjectable().getUnusedValues().isEmpty()); } - + /** * This should go well. It should reuse the identifier that was originally assigned to * Kate Capsise, but not used. @@ -1598,18 +1598,18 @@ public void test310AddUserWallyUnix() throws Exception { displayTestTitle(TEST_NAME); Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject sequenceBefore = getObject(SequenceType.class, SEQUENCE_UIDNUMBER_OID); display("Sequence before", sequenceBefore); assertEquals("Wrong sequence counter (precondition)", USER_WALLY_UID_NUMBER + 1, sequenceBefore.asObjectable().getCounter().intValue()); assertFalse("Missing unused values in the sequence (precondition)", sequenceBefore.asObjectable().getUnusedValues().isEmpty()); PrismObject user = createUser(USER_WALLY_USERNAME, USER_WALLY_FIST_NAME, USER_WALLY_LAST_NAME, ROLE_UNIX_OID); - + // WHEN displayWhen(TEST_NAME); addObject(user, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); @@ -1619,17 +1619,17 @@ public void test310AddUserWallyUnix() throws Exception { display("User after", userAfter); assertUserPosix(userAfter, USER_WALLY_USERNAME, USER_WALLY_FIST_NAME, USER_WALLY_LAST_NAME, USER_WALLY_UID_NUMBER); accountWallyOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountWallyOid); display("Shadow (model)", shadow); accountWallyDn = assertPosixAccount(shadow, USER_WALLY_UID_NUMBER); - + PrismObject sequenceAfter = getObject(SequenceType.class, SEQUENCE_UIDNUMBER_OID); display("Sequence after", sequenceAfter); assertEquals("Sequence has moved", USER_WALLY_UID_NUMBER + 1, sequenceAfter.asObjectable().getCounter().intValue()); assertTrue("Unexpected unused values in the sequence", sequenceAfter.asObjectable().getUnusedValues().isEmpty()); } - + /** * Remove posixAccount directly in LDAP server. Then try to get the account. MidPoint should survive that. */ @@ -1639,7 +1639,7 @@ public void test312AccountWallyRemovePosixObjectclassNative() throws Exception { displayTestTitle(TEST_NAME); Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + openDJController.executeLdifChange("dn: "+accountWallyDn+"\n"+ "changetype: modify\n"+ "delete: objectclass\n"+ @@ -1653,34 +1653,34 @@ public void test312AccountWallyRemovePosixObjectclassNative() throws Exception { "-\n"+ "delete: homeDirectory\n"+ "homeDirectory: /home/wally"); - + Entry entryWallyBefore = openDJController.fetchEntry(accountWallyDn); display("Wally LDAP account before", entryWallyBefore); - + // WHEN displayWhen(TEST_NAME); PrismObject shadow = modelService.getObject(ShadowType.class, accountWallyOid, null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + display("Shadow (model)", shadow); assertBasicAccount(shadow); - + PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountWallyOid, null, result); display("Shadow (repo)", repoShadow); PrismAsserts.assertNoItem(repoShadow, ShadowType.F_AUXILIARY_OBJECT_CLASS); // PrismAsserts.assertPropertyValue(repoShadow, ShadowType.F_AUXILIARY_OBJECT_CLASS); - + PrismObject userAfter = findUserByUsername(USER_WALLY_USERNAME); assertNotNull("No wally user", userAfter); display("User after", userAfter); assertUserPosix(userAfter, USER_WALLY_USERNAME, USER_WALLY_FIST_NAME, USER_WALLY_LAST_NAME, USER_WALLY_UID_NUMBER); - accountMancombOid = getSingleLinkOid(userAfter); + accountMancombOid = getSingleLinkOid(userAfter); } - + /** * Add posixAccount directly in LDAP server. Then try to get the account. MidPoint should survive that. */ @@ -1690,7 +1690,7 @@ public void test314AccountWallyAddPosixObjectclassNative() throws Exception { displayTestTitle(TEST_NAME); Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + openDJController.executeLdifChange("dn: "+accountWallyDn+"\n"+ "changetype: modify\n"+ "add: objectclass\n"+ @@ -1704,52 +1704,52 @@ public void test314AccountWallyAddPosixObjectclassNative() throws Exception { "-\n"+ "add: homeDirectory\n"+ "homeDirectory: /home/wally"); - + Entry entryWallyBefore = openDJController.fetchEntry(accountWallyDn); display("Wally LDAP account before", entryWallyBefore); - + // WHEN displayWhen(TEST_NAME); PrismObject shadow = modelService.getObject(ShadowType.class, accountWallyOid, null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + display("Shadow (model)", shadow); assertPosixAccount(shadow, USER_WALLY_UID_NUMBER); - + PrismObject repoShadow = repositoryService.getObject(ShadowType.class, accountWallyOid, null, result); display("Shadow (repo)", repoShadow); PrismAsserts.assertPropertyValue(repoShadow, ShadowType.F_AUXILIARY_OBJECT_CLASS, OPENDJ_ACCOUNT_POSIX_AUXILIARY_OBJECTCLASS_NAME); - + PrismObject userAfter = findUserByUsername(USER_WALLY_USERNAME); assertNotNull("No wally user", userAfter); display("User after", userAfter); assertUserPosix(userAfter, USER_WALLY_USERNAME, USER_WALLY_FIST_NAME, USER_WALLY_LAST_NAME, USER_WALLY_UID_NUMBER); - accountMancombOid = getSingleLinkOid(userAfter); + accountMancombOid = getSingleLinkOid(userAfter); } - + @Test public void test400ListAllAccountsObjectClass() throws Exception { final String TEST_NAME = "test400ListAllAccountsObjectClass"; displayTestTitle(TEST_NAME); Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), OPENDJ_ACCOUNT_STRUCTURAL_OBJECTCLASS_NAME, prismContext); - + // WHEN displayWhen(TEST_NAME); SearchResultList> objects = modelService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + display("found objects", objects); assertEquals("Wrong number of objects found", 7, objects.size()); } @@ -1760,67 +1760,67 @@ public void test401ListAllAccountsKindIntent() throws Exception { displayTestTitle(TEST_NAME); Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndKindIntent(getResourceOid(), ShadowKindType.ACCOUNT, "default", prismContext); display("query", query); - + // WHEN displayWhen(TEST_NAME); SearchResultList> objects = modelService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + display("found objects", objects); assertEquals("Wrong number of objects found", 7, objects.size()); } - + @Test public void test402ListLdapGroupsKindIntent() throws Exception { final String TEST_NAME = "test402ListLdapGroupsKindIntent"; displayTestTitle(TEST_NAME); Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndKindIntent(getResourceOid(), ShadowKindType.ENTITLEMENT, "ldapGroup", prismContext); display("query", query); - + // WHEN displayWhen(TEST_NAME); SearchResultList> objects = modelService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + display("found objects", objects); assertEquals("Wrong number of objects found", 2, objects.size()); } - + @Test public void test403ListUnixGroupsKindIntent() throws Exception { final String TEST_NAME = "test403ListUnixGroupsKindIntent"; displayTestTitle(TEST_NAME); Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + ObjectQuery query = ObjectQueryUtil.createResourceAndKindIntent(getResourceOid(), ShadowKindType.ENTITLEMENT, "unixGroup", prismContext); display("query", query); - + // WHEN displayWhen(TEST_NAME); SearchResultList> objects = modelService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + display("found objects", objects); assertEquals("Wrong number of objects found", 3, objects.size()); } @@ -1842,7 +1842,7 @@ public void test500AddUserStan() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_STAN_USERNAME); assertNotNull("No stan user", userAfter); display("User after", userAfter); @@ -1888,7 +1888,7 @@ public void test510StanDisablePosixAssocAndReconcile() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_STAN_USERNAME); assertNotNull("No stan user", userAfter); display("User after", userAfter); @@ -1897,9 +1897,9 @@ public void test510StanDisablePosixAssocAndReconcile() throws Exception { PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); - + assertAccountTest510(shadow); - + display("Rangers", getShadowModel(groupRangersOid)); /* @@ -1945,7 +1945,7 @@ private void addRoleAssignment(PrismObject user, String roleOid) { protected void assertUserHerman(PrismObject user) { assertUser(user, USER_HERMAN_USERNAME, USER_HERMAN_FIST_NAME, USER_HERMAN_LAST_NAME); } - + protected void assertUserStan(PrismObject user) { assertUser(user, USER_STAN_USERNAME, USER_STAN_FIST_NAME, USER_STAN_LAST_NAME); } @@ -1954,7 +1954,7 @@ protected void assertUser(PrismObject user, String username, String fi assertUser(user, user.getOid(), username, firstName + " " + lastName, firstName, lastName); } - + protected void assertUserPosix(PrismObject user, String username, String firstName, String lastName, int uidNumber) { assertUser(user, user.getOid(), username, firstName + " " + lastName, firstName, lastName); @@ -1966,7 +1966,7 @@ protected void assertUserPosix(PrismObject user, String username, Stri 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(), + assertTrue("Unexpected auxiliary objectclasses in "+shadow + ": "+shadowType.getAuxiliaryObjectClass(), shadowType.getAuxiliaryObjectClass().isEmpty()); String dn = (String) ShadowUtil.getSecondaryIdentifiers(shadow).iterator().next().getRealValue(); @@ -1975,14 +1975,14 @@ protected String assertBasicAccount(PrismObject shadow) throws Direc display("Posix account entry", entry); 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, + PrismAsserts.assertEqualsCollectionUnordered("Wrong auxiliary objectclasses in "+shadow, shadowType.getAuxiliaryObjectClass(), expectedAuxObjectClasses); String dn = (String) ShadowUtil.getSecondaryIdentifiers(shadow).iterator().next().getRealValue(); @@ -1990,14 +1990,14 @@ protected String assertAccount(PrismObject shadow, QName... expected assertNotNull("No ou LDAP entry for "+dn); display("Posix account entry", entry); 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, + PrismAsserts.assertEqualsCollectionUnordered("Wrong auxiliary objectclasses in "+shadow, shadowType.getAuxiliaryObjectClass(), OPENDJ_ACCOUNT_POSIX_AUXILIARY_OBJECTCLASS_NAME); String dn = (String) ShadowUtil.getSecondaryIdentifiers(shadow).iterator().next().getRealValue(); if (expectedUid != null) { @@ -2018,10 +2018,10 @@ protected String assertPosixAccount(PrismObject shadow, Integer expe openDJController.assertAttribute(entry, OPENDJ_UIDNUMBER_ATTRIBUTE_NAME, Integer.toString(expectedUid)); openDJController.assertAttribute(entry, OPENDJ_GIDNUMBER_ATTRIBUTE_NAME, Integer.toString(expectedUid)); } - + return entry.getDN().toString(); } - + protected ShadowAssociationType assertGroupAssociation(PrismObject accountShadow, String groupShadowOid) { ShadowAssociationType association = findAssociation(accountShadow, groupShadowOid); if (association != null) { @@ -2061,26 +2061,26 @@ private PrismObject createLdapGroupRole(String name) throws SchemaExce roleType.getAssignment().add(roleAssignemnt); return role; } - + private PrismObject createUnixGroupRole(String name, String metaRoleOid) throws SchemaException { PrismObject role = getRoleDefinition().instantiate(); RoleType roleType = role.asObjectable(); roleType.setName(new PolyStringType(name)); - + AssignmentType roleAssignemnt = new AssignmentType(); ObjectReferenceType roleTargetRef = new ObjectReferenceType(); roleTargetRef.setOid(metaRoleOid); roleTargetRef.setType(RoleType.COMPLEX_TYPE); roleAssignemnt.setTargetRef(roleTargetRef); roleType.getAssignment().add(roleAssignemnt); - + return role; } - + 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(), + assertTrue("Unexpected auxiliary objectclasses in "+shadow + ": "+shadowType.getAuxiliaryObjectClass(), shadowType.getAuxiliaryObjectClass().isEmpty()); String dn = (String) ShadowUtil.getSecondaryIdentifiers(shadow).iterator().next().getRealValue(); @@ -2089,14 +2089,14 @@ private String assertLdapGroup(PrismObject shadow) throws DirectoryE display("Ldap group entry", entry); 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, + PrismAsserts.assertEqualsCollectionUnordered("Wrong auxiliary objectclasses in "+shadow, shadowType.getAuxiliaryObjectClass(), OPENDJ_GROUP_POSIX_AUXILIARY_OBJECTCLASS_NAME); String dn = (String) ShadowUtil.getSecondaryIdentifiers(shadow).iterator().next().getRealValue(); ResourceAttribute gidNumberAttr = ShadowUtil.getAttribute(shadow, new QName(RESOURCE_OPENDJ_NAMESPACE, OPENDJ_GIDNUMBER_ATTRIBUTE_NAME)); @@ -2108,10 +2108,10 @@ private String assertUnixGroup(PrismObject shadow, Integer expectedG 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); 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 36dd6a3784d..79d1f4e0c6f 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 @@ -75,42 +75,42 @@ import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; /** - * Unix test with tolerant auxiliary object classes. - * + * 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"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class TestUnixTolerantAux extends TestUnix { - + protected static final File RESOURCE_OPENDJ_TOLERANT_AUX_FILE = new File(TEST_DIR, "resource-opendj-tolerant-aux.xml"); protected static final String RESOURCE_OPENDJ_TOLERANT_AUX_OID = "10000000-0000-0000-0000-000000000003"; private static final String URI_WHATEVER = "http://whatever/"; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { - super.initSystem(initTask, initResult); + super.initSystem(initTask, initResult); } - + @Override protected File getResourceFile() { return RESOURCE_OPENDJ_TOLERANT_AUX_FILE; } - + @Override protected String getResourceOid() { return RESOURCE_OPENDJ_TOLERANT_AUX_OID; } - + @Override protected void assertTest132User(PrismObject userAfter) { super.assertTest132User(userAfter); assertUserAuxes(userAfter, OPENDJ_ACCOUNT_POSIX_AUXILIARY_OBJECTCLASS_NAME); } - + @Override protected void assertTest132Audit() { display("Audit", dummyAuditService); @@ -120,7 +120,7 @@ protected void assertTest132Audit() { dummyAuditService.assertHasDelta(ChangeType.MODIFY, ShadowType.class); dummyAuditService.assertHasDelta(ChangeType.MODIFY, UserType.class); } - + @Override protected void assertTest135Audit() { display("Audit", dummyAuditService); @@ -130,23 +130,23 @@ protected void assertTest135Audit() { dummyAuditService.assertHasDelta(ChangeType.MODIFY, UserType.class); dummyAuditService.assertHasDelta(ChangeType.MODIFY, ShadowType.class); } - + @Override protected void assertAccountTest136(PrismObject shadow) throws Exception { assertPosixAccount(shadow, USER_LARGO_UID_NUMBER); } - + @Override protected void assertTest137User(PrismObject userAfter) { super.assertTest137User(userAfter); assertUserAuxes(userAfter, OPENDJ_ACCOUNT_POSIX_AUXILIARY_OBJECTCLASS_NAME); } - + @Override protected void assertTest137Account(PrismObject shadow) throws Exception { assertPosixAccount(shadow, USER_LARGO_UID_NUMBER); } - + @Test public void test140AssignUserLargoBasic() throws Exception { final String TEST_NAME = "test140AssignUserLargoBasic"; @@ -155,27 +155,27 @@ public void test140AssignUserLargoBasic() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + // WHEN displayWhen(TEST_NAME); assignRole(userBefore.getOid(), ROLE_BASIC_OID); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_LARGO_USERNAME); assertNotNull("No user after", userAfter); display("User after", userAfter); assertUser(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME); - + accountLargoOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountLargoOid); display("Shadow (model)", shadow); accountLargoDn = assertBasicAccount(shadow); } - + /** * Modify the account directly on resource: add aux object class, add the * attributes. Then reconcile the user. The recon should leave the aux object @@ -189,7 +189,7 @@ public void test142MeddleWithAccountAndReconcileUserLargo() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + openDJController.executeLdifChange( "dn: "+accountLargoDn+"\n"+ "changetype: modify\n" + @@ -197,38 +197,38 @@ public void test142MeddleWithAccountAndReconcileUserLargo() throws Exception { "objectClass: "+OPENDJ_ACCOUNT_LABELED_URI_OBJECT_AUXILIARY_OBJECTCLASS_NAME.getLocalPart()+"\n" + "-\n" + "add: labeledURI\n" + - "labeledURI: "+ URI_WHATEVER + "\n" + "labeledURI: "+ URI_WHATEVER + "\n" ); - + Entry entryBefore = openDJController.fetchEntry(accountLargoDn); display("Entry before", entryBefore); - + dummyAuditService.clear(); - + // WHEN displayWhen(TEST_NAME); reconcileUser(userBefore.getOid(), task, result); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_LARGO_USERNAME); assertNotNull("No user after", userAfter); display("User after", userAfter); assertUserPosix(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME, USER_LARGO_UID_NUMBER); assertUserAuxes(userAfter, OPENDJ_ACCOUNT_LABELED_URI_OBJECT_AUXILIARY_OBJECTCLASS_NAME); - + String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); assertAccount(shadow, OPENDJ_ACCOUNT_LABELED_URI_OBJECT_AUXILIARY_OBJECTCLASS_NAME); assertLabeledUri(shadow, URI_WHATEVER); - + // TODO: check audit } - + @Test public void test144AssignUserLargoUnix() throws Exception { final String TEST_NAME = "test144AssignUserLargoUnix"; @@ -237,29 +237,29 @@ public void test144AssignUserLargoUnix() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + // WHEN displayWhen(TEST_NAME); assignRole(userBefore.getOid(), ROLE_UNIX_OID); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_LARGO_USERNAME); assertNotNull("No user after", userAfter); display("User after", userAfter); assertUserPosix(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME, USER_LARGO_UID_NUMBER); assertUserAuxes(userAfter, OPENDJ_ACCOUNT_POSIX_AUXILIARY_OBJECTCLASS_NAME, OPENDJ_ACCOUNT_LABELED_URI_OBJECT_AUXILIARY_OBJECTCLASS_NAME); - + String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); assertAccount(shadow, OPENDJ_ACCOUNT_POSIX_AUXILIARY_OBJECTCLASS_NAME, OPENDJ_ACCOUNT_LABELED_URI_OBJECT_AUXILIARY_OBJECTCLASS_NAME); assertLabeledUri(shadow, URI_WHATEVER); } - + @Test public void test146UnassignUserLargoUnix() throws Exception { final String TEST_NAME = "test146UnassignUserLargoUnix"; @@ -268,29 +268,29 @@ public void test146UnassignUserLargoUnix() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + // WHEN displayWhen(TEST_NAME); unassignRole(userBefore.getOid(), ROLE_UNIX_OID); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_LARGO_USERNAME); assertNotNull("No user after", userAfter); display("User after", userAfter); assertUserPosix(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME, USER_LARGO_UID_NUMBER); assertUserAuxes(userAfter, OPENDJ_ACCOUNT_LABELED_URI_OBJECT_AUXILIARY_OBJECTCLASS_NAME); - + String accountOid = getSingleLinkOid(userAfter); - + PrismObject shadow = getShadowModel(accountOid); display("Shadow (model)", shadow); assertAccount(shadow, OPENDJ_ACCOUNT_LABELED_URI_OBJECT_AUXILIARY_OBJECTCLASS_NAME); assertLabeledUri(shadow, URI_WHATEVER); } - + @Test public void test149UnAssignUserLargoBasic() throws Exception { final String TEST_NAME = "test149UnAssignUserLargoBasic"; @@ -299,26 +299,26 @@ public void test149UnAssignUserLargoBasic() throws Exception { OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); - + // WHEN displayWhen(TEST_NAME); unassignRole(userBefore.getOid(), ROLE_BASIC_OID); - + // THEN displayThen(TEST_NAME); assertSuccess(result); - + PrismObject userAfter = findUserByUsername(USER_LARGO_USERNAME); assertNotNull("No user after", userAfter); display("User after", userAfter); assertUserPosix(userAfter, USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME, USER_LARGO_UID_NUMBER); assertLinks(userAfter, 0); - + assertNoObject(ShadowType.class, accountLargoOid, task, result); - + openDJController.assertNoEntry(accountLargoDn); } - + // The assignment was disabled in the repository. There was no change that went through // model. MidPoint won't remove the aux object class. @Override @@ -326,7 +326,7 @@ protected void assertAccountTest510(PrismObject shadow) throws Excep assertPosixAccount(shadow, null); assertGroupAssociation(shadow, groupMonkeyIslandOid); } - + @Override protected Long getTimestampAttribute(PrismObject shadow) throws Exception { String attributeValue = ShadowUtil.getAttributeValue(shadow, OPENDJ_MODIFY_TIMESTAMP_ATTRIBUTE_QNAME); @@ -339,12 +339,12 @@ protected Long getTimestampAttribute(PrismObject shadow) throws Exce GeneralizedTime gt = new GeneralizedTime(attributeValue); return gt.getCalendar().getTimeInMillis(); } - + private void assertUserAuxes(PrismObject userAfter, QName... expectedAuxClasses) { PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATIONAL_UNIT, Arrays.stream(expectedAuxClasses).map(x -> createPolyString(x.getLocalPart())).toArray(PolyString[]::new)); } - + private void assertLabeledUri(PrismObject shadow, String expecteduri) throws DirectoryException { ShadowType shadowType = shadow.asObjectable(); String dn = (String) ShadowUtil.getSecondaryIdentifiers(shadow).iterator().next().getRealValue(); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestUuid.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestUuid.java index 693cb082edd..75c751967b1 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestUuid.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestUuid.java @@ -46,22 +46,22 @@ @ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestUuid extends AbstractStoryTest { - + public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "uuid"); - + public static final File SYSTEM_CONFIGURATION_FILE = new File(TEST_DIR, "system-configuration.xml"); - + public static final File OBJECT_TEMPLATE_USER_FILE = new File(TEST_DIR, "object-template-user.xml"); public static final String OBJECT_TEMPLATE_USER_OID = "10000000-0000-0000-0000-000000000222"; - + 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; - + public static final File ROLE_CLIENT_FILE = new File(TEST_DIR, "role-client.xml"); public static final String ROLE_CLIENT_OID = "10000000-0000-0000-0000-000000000601"; public static final String ROLE_CLIENT_NAME = "Client"; - + private static final File OU_CLIENTS_LDIF_FILE = new File(TEST_DIR, "ou-clients.ldif"); private static final String USER_RAPP_GIVEN_NAME = "Rapp"; @@ -73,11 +73,11 @@ public class TestUuid extends AbstractStoryTest { private static final String USER_KATE_NAME = "c0c010c0-d34d-b33f-f00d-11111aa00001"; private static final String USER_KATE_GIVEN_NAME = "Kate"; private static final String USER_KATE_FAMILY_NAME = "Capsize"; - + private static final String USER_WALLY_OID = "c0c010c0-d34d-b33f-f00d-11111aa00002"; private static final String USER_WALLY_GIVEN_NAME = "Wally"; private static final String USER_WALLY_FAMILY_NAME = "Feed"; - + private static final String USER_ROGERS_OID = "c0c010c0-d34d-b33f-f00d-11111aa00003"; private static final String USER_ROGERS_GIVEN_NAME = "Rum"; private static final String USER_ROGERS_FAMILY_NAME = "Rogers"; @@ -86,13 +86,13 @@ public class TestUuid extends AbstractStoryTest { private static final String USER_MARTY_NAME = "marty"; private static final String USER_MARTY_GIVEN_NAME = "Mad"; private static final String USER_MARTY_FAMILY_NAME = "Marty"; - + protected ResourceType resourceOpenDjType; protected PrismObject resourceOpenDj; - + protected String userRappOid; protected String userMancombOid; - + @Override protected void startResources() throws Exception { openDJController.startCleanServer(); @@ -102,27 +102,27 @@ protected void startResources() throws Exception { public static void stopResources() throws Exception { openDJController.stop(); } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - - // Resources + + // Resources resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, RESOURCE_OPENDJ_FILE, RESOURCE_OPENDJ_OID, initTask, initResult); resourceOpenDjType = resourceOpenDj.asObjectable(); openDJController.setResource(resourceOpenDj); - + // Object Templates importObjectFromFile(OBJECT_TEMPLATE_USER_FILE, initResult); - + // Role importObjectFromFile(ROLE_CLIENT_FILE, initResult); - + // LDAP content openDJController.addEntryFromLdifFile(OU_CLIENTS_LDIF_FILE); - + } - + @Override protected File getSystemConfigurationFile() { return SYSTEM_CONFIGURATION_FILE; @@ -133,32 +133,32 @@ public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + OperationResult testResultOpenDj = modelService.testResource(RESOURCE_OPENDJ_OID, task); TestUtil.assertSuccess(testResultOpenDj); - + waitForTaskStart(TASK_TRIGGER_SCANNER_OID, true); waitForTaskStart(TASK_VALIDITY_SCANNER_OID, true); } - + @Test public void test100AddUserRapp() throws Exception { final String TEST_NAME = "test100AddUserRapp"; TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject user = createNoNameUser(USER_RAPP_GIVEN_NAME, USER_RAPP_FAMILY_NAME, true); - + // WHEN addObject(user, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + userRappOid = user.getOid(); - + user = getUser(userRappOid); assertUser(user, USER_RAPP_GIVEN_NAME, USER_RAPP_FAMILY_NAME); } @@ -169,53 +169,53 @@ public void test101RappAssignRoleClient() throws Exception { TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN assignRole(userRappOid, ROLE_CLIENT_OID, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(userRappOid); assertUser(userAfter, USER_RAPP_GIVEN_NAME, USER_RAPP_FAMILY_NAME); assertLdapClient(userAfter, USER_RAPP_GIVEN_NAME, USER_RAPP_FAMILY_NAME); } - + // TODO: modify user, account should be modified - + @Test public void test107RappUnAssignRoleClient() throws Exception { final String TEST_NAME = "test107RappUnAssignRoleClient"; TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + // WHEN unassignRole(userRappOid, ROLE_CLIENT_OID); - + // THEN PrismObject userAfter = getUser(userRappOid); assertUser(userAfter, USER_RAPP_GIVEN_NAME, USER_RAPP_FAMILY_NAME); assertNoLdapClient(userAfter); } - + @Test public void test110AddMancombWithRoleClient() throws Exception { final String TEST_NAME = "test110AddMancombWithRoleClient"; TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject user = createClientUser(null, null, USER_MANCOMB_GIVEN_NAME, USER_MANCOMB_FAMILY_NAME, true); - + // WHEN addObject(user, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); userMancombOid = user.getOid(); - + PrismObject userAfter = getUser(userMancombOid); assertUser(userAfter, USER_MANCOMB_GIVEN_NAME, USER_MANCOMB_FAMILY_NAME); assertLdapClient(userAfter, USER_MANCOMB_GIVEN_NAME, USER_MANCOMB_FAMILY_NAME); @@ -231,41 +231,41 @@ public void test112RenameMancomb() throws Exception { TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + try { // WHEN modifyUserReplace(userMancombOid, UserType.F_NAME, task, result, PrismTestUtil.createPolyString("whatever")); - + AssertJUnit.fail("Unexpected success"); } catch (PolicyViolationException e) { // This is expected result.computeStatus(); TestUtil.assertFailure(result); } - + PrismObject userAfter = getUser(userMancombOid); assertUser(userAfter, USER_MANCOMB_GIVEN_NAME, USER_MANCOMB_FAMILY_NAME); assertLdapClient(userAfter, USER_MANCOMB_GIVEN_NAME, USER_MANCOMB_FAMILY_NAME); } - + @Test public void test119MancombDelete() throws Exception { final String TEST_NAME = "test119MancombDelete"; TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN deleteObject(UserType.class, userMancombOid, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + assertNoObject(UserType.class, userMancombOid, task, result); openDJController.assertNoEntry("uid="+userMancombOid+",ou=clients,dc=example,dc=com"); } - + /** * Kate nas a name. But no OID. */ @@ -275,16 +275,16 @@ public void test120AddKateWithRoleClient() throws Exception { TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject user = createClientUser(null, USER_KATE_NAME, USER_KATE_GIVEN_NAME, USER_KATE_FAMILY_NAME, true); - + // WHEN addObject(user, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_KATE_NAME); assertUser(userAfter, USER_WALLY_GIVEN_NAME, USER_WALLY_FAMILY_NAME); assertLdapClient(userAfter, USER_WALLY_GIVEN_NAME, USER_WALLY_FAMILY_NAME); @@ -299,21 +299,21 @@ public void test122AddWallyWithRoleClient() throws Exception { TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject user = createClientUser(USER_WALLY_OID, null, USER_WALLY_GIVEN_NAME, USER_WALLY_FAMILY_NAME, true); - + // WHEN addObject(user, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_WALLY_OID); assertUser(userAfter, USER_WALLY_GIVEN_NAME, USER_WALLY_FAMILY_NAME); assertLdapClient(userAfter, USER_WALLY_GIVEN_NAME, USER_WALLY_FAMILY_NAME); } - + /** * rogers has both OID and name and they do match. */ @@ -323,21 +323,21 @@ public void test124AddRogersWithRoleClient() throws Exception { TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject user = createClientUser(USER_ROGERS_OID, USER_ROGERS_OID, USER_ROGERS_GIVEN_NAME, USER_ROGERS_FAMILY_NAME, true); - + // WHEN addObject(user, task, result); - + // THEN result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject userAfter = getUser(USER_ROGERS_OID); assertUser(userAfter, USER_ROGERS_GIVEN_NAME, USER_ROGERS_FAMILY_NAME); assertLdapClient(userAfter, USER_ROGERS_GIVEN_NAME, USER_ROGERS_FAMILY_NAME); } - + /** * marty has both OID and name and they do NOT match. */ @@ -347,26 +347,26 @@ public void test126AddMartyWithRoleClient() throws Exception { TestUtil.displayTestTitle(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject user = createClientUser(USER_MARTY_OID, USER_MARTY_NAME, USER_MARTY_GIVEN_NAME, USER_MARTY_FAMILY_NAME, true); - + try { // WHEN addObject(user, task, result); - + AssertJUnit.fail("Unexpected success"); } catch (PolicyViolationException e) { // This is expected result.computeStatus(); TestUtil.assertFailure(result); } - + // THEN - + assertNoObject(UserType.class, USER_MARTY_OID, task, result); openDJController.assertNoEntry("uid="+USER_MARTY_OID+",ou=clients,dc=example,dc=com"); } - + private void assertUser(PrismObject user, String firstName, String lastName) { display("User", user); String oid = user.getOid(); @@ -379,7 +379,7 @@ private void assertLdapClient(PrismObject user, String firstName, Stri assertLinks(user, 1); assertAssignments(user, RoleType.class, 1); assertAssignedRole(user, ROLE_CLIENT_OID); - + assertAccount(user, RESOURCE_OPENDJ_OID); PrismReferenceValue linkRef = getLinkRef(user, RESOURCE_OPENDJ_OID); PrismObject shadow = getShadowModel(linkRef.getOid()); @@ -387,15 +387,15 @@ private void assertLdapClient(PrismObject user, String firstName, Stri IntegrationTestTools.assertSecondaryIdentifier(shadow, "uid="+user.getOid()+",ou=clients,dc=example,dc=com"); // TODO: cn, sn, givenName } - + private void assertNoLdapClient(PrismObject user) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, DirectoryException { assertLinks(user, 0); assertAssignments(user, RoleType.class, 0); assertNotAssignedRole(user, ROLE_CLIENT_OID); - + openDJController.assertNoEntry("uid="+user.getOid()+",ou=clients,dc=example,dc=com"); } - + protected PrismObject createNoNameUser(String givenName, String familyName, Boolean enabled) throws SchemaException { PrismObject user = getUserDefinition().instantiate(); UserType userType = user.asObjectable(); @@ -412,7 +412,7 @@ protected PrismObject createNoNameUser(String givenName, String family } return user; } - + private PrismObject createClientUser(String oid, String name, String givenName, String familyName, boolean enabled) throws SchemaException { PrismObject user = createNoNameUser(givenName, familyName, enabled); @@ -428,5 +428,5 @@ private PrismObject createClientUser(String oid, String name, String g } return user; } - + } 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 7725d925432..0b11e68d5c1 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 @@ -67,44 +67,44 @@ @ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestVillage extends AbstractStoryTest { - + public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "village"); - + public static final File SYSTEM_CONFIGURATION_FILE = new File(TEST_DIR, "system-configuration.xml"); - + public static final File OBJECT_TEMPLATE_USER_FILE = new File(TEST_DIR, "object-template-user.xml"); public static final String OBJECT_TEMPLATE_USER_OID = "10000000-0000-0000-0000-000000000222"; - + protected static final File RESOURCE_DUMMY_SOURCE_FILE = new File(TEST_DIR, "resource-dummy-source.xml"); protected static final String RESOURCE_DUMMY_SOURCE_ID = "SRC"; protected static final String RESOURCE_DUMMY_SOURCE_OID = "10000000-0000-0000-0000-000000000001"; protected static final String RESOURCE_DUMMY_SOURCE_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_SRC_FIRST_NAME = "firstname"; private static final String DUMMY_ACCOUNT_ATTRIBUTE_SRC_LAST_NAME = "lastname"; private static final String DUMMY_ACCOUNT_ATTRIBUTE_SRC_TYPE = "type"; private static final String DUMMY_ACCOUNT_ATTRIBUTE_SRC_LOC = "loc"; private static final String DUMMY_ACCOUNT_ATTRIBUTE_SRC_ORG = "org"; - + public static final File ROLE_BASIC_FILE = new File(TEST_DIR, "role-basic.xml"); public static final String ROLE_BASIC_OID = "10000000-0000-0000-0000-000000000601"; public static final String ROLE_BASIC_NAME = "Basic"; - + public static final File ROLE_SIMPLE_FILE = new File(TEST_DIR, "role-account-construction.xml"); public static final String ROLE_SIMPLE_OID = "10000000-0000-0000-0000-000000000602"; public static final String ROLE_SIMPLE_NAME = "Simple account construction"; - + public static final File ROLE_META_FUNCTIONAL_ORG_FILE = new File(TEST_DIR, "role-meta-functional-org.xml"); public static final String ROLE_META_FUNCTIONAL_ORG_OID = "74aac2c8-ca0f-11e3-bb29-001e8c717e5b"; - + public static final File ROLE_META_PROJECT_ORG_FILE = new File(TEST_DIR, "role-meta-project-org.xml"); public static final String ROLE_META_PROJECT_ORG_OID = "ab33ec1e-0c0b-11e4-ba88-001e8c717e5b"; - + protected static final File ORGS_FILE = new File(TEST_DIR, "orgs.xml"); public static final String ORG_GOV_NAME = "Gov"; public static final String ORG_EXEC_NAME = "Exec"; @@ -115,13 +115,13 @@ public class TestVillage extends AbstractStoryTest { private static final String ORG_PASSWORD_POLICY_OID = "81818181-76e0-59e2-8888-3d4f02d3fffe"; private static final File GLOBAL_PASSWORD_POLICY_FILE = new File(TEST_DIR, "global-password-policy.xml"); private static final File ORG_PASSWORD_POLICY_FILE = new File(TEST_DIR, "org-password-policy.xml"); - + public static final File ORG_PROJECT_JOLLY_ROGER_FILE = new File(TEST_DIR, "org-project-jolly-roger.xml"); public static final String ORG_PROJECT_JOLLY_ROGER_OID = "a9ac1aa2-0c0f-11e4-9214-001e8c717e5b"; - + protected static final File TASK_LIVE_SYNC_DUMMY_SOURCE_FILE = new File(TEST_DIR, "task-dumy-source-livesync.xml"); protected static final String TASK_LIVE_SYNC_DUMMY_SOURCE_OID = "10000000-0000-0000-5555-555500000001"; - + private static final File USER_MIKE_FILE = new File(COMMON_DIR, "user-mike.xml"); private static final String USER_MIKE_OID = "c0c010c0-d34d-b33f-f00d-222333111111"; @@ -134,7 +134,7 @@ public class TestVillage extends AbstractStoryTest { 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 ACCOUNT_LEMONHEAD_USERNAME = "lemonhead"; private static final String ACCOUNT_LEMONHEAD_FIST_NAME = "Lemonhead"; private static final String ACCOUNT_LEMONHEAD_LAST_NAME = "Canibal"; @@ -149,14 +149,14 @@ public class TestVillage extends AbstractStoryTest { 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_MANCOMB_USERNAME = "mancomb"; private static final String ACCOUNT_MANCOMB_FIST_NAME = "Mancomb"; 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 ACCOUNT_COBB_USERNAME = "cobb"; private static final String ACCOUNT_COBB_FIST_NAME = "Cobb"; private static final String ACCOUNT_COBB_LAST_NAME = "Loom"; @@ -164,32 +164,32 @@ public class TestVillage extends AbstractStoryTest { private static final String ACCOUNT_LARGO_USERNAME = "largo"; private static final String ACCOUNT_LARGO_FIST_NAME = "Largo"; private static final String ACCOUNT_LARGO_LAST_NAME = "LaGrande"; - + 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_CAPSIZE_USERNAME = "capsize"; private static final String ACCOUNT_CAPSIZE_FIST_NAME = "Kate"; private static final String ACCOUNT_CAPSIZE_LAST_NAME = "Capsize"; - + 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 ACCOUNT_AUGUSTUS_USERNAME = "augustus"; private static final String ACCOUNT_AUGUSTUS_FIST_NAME = "Augustus"; private static final String ACCOUNT_AUGUSTUS_LAST_NAME = "DeWaat"; - + private static final String ACCOUNT_ROGERSSR_USERNAME = "rogers,sr"; private static final String ACCOUNT_ROGERSSR_FIST_NAME = "Rum"; private static final String ACCOUNT_ROGERSSR_LAST_NAME = "Rogers, Sr."; - + private static final String ACCOUNT_TELEKE_USERNAME = "tőlőkë"; private static final String ACCOUNT_TELEKE_FIST_NAME = "Félix"; private static final String ACCOUNT_TELEKE_LAST_NAME = "Tőlőkë"; - + private static final File GROUP_GOV_MONKEY_ISLAND_LDIF_FILE = new File(TEST_DIR, "group-gov-monkey-island.ldif"); private static final File GROUP_EXEC_MONKEY_ISLAND_LDIF_FILE = new File(TEST_DIR, "group-exec-monkey-island.ldif"); @@ -207,10 +207,10 @@ public class TestVillage extends AbstractStoryTest { protected static DummyResourceContoller dummyResourceCtlSrc; protected ResourceType resourceDummySrcType; protected PrismObject resourceDummySrc; - + protected ResourceType resourceOpenDjType; protected PrismObject resourceOpenDj; - + @Override protected void startResources() throws Exception { openDJController.startCleanServer(); @@ -220,11 +220,11 @@ protected void startResources() throws Exception { public static void stopResources() throws Exception { openDJController.stop(); } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + // Resources dummyResourceCtlSrc = DummyResourceContoller.create(RESOURCE_DUMMY_SOURCE_ID, resourceDummySrc); DummyObjectClass dummyAdAccountObjectClass = dummyResourceCtlSrc.getDummyResource().getAccountObjectClass(); @@ -238,61 +238,61 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti resourceDummySrcType = resourceDummySrc.asObjectable(); dummyResourceCtlSrc.setResource(resourceDummySrc); dummyResourceSrc.setSyncStyle(DummySyncStyle.SMART); - + resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, RESOURCE_OPENDJ_FILE, RESOURCE_OPENDJ_OID, initTask, initResult); resourceOpenDjType = resourceOpenDj.asObjectable(); openDJController.setResource(resourceOpenDj); - + // Object Templates importObjectFromFile(OBJECT_TEMPLATE_USER_FILE, initResult); setDefaultUserTemplate(OBJECT_TEMPLATE_USER_OID); - + // Role importObjectFromFile(ROLE_BASIC_FILE, initResult); importObjectFromFile(ROLE_SIMPLE_FILE, initResult); importObjectFromFile(ROLE_META_FUNCTIONAL_ORG_FILE, initResult); importObjectFromFile(ROLE_META_PROJECT_ORG_FILE, initResult); - + // Org repoAddObjectsFromFile(ORGS_FILE, OrgType.class, initResult); - + // LDAP content openDJController.addEntryFromLdifFile(GROUP_GOV_MONKEY_ISLAND_LDIF_FILE); openDJController.addEntryFromLdifFile(GROUP_EXEC_MONKEY_ISLAND_LDIF_FILE); // Tasks importObjectFromFile(TASK_LIVE_SYNC_DUMMY_SOURCE_FILE, initResult); - + InternalMonitor.setTrace(InternalOperationClasses.PRISM_OBJECT_CLONES, true); - + } - + @Override protected File getSystemConfigurationFile() { return SYSTEM_CONFIGURATION_FILE; } - + @Test public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + OperationResult testResultHr = modelService.testResource(RESOURCE_DUMMY_SOURCE_OID, task); TestUtil.assertSuccess(testResultHr); - + OperationResult testResultOpenDj = modelService.testResource(RESOURCE_OPENDJ_OID, task); TestUtil.assertSuccess(testResultOpenDj); - + SystemConfigurationType systemConfiguration = getSystemConfiguration(); assertNotNull("No system configuration", systemConfiguration); display("System config", systemConfiguration); - + waitForTaskStart(TASK_TRIGGER_SCANNER_OID, true); waitForTaskStart(TASK_VALIDITY_SCANNER_OID, true); waitForTaskStart(TASK_LIVE_SYNC_DUMMY_SOURCE_OID, false); } - + /** * MID-3424 */ @@ -302,33 +302,33 @@ public void test020ResourceOpenDjGet() throws Exception { displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + rememberCounter(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT); rememberCounter(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT); rememberCounter(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT); rememberCounter(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT); rememberCounter(InternalCounters.PRISM_OBJECT_CLONE_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); modelService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + // variable number of clones because of trigger scanner task assertCounterIncrement(InternalCounters.PRISM_OBJECT_CLONE_COUNT, 1, 2); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); } - + /** * MID-3424 */ @@ -338,67 +338,67 @@ public void test022ResourceOpenDjRefinedSchema() throws Exception { displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + PrismObject resourceBefore = modelService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, task, result); ResourceSchema resourceSchemaBefore = RefinedResourceSchema.getResourceSchema(resourceBefore, prismContext); RefinedResourceSchema refinedSchemaBefore = RefinedResourceSchema.getRefinedSchema(resourceBefore); - + rememberCounter(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT); rememberCounter(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT); rememberCounter(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT); rememberCounter(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT); rememberCounter(InternalCounters.PRISM_OBJECT_CLONE_COUNT); - + // WHEN TestUtil.displayWhen(TEST_NAME); long t0 = System.currentTimeMillis(); PrismObject resourceAfter = modelService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, task, result); long t1 = System.currentTimeMillis(); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + long t2 = System.currentTimeMillis(); ResourceSchema resourceSchemaAfter = RefinedResourceSchema.getResourceSchema(resourceAfter, prismContext); long t3 = System.currentTimeMillis(); 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"); - + // variable number of clones: 1 or 2 because of trigger scanner task assertCounterIncrement(InternalCounters.PRISM_OBJECT_CLONE_COUNT, 1, 2); - + assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); - + assertTrue("Resource schema has changed", resourceSchemaBefore == resourceSchemaAfter ); assertTrue("Refined schema has changed", refinedSchemaBefore == refinedSchemaAfter ); } - + @Test public void test100AddSrcAccountHerman() throws Exception { final String TEST_NAME = "test100AddSrcAccountHerman"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.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); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_LOC, ACCOUNT_HERMAN_LOC); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_ORG, ACCOUNT_HERMAN_ORG); - + // WHEN dummyResourceSrc.addAccount(newAccount); waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_SOURCE_OID, true); - + // THEN PrismObject user = findUserByUsername(USER_HERMAN_NAME); assertUserNoRole(user, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG); @@ -410,49 +410,49 @@ public void test101HermanAssignBasicRole() throws Exception { final String TEST_NAME = "test101HermanAssignBasicRole"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + PrismObject user = findUserByUsername(USER_HERMAN_NAME); - + // WHEN assignRole(user.getOid(), ROLE_BASIC_OID); - + // THEN PrismObject userAfter = getUser(user.getOid()); assertUserLdap(userAfter, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG); assertLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG); assertLdapLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG); } - + @Test public void test102HermanUnAssignBasicRole() throws Exception { final String TEST_NAME = "test102HermanUnAssignBasicRole"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + PrismObject user = findUserByUsername(USER_HERMAN_NAME); - + // WHEN unassignRole(user.getOid(), ROLE_BASIC_OID); - + // THEN PrismObject userAfter = getUser(user.getOid()); assertUserNoRole(userAfter, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG); assertLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG); assertNoLdapLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG); } - + @Test public void test103HermanAssignBasicAndSimpleRole() throws Exception { final String TEST_NAME = "test103HermanAssignBasicAndSimpleRole"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + PrismObject user = findUserByUsername(USER_HERMAN_NAME); - + // WHEN assignRole(user.getOid(), ROLE_SIMPLE_OID); assignRole(user.getOid(), ROLE_BASIC_OID); - + // THEN PrismObject userAfter = getUser(user.getOid()); assertUserLdap(userAfter, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG, 2); @@ -460,103 +460,103 @@ public void test103HermanAssignBasicAndSimpleRole() throws Exception { assertLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG); assertLdapLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG); } - + @Test public void test104HermanUnAssignSimpleRoleThenBasic() throws Exception { final String TEST_NAME = "test104HermanUnAssignSimpleRoleThenBasic"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + PrismObject user = findUserByUsername(USER_HERMAN_NAME); - + // WHEN unassignRole(user.getOid(), ROLE_BASIC_OID); - + // THEN PrismObject userAfter = getUser(user.getOid()); assertAssignedRole(userAfter, ROLE_SIMPLE_OID); // assertUserLdap(userAfter, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG); assertLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG); assertNoLdapLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG); - + // WHEN unassignRole(user.getOid(), ROLE_SIMPLE_OID); - + // THEN userAfter = getUser(user.getOid()); assertUserNoRole(userAfter, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG); assertLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG); assertNoLdapLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG); } - + @Test public void test105ModifySrcAccountHermanRemoveLoc() throws Exception { final String TEST_NAME = "test105ModifySrcAccountHermanRemoveLoc"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + DummyAccount account = dummyResourceSrc.getAccountByUsername(ACCOUNT_HERMAN_USERNAME); - + // WHEN account.replaceAttributeValues(DUMMY_ACCOUNT_ATTRIBUTE_SRC_LOC); waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_SOURCE_OID, true); - + // THEN PrismObject user = findUserByUsername(USER_HERMAN_NAME); assertUserNoRole(user, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG); assertLocGov(user, null, ACCOUNT_HERMAN_ORG); } - + @Test public void test106HermanAssignBasicRole() throws Exception { final String TEST_NAME = "test106HermanAssignBasicRole"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + PrismObject user = findUserByUsername(USER_HERMAN_NAME); - + // WHEN assignRole(user.getOid(), ROLE_BASIC_OID); - + // THEN PrismObject userAfter = getUser(user.getOid()); assertUserLdap(userAfter, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG); assertLocGov(userAfter, null, ACCOUNT_HERMAN_ORG); assertNoLdapLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG); } - + @Test public void test107ModifySrcAccountHermanAddLoc() throws Exception { final String TEST_NAME = "test107ModifySrcAccountHermanAddLoc"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + DummyAccount account = dummyResourceSrc.getAccountByUsername(ACCOUNT_HERMAN_USERNAME); - + // WHEN account.replaceAttributeValues(DUMMY_ACCOUNT_ATTRIBUTE_SRC_LOC, ACCOUNT_HERMAN_LOC); waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_SOURCE_OID, true); - + // THEN PrismObject user = findUserByUsername(USER_HERMAN_NAME); assertUserLdap(user, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG); assertLocGov(user, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG); assertLdapLocGov(user, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG); } - + @Test public void test108ModifySrcAccountHermanRemoveLoc() throws Exception { final String TEST_NAME = "test108ModifySrcAccountHermanRemoveLoc"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + DummyAccount account = dummyResourceSrc.getAccountByUsername(ACCOUNT_HERMAN_USERNAME); - + // WHEN account.replaceAttributeValues(DUMMY_ACCOUNT_ATTRIBUTE_SRC_LOC); waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_SOURCE_OID, true); - + // THEN PrismObject user = findUserByUsername(USER_HERMAN_NAME); assertUserLdap(user, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG); @@ -569,43 +569,43 @@ public void test109HermanUnAssignBasicRole() throws Exception { final String TEST_NAME = "test109HermanUnAssignBasicRole"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + PrismObject user = findUserByUsername(USER_HERMAN_NAME); - + // WHEN unassignRole(user.getOid(), ROLE_BASIC_OID); - + // THEN PrismObject userAfter = getUser(user.getOid()); assertUserNoRole(userAfter, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ACCOUNT_HERMAN_ORG); assertLocGov(userAfter, null, ACCOUNT_HERMAN_ORG); assertNoLdapLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG); } - + @Test public void test110AddSrcAccountLemonhead() throws Exception { final String TEST_NAME = "test110AddSrcAccountLemonhead"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.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); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_TYPE, ROLE_BASIC_NAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_LOC, ACCOUNT_LEMONHEAD_LOC); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_ORG, ACCOUNT_LEMONHEAD_ORG); - + // WHEN dummyResourceSrc.addAccount(newAccount); waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_SOURCE_OID, true); - + // THEN PrismObject userAfter = findUserByUsername(USER_LEMONHEAD_NAME); assertUserLdap(userAfter, ACCOUNT_LEMONHEAD_FIST_NAME, ACCOUNT_LEMONHEAD_LAST_NAME, ACCOUNT_LEMONHEAD_ORG); assertLocGov(userAfter, ACCOUNT_LEMONHEAD_LOC, ACCOUNT_LEMONHEAD_ORG); assertLdapLocGov(userAfter, ACCOUNT_LEMONHEAD_LOC, ACCOUNT_LEMONHEAD_ORG); } - + /** * Wally has no org. User without an org should be created. */ @@ -614,15 +614,15 @@ public void test120AddSrcAccountWally() throws Exception { final String TEST_NAME = "test120AddSrcAccountWally"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.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); - + // WHEN dummyResourceSrc.addAccount(newAccount); waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_SOURCE_OID, true); - + // THEN PrismObject userAfter = findUserByUsername(USER_WALLY_NAME); assertUserNoRole(userAfter, ACCOUNT_WALLY_FIST_NAME, ACCOUNT_WALLY_LAST_NAME, null); @@ -634,29 +634,29 @@ public void test121WallyAssignBasicRole() throws Exception { final String TEST_NAME = "test121WallyAssignBasicRole"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + PrismObject user = findUserByUsername(USER_WALLY_NAME); - + // WHEN assignRole(user.getOid(), ROLE_BASIC_OID); - + // THEN PrismObject userAfter = getUser(user.getOid()); assertUserLdap(userAfter, ACCOUNT_WALLY_FIST_NAME, ACCOUNT_WALLY_LAST_NAME, null); assertLocGov(userAfter, null, null); } - + @Test public void test122WallyUnAssignBasicRole() throws Exception { final String TEST_NAME = "test122WallyUnAssignBasicRole"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + PrismObject user = findUserByUsername(USER_WALLY_NAME); - + // WHEN unassignRole(user.getOid(), ROLE_BASIC_OID); - + // THEN PrismObject userAfter = getUser(user.getOid()); assertUserNoRole(userAfter, ACCOUNT_WALLY_FIST_NAME, ACCOUNT_WALLY_LAST_NAME, null); @@ -671,17 +671,17 @@ public void test130AddSrcAccountMancomb() throws Exception { final String TEST_NAME = "test130AddSrcAccountMancomb"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.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); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_LOC, ACCOUNT_MANCOMB_LOC); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_ORG, ACCOUNT_MANCOMB_ORG); - + // WHEN dummyResourceSrc.addAccount(newAccount); waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_SOURCE_OID, true); - + // THEN PrismObject userAfter = findUserByUsername(USER_MANCOMB_NAME); assertUserNoRole(userAfter, ACCOUNT_MANCOMB_FIST_NAME, ACCOUNT_MANCOMB_LAST_NAME, null); @@ -693,36 +693,36 @@ public void test131MancombAssignBasicRole() throws Exception { final String TEST_NAME = "test131WallyAssignBasicRole"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + PrismObject user = findUserByUsername(USER_MANCOMB_NAME); - + // WHEN assignRole(user.getOid(), ROLE_BASIC_OID); - + // THEN PrismObject userAfter = getUser(user.getOid()); assertUserLdap(userAfter, ACCOUNT_MANCOMB_FIST_NAME, ACCOUNT_MANCOMB_LAST_NAME, null); assertLocGov(userAfter, ACCOUNT_MANCOMB_LOC, ACCOUNT_MANCOMB_ORG); } - + @Test public void test132MancombUnAssignBasicRole() throws Exception { final String TEST_NAME = "test132MancombUnAssignBasicRole"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + PrismObject user = findUserByUsername(USER_MANCOMB_NAME); - + // WHEN unassignRole(user.getOid(), ROLE_BASIC_OID); - + // THEN PrismObject userAfter = getUser(user.getOid()); assertUserNoRole(userAfter, ACCOUNT_MANCOMB_FIST_NAME, ACCOUNT_MANCOMB_LAST_NAME, null); assertLocGov(userAfter, ACCOUNT_MANCOMB_LOC, ACCOUNT_MANCOMB_ORG); } - + /** * Change of org should trigger rename */ @@ -731,22 +731,22 @@ public void test150ModifySrcAccountHermanReplaceOrg() throws Exception { final String TEST_NAME = "test150ModifySrcAccountHermanReplaceOrg"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + DummyAccount account = dummyResourceSrc.getAccountByUsername(ACCOUNT_HERMAN_USERNAME); - + // WHEN account.replaceAttributeValues(DUMMY_ACCOUNT_ATTRIBUTE_SRC_ORG, ORG_INFRA_NAME); waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_SOURCE_OID, true); - + // THEN PrismObject user = findUserByUsername(getUsername(ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ORG_INFRA_NAME)); assertUserNoRole(user, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ORG_INFRA_NAME); assertLocGov(user, null, ORG_INFRA_NAME); - + PrismObject userGone = findUserByUsername(USER_HERMAN_NAME); assertNull("Original herman is not gone", userGone); } - + /** * Change of org should trigger rename */ @@ -755,61 +755,61 @@ public void test152ModifySrcAccountHermanDeleteOrg() throws Exception { final String TEST_NAME = "test152ModifySrcAccountHermanDeleteOrg"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + DummyAccount account = dummyResourceSrc.getAccountByUsername(ACCOUNT_HERMAN_USERNAME); - + // WHEN TestUtil.displayWhen(TEST_NAME); account.replaceAttributeValues(DUMMY_ACCOUNT_ATTRIBUTE_SRC_ORG); waitForTaskNextRunAssertSuccess(TASK_LIVE_SYNC_DUMMY_SOURCE_OID, true); - + // THEN TestUtil.displayThen(TEST_NAME); PrismObject user = findUserByUsername(getUsername(ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, null)); assertUserNoRole(user, ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, null); assertLocGov(user, null, null); - + PrismObject userGone = findUserByUsername(USER_HERMAN_NAME); assertNull("Original herman is not gone", userGone); userGone = findUserByUsername(getUsername(ACCOUNT_HERMAN_FIST_NAME, ACCOUNT_HERMAN_LAST_NAME, ORG_INFRA_NAME)); assertNull("First renamed herman is not gone", userGone); } - + @Test public void test200createUserAssignOrgPwdPolicy() throws Exception{ - + final String TEST_NAME = "test200createUserAssignOrgPwdPolicy"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); OperationResult result = new OperationResult(TEST_NAME); - + //prepare password policies addObject(GLOBAL_PASSWORD_POLICY_FILE); addObject(ORG_PASSWORD_POLICY_FILE); - + ObjectDelta orgPasswordPolicyRefDelta = ObjectDelta.createModificationAddReference(OrgType.class, ORG_INFRA_OID, OrgType.F_PASSWORD_POLICY_REF, prismContext, ORG_PASSWORD_POLICY_OID); - + Collection deltas = MiscUtil.createCollection(orgPasswordPolicyRefDelta); modelService.executeChanges(deltas, null, task, result); - + InternalsConfig.setAvoidLoggingChange(true); ObjectDelta sysConfigPasswordPolicyRefDelta = ObjectDelta.createModificationAddReference(SystemConfigurationType.class, SYSTEM_CONFIGURATION_OID, SystemConfigurationType.F_GLOBAL_PASSWORD_POLICY_REF, prismContext, GLOBAL_PASSWORD_POLICY_OID); deltas = MiscUtil.createCollection(sysConfigPasswordPolicyRefDelta); modelService.executeChanges(deltas, null, task, result); InternalsConfig.setAvoidLoggingChange(false); - + //add user + assign role + assign org with the password policy specified PrismObject objectToAdd = PrismTestUtil.parseObject(USER_MIKE_FILE); ObjectDelta addUser = ObjectDelta.createAddDelta(objectToAdd); - + deltas = MiscUtil.createCollection(addUser); //The user's password has length 4..if the policy is not chosen correctly, it fails modelService.executeChanges(deltas, null, task, result); //TODO: assert added user - + } - + @Test public void test201unassignRole() throws Exception{ final String TEST_NAME = "test201unassignRole"; @@ -817,43 +817,43 @@ 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"; displayTestTitle(TEST_NAME); - + //this will throw exception, if incorrect pwd policy is selected...but some assertion will be nice :) assignRole(USER_MIKE_OID, ROLE_BASIC_OID); - + //TODO: assertion } - + @Test public void test300AddProjectJollyRoger() throws Exception { final String TEST_NAME = "test300AddProjectJollyRoger"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); addObject(ORG_PROJECT_JOLLY_ROGER_FILE, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + PrismObject org = getObject(OrgType.class, ORG_PROJECT_JOLLY_ROGER_OID); display("Org", org); assertLinks(org, 2); - + 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 } - + /** * MID-3429 */ @@ -863,14 +863,14 @@ public void test310ProjectJollyRogerNestedGroup() throws Exception { displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.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"); - + display("LDAP entries", openDJController.dumpEntries()); - + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassFilterPrefix(RESOURCE_OPENDJ_OID, GROUP_OF_UNIQUE_NAMES_OBJECTCLASS_QNAME, prismContext) .and().itemWithDef( new PrismPropertyDefinitionImpl<>(new QName(RESOURCE_OPENDJ_NAMESPACE, "cn"), DOMUtil.XSD_STRING, prismContext), @@ -881,12 +881,12 @@ ShadowType.F_ATTRIBUTES, new QName(RESOURCE_OPENDJ_NAMESPACE, "cn")).eq("admins" TestUtil.displayWhen(TEST_NAME); // TODO: search for cn=admins,ou=Jolly Roger,dc=example,dc=com SearchResultList> groupShadows = modelService.searchObjects(ShadowType.class, query, null, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + display("groupShadows", groupShadows); assertEquals("Wrong number of shadows found", 1, groupShadows.size()); PrismObject groupShadow = groupShadows.get(0); @@ -894,28 +894,28 @@ ShadowType.F_ATTRIBUTES, new QName(RESOURCE_OPENDJ_NAMESPACE, "cn")).eq("admins" // MID-3430, MID-3429 // assertEquals("Wrong number of associations in "+groupShadow, 1, associations.size()); } - + @Test public void test319DeleteProjectJollyRoger() throws Exception { final String TEST_NAME = "test319DeleteProjectJollyRoger"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - + // WHEN TestUtil.displayWhen(TEST_NAME); deleteObject(OrgType.class, ORG_PROJECT_JOLLY_ROGER_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + assertNoObject(OrgType.class, ORG_PROJECT_JOLLY_ROGER_OID, task, result); openDJController.assertNoEntry("ou=Jolly Roger,dc=example,dc=com"); openDJController.assertNoEntry("cn=admins,ou=Jolly Roger,dc=example,dc=com"); } - + /** * User is added to repo directly, so he does not have OID in employee number. * Recompute should fix that. This is a migration scenario. @@ -929,27 +929,27 @@ public void test350AddRepoUserNoEmployeeNumberRecompute() throws Exception { PrismObject user = PrismTestUtil.parseObject(USER_MURRAY_FILE); repositoryService.addObject(user, null, result); - + // WHEN TestUtil.displayWhen(TEST_NAME); recomputeUser(USER_MURRAY_OID, task, result); - + // THEN TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + user = getUser(USER_MURRAY_OID); - assertEmployeeNumber(user); + assertEmployeeNumber(user); } - + 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()); if (expOrg == null) { assertTrue("Unexpected organization in "+user+": "+userType.getOrganization(), userType.getOrganization().isEmpty()); } else { - PrismAsserts.assertEqualsCollectionUnordered("Wrong organization in "+user, userType.getOrganization(), + PrismAsserts.assertEqualsCollectionUnordered("Wrong organization in "+user, userType.getOrganization(), PrismTestUtil.createPolyStringType(expOrg)); } if (expLoc == null || expOrg == null) { @@ -961,7 +961,7 @@ private void assertLocGov(PrismObject user, String expLoc, String expO 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()); } else { @@ -970,7 +970,7 @@ private void assertLocGov(PrismObject user, String expLoc, String expO 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); @@ -988,7 +988,7 @@ private void assertUserNoRole(PrismObject user, String firstName, Stri private void assertUserLdap(PrismObject user, String firstName, String lastName, String orgName) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { assertUserLdap(user, firstName, lastName, orgName, 1); } - + 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); @@ -998,17 +998,17 @@ private void assertUserLdap(PrismObject user, String firstName, String assertEmployeeNumber(user); assertLinks(user, 2); assertAccount(user, RESOURCE_DUMMY_SOURCE_OID); - + assertAssignments(user, RoleType.class, assignments); assertAssignedRole(user, ROLE_BASIC_OID); - + 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"); } - + private void assertEmployeeNumber(PrismObject user) { String employeeNumber = user.asObjectable().getEmployeeNumber(); assertEquals("Wrong employeeNumber in "+user, user.getOid(), employeeNumber); @@ -1022,24 +1022,24 @@ private String getUsername(String firstName, String lastName, String orgName) th } 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(); Entry groupEntry = openDJController.fetchAndAssertEntry(groupDn, "groupOfUniqueNames"); display("Group entry", groupEntry); - + PrismReferenceValue accountLinkRef = getLinkRef(user, RESOURCE_OPENDJ_OID); PrismObject accountShadow = getShadowModel(accountLinkRef.getOid()); String accountDn = IntegrationTestTools.getSecondaryIdentifier(accountShadow); openDJController.assertUniqueMember(groupEntry, accountDn); } - + private void assertNoLdapLocGov(PrismObject user, String expLoc, String expOrg) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, DirectoryException { UserType userType = user.asObjectable(); - + String groupCn = expOrg+":"+expLoc; String groupDn = "cn="+groupCn+",ou=groups,"+openDJController.getSuffix(); Entry groupEntry = openDJController.fetchAndAssertEntry(groupDn, "groupOfUniqueNames"); @@ -1047,5 +1047,5 @@ private void assertNoLdapLocGov(PrismObject user, String expLoc, Strin 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/ldaphierarchy/AbstractLdapHierarchyTest.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldaphierarchy/AbstractLdapHierarchyTest.java index 8fa8b404770..b1519f71bc8 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldaphierarchy/AbstractLdapHierarchyTest.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldaphierarchy/AbstractLdapHierarchyTest.java @@ -78,20 +78,20 @@ /** * Common superclass for LDAP hierarchy tests TestLdapFlat, TestLdapNested - * + * * @author Radovan Semancik * */ @ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public abstract class AbstractLdapHierarchyTest extends AbstractStoryTest { - + 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 String ORG_TOP_OID = "00000000-8888-6666-0000-100000000001"; - + public static final String ROLE_META_ORG_OID = "10000000-0000-0000-0000-000000006601"; protected static final String ORG_ROYULA_CARPATHIA_NAME = "Royula Carpathia"; @@ -107,7 +107,7 @@ public abstract class AbstractLdapHierarchyTest extends AbstractStoryTest { protected static final String USER_TELEKE_USERNAME = "teleke"; protected static final String USER_TELEKE_GIVEN_NAME = "Felix"; 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"; @@ -116,7 +116,7 @@ public abstract class AbstractLdapHierarchyTest extends AbstractStoryTest { protected static final String USER_DEZI_USERNAME = "dezi"; protected static final String USER_DEZI_GIVEN_NAME = "Vilja"; protected static final String USER_DEZI_FAMILY_NAME = "Dézi"; - + protected ResourceType resourceOpenDjType; protected PrismObject resourceOpenDj; @@ -125,17 +125,17 @@ public abstract class AbstractLdapHierarchyTest extends AbstractStoryTest { protected String orgVysneVlkodlakyOid; protected String orgRolyulaDiabolicaOid; protected String userGorcOid; - + protected abstract File getTestDir(); - + protected File getResourceOpenDjFile() { return new File(getTestDir(), "resource-opendj.xml"); } - + protected File getOrgTopFile() { return new File(getTestDir(), "org-top.xml"); } - + protected File getRoleMetaOrgFile() { return new File(getTestDir(), "role-meta-org.xml"); } @@ -149,13 +149,13 @@ protected void startResources() throws Exception { public static void stopResources() throws Exception { openDJController.stop(); } - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - - - // Resources + + + // Resources resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, getResourceOpenDjFile(), RESOURCE_OPENDJ_OID, initTask, initResult); resourceOpenDjType = resourceOpenDj.asObjectable(); openDJController.setResource(resourceOpenDj); @@ -166,20 +166,20 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti // Role importObjectFromFile(getRoleMetaOrgFile(), initResult); } - + @Test public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; displayTestTitle(TEST_NAME); Task task = taskManager.createTaskInstance(TestTrafo.class.getName() + "." + TEST_NAME); - + OperationResult testResultOpenDj = modelService.testResource(RESOURCE_OPENDJ_OID, task); TestUtil.assertSuccess(testResultOpenDj); dumpOrgTree(); dumpLdap(); } - + @Test public void test100AddOrgRoyulaCarpathia() throws Exception { final String TEST_NAME = "test100AddOrgRoyulaCarpathia"; @@ -188,7 +188,7 @@ public void test100AddOrgRoyulaCarpathia() throws Exception { OperationResult result = task.getResult(); PrismObject orgBefore = createOrg(ORG_ROYULA_CARPATHIA_NAME, ORG_TOP_OID); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("Adding org", orgBefore); @@ -198,17 +198,17 @@ public void test100AddOrgRoyulaCarpathia() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject orgAfter = getAndAssertFunctionalOrg(ORG_ROYULA_CARPATHIA_NAME, ORG_TOP_OID); orgRolyulaCarpathiaOid = orgAfter.getOid(); assertSubOrgs(orgAfter, 0); assertSubOrgs(ORG_TOP_OID, 1); } - + @Test public void test110AddUserTeleke() throws Exception { final String TEST_NAME = "test110AddUserTeleke"; @@ -216,9 +216,9 @@ public void test110AddUserTeleke() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - PrismObject userBefore = createUser(USER_TELEKE_USERNAME, + PrismObject userBefore = createUser(USER_TELEKE_USERNAME, USER_TELEKE_GIVEN_NAME, USER_TELEKE_FAMILY_NAME, orgRolyulaCarpathiaOid); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("Adding user", userBefore); @@ -228,18 +228,18 @@ public void test110AddUserTeleke() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject userAfter = getAndAssertUser(USER_TELEKE_USERNAME, ORG_ROYULA_CARPATHIA_NAME); - + PrismObject orgAfter = getAndAssertFunctionalOrg(ORG_ROYULA_CARPATHIA_NAME, ORG_TOP_OID); assertSubOrgs(orgAfter, 0); assertSubOrgs(ORG_TOP_OID, 1); } - + @Test public void test200AddOrgCortuvHrad() throws Exception { final String TEST_NAME = "test200AddOrgCortuvHrad"; @@ -248,7 +248,7 @@ public void test200AddOrgCortuvHrad() throws Exception { OperationResult result = task.getResult(); PrismObject orgBefore = createOrg(ORG_CORTUV_HRAD_NAME, orgRolyulaCarpathiaOid); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("Adding org", orgBefore); @@ -258,10 +258,10 @@ public void test200AddOrgCortuvHrad() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject orgAfter = getAndAssertFunctionalOrg(ORG_CORTUV_HRAD_NAME, orgRolyulaCarpathiaOid); orgCortuvHradOid = orgAfter.getOid(); @@ -269,7 +269,7 @@ public void test200AddOrgCortuvHrad() throws Exception { assertSubOrgs(orgRolyulaCarpathiaOid, 1); assertSubOrgs(ORG_TOP_OID, 1); } - + @Test public void test210AddUserGorc() throws Exception { final String TEST_NAME = "test210AddUserGorc"; @@ -277,9 +277,9 @@ public void test210AddUserGorc() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - PrismObject userBefore = createUser(USER_GORC_USERNAME, + PrismObject userBefore = createUser(USER_GORC_USERNAME, USER_GORC_GIVEN_NAME, USER_GORC_FAMILY_NAME, orgCortuvHradOid); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("Adding user", userBefore); @@ -289,10 +289,10 @@ public void test210AddUserGorc() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject userAfter = getAndAssertUser(USER_GORC_USERNAME, ORG_CORTUV_HRAD_NAME, ORG_ROYULA_CARPATHIA_NAME); userGorcOid = userAfter.getOid(); } @@ -305,7 +305,7 @@ public void test220AddOrgVysneVlkodlaky() throws Exception { OperationResult result = task.getResult(); PrismObject orgBefore = createOrg(ORG_VYSNE_VLKODLAKY_NAME, orgCortuvHradOid); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("Adding org", orgBefore); @@ -315,10 +315,10 @@ public void test220AddOrgVysneVlkodlaky() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject orgAfter = getAndAssertFunctionalOrg(ORG_VYSNE_VLKODLAKY_NAME, orgCortuvHradOid); orgVysneVlkodlakyOid = orgAfter.getOid(); @@ -326,7 +326,7 @@ public void test220AddOrgVysneVlkodlaky() throws Exception { assertSubOrgs(orgRolyulaCarpathiaOid, 1); assertSubOrgs(ORG_TOP_OID, 1); } - + @Test public void test230AddUserViljaDezi() throws Exception { final String TEST_NAME = "test230AddUserViljaDezi"; @@ -334,9 +334,9 @@ public void test230AddUserViljaDezi() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - PrismObject userBefore = createUser(USER_DEZI_USERNAME, + PrismObject userBefore = createUser(USER_DEZI_USERNAME, USER_DEZI_GIVEN_NAME, USER_DEZI_FAMILY_NAME, orgVysneVlkodlakyOid); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("Adding user", userBefore); @@ -346,11 +346,11 @@ public void test230AddUserViljaDezi() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - - PrismObject userAfter = getAndAssertUser(USER_DEZI_USERNAME, ORG_VYSNE_VLKODLAKY_NAME, ORG_CORTUV_HRAD_NAME, ORG_ROYULA_CARPATHIA_NAME); + + PrismObject userAfter = getAndAssertUser(USER_DEZI_USERNAME, ORG_VYSNE_VLKODLAKY_NAME, ORG_CORTUV_HRAD_NAME, ORG_ROYULA_CARPATHIA_NAME); } @Test @@ -361,7 +361,7 @@ public void test300RenameOrgCortuvHrad() throws Exception { OperationResult result = task.getResult(); PrismObject orgBefore = createOrg(ORG_CORTUV_HRAD_NAME, orgRolyulaCarpathiaOid); - + // WHEN TestUtil.displayWhen(TEST_NAME); display("Adding org", orgBefore); @@ -371,10 +371,10 @@ public void test300RenameOrgCortuvHrad() throws Exception { TestUtil.displayThen(TEST_NAME); result.computeStatus(); TestUtil.assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject orgAfter = getAndAssertFunctionalOrg(ORG_CORTUV_HRAD_NAME2, orgRolyulaCarpathiaOid); assertEquals("Cortuv hrad org OID changed after rename", orgCortuvHradOid, orgAfter.getOid()); @@ -385,7 +385,7 @@ public void test300RenameOrgCortuvHrad() throws Exception { assertSubOrgs(ORG_TOP_OID, 1); assertSubOrgs(orgVysneVlkodlakyOid, 0); } - + @Test public void test310RenameUserGorc() throws Exception { final String TEST_NAME = "test310RenameUserGorc"; @@ -393,9 +393,9 @@ public void test310RenameUserGorc() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - PrismObject userBefore = createUser(USER_GORC_USERNAME, + PrismObject userBefore = createUser(USER_GORC_USERNAME, USER_GORC_GIVEN_NAME, USER_GORC_FAMILY_NAME, orgCortuvHradOid); - + // WHEN displayWhen(TEST_NAME); modifyObjectReplaceProperty(UserType.class, userGorcOid, UserType.F_NAME, task, result, new PolyString(USER_GORC_USERNAME2)); @@ -403,13 +403,13 @@ public void test310RenameUserGorc() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject userAfter = getAndAssertUser(USER_GORC_USERNAME2, ORG_CORTUV_HRAD_NAME2, ORG_ROYULA_CARPATHIA_NAME); } - + @Test public void test320AddOrgRoyulaDiabolica() throws Exception { final String TEST_NAME = "test320AddOrgRoyulaDiabolica"; @@ -418,7 +418,7 @@ public void test320AddOrgRoyulaDiabolica() throws Exception { OperationResult result = task.getResult(); PrismObject orgBefore = createOrg(ORG_ROYULA_DIABOLICA_NAME, ORG_TOP_OID); - + // WHEN displayWhen(TEST_NAME); display("Adding org", orgBefore); @@ -427,10 +427,10 @@ public void test320AddOrgRoyulaDiabolica() throws Exception { // THEN displayThen(TEST_NAME); assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject orgAfter = getAndAssertFunctionalOrg(ORG_ROYULA_DIABOLICA_NAME, ORG_TOP_OID); orgRolyulaDiabolicaOid = orgAfter.getOid(); @@ -439,7 +439,7 @@ public void test320AddOrgRoyulaDiabolica() throws Exception { assertSubOrgs(orgRolyulaDiabolicaOid, 0); assertSubOrgs(orgRolyulaCarpathiaOid, 1); } - + @Test public void test322MoveOrgZblo() throws Exception { final String TEST_NAME = "test322MoveOrgZblo"; @@ -449,7 +449,7 @@ public void test322MoveOrgZblo() throws Exception { PrismObject orgBefore = getOrg(ORG_CORTUV_HRAD_NAME2); ObjectDelta delta = orgBefore.createModifyDelta(); - + PrismContainerValue oldAssignment = null; for (PrismContainerValue aval: orgBefore.findContainer(OrgType.F_ASSIGNMENT).getValues()) { oldAssignment = (PrismContainerValue)aval; @@ -462,28 +462,28 @@ public void test322MoveOrgZblo() throws Exception { AssignmentType newAssignmentType = new AssignmentType(); newAssignmentType.targetRef(orgRolyulaDiabolicaOid, OrgType.COMPLEX_TYPE); delta.addModificationAddContainer(OrgType.F_ASSIGNMENT, newAssignmentType); - + // WHEN displayWhen(TEST_NAME); - + display("Modifying "+orgBefore+"with delta", delta); modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); // THEN displayThen(TEST_NAME); assertSuccess(result); - + dumpOrgTree(); dumpLdap(); - + PrismObject orgAfter = getAndAssertFunctionalOrg(ORG_CORTUV_HRAD_NAME2, orgRolyulaDiabolicaOid); assertEquals("Cortuv hrad org OID changed after rename", orgCortuvHradOid, orgAfter.getOid()); - + recomputeIfNeeded(orgCortuvHradOid); - + dumpOrgTree(); dumpLdap(); - + getAndAssertUser(USER_GORC_USERNAME2, ORG_CORTUV_HRAD_NAME2, ORG_ROYULA_DIABOLICA_NAME); getAndAssertUser(USER_DEZI_USERNAME, ORG_VYSNE_VLKODLAKY_NAME, ORG_CORTUV_HRAD_NAME2, ORG_ROYULA_DIABOLICA_NAME); @@ -493,7 +493,7 @@ public void test322MoveOrgZblo() throws Exception { assertSubOrgs(ORG_TOP_OID, 2); assertSubOrgs(orgVysneVlkodlakyOid, 0); } - + protected void recomputeIfNeeded(String changedOrgOid) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { // nothing to do by default } @@ -552,7 +552,7 @@ protected PrismObject getAndAssertUser(String username, String directO assertNotNull("No account LDAP entry for "+username, accountEntry); display("account entry", openDJController.toHumanReadableLdifoid(accountEntry)); openDJController.assertObjectClass(accountEntry, "inetOrgPerson"); - + return user; } @@ -589,13 +589,13 @@ protected PrismObject getOrg(String orgName) throws SchemaException, Ob protected void dumpOrgTree() throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { display("Org tree", dumpOrgTree(ORG_TOP_OID)); } - + protected void dumpLdap() throws DirectoryException { display("LDAP server tree", openDJController.dumpTree()); display("LDAP server content", openDJController.dumpEntries()); } - - + + protected void assertGroupMembers(PrismObject org, String... members) throws Exception { String groupOid = getLinkRefOid(org, RESOURCE_OPENDJ_OID, ShadowKindType.ENTITLEMENT, "org-group"); PrismObject groupShadow = getShadowModel(groupOid); @@ -607,7 +607,7 @@ protected void assertNoGroupMembers(PrismObject org) throws Exception { PrismObject groupShadow = getShadowModel(groupOid); assertNoAttribute(resourceOpenDj, groupShadow.asObjectable(), new QName(MidPointConstants.NS_RI, "uniqueMember")); } - + protected void reconcileAllUsers() throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { final Task task = createTask("reconcileAllUsers"); OperationResult result = task.getResult(); @@ -628,7 +628,7 @@ public boolean handle(PrismObject object, OperationResult parentResult display("Reconciling all users"); modelService.searchObjectsIterative(UserType.class, null, handler, null, task, result); } - + protected void reconcileAllOrgs() throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { final Task task = createTask("reconcileAllOrgs"); OperationResult result = task.getResult(); @@ -649,5 +649,5 @@ public boolean handle(PrismObject object, OperationResult parentResult) 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/ldaphierarchy/TestLdapDeeplyHierarchical.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldaphierarchy/TestLdapDeeplyHierarchical.java index 41f50090163..dc7f332bf0a 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldaphierarchy/TestLdapDeeplyHierarchical.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldaphierarchy/TestLdapDeeplyHierarchical.java @@ -58,42 +58,42 @@ * reflected to hierachical OUs (OUs inside OUs). Each OU contains groups. Users are members of * the groups to reflect their direct membership in orgstruct. Groups are members of parent OU * groups. - * + * * @author Radovan Semancik * */ @ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestLdapDeeplyHierarchical extends AbstractLdapHierarchyTest { - + public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "ldap-deeply-hierarchical"); private static final String LDAP_OU_INTENT = "ou"; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); } - + @Override protected File getTestDir() { return TEST_DIR; } - + @Override protected PrismObject getAndAssertUser(String username, String directOrgGroupname, String... indirectGroupNames) throws SchemaException, CommonException, SecurityViolationException, CommunicationException, ConfigurationException, DirectoryException { PrismObject user = super.getAndAssertUser(username, directOrgGroupname, indirectGroupNames); Entry accountEntry = openDJController.searchSingle("uid="+username); - + String expectedDn = getAccountDn(user); assertEquals("Wrong account DN", expectedDn, accountEntry.getDN().toString().toLowerCase()); Entry groupEntry = openDJController.searchSingle("cn="+directOrgGroupname); assertNotNull("No group LDAP entry for "+directOrgGroupname, groupEntry); openDJController.assertUniqueMember(groupEntry, accountEntry.getDN().toString()); - + return user; } - + @Override protected PrismObject getAndAssertFunctionalOrg(String orgName, String directParentOrgOid) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, DirectoryException, ExpressionEvaluationException { PrismObject org = super.getAndAssertFunctionalOrg(orgName, directParentOrgOid); @@ -105,22 +105,22 @@ protected PrismObject getAndAssertFunctionalOrg(String orgName, String display("parent group entry", openDJController.toHumanReadableLdifoid(parentGroupEntry)); openDJController.assertUniqueMember(parentGroupEntry, groupEntry.getDN().toString()); } - + String ouOid = getLinkRefOid(org, RESOURCE_OPENDJ_OID, ShadowKindType.GENERIC, LDAP_OU_INTENT); PrismObject ouShadow = getShadowModel(ouOid); display("Org "+orgName+" ou shadow", ouShadow); - + Entry groupEntry = openDJController.searchSingle("ou="+orgName); assertNotNull("No UO LDAP entry for "+orgName, groupEntry); display("OU entry", openDJController.toHumanReadableLdifoid(groupEntry)); openDJController.assertObjectClass(groupEntry, "organizationalUnit"); - + String expectedDn = getOuDn(org); assertEquals("Wrong OU DN", expectedDn, groupEntry.getDN().toString().toLowerCase()); - + return org; } - + private String getOuDn(PrismObject org) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { StringBuilder sb = new StringBuilder(); while (true) { @@ -140,7 +140,7 @@ private String getOuDn(PrismObject org) throws ObjectNotFoundException, sb.append("dc=example,dc=com"); return sb.toString(); } - + private String getAccountDn(PrismObject user) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { StringBuilder sb = new StringBuilder(); sb.append("uid=").append(user.getName().getOrig()).append(","); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldaphierarchy/TestLdapFlat.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldaphierarchy/TestLdapFlat.java index ada66348f10..f3ca5594225 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldaphierarchy/TestLdapFlat.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldaphierarchy/TestLdapFlat.java @@ -49,16 +49,16 @@ * Flat LDAP structure. All accounts in ou=people. The organizational structure is * reflected to (non-nested) LDAP groups. Users are members of the groups to reflect * the orgstruct. - * + * * @author Radovan Semancik * */ @ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestLdapFlat extends AbstractLdapHierarchyTest { - + public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "ldap-flat"); - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -68,12 +68,12 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti protected File getTestDir() { return TEST_DIR; } - + @Override protected PrismObject getAndAssertUser(String username, String directOrgGroupname, String... indirectGroupNames) throws SchemaException, CommonException, SecurityViolationException, CommunicationException, ConfigurationException, DirectoryException { PrismObject user = super.getAndAssertUser(username, directOrgGroupname, indirectGroupNames); Entry accountEntry = openDJController.searchSingle("uid="+username); - + Entry groupEntry = openDJController.searchSingle("cn="+directOrgGroupname); assertNotNull("No group LDAP entry for "+directOrgGroupname, groupEntry); openDJController.assertUniqueMember(groupEntry, accountEntry.getDN().toString()); @@ -85,13 +85,13 @@ protected PrismObject getAndAssertUser(String username, String directO openDJController.assertUniqueMember(groupEntry, accountEntry.getDN().toString()); } } - + return user; } - + @Override protected void recomputeIfNeeded(String changedOrgOid) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { reconcileAllUsers(); } - + } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldaphierarchy/TestLdapHierarchical.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldaphierarchy/TestLdapHierarchical.java index 5eaf15a5df2..9b58763757f 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldaphierarchy/TestLdapHierarchical.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldaphierarchy/TestLdapHierarchical.java @@ -56,27 +56,27 @@ * reflected to hierachical OUs (OUs inside OUs). Each OU contains groups. Users are members of * the groups to reflect their direct membership in orgstruct. Groups are members of parent OU * groups. - * + * * @author Radovan Semancik * */ @ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestLdapHierarchical extends AbstractLdapHierarchyTest { - + public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "ldap-hierarchical"); private static final String LDAP_OU_INTENT = "ou"; - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); } - + @Override protected File getTestDir() { return TEST_DIR; } - + @Override protected PrismObject getAndAssertUser(String username, String directOrgGroupname, String... indirectGroupNames) throws SchemaException, CommonException, SecurityViolationException, CommunicationException, ConfigurationException, DirectoryException { PrismObject user = super.getAndAssertUser(username, directOrgGroupname, indirectGroupNames); @@ -85,10 +85,10 @@ protected PrismObject getAndAssertUser(String username, String directO Entry groupEntry = openDJController.searchSingle("cn="+directOrgGroupname); assertNotNull("No group LDAP entry for "+directOrgGroupname, groupEntry); openDJController.assertUniqueMember(groupEntry, accountEntry.getDN().toString()); - + return user; } - + @Override protected PrismObject getAndAssertFunctionalOrg(String orgName, String directParentOrgOid) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, DirectoryException, ExpressionEvaluationException { PrismObject org = super.getAndAssertFunctionalOrg(orgName, directParentOrgOid); @@ -100,22 +100,22 @@ protected PrismObject getAndAssertFunctionalOrg(String orgName, String display("parent group entry", openDJController.toHumanReadableLdifoid(parentGroupEntry)); openDJController.assertUniqueMember(parentGroupEntry, groupEntry.getDN().toString()); } - + String ouOid = getLinkRefOid(org, RESOURCE_OPENDJ_OID, ShadowKindType.GENERIC, LDAP_OU_INTENT); PrismObject ouShadow = getShadowModel(ouOid); display("Org "+orgName+" ou shadow", ouShadow); - + Entry groupEntry = openDJController.searchSingle("ou="+orgName); assertNotNull("No UO LDAP entry for "+orgName, groupEntry); display("OU entry", openDJController.toHumanReadableLdifoid(groupEntry)); openDJController.assertObjectClass(groupEntry, "organizationalUnit"); - + String expectedDn = getOuDn(org); assertEquals("Wrong OU DN", expectedDn, groupEntry.getDN().toString().toLowerCase()); - + return org; } - + private String getOuDn(PrismObject org) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { StringBuilder sb = new StringBuilder(); while (true) { diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldaphierarchy/TestLdapNested.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldaphierarchy/TestLdapNested.java index 93eba729e3f..0a0a60c53ab 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldaphierarchy/TestLdapNested.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldaphierarchy/TestLdapNested.java @@ -46,26 +46,26 @@ * reflected to nested LDAP groups. Users are members of the groups to reflect * their direct membership in orgstruct. Group are member of other groups to reflect * the org tree. Not there is no structure of OUs. - * + * * @author Radovan Semancik * */ @ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestLdapNested extends AbstractLdapHierarchyTest { - + public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "ldap-nested"); - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); } - + @Override protected File getTestDir() { return TEST_DIR; } - + @Override protected PrismObject getAndAssertUser(String username, String directOrgGroupname, String... indirectGroupNames) throws SchemaException, CommonException, SecurityViolationException, CommunicationException, ConfigurationException, DirectoryException { PrismObject user = super.getAndAssertUser(username, directOrgGroupname, indirectGroupNames); @@ -74,10 +74,10 @@ protected PrismObject getAndAssertUser(String username, String directO Entry groupEntry = openDJController.searchSingle("cn="+directOrgGroupname); assertNotNull("No group LDAP entry for "+directOrgGroupname, groupEntry); openDJController.assertUniqueMember(groupEntry, accountEntry.getDN().toString()); - + return user; } - + @Override protected PrismObject getAndAssertFunctionalOrg(String orgName, String directParentOrgOid) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, DirectoryException, ExpressionEvaluationException { PrismObject org = super.getAndAssertFunctionalOrg(orgName, directParentOrgOid); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/AbstractNotoriousTest.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/AbstractNotoriousTest.java index 17e1f1bbad7..1b6c3bbd194 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/AbstractNotoriousTest.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/AbstractNotoriousTest.java @@ -69,7 +69,7 @@ /** * Testing bushy roles hierarchy. Especially reuse of the same role * in the rich role hierarchy. It looks like this: - * + * * user * | * +------+------+-----+-----+-.... @@ -86,52 +86,52 @@ * | | | | | * v v v v v * Rb1 Rb2 Rb3 Rb4 Rb5 - * + * * Naive mode of evaluation would imply cartesian product of all Rax and Rbx * combinations. That's painfully inefficient. Therefore make sure that the * notorious roles is evaluated only once and the results of the evaluation * are reused. - * + * * @author Radovan Semancik */ @ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public abstract class AbstractNotoriousTest extends AbstractStoryTest { - + public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "notorious"); - + private static final int NUMBER_OF_ORDINARY_ROLES = 1; // including superuser role - + protected static final int NUMBER_OF_LEVEL_A_ROLES = 100; protected static final String ROLE_LEVEL_A_NAME_FORMAT = "Role A %06d"; protected static final String ROLE_LEVEL_A_ROLETYPE = "levelA"; protected static final String ROLE_LEVEL_A_OID_FORMAT = "00000000-0000-ffff-2a00-000000%06d"; - + protected static final int NUMBER_OF_LEVEL_B_ROLES = 300; protected static final String ROLE_LEVEL_B_NAME_FORMAT = "Role B %06d"; protected static final String ROLE_LEVEL_B_ROLETYPE = "levelB"; protected static final String ROLE_LEVEL_B_OID_FORMAT = "00000000-0000-ffff-2b00-000000%06d"; - + private static final Trace LOGGER = TraceManager.getTrace(AbstractNotoriousTest.class); - + protected CountingInspector inspector; - + protected abstract String getNotoriousOid(); - + protected abstract File getNotoriousFile(); - + protected abstract QName getNotoriousType(); - + protected abstract int getNumberOfExtraRoles(); - + protected abstract int getNumberOfExtraOrgs(); - + protected abstract QName getAltRelation(); - + @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - + generateRoles(NUMBER_OF_LEVEL_A_ROLES, ROLE_LEVEL_A_NAME_FORMAT, ROLE_LEVEL_A_OID_FORMAT, (role,i) -> { role.roleType(ROLE_LEVEL_A_ROLETYPE); @@ -140,26 +140,26 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti initResult); addNotoriousRole(initResult); - + // Add these using model, so they have proper roleMembershipRef generateRoles(NUMBER_OF_LEVEL_B_ROLES, ROLE_LEVEL_B_NAME_FORMAT, ROLE_LEVEL_B_OID_FORMAT, this::fillLevelBRole, role -> addObject(role, initTask, initResult), initResult); - + inspector = new CountingInspector(); InternalMonitor.setInspector(inspector); - + InternalMonitor.setTrace(InternalOperationClasses.ROLE_EVALUATIONS, true); } - + protected abstract void addNotoriousRole(OperationResult result) throws Exception; - + protected void fillLevelBRole(RoleType roleType, int i) { roleType .roleType(ROLE_LEVEL_B_ROLETYPE); } - + protected void fillNotorious(AbstractRoleType roleType) throws Exception { for(int i=0; i < NUMBER_OF_LEVEL_B_ROLES; i++) { roleType.beginInducement() @@ -172,15 +172,15 @@ protected void fillNotorious(AbstractRoleType roleType) throws Exception { private String generateRoleOid(String oidFormat, int num) { return String.format(oidFormat, num); } - + private String generateRoleAOid(int num) { return String.format(ROLE_LEVEL_A_OID_FORMAT, num); } - + private String generateRoleBOid(int num) { return String.format(ROLE_LEVEL_B_OID_FORMAT, num); } - + @Test public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; @@ -188,11 +188,11 @@ public void test000Sanity() throws Exception { assertObjects(RoleType.class, NUMBER_OF_LEVEL_A_ROLES + NUMBER_OF_LEVEL_B_ROLES + NUMBER_OF_ORDINARY_ROLES + getNumberOfExtraRoles()); assertObjects(OrgType.class, getNumberOfExtraOrgs()); - + display("Repo reads", InternalMonitor.getCount(InternalCounters.REPOSITORY_READ_COUNT)); display("Object compares", InternalMonitor.getCount(InternalCounters.PRISM_OBJECT_COMPARE_COUNT)); } - + @Test public void test100AssignRa0ToJack() throws Exception { final String TEST_NAME = "test100AssignRa0ToJack"; @@ -200,31 +200,31 @@ public void test100AssignRa0ToJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); - + long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, generateRoleAOid(0), task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Ra0 assign in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 2))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertJackRoleAMembershipRef(userAfter, 1); assertNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - + assertRoleEvaluationCount(1, 0); - + assertCounterIncrement(InternalCounters.PROJECTOR_RUN_COUNT, hackify(1)); assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(NUMBER_OF_LEVEL_B_ROLES + 2)); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); @@ -237,32 +237,32 @@ public void test102RecomputeJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Ra0 recompute in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 2))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertJackRoleAMembershipRef(userAfter, 1); assertNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - + assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(NUMBER_OF_LEVEL_B_ROLES + 2)); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + @Test public void test104PreviewChangesJack() throws Exception { final String TEST_NAME = "test104PreviewChangesJack"; @@ -270,39 +270,39 @@ public void test104PreviewChangesJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User before", assignmentSummary(userBefore)); - + ObjectDelta delta = userBefore.createModifyDelta(); delta.addModificationReplaceProperty(UserType.F_EMPLOYEE_NUMBER, "123"); - + prepareTest(); long startMillis = System.currentTimeMillis(); - + // WHEN - displayWhen(TEST_NAME); + displayWhen(TEST_NAME); ModelContext modelContext = modelInteractionService.previewChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Ra0 preview changes in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 2))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertJackRoleAMembershipRef(userAfter, 1); assertNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - + assertCounterIncrement(InternalCounters.PROJECTOR_RUN_COUNT, 1); assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, (NUMBER_OF_LEVEL_B_ROLES + 2)*2); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + @Test public void test109UnassignRa0FromJack() throws Exception { final String TEST_NAME = "test109UnassignRa0FromJack"; @@ -310,33 +310,33 @@ public void test109UnassignRa0FromJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, generateRoleAOid(0), task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Ra0 unassign in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 2))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertNoAssignments(userAfter); assertRoleMembershipRefs(userAfter, 0); assertNoNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - - assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(NUMBER_OF_LEVEL_B_ROLES + 2)); + + assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(NUMBER_OF_LEVEL_B_ROLES + 2)); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + @Test public void test110Assign5ARolesToJack() throws Exception { final String TEST_NAME = "test110AssignAllARolesToJack"; @@ -344,32 +344,32 @@ public void test110Assign5ARolesToJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); assignJackARoles(5, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Assign 5 A roles in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 1 + 5))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertJackRoleAMembershipRef(userAfter, 5); assertNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - + assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(NUMBER_OF_LEVEL_B_ROLES + 1 + 5)); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + @Test public void test112RecomputeJack() throws Exception { final String TEST_NAME = "test112RecomputeJack"; @@ -377,32 +377,32 @@ public void test112RecomputeJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Recompute 5 A roles in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 1 + 5))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertJackRoleAMembershipRef(userAfter, 5); assertNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - + assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(NUMBER_OF_LEVEL_B_ROLES + 1 + 5)); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + @Test public void test119Unassign5ARolesFromJack() throws Exception { final String TEST_NAME = "test119Unassign5ARolesFromJack"; @@ -410,33 +410,33 @@ public void test119Unassign5ARolesFromJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); unassignJackARoles(5, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Ra0 unassign in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 1 + 5))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertNoAssignments(userAfter); assertRoleMembershipRefs(userAfter, 0); assertNoNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - - assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(NUMBER_OF_LEVEL_B_ROLES + 1 + 5)); + + assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(NUMBER_OF_LEVEL_B_ROLES + 1 + 5)); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + @Test public void test120AssignAllARolesToJack() throws Exception { final String TEST_NAME = "test120AssignAllARolesToJack"; @@ -444,32 +444,32 @@ public void test120AssignAllARolesToJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); assignJackARoles(NUMBER_OF_LEVEL_A_ROLES, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Assign all A roles in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 1 + NUMBER_OF_LEVEL_A_ROLES))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertJackRoleAMembershipRef(userAfter, NUMBER_OF_LEVEL_A_ROLES); assertNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - + assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(NUMBER_OF_LEVEL_B_ROLES + 1 + NUMBER_OF_LEVEL_A_ROLES)); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + @Test public void test122RecomputeJack() throws Exception { final String TEST_NAME = "test122RecomputeJack"; @@ -477,32 +477,32 @@ public void test122RecomputeJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Recompute all A roles in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 1 + NUMBER_OF_LEVEL_A_ROLES))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertJackRoleAMembershipRef(userAfter, NUMBER_OF_LEVEL_A_ROLES); assertNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - + assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(NUMBER_OF_LEVEL_B_ROLES + 1 + NUMBER_OF_LEVEL_A_ROLES)); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + @Test public void test124PreviewChangesJack() throws Exception { final String TEST_NAME = "test124PreviewChangesJack"; @@ -510,39 +510,39 @@ public void test124PreviewChangesJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + PrismObject userBefore = getUser(USER_JACK_OID); display("User before", assignmentSummary(userBefore)); - + ObjectDelta delta = userBefore.createModifyDelta(); delta.addModificationReplaceProperty(UserType.F_EMPLOYEE_NUMBER, "123"); - + prepareTest(); long startMillis = System.currentTimeMillis(); - + // WHEN - displayWhen(TEST_NAME); + displayWhen(TEST_NAME); ModelContext modelContext = modelInteractionService.previewChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Preview changes (all A roles) in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 1 + NUMBER_OF_LEVEL_A_ROLES))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertJackRoleAMembershipRef(userAfter, NUMBER_OF_LEVEL_A_ROLES); assertNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - + assertCounterIncrement(InternalCounters.PROJECTOR_RUN_COUNT, 1); assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, (NUMBER_OF_LEVEL_B_ROLES + 1 + NUMBER_OF_LEVEL_A_ROLES)*2); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + @Test public void test129UnassignAllARolesFromJack() throws Exception { final String TEST_NAME = "test129UnassignAllARolesFromJack"; @@ -550,33 +550,33 @@ public void test129UnassignAllARolesFromJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); unassignJackARoles(NUMBER_OF_LEVEL_A_ROLES, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Unassign all A roles in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 1 + NUMBER_OF_LEVEL_A_ROLES))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertNoAssignments(userAfter); assertRoleMembershipRefs(userAfter, 0); assertNoNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - - assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(NUMBER_OF_LEVEL_B_ROLES + 1 + NUMBER_OF_LEVEL_A_ROLES)); + + assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(NUMBER_OF_LEVEL_B_ROLES + 1 + NUMBER_OF_LEVEL_A_ROLES)); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + @Test public void test130AssignRb0ToJack() throws Exception { final String TEST_NAME = "test130AssignRb0ToJack"; @@ -584,36 +584,36 @@ public void test130AssignRb0ToJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); - + long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, generateRoleBOid(0), task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Rb0 assign in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 2))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertRoleMembershipRef(userAfter, generateRoleBOid(0)); assertNoNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - + assertRoleEvaluationCount(0, 1); - + assertCounterIncrement(InternalCounters.PROJECTOR_RUN_COUNT, hackify(1)); assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(1)); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + /** * Now jack has RoleB0 assigned in two ways: directly and through RA0->notorious->RB0 * This may cause problems e.g. for supernotorious roles where the direct assignment @@ -627,31 +627,31 @@ public void test132AssignRa0ToJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); - + long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, generateRoleAOid(0), task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Ra0 assign in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 2))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertJackRoleAMembershipRef(userAfter, 1); assertNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - + assertRoleEvaluationCount(1, 1); - + assertCounterIncrement(InternalCounters.PROJECTOR_RUN_COUNT, hackify(1)); assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(NUMBER_OF_LEVEL_B_ROLES + 2 + 1)); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); @@ -664,34 +664,34 @@ public void test134RecomputeJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Ra0+Rb0 recompute in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 2))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertJackRoleAMembershipRef(userAfter, 1); assertNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - + assertRoleEvaluationCount(1, 1); - + assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(NUMBER_OF_LEVEL_B_ROLES + 2 + 1)); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + @Test public void test136UnassignRb0FromJack() throws Exception { final String TEST_NAME = "test136UnassignRb0FromJack"; @@ -699,36 +699,36 @@ public void test136UnassignRb0FromJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); - + long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, generateRoleBOid(0), task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Rb0 unassign in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 2))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertJackRoleAMembershipRef(userAfter, 1); assertNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - + assertRoleEvaluationCount(1, 1); - + assertCounterIncrement(InternalCounters.PROJECTOR_RUN_COUNT, hackify(1)); assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(NUMBER_OF_LEVEL_B_ROLES + 2 + 1)); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + @Test public void test138AssignRb0ToJackAgain() throws Exception { final String TEST_NAME = "test138AssignRb0ToJackAgain"; @@ -736,36 +736,36 @@ public void test138AssignRb0ToJackAgain() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); - + long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); assignRole(USER_JACK_OID, generateRoleBOid(0), task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Rb0 assign in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 2))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertJackRoleAMembershipRef(userAfter, 1); assertNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - + assertRoleEvaluationCount(1, 1); - + assertCounterIncrement(InternalCounters.PROJECTOR_RUN_COUNT, hackify(1)); assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(NUMBER_OF_LEVEL_B_ROLES + 2 + 1)); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + @Test public void test140RecomputeJackAgain() throws Exception { final String TEST_NAME = "test140RecomputeJackAgain"; @@ -773,70 +773,70 @@ public void test140RecomputeJackAgain() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Ra0+Rb0 recompute again in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 2))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertJackRoleAMembershipRef(userAfter, 1); assertNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - + assertRoleEvaluationCount(1, 1); - + assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(NUMBER_OF_LEVEL_B_ROLES + 2 + 1)); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + @Test public void test142RecomputeJackAlt() throws Exception { final String TEST_NAME = "test142RecomputeJackAlt"; displayTestTitle(TEST_NAME); - + Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); InternalsConfig.setTestingPaths(TestingPaths.REVERSED); long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Ra0+Rb0 recompute again in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 2))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertJackRoleAMembershipRef(userAfter, 1); assertNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - + assertRoleEvaluationCount(1, 1); - + assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(NUMBER_OF_LEVEL_B_ROLES + 2 + 1)); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + @Test public void test144UnassignRa0FromJack() throws Exception { final String TEST_NAME = "test144UnassignRa0FromJack"; @@ -844,36 +844,36 @@ public void test144UnassignRa0FromJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); - + long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, generateRoleAOid(0), task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Ra0 unassign in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 2))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertRoleMembershipRef(userAfter, generateRoleBOid(0)); assertNoNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - + assertRoleEvaluationCount(1, 1); - + assertCounterIncrement(InternalCounters.PROJECTOR_RUN_COUNT, hackify(1)); assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(NUMBER_OF_LEVEL_B_ROLES + 2 + 1)); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + @Test public void test149UnassignRb0FromJack() throws Exception { final String TEST_NAME = "test149UnassignRb0FromJack"; @@ -881,37 +881,37 @@ public void test149UnassignRb0FromJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); - + long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); unassignRole(USER_JACK_OID, generateRoleBOid(0), task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Rb0 unassign in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 2))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertNoAssignments(userAfter); assertRoleMembershipRefs(userAfter, 0); assertNoNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - + assertRoleEvaluationCount(0, 1); - + assertCounterIncrement(InternalCounters.PROJECTOR_RUN_COUNT, hackify(1)); assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(1)); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + /** * Assign notorious role to Jack directly. That should behave correctly. * No special expectations here. @@ -923,32 +923,32 @@ public void test150AssignNotoriousDefaultToJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); - + long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); - modifyFocusAssignment(UserType.class, USER_JACK_OID, + modifyFocusAssignment(UserType.class, USER_JACK_OID, getNotoriousOid(), getNotoriousType(), null, task, null, null, true, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Notorious relation=default assign in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 2))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertJackRoleAMembershipRef(userAfter, 0); assertNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - + assertRoleEvaluationCount(1, 0); - + assertCounterIncrement(InternalCounters.PROJECTOR_RUN_COUNT, hackify(1)); assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(1 + NUMBER_OF_LEVEL_B_ROLES)); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); @@ -966,43 +966,43 @@ public void test152AssignNotoriousAltRelationToJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); - + long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); - modifyFocusAssignment(UserType.class, USER_JACK_OID, + modifyFocusAssignment(UserType.class, USER_JACK_OID, getNotoriousOid(), getNotoriousType(), getAltRelation(), task, null, null, true, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Notorious relation="+getAltRelation().getLocalPart()+" assign in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 2))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); - + assertRoleMembershipRefNonExclusive(userAfter, getNotoriousOid(), getNotoriousType(), SchemaConstants.ORG_DEFAULT); assertRoleMembershipRefNonExclusive(userAfter, getNotoriousOid(), getNotoriousType(), getAltRelation()); assertRoleMembershipRefs(userAfter, ROLE_LEVEL_B_OID_FORMAT, NUMBER_OF_LEVEL_B_ROLES, SchemaConstants.ORG_DEFAULT); - + assertRoleMembershipRefs(userAfter, 2 + NUMBER_OF_LEVEL_B_ROLES); - + assertNotoriousParentOrgRefRelations(userAfter, SchemaConstants.ORG_DEFAULT, getAltRelation()); - + displayCountersAndInspector(); - + assertRoleEvaluationCount(2, 0); - + assertCounterIncrement(InternalCounters.PROJECTOR_RUN_COUNT, hackify(1)); assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(2*(1 + NUMBER_OF_LEVEL_B_ROLES))); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + @Test public void test154RecomputeJack() throws Exception { final String TEST_NAME = "test154RecomputeJack"; @@ -1010,46 +1010,46 @@ public void test154RecomputeJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); - + long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Notorious relation="+getAltRelation().getLocalPart()+" assign in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 2))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); - + assertRoleMembershipRefNonExclusive(userAfter, getNotoriousOid(), getNotoriousType(), SchemaConstants.ORG_DEFAULT); assertRoleMembershipRefNonExclusive(userAfter, getNotoriousOid(), getNotoriousType(), getAltRelation()); assertRoleMembershipRefs(userAfter, ROLE_LEVEL_B_OID_FORMAT, NUMBER_OF_LEVEL_B_ROLES, SchemaConstants.ORG_DEFAULT); - + assertRoleMembershipRefs(userAfter, 2 + NUMBER_OF_LEVEL_B_ROLES); - + assertNotoriousParentOrgRefRelations(userAfter, SchemaConstants.ORG_DEFAULT, getAltRelation()); - + displayCountersAndInspector(); - + assertRoleEvaluationCount(2, 0); - + assertCounterIncrement(InternalCounters.PROJECTOR_RUN_COUNT, hackify(1)); assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(getTest15xRoleEvaluationIncrement())); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + protected int getTest15xRoleEvaluationIncrement() { return 2*(1 + NUMBER_OF_LEVEL_B_ROLES); } - + @Test public void test156RecomputeJackAlt() throws Exception { final String TEST_NAME = "test156RecomputeJackAlt"; @@ -1057,42 +1057,42 @@ public void test156RecomputeJackAlt() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); InternalsConfig.setTestingPaths(TestingPaths.REVERSED); long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); recomputeUser(USER_JACK_OID, task, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Notorious relation="+getAltRelation().getLocalPart()+" unassign in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 2))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); - + assertRoleMembershipRefNonExclusive(userAfter, getNotoriousOid(), getNotoriousType(), SchemaConstants.ORG_DEFAULT); assertRoleMembershipRefNonExclusive(userAfter, getNotoriousOid(), getNotoriousType(), getAltRelation()); assertRoleMembershipRefs(userAfter, ROLE_LEVEL_B_OID_FORMAT, NUMBER_OF_LEVEL_B_ROLES, SchemaConstants.ORG_DEFAULT); - + assertRoleMembershipRefs(userAfter, 2 + NUMBER_OF_LEVEL_B_ROLES); - + assertNotoriousParentOrgRefRelations(userAfter, SchemaConstants.ORG_DEFAULT, getAltRelation()); - + displayCountersAndInspector(); - + assertRoleEvaluationCount(2, 0); - + assertCounterIncrement(InternalCounters.PROJECTOR_RUN_COUNT, hackify(1)); assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(getTest15xRoleEvaluationIncrement())); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + @Test public void test158UnassignNotoriousDefaultFromJack() throws Exception { final String TEST_NAME = "test156UnassignNotoriousDefaultFromJack"; @@ -1100,37 +1100,37 @@ public void test158UnassignNotoriousDefaultFromJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); - + long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); - modifyFocusAssignment(UserType.class, USER_JACK_OID, + modifyFocusAssignment(UserType.class, USER_JACK_OID, getNotoriousOid(), getNotoriousType(), null, task, null, null, false, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Notorious relation=default unassign in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 2))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertTest158RoleMembershipRef(userAfter); assertNotoriousParentOrgRefRelations(userAfter, getAltRelation()); - + displayCountersAndInspector(); - + assertRoleEvaluationCount(2, 1); - + assertCounterIncrement(InternalCounters.PROJECTOR_RUN_COUNT, hackify(1)); assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify(getTest15xRoleEvaluationIncrement())); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); } - + protected void assertTest158RoleMembershipRef(PrismObject userAfter) { assertJackRoleAMembershipRef(userAfter, 0, getAltRelation()); } @@ -1142,33 +1142,33 @@ public void test159UnassignNotoriousAltRelationFromJack() throws Exception { Task task = createTask(TEST_NAME); OperationResult result = task.getResult(); - + prepareTest(); - + long startMillis = System.currentTimeMillis(); - + // WHEN displayWhen(TEST_NAME); - modifyFocusAssignment(UserType.class, USER_JACK_OID, + modifyFocusAssignment(UserType.class, USER_JACK_OID, getNotoriousOid(), getNotoriousType(), getAltRelation(), task, null, null, false, result); - + // THEN displayThen(TEST_NAME); long endMillis = System.currentTimeMillis(); assertSuccess(result); - + display("Notorious relation="+getAltRelation().getLocalPart()+" assign in "+(endMillis - startMillis)+"ms ("+((endMillis - startMillis)/(NUMBER_OF_LEVEL_B_ROLES + 2))+"ms per assigned role)"); - + PrismObject userAfter = getUser(USER_JACK_OID); display("User after", assignmentSummary(userAfter)); assertNoAssignments(userAfter); assertRoleMembershipRefs(userAfter, 0); assertNoNotoriousParentOrgRef(userAfter); - + displayCountersAndInspector(); - + assertRoleEvaluationCount(1, 0); - + assertCounterIncrement(InternalCounters.PROJECTOR_RUN_COUNT, hackify(1)); assertCounterIncrement(InternalCounters.ROLE_EVALUATION_COUNT, hackify((1 + NUMBER_OF_LEVEL_B_ROLES))); assertCounterIncrement(InternalCounters.PRISM_OBJECT_COMPARE_COUNT, 0); @@ -1177,31 +1177,31 @@ public void test159UnassignNotoriousAltRelationFromJack() throws Exception { private void assignJackARoles(int numberOfRoles, Task task, OperationResult result) throws Exception { modifyJackARolesAssignment(numberOfRoles, true, task, result); } - + private void unassignJackARoles(int numberOfRoles, Task task, OperationResult result) throws Exception { modifyJackARolesAssignment(numberOfRoles, false, task, result); } - + private void modifyJackARolesAssignment(int numberOfRoles, boolean add, Task task, OperationResult result) throws Exception { Collection> modifications = new ArrayList<>(); for (int i=0; i delta = ObjectDelta.createModifyDelta(USER_JACK_OID, modifications, UserType.class, prismContext); - + executeChanges(delta, null, task, result); } - + private void assertJackRoleAMembershipRef(PrismObject user, int numberOfLevelARoles) { assertJackRoleAMembershipRef(user, numberOfLevelARoles, SchemaConstants.ORG_DEFAULT); } private void assertJackRoleAMembershipRef(PrismObject user, int numberOfLevelARoles, QName notoriousRelation) { - + assertRoleMembershipRefs(user, ROLE_LEVEL_A_OID_FORMAT, numberOfLevelARoles, SchemaConstants.ORG_DEFAULT); assertRoleMembershipRefNonExclusive(user, getNotoriousOid(), getNotoriousType(), notoriousRelation); assertRoleMembershipRefs(user, ROLE_LEVEL_B_OID_FORMAT, NUMBER_OF_LEVEL_B_ROLES, SchemaConstants.ORG_DEFAULT); - + assertRoleMembershipRefs(user, numberOfLevelARoles + 1 + NUMBER_OF_LEVEL_B_ROLES); } @@ -1210,7 +1210,7 @@ private void assertRoleMembershipRefs(PrismObject user, String oidForm assertRoleMembershipRefNonExclusive(user, generateRoleOid(oidFormat, i), RoleType.COMPLEX_TYPE, relation); } } - + private void assertRoleMembershipRefNonExclusive(PrismObject user, String roleOid, QName roleType, QName relation) { List roleMembershipRefs = user.asObjectable().getRoleMembershipRef(); for (ObjectReferenceType roleMembershipRef: roleMembershipRefs) { @@ -1220,19 +1220,19 @@ private void assertRoleMembershipRefNonExclusive(PrismObject user, Str } fail("Cannot find membership of role "+roleOid+" in "+user); } - + protected void assertRoleEvaluationCount(int numberOfLevelAAssignments, int numberOfOtherAssignments) { // for subclasses } - + protected void assertNoNotoriousParentOrgRef(PrismObject userAfter) { assertHasNoOrg(userAfter, getNotoriousOid()); } - + protected void assertNotoriousParentOrgRef(PrismObject userAfter) { assertNotoriousParentOrgRefRelations(userAfter, SchemaConstants.ORG_DEFAULT); } - + protected void assertNotoriousParentOrgRefRelations(PrismObject userAfter, QName... relations) { // for subclasses } @@ -1248,7 +1248,7 @@ private void prepareTest() { private void displayCountersAndInspector() { displayCounters( - InternalCounters.REPOSITORY_READ_COUNT, + InternalCounters.REPOSITORY_READ_COUNT, InternalCounters.PROJECTOR_RUN_COUNT, InternalCounters.ROLE_EVALUATION_COUNT, InternalCounters.ROLE_EVALUATION_SKIP_COUNT, @@ -1261,5 +1261,5 @@ protected int hackify(int i) { // TODO: projector now runs three times instead of one. return i*3; } - + } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/TestNotoriousOrg.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/TestNotoriousOrg.java index 151861c9fe3..a18c01e1465 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/TestNotoriousOrg.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/TestNotoriousOrg.java @@ -62,7 +62,7 @@ /** * Testing bushy roles hierarchy. Especially reuse of the same role * in the rich role hierarchy. It looks like this: - * + * * user * | * +------+------+-----+-----+-.... @@ -79,28 +79,28 @@ * | | | | | * v v v v v * Rb1 Rb2 Rb3 Rb4 Rb5 - * + * * Naive mode of evaluation would imply cartesian product of all Rax and Rbx * combinations. That's painfully inefficient. Therefore make sure that the * notorious roles is evaluated only once and the results of the evaluation * are reused. - * + * * @author Radovan Semancik */ @ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestNotoriousOrg extends AbstractNotoriousTest { - + public static final File ORG_NOTORIOUS_FILE = new File(TEST_DIR, "org-notorious.xml"); public static final String ORG_NOTORIOUS_OID = "f79fc21a-4d0a-11e7-ad8d-f7fe1a23c68a"; - + private static final Trace LOGGER = TraceManager.getTrace(TestNotoriousOrg.class); @Override protected String getNotoriousOid() { return ORG_NOTORIOUS_OID; } - + @Override protected File getNotoriousFile() { return ORG_NOTORIOUS_FILE; @@ -110,12 +110,12 @@ protected File getNotoriousFile() { protected QName getNotoriousType() { return OrgType.COMPLEX_TYPE; } - + @Override protected QName getAltRelation() { return SchemaConstants.ORG_MANAGER; } - + @Override protected int getNumberOfExtraRoles() { return 0; @@ -134,7 +134,7 @@ protected void addNotoriousRole(OperationResult result) throws Exception { LOGGER.info("Adding {}:\n{}", org, org.debugDump(1)); repositoryService.addObject(org, null, result); } - + @Override protected void assertNotoriousParentOrgRefRelations(PrismObject userAfter, QName... relations) { for (QName relation: relations) { diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/TestNotoriousRole.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/TestNotoriousRole.java index 7c20924aa6f..bdda402d22e 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/TestNotoriousRole.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/TestNotoriousRole.java @@ -61,7 +61,7 @@ /** * Testing bushy roles hierarchy. Especially reuse of the same role * in the rich role hierarchy. It looks like this: - * + * * user * | * +------+------+-----+-----+-.... @@ -78,28 +78,28 @@ * | | | | | * v v v v v * Rb1 Rb2 Rb3 Rb4 Rb5 - * + * * Naive mode of evaluation would imply cartesian product of all Rax and Rbx * combinations. That's painfully inefficient. Therefore make sure that the * notorious roles is evaluated only once and the results of the evaluation * are reused. - * + * * @author Radovan Semancik */ @ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestNotoriousRole extends AbstractNotoriousTest { - + public static final File ROLE_NOTORIOUS_FILE = new File(TEST_DIR, "role-notorious.xml"); public static final String ROLE_NOTORIOUS_OID = "1e95a1b8-46d1-11e7-84c5-e36e43bb0f00"; - + private static final Trace LOGGER = TraceManager.getTrace(TestNotoriousRole.class); @Override protected String getNotoriousOid() { return ROLE_NOTORIOUS_OID; } - + @Override protected File getNotoriousFile() { return ROLE_NOTORIOUS_FILE; @@ -114,7 +114,7 @@ protected QName getNotoriousType() { protected QName getAltRelation() { return SchemaConstants.ORG_OWNER; } - + @Override protected int getNumberOfExtraRoles() { return 1; @@ -133,13 +133,13 @@ protected void addNotoriousRole(OperationResult result) throws Exception { LOGGER.info("Adding {}:\n{}", role, role.debugDump(1)); repositoryService.addObject(role, null, result); } - + // Owner relation is non-evaluated @Override protected int getTest15xRoleEvaluationIncrement() { return 1 + NUMBER_OF_LEVEL_B_ROLES; } - + // Owner relation is non-evaluated, therefore the B-level roles are not in roleMembershipRef here @Override protected void assertTest158RoleMembershipRef(PrismObject userAfter) { diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/TestSupernotoriousOrg.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/TestSupernotoriousOrg.java index 383d03f41bd..2bf64020941 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/TestSupernotoriousOrg.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/notorious/TestSupernotoriousOrg.java @@ -66,7 +66,7 @@ /** * Testing bushy roles hierarchy. Especially reuse of the same role * in the rich role hierarchy. It looks like this: - * + * * user * | * +------+------+-----+-----+-.... @@ -78,37 +78,37 @@ * | * v * +--assignment--> supernotorious org - * | | + * | | * | +------+------+-----+-----+-.... * | | | | | | * | v v v v v * +-- Rb1 Rb2 Rb3 Rb4 Rb5 ---.. - * + * * Naive mode of evaluation would imply cartesian product of all Rax and Rbx * combinations. That's painfully inefficient. Therefore make sure that the * notorious roles is evaluated only once and the results of the evaluation * are reused. - * + * * @author Radovan Semancik */ @ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class TestSupernotoriousOrg extends TestNotoriousOrg { - + public static final File ORG_SUPERNOTORIOUS_FILE = new File(TEST_DIR, "org-supernotorious.xml"); public static final String ORG_SUPERNOTORIOUS_OID = "16baebbe-5046-11e7-82a0-eb7b7e3400f6"; - + @Override protected String getNotoriousOid() { return ORG_SUPERNOTORIOUS_OID; } - + @Override protected File getNotoriousFile() { return ORG_SUPERNOTORIOUS_FILE; } - + @Override protected void fillLevelBRole(RoleType roleType, int i) { super.fillLevelBRole(roleType, i); @@ -118,19 +118,19 @@ protected void fillLevelBRole(RoleType roleType, int i) { // .focusType(RoleType.COMPLEX_TYPE) .end(); } - + @Test public void test010LevelBRolesSanity() throws Exception { final String TEST_NAME = "test010LevelBRolesSanity"; displayTestTitle(TEST_NAME); ObjectQuery query = queryFor(RoleType.class).item(RoleType.F_ROLE_TYPE).eq(ROLE_LEVEL_B_ROLETYPE).build(); - searchObjectsIterative(RoleType.class, query, + searchObjectsIterative(RoleType.class, query, role -> { assertRoleMembershipRef(role, getNotoriousOid()); }, NUMBER_OF_LEVEL_B_ROLES); } - + @Override protected void assertRoleEvaluationCount(int numberOfNotoriousAssignments, int numberOfOtherAssignments) { inspector.assertRoleEvaluations(getNotoriousOid(), hackify(numberOfNotoriousAssignments)); diff --git a/testing/story/src/test/resources/unix/resource-opendj-tolerant-aux.xml b/testing/story/src/test/resources/unix/resource-opendj-tolerant-aux.xml index 24d2a55d693..517222ef26b 100644 --- a/testing/story/src/test/resources/unix/resource-opendj-tolerant-aux.xml +++ b/testing/story/src/test/resources/unix/resource-opendj-tolerant-aux.xml @@ -56,6 +56,7 @@ isMemberOf modifyTimestamp string + true diff --git a/testing/wstest/src/test/java/com/evolveum/midpoint/testing/wstest/ClientPasswordHandler.java b/testing/wstest/src/test/java/com/evolveum/midpoint/testing/wstest/ClientPasswordHandler.java index 198ba022787..368247405f2 100644 --- a/testing/wstest/src/test/java/com/evolveum/midpoint/testing/wstest/ClientPasswordHandler.java +++ b/testing/wstest/src/test/java/com/evolveum/midpoint/testing/wstest/ClientPasswordHandler.java @@ -28,13 +28,13 @@ * */ public class ClientPasswordHandler implements CallbackHandler { - + private static String password; public static void setPassword(String password) { ClientPasswordHandler.password = password; } - + @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { WSPasswordCallback pc = (WSPasswordCallback) callbacks[0]; diff --git a/tools/repo-ninja/src/main/java/com/evolveum/midpoint/tools/ninja/ExportObjects.java b/tools/repo-ninja/src/main/java/com/evolveum/midpoint/tools/ninja/ExportObjects.java index f058a6a3cbd..8e2edbe1072 100644 --- a/tools/repo-ninja/src/main/java/com/evolveum/midpoint/tools/ninja/ExportObjects.java +++ b/tools/repo-ninja/src/main/java/com/evolveum/midpoint/tools/ninja/ExportObjects.java @@ -40,7 +40,7 @@ private String createHeaderForXml() { return builder.toString(); } - + public boolean execute() throws UnsupportedEncodingException, FileNotFoundException { System.out.println("Starting objects export."); @@ -52,33 +52,33 @@ public boolean execute() throws UnsupportedEncodingException, FileNotFoundExcept final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(CONTEXTS); final OutputStreamWriter stream = new OutputStreamWriter(new FileOutputStream(file), "utf-8"); - + try { - + System.out.println("Loading spring contexts."); - + System.out.println("Set repository."); - + RepositoryService repository = context.getBean("repositoryService", RepositoryService.class); - - ResultHandler handler = new ResultHandler() + + ResultHandler handler = new ResultHandler() { - + PrismContext prismContext = context.getBean(PrismContext.class); @Override - public boolean handle(PrismObject object, OperationResult parentResult) + public boolean handle(PrismObject object, OperationResult parentResult) { String displayName = getDisplayName(object); System.out.println("Exporting object " + displayName); OperationResult resultExport = new OperationResult("Export " + displayName); - try + try { String stringObject = prismContext.serializeObjectToString(object, PrismContext.LANG_XML); stream.write("\t" + stringObject + "\n"); - } - catch (Exception ex) + } + catch (Exception ex) { System.out.println("Failed to parse objects to string for xml. Reason: " + ex); resultExport.recordFatalError("Failed to parse objects to string for xml. Reason: ", ex); @@ -87,24 +87,24 @@ public boolean handle(PrismObject object, OperationResult parentResu return true; } }; - + stream.write(createHeaderForXml()); - + OperationResult result = new OperationResult("search set"); System.out.println("Creating xml file " + file.getName()); repository.searchObjectsIterative(ObjectType.class, null, handler, null, false, result); - + stream.write(""); System.out.println("Created xml file " + file.getName()); - + } catch (Exception ex) { System.out.println("Exception occurred during context loading, reason: " + ex.getMessage()); ex.printStackTrace(); } finally { destroyContext(context); - if (stream != null) + if (stream != null) { IOUtils.closeQuietly(stream); } @@ -115,7 +115,7 @@ public boolean handle(PrismObject object, OperationResult parentResu System.out.println("Objects export finished."); return true; } - + private String getDisplayName(PrismObject object) { StringBuilder builder = new StringBuilder(); diff --git a/tools/repo-ninja/src/main/java/com/evolveum/midpoint/tools/ninja/FileTransformer.java b/tools/repo-ninja/src/main/java/com/evolveum/midpoint/tools/ninja/FileTransformer.java index 3edd61749c4..06df2b9b6a3 100644 --- a/tools/repo-ninja/src/main/java/com/evolveum/midpoint/tools/ninja/FileTransformer.java +++ b/tools/repo-ninja/src/main/java/com/evolveum/midpoint/tools/ninja/FileTransformer.java @@ -16,37 +16,37 @@ import com.evolveum.midpoint.util.exception.SchemaException; public class FileTransformer extends BaseNinjaAction{ - + private String outputDirecorty; private String input; private String outputFormat; - + public void setOutputDirecorty(String outputDirecorty) { this.outputDirecorty = outputDirecorty; } - + public void setOutputFormat(String outputFormat) { this.outputFormat = outputFormat; } - + public void setInput(String input) { this.input = input; } - + public void execute(){ ApplicationContext context = new ClassPathXmlApplicationContext(CONTEXTS); PrismContext prismContext = context.getBean(PrismContext.class); - - + + File inFile = new File(input); - + File[] files = null; if (inFile.isDirectory()){ files = inFile.listFiles(); } - + String output = getOutput(inFile); - + String outLang = getOutputLanguage(outputFormat); int errors = 0; int processed = 0; @@ -56,7 +56,7 @@ public void execute(){ for (int i = 0; i < files.length; i++){ try { transform(prismContext, files[i], output, outLang); - + } catch (SchemaException | IOException e) { System.out.println("failed to transform: " + e.getMessage()+ ". Stack: " + e); errors++; @@ -72,48 +72,48 @@ public void execute(){ failedToParse.add(inFile.getName()); } } - - System.out.println("Processed " + processed +" files, got " +errors+ " errors. Files that was not successfully processed " + failedToParse); - - + + System.out.println("Processed " + processed +" files, got " +errors+ " errors. Files that was not successfully processed " + failedToParse); + + } - + private void transform(PrismContext prismContext, File inFile, String output, String lang) throws SchemaException, IOException{ - + PrismObject parsed = prismContext.parseObject(inFile); - + String s = prismContext.serializeObjectToString(parsed, lang); - - + + if (StringUtils.isNotBlank(outputDirecorty)){ } - + String outName = getOutputFileName(inFile, lang); System.out.println("file will be saved as: " + outName); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(outputDirecorty, outName))); - + PrismObject object = prismContext.parseObject(inFile); String serialized = prismContext.serializeObjectToString(object, lang); - + bos.write(serialized.getBytes()); bos.flush(); bos.close(); - + } - + private String getOutputFileName(File inFile, String outFormat) { String out = inFile.getName(); - + if (out.endsWith(".xml")){ return out.replace("xml", outFormat); } else if (out.endsWith(".json")){ return out.replace("json", outFormat); } else if (out.endsWith(".yaml")){ return out.replace("yaml", outFormat); - } else + } else throw new UnsupportedOperationException("Transformation for file " + inFile.getName() +" not supported."); - - + + } private String getOutput(File inFile) { @@ -136,7 +136,7 @@ private String getOutputLanguage(String outFormat){ return PrismContext.LANG_YAML; } else if (outFormat.toLowerCase().equals(PrismContext.LANG_XML)){ return PrismContext.LANG_XML; - } else + } else throw new UnsupportedOperationException("Specified output format '"+outFormat+"'not supported"); } diff --git a/tools/repo-ninja/src/main/java/com/evolveum/midpoint/tools/ninja/KeyStoreDumper.java b/tools/repo-ninja/src/main/java/com/evolveum/midpoint/tools/ninja/KeyStoreDumper.java index 79da8d35d54..8598ece9237 100644 --- a/tools/repo-ninja/src/main/java/com/evolveum/midpoint/tools/ninja/KeyStoreDumper.java +++ b/tools/repo-ninja/src/main/java/com/evolveum/midpoint/tools/ninja/KeyStoreDumper.java @@ -20,30 +20,30 @@ import com.evolveum.midpoint.prism.crypto.Protector; public class KeyStoreDumper extends BaseNinjaAction{ - + public void execute(){ - + try{ ApplicationContext context = new ClassPathXmlApplicationContext(CONTEXTS); - + Protector protector = context.getBean("protector", Protector.class); KeyStore keyStore = protector.getKeyStore(); - + System.out.println("###################################################"); System.out.println("Printing keys from key store"); - + if (protector instanceof ProtectorImpl){ ProtectorImpl aesProtector = (ProtectorImpl) protector; System.out.println("Using key store from location: " + aesProtector.getKeyStorePath()); // System.out.println("Cipher: " + aesProtector.getXmlCipher()); - + } - + Enumeration aliases = keyStore.aliases(); - + while (aliases.hasMoreElements()){ String alias = aliases.nextElement(); - + System.out.println("===== ALIAS: "+ alias +"====="); System.out.println("Creation date: " + keyStore.getCreationDate(alias)); System.out.println("Type: " + keyStore.getType()); @@ -53,11 +53,11 @@ public void execute(){ if (keyStore.getCertificateChain(alias) != null){ System.out.println("Certificate chain: " + keyStore.getCertificateChain(alias)); } - + ProtectionParameter protParam = new KeyStore.PasswordProtection("midpoint".toCharArray()); Entry entry = keyStore.getEntry(alias, protParam); - - + + if (entry instanceof SecretKeyEntry){ System.out.println("Secret key entry: "); SecretKeyEntry skEntry = (SecretKeyEntry) entry; @@ -71,17 +71,17 @@ public void execute(){ // Cipher cipher = Cipher.getInstance(key.getAlgorithm()); // System.out.println(" Cipher algorithm" + cipher.getAlgorithm()); } - - - + + + //TODO: add dump also for other types of keys Provider provider = keyStore.getProvider(); System.out.println("Provder name: " + provider.getName() +"\n"); - + } - + System.out.println("###################################################"); - + } catch (KeyStoreException ex){ System.out.println("Failed to print information about keyStore. Reason: " + ex.getMessage()); return; @@ -95,11 +95,11 @@ public void execute(){ System.out.println("Failed to print information about keyStore. Reason: " + ex.getMessage()); return; } - - - - - + + + + + } } diff --git a/tools/repo-ninja/src/main/java/com/evolveum/midpoint/tools/ninja/Main.java b/tools/repo-ninja/src/main/java/com/evolveum/midpoint/tools/ninja/Main.java index 4fa008440ad..e24360b8713 100644 --- a/tools/repo-ninja/src/main/java/com/evolveum/midpoint/tools/ninja/Main.java +++ b/tools/repo-ninja/src/main/java/com/evolveum/midpoint/tools/ninja/Main.java @@ -102,12 +102,12 @@ public static void main(String[] args) { ExportObjects objects = new ExportObjects(path); objects.execute(); } - + if (line.hasOption(keyStore.getOpt())){ KeyStoreDumper keyStoreDumper = new KeyStoreDumper(); keyStoreDumper.execute(); } - + if (line.hasOption(trans.getOpt())){ if (!checkCommand(line)){ return; @@ -129,7 +129,7 @@ private static void configureTransformer(FileTransformer transformer, CommandLin transformer.setOutputDirecorty(line.getOptionValue(outputDirectory.getOpt())); transformer.setOutputFormat(line.getOptionValue(outputFormat.getOpt())); transformer.setInput(line.getOptionValue(input.getOpt())); - + } private static boolean checkCommand(CommandLine line) { diff --git a/tools/schema-dist-maven-plugin/src/main/java/com/evolveum/midpoint/tools/schemadist/ArtifactItem.java b/tools/schema-dist-maven-plugin/src/main/java/com/evolveum/midpoint/tools/schemadist/ArtifactItem.java index 5dd83c13148..15ef7706d80 100644 --- a/tools/schema-dist-maven-plugin/src/main/java/com/evolveum/midpoint/tools/schemadist/ArtifactItem.java +++ b/tools/schema-dist-maven-plugin/src/main/java/com/evolveum/midpoint/tools/schemadist/ArtifactItem.java @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * + * * This file is inspired and uses minor parts of the maven-dependency-plugin by Brian Fox. */ @@ -24,7 +24,7 @@ import org.apache.xml.resolver.Catalog; public class ArtifactItem { - + /** * @parameter * @required @@ -59,9 +59,9 @@ public class ArtifactItem { private String catalog; // intentionally no default private Artifact artifact; - + private File workDir; - + private Catalog resolveCatalog; public String getGroupId() { @@ -136,5 +136,5 @@ public void setResolveCatalog(Catalog resolveCatalog) { this.resolveCatalog = resolveCatalog; } - + } diff --git a/tools/schema-dist-maven-plugin/src/main/java/com/evolveum/midpoint/tools/schemadist/SchemaDistMojo.java b/tools/schema-dist-maven-plugin/src/main/java/com/evolveum/midpoint/tools/schemadist/SchemaDistMojo.java index c5ee4495edf..b6d91a2b0af 100644 --- a/tools/schema-dist-maven-plugin/src/main/java/com/evolveum/midpoint/tools/schemadist/SchemaDistMojo.java +++ b/tools/schema-dist-maven-plugin/src/main/java/com/evolveum/midpoint/tools/schemadist/SchemaDistMojo.java @@ -12,8 +12,8 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - * This file is inspired and uses minor parts of the maven-dependency-plugin by Brian Fox. + * + * This file is inspired and uses minor parts of the maven-dependency-plugin by Brian Fox. */ package com.evolveum.midpoint.tools.schemadist; @@ -86,12 +86,12 @@ public class SchemaDistMojo extends AbstractMojo { * @parameter default-value="${project.build.directory}/schemadist-work" required=true */ private File workDirectory; - + /** * @parameter */ private List artifactItems; - + /** * @parameter default-value="true" required=true */ @@ -107,10 +107,10 @@ public class SchemaDistMojo extends AbstractMojo { /** @parameter default-value="${localRepository}" */ private ArtifactRepository local; - + /** @parameter default-value="${project.remoteArtifactRepositories}" */ protected List remoteRepos; - + /** * @component */ @@ -120,12 +120,12 @@ public class SchemaDistMojo extends AbstractMojo { * @component */ private ArtifactResolver resolver; - + /** * @component */ private ArchiverManager archiverManager; - + /** * @component */ @@ -139,7 +139,7 @@ private void processArtifactItems() throws MojoExecutionException, InvalidVersio artifactItem.setArtifact(getArtifact(artifactItem)); } } - + private void fillMissingArtifactVersion(ArtifactItem artifactItem) throws MojoExecutionException { List deps = project.getDependencies(); List depMngt = project.getDependencyManagement() == null @@ -155,7 +155,7 @@ private void fillMissingArtifactVersion(ArtifactItem artifactItem) throws MojoEx + " in either dependency list or in project's dependency management." ); } } - + private boolean findDependencyVersion(ArtifactItem artifact, List dependencies, boolean looseMatch) { for ( Dependency dependency : dependencies ) { if ( StringUtils.equals( dependency.getArtifactId(), artifact.getArtifactId() ) @@ -172,9 +172,9 @@ private boolean findDependencyVersion(ArtifactItem artifact, List de protected Artifact getArtifact(ArtifactItem artifactItem) throws MojoExecutionException, InvalidVersionSpecificationException { Artifact artifact; - + VersionRange vr = VersionRange.createFromVersionSpec(artifactItem.getVersion()); - + if (StringUtils.isEmpty(artifactItem.getClassifier())) { artifact = factory.createDependencyArtifact( artifactItem.getGroupId(), artifactItem.getArtifactId(), vr, artifactItem.getType(), null, Artifact.SCOPE_COMPILE ); @@ -183,13 +183,13 @@ protected Artifact getArtifact(ArtifactItem artifactItem) throws MojoExecutionEx artifactItem.getType(), artifactItem.getClassifier(), Artifact.SCOPE_COMPILE ); } - + try { resolver.resolve(artifact, remoteRepos, local); } catch (ArtifactResolutionException | ArtifactNotFoundException e) { throw new MojoExecutionException("Error resolving artifact "+artifact, e); } - + return artifact; } @@ -205,7 +205,7 @@ public void execute() throws MojoExecutionException, MojoFailureException { CatalogManager catalogManager = new CatalogManager(); catalogManager.setVerbosity(999); - + for (ArtifactItem artifactItem: artifactItems) { Artifact artifact = artifactItem.getArtifact(); getLog().info( "SchemaDist unpacking artifact " + artifact); @@ -213,7 +213,7 @@ public void execute() throws MojoExecutionException, MojoFailureException { initializeOutDir(workDir); artifactItem.setWorkDir(workDir); unpack(artifactItem, workDir); - + if (translateSchemaLocation) { String catalogPath = artifactItem.getCatalog(); if (catalogPath != null) { @@ -302,7 +302,7 @@ public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOEx } catch (IOException e) { throw new MojoExecutionException("Error processing files of artifact "+artifact, e); } - + } getLog().info( "SchemaDist plugin finished" ); } @@ -315,7 +315,7 @@ private void processXsd(Path filePath, File workDir, File outDir) throws MojoExe } serializeXml(dom, filePath, workDir, outDir); } - + private void serializeXml(Document dom, Path filePath, File workDir, File outDir) throws MojoFailureException, MojoExecutionException { Path fileRelPath = workDir.toPath().relativize(filePath); File outFile = new File(outDir, fileRelPath.toString()); @@ -363,7 +363,7 @@ private void processXsdElement(Element rootElement, Path filePath, File workDir, private void processWsdl(Path filePath, File workDir, File outDir) throws MojoExecutionException, MojoFailureException { Document dom = DOMUtil.parseFile(filePath.toFile()); - + if (translateSchemaLocation) { Element rootElement = DOMUtil.getFirstChildElement(dom); List importElements = DOMUtil.getChildElements(rootElement, DOMUtil.WSDL_IMPORT_ELEMENT); @@ -378,13 +378,13 @@ private void processWsdl(Path filePath, File workDir, File outDir) throws MojoEx importElement.setAttribute(DOMUtil.WSDL_ATTR_LOCATION.getLocalPart(), schemaLocation); } - + List typesElements = DOMUtil.getChildElements(rootElement, DOMUtil.WSDL_TYPES_ELEMENT); for(Element typesElement: typesElements) { processXsdElement(DOMUtil.getFirstChildElement(typesElement),filePath,workDir,outDir); } } - + serializeXml(dom, filePath, workDir, outDir); } @@ -406,13 +406,13 @@ private String resolveSchemaLocation(String namespaceOrLocation, Path filePath, String resolvedPathString = resolvedUrl.getPath(); Path resolvedPath = new File(resolvedPathString).toPath(); Path workDirPath = workDir.toPath(); - + Path resolvedRelativeToCatalogWorkdir = artifactItem.getWorkDir().toPath().relativize(resolvedPath); Path fileRelativeToWorkdir = workDirPath.relativize(filePath); - + getLog().debug("workDirPath: "+workDirPath); getLog().debug("resolvedRelativeToCatalogWorkdir: "+resolvedRelativeToCatalogWorkdir+", fileRelativeToWorkdir: "+fileRelativeToWorkdir); - + Path relativePath = fileRelativeToWorkdir.getParent().relativize(resolvedRelativeToCatalogWorkdir); getLog().debug("Rel: "+relativePath); String unixSeparators = FilenameUtils.separatorsToUnix(relativePath.toString()); @@ -452,25 +452,25 @@ private void unpack(ArtifactItem artifactItem, File destDir) throws MojoExecutio UnArchiver unArchiver = archiverManager.getUnArchiver( artifact.getType() ); unArchiver.setSourceFile(file); unArchiver.setDestDirectory(destDir); - + if (StringUtils.isNotEmpty(excludes) || StringUtils.isNotEmpty(includes)) { // Create the selectors that will filter // based on include/exclude parameters // MDEP-47 IncludeExcludeFileSelector[] selectors = new IncludeExcludeFileSelector[]{ new IncludeExcludeFileSelector() }; - + if ( StringUtils.isNotEmpty( excludes ) ) { selectors[0].setExcludes( excludes.split( "," ) ); } - + if ( StringUtils.isNotEmpty( includes ) ) { selectors[0].setIncludes( includes.split( "," ) ); } - + unArchiver.setFileSelectors( selectors ); } - + unArchiver.extract(); } catch (ArchiverException | NoSuchArchiverException e) { throw new MojoExecutionException( diff --git a/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/AlphabeticalMethodInterceptor.java b/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/AlphabeticalMethodInterceptor.java index 635094cebba..1aae147d6fa 100644 --- a/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/AlphabeticalMethodInterceptor.java +++ b/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/AlphabeticalMethodInterceptor.java @@ -58,9 +58,9 @@ public int compare(IMethodInstance o1, IMethodInstance o2) { Arrays.sort(array, comparator); result.addAll(Arrays.asList(array)); } - + System.out.println("AlphabeticalMethodInterceptor: "+result); - return result; + return result; } } diff --git a/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/TestListener.java b/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/TestListener.java index a5ca3ea45f0..6eeaf62cacf 100644 --- a/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/TestListener.java +++ b/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/TestListener.java @@ -24,7 +24,7 @@ import org.testng.ITestResult; public class TestListener implements ITestListener { - + private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); private static final String PREFIX = " ####[ "; private static final String SUFFIX = " ]####"; @@ -72,5 +72,5 @@ private void print(String message) { sb.append(SUFFIX); System.out.println(sb.toString()); } - + } diff --git a/tools/xjc-plugin/src/main/java/com/evolveum/midpoint/schema/xjc/schema/SchemaProcessor.java b/tools/xjc-plugin/src/main/java/com/evolveum/midpoint/schema/xjc/schema/SchemaProcessor.java index e567c30b0af..d81753d9a68 100644 --- a/tools/xjc-plugin/src/main/java/com/evolveum/midpoint/schema/xjc/schema/SchemaProcessor.java +++ b/tools/xjc-plugin/src/main/java/com/evolveum/midpoint/schema/xjc/schema/SchemaProcessor.java @@ -98,22 +98,22 @@ public class SchemaProcessor implements Processor { public static final QName A_PRISM_CONTAINER = new QName(PrefixMapper.A.getNamespace(), "container"); public static final QName A_PRISM_OBJECT = new QName(PrefixMapper.A.getNamespace(), "object"); public static final QName A_RAW_TYPE = new QName(PrefixMapper.A.getNamespace(), "rawType"); - + //Public fields private static final String COMPLEX_TYPE_FIELD_NAME = "COMPLEX_TYPE"; - + // Public generated methods // The "as" prefix is chosen to avoid clash with usual "get" for the fields and also to indicate that // the it returns the same object in a different representation and not a composed/aggregated object public static final String METHOD_AS_PRISM_OBJECT = "asPrismObject"; public static final String METHOD_AS_PRISM_CONTAINER_VALUE = "asPrismContainerValue"; private static final String METHOD_AS_PRISM_CONTAINER = "asPrismContainer"; - // The "setup" prefix is chosen avoid collision with regular setters for generated fields + // The "setup" prefix is chosen avoid collision with regular setters for generated fields public static final String METHOD_SETUP_CONTAINER_VALUE = "setupContainerValue"; public static final String METHOD_SETUP_CONTAINER = "setupContainer"; public static final String METHOD_AS_REFERENCE_VALUE = "asReferenceValue"; public static final String METHOD_SETUP_REFERENCE_VALUE = "setupReferenceValue"; - + // Internal fields and methods. Although some of these fields needs to be public (so they can be used by // prism classes), they are not really intended for public usage. We also want to avoid conflicts with code // generated for regular fields. Hence the underscore. @@ -122,7 +122,7 @@ public class SchemaProcessor implements Processor { private static final String METHOD_GET_CONTAINER_NAME = "_getContainerName"; private static final String METHOD_GET_CONTAINER_TYPE = "_getContainerType"; private static final String REFERENCE_VALUE_FIELD_NAME = "_referenceValue"; - + //methods in PrismForJAXBUtil private static final String METHOD_PRISM_UTIL_GET_FIELD_SINGLE_CONTAINERABLE = "getFieldSingleContainerable"; private static final String METHOD_PRISM_UTIL_GET_PROPERTY_VALUE = "getPropertyValue"; @@ -144,14 +144,14 @@ public class SchemaProcessor implements Processor { // ??? private static final String METHOD_PRISM_GET_ANY = "getAny"; - + private static final String METHOD_CONTAINER_GET_VALUE = "getValue"; - + private static final String CONTAINER_VALUE_LOCAL_VAR_NAME = "containerValue"; private static final String FIELD_CONTAINER_VALUE_LOCAL_VAR_NAME = "fieldContainerValue"; private static final String OBJECT_LOCAL_FIELD_NAME = "object"; private static final String REFERENCE_LOCAL_VARIABLE_NAME = "reference"; - + //equals, toString, hashCode methods private static final String METHOD_TO_STRING = "toString"; private static final String METHOD_DEBUG_DUMP = "debugDump"; @@ -169,7 +169,7 @@ public JClass get(Object o) { return clazz; } }; - + @Override public boolean run(Outline outline, Options options, ErrorHandler errorHandler) throws SAXException { @@ -270,13 +270,13 @@ private void updateObjectReferenceType(JDefinedClass definedClass, JMethod getRe body._return(JExpr.invoke(JExpr.invoke(getReference), "getTargetType")); definedClass.removeField(typeField); - + JMethod setType = recreateMethod(findMethod(definedClass, "setType"), definedClass); body = setType.body(); JInvocation invocation = body.invoke(JExpr.invoke(getReference), "setTargetType"); invocation.arg(setType.listParams()[0]); invocation.arg(JExpr.lit(true)); - + JFieldVar targetNameField = definedClass.fields().get("targetName"); JMethod getTargetName = recreateMethod(findMethod(definedClass, "getTargetName"), definedClass); copyAnnotations(getTargetName, targetNameField); @@ -286,12 +286,12 @@ private void updateObjectReferenceType(JDefinedClass definedClass, JMethod getRe getTargetNamebody._return(getTargetNameInvocation); definedClass.removeField(targetNameField); - + JMethod setTargetName = recreateMethod(findMethod(definedClass, "setTargetName"), definedClass); JBlock setTargetNamebody = setTargetName.body(); JInvocation setTagetNameInvocation = setTargetNamebody.staticInvoke(CLASS_MAP.get(PrismForJAXBUtil.class), METHOD_PRISM_UTIL_SET_REFERENCE_TARGET_NAME); setTagetNameInvocation.arg(JExpr.invoke(getReference)); - setTagetNameInvocation.arg(setTargetName.listParams()[0]); + setTagetNameInvocation.arg(setTargetName.listParams()[0]); } private void updateObjectReferenceRelation(JDefinedClass definedClass, JMethod getReference) { @@ -321,7 +321,7 @@ private void updateObjectReferenceOid(JDefinedClass definedClass, JMethod getRef JInvocation invocation = body.invoke(JExpr.invoke(getReference), setOid.name()); invocation.arg(setOid.listParams()[0]); } - + private void updateObjectReferenceDescription(JDefinedClass definedClass, JMethod getReference) { JFieldVar descriptionField = definedClass.fields().get("description"); JMethod getDescription = recreateMethod(findMethod(definedClass, "getDescription"), definedClass); @@ -335,10 +335,10 @@ private void updateObjectReferenceDescription(JDefinedClass definedClass, JMetho JInvocation invocation = body.invoke(JExpr.invoke(getReference), setDescription.name()); invocation.arg(setDescription.listParams()[0]); } - + private void updateObjectReferenceFilter(JDefinedClass definedClass, JMethod asReferenceValue) { JFieldVar filterField = definedClass.fields().get("filter"); - + JMethod getFilter = recreateMethod(findMethod(definedClass, "getFilter"), definedClass); copyAnnotations(getFilter, filterField); definedClass.removeField(filterField); @@ -358,7 +358,7 @@ private void updateObjectReferenceFilter(JDefinedClass definedClass, JMethod asR invocation.arg(setFilter.listParams()[0]); body.add(invocation); } - + private void updateObjectReferenceResolutionTime(JDefinedClass definedClass, JMethod getReference) { JFieldVar typeField = definedClass.fields().get("resolutionTime"); JMethod getType = recreateMethod(findMethod(definedClass, "getResolutionTime"), definedClass); @@ -482,7 +482,7 @@ private void createAsPrismContainerValueInObject(JDefinedClass definedClass) { JBlock body = getContainer.body(); body._return(JExpr.invoke(METHOD_AS_PRISM_CONTAINER).invoke(METHOD_CONTAINER_GET_VALUE)); } - + private void createAsPrismContainerValue(JDefinedClass definedClass, JVar containerValueVar) { JMethod getContainer = definedClass.method(JMod.PUBLIC, CLASS_MAP.get(PrismContainerValue.class), METHOD_AS_PRISM_CONTAINER_VALUE); @@ -670,7 +670,7 @@ private void updateClassAnnotation(ClassOutline classOutline) { throw new RuntimeException(ex.getMessage(), ex); } } - + private String extractString(JAnnotationValue jAnnValue) { StringWriter writer = new StringWriter(); JFormatter formatter = new JFormatter(writer); @@ -872,7 +872,7 @@ private JMethod createSetContainerValueMethod(JDefinedClass definedClass, JVar c body.assign(JExpr._this().ref(container), methodContainer); return setContainer; } - + private void createSetContainerValueMethodInObject(JDefinedClass definedClass, JVar container) { JMethod setContainerValue = definedClass.method(JMod.PUBLIC, void.class, METHOD_SETUP_CONTAINER_VALUE); setContainerValue.annotate(CLASS_MAP.get(Override.class)); @@ -1070,7 +1070,7 @@ private void addFieldQNames(Outline outline, Map namespaceFie if (fields == null) { continue; } - + boolean isObject = hasAnnotation(classOutline, A_PRISM_OBJECT); List> boxes = new ArrayList>(); @@ -1301,7 +1301,7 @@ private JDefinedClass createFieldReferenceGetterListAnon(JFieldVar field, ClassO JMethod getValueFrom = anonymous.method(JMod.PROTECTED, CLASS_MAP.get(PrismReferenceValue.class), "getValueFrom"); getValueFrom.annotate(CLASS_MAP.get(Override.class)); getValueFrom.param(type, "value"); - + JMethod willClear = anonymous.method(JMod.PROTECTED, boolean.class, "willClear"); willClear.annotate(CLASS_MAP.get(Override.class)); willClear.param(CLASS_MAP.get(PrismReferenceValue.class), "value"); @@ -1351,13 +1351,13 @@ private void createFieldReferenceGetValueFrom(JFieldVar field, JMethod method) { JBlock body = method.body(); body._return(JExpr.invoke(method.listParams()[0], METHOD_AS_REFERENCE_VALUE)); } - + private void createFieldReferenceWillClear(JFieldVar field, JMethod method) { JBlock body = method.body(); JInvocation getObject = JExpr.invoke(method.listParams()[0], "getObject"); body._return(getObject.eq(JExpr._null())); } - + private void createFieldReferenceUseWillClear(JFieldVar field, JMethod method) { JBlock body = method.body(); JInvocation getObject = JExpr.invoke(method.listParams()[0], "getObject"); @@ -1373,7 +1373,7 @@ private void createFieldReferenceGetterBody(JFieldVar field, ClassOutline classO JVar pcv = body.decl(CLASS_MAP.get(PrismContainerValue.class), "pcv", JExpr.invoke(METHOD_AS_PRISM_CONTAINER_VALUE)); // PrismReference reference = PrismForJAXBUtil.getReference(pcv, F_LINK_REF); - JInvocation invoke = CLASS_MAP.get(PrismForJAXBUtil.class).staticInvoke(METHOD_PRISM_UTIL_GET_REFERENCE); + JInvocation invoke = CLASS_MAP.get(PrismForJAXBUtil.class).staticInvoke(METHOD_PRISM_UTIL_GET_REFERENCE); invoke.arg(pcv); invoke.arg(qnameRef); JVar reference = body.decl(CLASS_MAP.get(PrismReference.class), REFERENCE_LOCAL_VARIABLE_NAME, invoke); @@ -1460,12 +1460,12 @@ private void createFieldReferenceUseCreateItemBody(JFieldVar field, JMethod meth private void createFieldReferenceUseGetValueFrom(JFieldVar field, JMethod method) { JBlock body = method.body(); - + JInvocation invocation = CLASS_MAP.get(PrismForJAXBUtil.class).staticInvoke(METHOD_PRISM_UTIL_OBJECTABLE_AS_REFERENCE_VALUE); invocation.arg(method.listParams()[0]); invocation.arg(JExpr.invoke("getReference")); body._return(invocation); - + // JVar object = body.decl(CLASS_MAP.get(PrismObject.class), "object", // JExpr.invoke(method.listParams()[0], METHOD_AS_PRISM_OBJECT)); // JVar reference = body.decl(CLASS_MAP.get(PrismReference.class), "reference", @@ -1937,12 +1937,12 @@ private void createContainerFieldGetterBody(JFieldVar field, ClassOutline classO } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException(e.getMessage(), e); } - mfield.setAccessible(false); + mfield.setAccessible(false); map.remove("name"); annotation.param("name", normalizeFieldName(field.name())); } } - + if (isList(field.type())) { //JClass list = (JClass) field.type(); //JClass listType = list.getTypeParameters().get(0); @@ -1969,7 +1969,7 @@ private void createContainerFieldGetterBody(JFieldVar field, ClassOutline classO return; } - + JInvocation invocation = CLASS_MAP.get(PrismForJAXBUtil.class).staticInvoke(METHOD_PRISM_UTIL_GET_FIELD_SINGLE_CONTAINERABLE); invocation.arg(JExpr.invoke(METHOD_AS_PRISM_CONTAINER_VALUE)); invocation.arg(JExpr.ref(fieldFPrefixUnderscoredUpperCase(field.name()))); diff --git a/tools/xjc-plugin/src/main/java/com/evolveum/midpoint/schema/xjc/util/ProcessorUtils.java b/tools/xjc-plugin/src/main/java/com/evolveum/midpoint/schema/xjc/util/ProcessorUtils.java index 810f8aa2405..32eca1049c5 100644 --- a/tools/xjc-plugin/src/main/java/com/evolveum/midpoint/schema/xjc/util/ProcessorUtils.java +++ b/tools/xjc-plugin/src/main/java/com/evolveum/midpoint/schema/xjc/util/ProcessorUtils.java @@ -229,7 +229,7 @@ public static Field getField(Class clazz, String name) { return null; } - + private static BIDeclaration hasAnnotation(XSAnnotation annotation, QName qname) { if (annotation == null) { return null; @@ -254,7 +254,7 @@ private static BIDeclaration hasAnnotation(XSAnnotation annotation, QName qname) return null; } - + public static BIDeclaration hasAnnotation(ClassOutline classOutline, JFieldVar field, QName qname) { CPropertyInfo propertyInfo = classOutline.target.getProperty(field.name()); if (propertyInfo == null || !(propertyInfo.getSchemaComponent() instanceof XSParticle)) { @@ -265,7 +265,7 @@ public static BIDeclaration hasAnnotation(ClassOutline classOutline, JFieldVar f return null; } XSAnnotation annotation = particle.getTerm().getAnnotation(false); - + return hasAnnotation(annotation, qname); } @@ -310,7 +310,7 @@ public static ClassOutline findClassOutline(JDefinedClass definedClass, Outline return classOutline; } - + public static String normalizeFieldName(String fieldName) { if (fieldName.startsWith("_")) { return fieldName.substring(1);